use crate::error::BmpfError;
const MAGIC: &[u8] = b"Unreal Software Bitmap Font Wizard bmpf File\r\n";
const MAGIC_LEN: usize = 46;
#[derive(Debug, Clone)]
pub struct BmpfChar {
pub code: u8,
pub advance: u16,
}
#[derive(Debug, Clone)]
pub struct BmpfFont {
pub chars: Vec<BmpfChar>,
pub tile_w: u16,
pub tile_h: u16,
pub frames: u16,
}
impl BmpfFont {
pub fn parse(data: &[u8]) -> Result<Self, BmpfError> {
if data.len() < MAGIC_LEN + 6 {
return Err(BmpfError::BadHeader);
}
if &data[..MAGIC_LEN] != MAGIC {
return Err(BmpfError::BadMagic);
}
let rest = &data[MAGIC_LEN..];
let frames = u16::from_le_bytes([rest[0], rest[1]]);
let tile_w = u16::from_le_bytes([rest[2], rest[3]]);
let tile_h = u16::from_le_bytes([rest[4], rest[5]]);
let records_data = &rest[6..];
let mut chars = Vec::with_capacity(frames as usize);
let mut i = 0;
while i + 3 <= records_data.len() {
if records_data[i] == 0
&& records_data[i + 1] == 0
&& records_data[i + 2] == 0
{
break;
}
let code = records_data[i];
let advance =
u16::from_le_bytes([records_data[i + 1], records_data[i + 2]]);
chars.push(BmpfChar { code, advance });
i += 3;
}
Ok(BmpfFont {
chars,
tile_w,
tile_h,
frames,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_font_norm() {
let mut data = MAGIC.to_vec();
data.extend_from_slice(&[0x03, 0x00, 0x10, 0x00, 0x13, 0x00]);
data.extend_from_slice(&[0x65, 0x0a, 0x00]); data.extend_from_slice(&[0x21, 0x06, 0x00]); data.extend_from_slice(&[0x22, 0x09, 0x00]); data.extend_from_slice(&[0x00, 0x00, 0x00]);
let font = BmpfFont::parse(&data).unwrap();
assert_eq!(font.frames, 3);
assert_eq!(font.tile_w, 16);
assert_eq!(font.tile_h, 19);
assert_eq!(font.chars.len(), 3);
assert_eq!(font.chars[0].code, 0x65);
assert_eq!(font.chars[0].advance, 10);
assert_eq!(font.chars[1].code, 0x21);
assert_eq!(font.chars[1].advance, 6);
assert_eq!(font.chars[2].code, 0x22);
assert_eq!(font.chars[2].advance, 9);
}
#[test]
fn test_parse_real_font_norm() {
let raw = include_bytes!("../tests/in/font_norm.bmpf");
let font = BmpfFont::parse(raw).unwrap();
assert_eq!(font.frames, 101);
assert_eq!(font.tile_w, 16);
assert_eq!(font.tile_h, 19);
assert!(!font.chars.is_empty());
assert!(font.chars.iter().any(|c| c.code == b'e'));
let e_char = font.chars.iter().find(|c| c.code == b'e').unwrap();
assert_eq!(e_char.advance, 10);
}
#[test]
fn test_parse_real_font_tiny() {
let raw = include_bytes!("../tests/in/font_tiny.bmpf");
let font = BmpfFont::parse(raw).unwrap();
assert_eq!(font.frames, 256);
assert_eq!(font.tile_w, 13);
assert_eq!(font.tile_h, 16);
assert!(font.chars.len() > 200);
}
#[test]
fn test_reject_bad_magic() {
let data = b"not a bmpf file";
let result = BmpfFont::parse(data);
assert!(result.is_err());
}
#[test]
fn test_reject_too_short() {
let data = MAGIC.to_vec();
let result = BmpfFont::parse(&data);
assert!(result.is_err());
}
}