//! Original UI atlas rectangles selected through the game resource table. use crate::ui_configuration::{field, number, object, read}; use fparkan_nres::{decode, EntryId, NresDocument, ReadProfile}; use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage}; use fparkan_vfs::Vfs; use std::{collections::HashMap, sync::Arc}; /// Load a named page from the original game UI texture catalog. pub fn load_ui_page(vfs: &dyn Vfs, name: &str) -> Result { let game = read(vfs, "ui/game_resources.cfg")?; let game = String::from_utf8_lossy(&game); let textures = object(&game, "textures").ok_or("missing UI texture catalog")?; let page = number(&textures, &name.to_ascii_uppercase())?; let archive = open_atlas(vfs, field(&textures, "LIBRARY")?)?; decode_page(&archive, page) } pub fn load_ui_sprites( vfs: &dyn Vfs, config: &str, names: [&str; N], ) -> Result<[RgbaImage; N], String> { let definitions = read(vfs, config)?; let definitions = String::from_utf8_lossy(&definitions); let game = read(vfs, "ui/game_resources.cfg")?; let game = String::from_utf8_lossy(&game); let textures = object(&game, "textures").ok_or("missing UI texture catalog")?; let archive = open_atlas(vfs, field(&textures, "LIBRARY")?)?; let mut pages = HashMap::new(); let mut sprites = Vec::with_capacity(N); for name in names { let region = object(&definitions, name).ok_or_else(|| format!("missing UI sprite {name}"))?; let page = number(&textures, &field(®ion, "TEXTURE")?.to_ascii_uppercase())?; let image = match pages.entry(page) { std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), std::collections::hash_map::Entry::Vacant(entry) => { entry.insert(decode_page(&archive, page)?) } }; let [x, y, width, height] = ["OFFSET_X", "OFFSET_Y", "WIDTH", "HEIGHT"].map(|key| number(®ion, key)); let [x, y, width, height] = [x?, y?, width?, height?]; if width == 0 || height == 0 || x.checked_add(width).is_none_or(|right| right > image.width) || y.checked_add(height) .is_none_or(|bottom| bottom > image.height) { return Err(format!("UI sprite {name} is outside atlas page {page}")); } let rgba8 = (y..y + height) .flat_map(|row| { let start = (row as usize * image.width as usize + x as usize) * 4; image.rgba8[start..start + width as usize * 4] .iter() .copied() }) .collect(); sprites.push(RgbaImage { width, height, rgba8, }); } Ok(sprites .try_into() .expect("one rectangle per UI sprite name")) } fn open_atlas(vfs: &dyn Vfs, path: &str) -> Result { decode(read(vfs, path)?, ReadProfile::Strict).map_err(|error| error.to_string()) } fn decode_page(archive: &NresDocument, page: u32) -> Result { let payload = archive .payload(EntryId(page)) .map_err(|error| error.to_string())?; let texture = decode_texm(Arc::from(payload)).map_err(|error| error.to_string())?; decode_mip_rgba8(&texture, 0).map_err(|error| error.to_string()) }