Skip to main content

ob_game/
resources.rs

1//! Locates and loads the original Blood data files supplied by the user.
2
3use ob_engine::art::TileSet;
4use ob_engine::palette::{Palette, NUM_SHADES};
5use ob_engine::render::ShadeLuts;
6use ob_engine::rff::Rff;
7use std::io;
8use std::path::{Path, PathBuf};
9
10/// Palette lookup tables shipped in BLOOD.RFF, by palookup number.
11pub const PLU_NAMES: [&str; 15] = [
12    "NORMAL", "SATURATE", "BEAST", "TOMMY", "SPIDER3", "GRAY", "GRAYISH", "SPIDER1", "SPIDER2", "FLAME", "COLD", "P1",
13    "P2", "P3", "P4",
14];
15
16/// Base palettes: 0 normal, 1 water, 2 beast, 3 sewer, 4 invulnerability.
17pub const PAL_NAMES: [&str; 5] = ["BLOOD", "WATER", "BEAST", "SEWER", "INVULN1"];
18
19pub struct Resources {
20    pub dir: PathBuf,
21    pub blood: Rff,
22    pub sounds: Option<Rff>,
23    pub tiles: TileSet,
24    pub palettes: Vec<Palette>,
25    /// Raw 8-bit palookups (`64 * 256`), by palookup number.
26    pub plu: Vec<Option<Vec<u8>>>,
27    pub trans: Vec<u8>,
28    pub surface: Vec<u8>,
29    pub voxel_ids: Vec<i16>,
30    pub ini: crate::ini::BloodIni,
31    /// Voxel models from BLOOD.RFF, indexed by KVX id.
32    pub voxels: Vec<Option<ob_engine::voxel::Voxel>>,
33}
34
35fn find_file(dir: &Path, name: &str) -> Option<PathBuf> {
36    let direct = dir.join(name);
37    if direct.exists() {
38        return Some(direct);
39    }
40    // Case-insensitive lookup for copies made on case-sensitive file systems.
41    std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).find(|p| {
42        p.file_name()
43            .and_then(|n| n.to_str())
44            .is_some_and(|n| n.eq_ignore_ascii_case(name))
45    })
46}
47
48impl Resources {
49    pub fn load(dir: impl AsRef<Path>) -> io::Result<Self> {
50        let dir = dir.as_ref().to_path_buf();
51        let rff_path = find_file(&dir, "BLOOD.RFF").ok_or_else(|| {
52            io::Error::new(
53                io::ErrorKind::NotFound,
54                format!(
55                    "BLOOD.RFF not found in {} - point OpenBlood at your original Blood directory",
56                    dir.display()
57                ),
58            )
59        })?;
60        let blood = Rff::open(rff_path)?;
61        let sounds = find_file(&dir, "SOUNDS.RFF").and_then(|p| Rff::open(p).ok());
62        let tiles = TileSet::load_dir(&dir)?;
63        let palettes = PAL_NAMES
64            .iter()
65            .map(|n| blood.read_name(&format!("{n}.PAL")).map(|b| Palette::from_vga(&b)))
66            .collect::<Option<Vec<_>>>()
67            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "palette missing from BLOOD.RFF"))?;
68        let mut plu = vec![None; 256];
69        for (i, n) in PLU_NAMES.iter().enumerate() {
70            plu[i] = blood
71                .read_name(&format!("{n}.PLU"))
72                .filter(|b| b.len() >= NUM_SHADES * 256);
73        }
74        let trans = blood.read_name("TRANS.TLU").unwrap_or_default();
75        let surface = find_file(&dir, "SURFACE.DAT")
76            .and_then(|p| std::fs::read(p).ok())
77            .unwrap_or_default();
78        let voxel_ids = find_file(&dir, "VOXEL.DAT")
79            .and_then(|p| std::fs::read(p).ok())
80            .map(|b| {
81                b.as_chunks::<2>()
82                    .0
83                    .iter()
84                    .map(|c| i16::from_le_bytes([c[0], c[1]]))
85                    .collect()
86            })
87            .unwrap_or_default();
88        let ini = find_file(&dir, "BLOOD.INI")
89            .and_then(|p| std::fs::read(p).ok())
90            .map(|b| crate::ini::BloodIni::parse(&String::from_utf8_lossy(&b)))
91            .unwrap_or_default();
92        let mut voxels: Vec<Option<ob_engine::voxel::Voxel>> = Vec::new();
93        for e in blood.entries.iter().filter(|e| e.ext == "KVX") {
94            let id = e.id as usize;
95            if id >= 4096 {
96                continue;
97            }
98            if voxels.len() <= id {
99                voxels.resize(id + 1, None);
100            }
101            voxels[id] = blood.read(e).ok().and_then(|b| ob_engine::voxel::Voxel::parse(&b));
102        }
103        Ok(Resources {
104            dir,
105            blood,
106            sounds,
107            tiles,
108            palettes,
109            plu,
110            trans,
111            surface,
112            voxel_ids,
113            ini,
114            voxels,
115        })
116    }
117
118    /// Builds true-colour shade tables for the given base palette.
119    pub fn build_luts(&self, base_pal: usize) -> ShadeLuts {
120        let pal = &self.palettes[base_pal.min(self.palettes.len() - 1)];
121        let tables = self
122            .plu
123            .iter()
124            .map(|p| {
125                p.as_ref().map(|lk| {
126                    let mut out = vec![0u32; NUM_SHADES * 256];
127                    for (o, &i) in out.iter_mut().zip(lk.iter()) {
128                        *o = pal.colors[i as usize];
129                    }
130                    out
131                })
132            })
133            .collect();
134        ShadeLuts { tables }
135    }
136
137    /// Voxel model id for a tile, if the tile is drawn as a voxel.
138    pub fn voxel_for_tile(&self, pic: i32) -> Option<u32> {
139        let id = *self.voxel_ids.get(pic.max(0) as usize)?;
140        (id >= 0 && self.voxels.get(id as usize).is_some_and(|v| v.is_some())).then_some(id as u32)
141    }
142
143    pub fn surface_of(&self, pic: i32) -> u8 {
144        self.surface.get(pic.max(0) as usize).copied().unwrap_or(0)
145    }
146}