extern crate rusttype;
use self::rusttype::{FontCollection, Scale, point, PositionedGlyph};
pub fn calculate_character_brightness(c: char) -> i32 {
let string = c.to_string();
let font_data = include_bytes!("Inconsolata-Regular.ttf");
let collection = FontCollection::from_bytes(font_data as &[u8]);
let font = collection.into_font().unwrap();
let height: f32 = 50.0;
let width = 50;
let pixel_height = height.ceil() as usize;
let scale = Scale { x: height * 2.0, y: height };
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let glyphs: Vec<PositionedGlyph> = font.layout(&string, scale, offset).collect();
let glyph: PositionedGlyph = glyphs.last().unwrap().standalone();
let mut pixel_data = vec![0.0; width * pixel_height];
if let Some(bb) = glyph.pixel_bounding_box() {
glyph.draw(|x, y, v| {
let positive_v = if v < 0.0 { 0.0 } else { v };
let scaled_v = positive_v * 255.0;
let x = x as i32 + bb.min.x;
let y = y as i32 + bb.min.y;
if x >= 0 && x < width as i32 &&y >= 0 && y < pixel_height as i32 {
let x = x as usize;
let y = y as usize;
pixel_data[(x + y * width)] = scaled_v;
}
})
}
let total_brightness = pixel_data.iter().fold(0.0, |mut sum, &value| {sum += value; sum});
let num_pixels = pixel_data.len() as f32;
if total_brightness == 0.0 || num_pixels == 0.0 {
0
}
else {
(total_brightness/num_pixels) as i32
}
}