servicepoint-simulator/src/font.rs

74 lines
2.2 KiB
Rust
Raw Normal View History

2024-10-13 13:11:12 +02:00
use crate::static_font;
2024-05-16 17:24:41 +02:00
use font_kit::canvas::{Canvas, Format, RasterizationOptions};
2024-05-18 17:20:30 +02:00
use font_kit::font::Font;
2024-05-10 18:24:26 +02:00
use font_kit::hinting::HintingOptions;
use pathfinder_geometry::transform2d::Transform2F;
use pathfinder_geometry::vector::{vec2f, vec2i};
2024-05-26 15:24:44 +02:00
use servicepoint::{Grid, PixelGrid, TILE_SIZE};
2024-05-10 18:24:26 +02:00
2024-05-18 17:20:30 +02:00
const DEFAULT_FONT_FILE: &[u8] = include_bytes!("../Web437_IBM_BIOS.woff");
2024-10-13 13:11:12 +02:00
const CHAR_COUNT: usize = u8::MAX as usize + 1;
2024-05-10 18:24:26 +02:00
pub struct BitmapFont {
2024-10-13 13:11:12 +02:00
bitmaps: [PixelGrid; CHAR_COUNT],
2024-05-10 18:24:26 +02:00
}
impl BitmapFont {
2024-10-13 13:11:12 +02:00
pub fn new(bitmaps: [PixelGrid; CHAR_COUNT]) -> Self {
Self { bitmaps }
}
pub fn load(font: Font, size: usize) -> BitmapFont {
2024-06-26 17:23:41 +02:00
let mut bitmaps =
core::array::from_fn(|_| PixelGrid::new(TILE_SIZE, TILE_SIZE));
2024-10-13 13:11:12 +02:00
let mut canvas =
Canvas::new(vec2i(size as i32, size as i32), Format::A8);
let size_f = size as f32;
let transform = Transform2F::default();
2024-05-10 18:24:26 +02:00
2024-10-12 20:40:11 +02:00
for char_code in u8::MIN..=u8::MAX {
2024-05-10 18:24:26 +02:00
let char = char_code as char;
let glyph_id = match font.glyph_for_char(char) {
None => continue,
Some(val) => val,
};
2024-10-13 13:11:12 +02:00
canvas.pixels.fill(0);
2024-05-10 18:24:26 +02:00
font.rasterize_glyph(
&mut canvas,
glyph_id,
2024-10-13 13:11:12 +02:00
size_f,
Transform2F::from_translation(vec2f(0f32, size_f)) * transform,
2024-05-10 18:24:26 +02:00
HintingOptions::None,
RasterizationOptions::GrayscaleAa,
)
2024-05-16 17:24:41 +02:00
.unwrap();
2024-05-10 18:24:26 +02:00
2024-10-13 13:11:12 +02:00
assert_eq!(canvas.pixels.len(), size * size);
assert_eq!(canvas.stride, size);
2024-05-10 18:24:26 +02:00
2024-10-13 13:11:12 +02:00
let bitmap = &mut bitmaps[char_code as usize];
2024-05-26 10:50:29 +02:00
for y in 0..TILE_SIZE {
for x in 0..TILE_SIZE {
let index = x + y * TILE_SIZE;
2024-05-10 18:24:26 +02:00
let canvas_val = canvas.pixels[index] != 0;
2024-10-13 13:11:12 +02:00
bitmap.set(x, y, canvas_val);
2024-05-10 18:24:26 +02:00
}
}
}
2024-10-13 13:11:12 +02:00
Self::new(bitmaps)
2024-05-10 18:24:26 +02:00
}
pub fn get_bitmap(&self, char_code: u8) -> &PixelGrid {
&self.bitmaps[char_code as usize]
}
}
2024-05-18 17:20:30 +02:00
impl Default for BitmapFont {
fn default() -> Self {
2024-10-13 13:11:12 +02:00
static_font::load_static()
2024-05-18 17:20:30 +02:00
}
}