1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::Read;
use rusttype::{Rect, Point};
use glium::backend::Facade;
#[derive(Debug)]
pub enum Error {
NoGlyph(char),
}
pub struct FontTexture {
}
#[derive(Copy, Clone, Debug)]
pub struct CharacterInfos {
pub(crate) tex_coords: (f32, f32),
pub(crate) tex_size: (f32, f32),
pub(crate) size: (f32, f32),
pub(crate) height_over_line: f32,
pub(crate) left_padding: f32,
pub(crate) right_padding: f32,
}
pub(crate) struct TextureData {
data: Vec<f32>,
pub(crate) width: u32,
pub(crate) height: u32,
}
impl<'a> glium::texture::Texture2dDataSource<'a> for &'a TextureData {
type Data = f32;
fn into_raw(self) -> glium::texture::RawImage2d<'a, f32> {
glium::texture::RawImage2d {
data: Cow::Borrowed(&self.data),
width: self.width,
height: self.height,
format: glium::texture::ClientFormat::F32,
}
}
}
impl FontTexture {
pub fn ascii_character_list() -> Vec<char> {
(0 .. 255).filter_map(|c| ::std::char::from_u32(c)).collect()
}
pub fn new<R, F, I>(_facade: &F, font: R, font_size: u32, characters_list: I)
-> Result<(glium::texture::RawImage2d<f32>, HashMap<char, CharacterInfos>), Error>
where R: Read, F: Facade, I: IntoIterator<Item=char>
{
let font: Vec<u8> = font.bytes().map(|c| c.unwrap()).collect();
let collection = ::rusttype::FontCollection::from_bytes(&font[..]);
let font = collection.into_font().unwrap();
let (texture_data, chr_infos) =
build_font_image(font, characters_list.into_iter(), font_size)?;
Ok((
glium::texture::RawImage2d {
data: Cow::Owned(texture_data.data),
width: texture_data.width,
height: texture_data.height,
format: glium::texture::ClientFormat::F32,
},
chr_infos
))
}
}
fn build_font_image<I>(font: rusttype::Font, characters_list: I, font_size: u32)
-> Result<(TextureData, HashMap<char, CharacterInfos>), Error>
where I: Iterator<Item=char>
{
use std::iter;
const MARGIN: u32 = 10;
let invalid_character_width = font_size / 2;
let size_estimation = characters_list.size_hint().1.unwrap_or(0);
let mut texture_data: Vec<f32> = Vec::with_capacity(
size_estimation * font_size as usize * font_size as usize
);
let texture_width = get_nearest_po2(std::cmp::max(font_size * 2 as u32,
((((size_estimation as u32) * font_size * font_size) as f32).sqrt()) as u32));
let mut cursor_offset = (0u32, 0u32);
let mut rows_to_skip = 0u32;
let em_pixels = font_size as f32;
let characters_infos = characters_list.map(|character| {
struct Bitmap {
rows : i32,
width : i32,
buffer : Vec<u8>
}
let scaled_glyph = font.glyph(character)
.ok_or_else(|| Error::NoGlyph(character))?
.scaled(::rusttype::Scale {x : font_size as f32, y : font_size as f32 });
let h_metrics = scaled_glyph.h_metrics();
let glyph = scaled_glyph
.positioned(::rusttype::Point {x : 0.0, y : 0.0 });
let bb = glyph.pixel_bounding_box();
let bb = if let Some(bb) = bb {
bb
} else {
Rect {
min: Point {x: 0, y: 0},
max: Point {x: invalid_character_width as i32, y: 0}
}
};
let mut buffer = vec![0; (bb.height() * bb.width()) as usize];
glyph.draw(|x, y, v| {
let x = x;
let y = y;
buffer[(y * bb.width() as u32 + x) as usize] = (v * 255.0) as u8;
});
let bitmap : Bitmap = Bitmap {
rows : bb.height(),
width : bb.width(),
buffer : buffer
};
cursor_offset.0 += MARGIN;
if cursor_offset.0 + (bitmap.width as u32) + MARGIN >= texture_width {
assert!(bitmap.width as u32 <= texture_width);
cursor_offset.0 = 0;
cursor_offset.1 += rows_to_skip;
rows_to_skip = 0;
}
if rows_to_skip < MARGIN + bitmap.rows as u32 {
let diff = MARGIN + (bitmap.rows as u32) - rows_to_skip;
rows_to_skip = MARGIN + bitmap.rows as u32;
texture_data.extend(iter::repeat(0.0).take((diff * texture_width) as usize));
}
let offset_x_before_copy = cursor_offset.0;
if bitmap.rows >= 1 {
let destination = &mut texture_data[(cursor_offset.0 + cursor_offset.1 * texture_width) as usize ..];
let source = &bitmap.buffer;
for y in 0 .. bitmap.rows as u32 {
let source = &source[(y * bitmap.width as u32) as usize ..];
let destination = &mut destination[(y * texture_width) as usize ..];
for x in 0 .. bitmap.width {
let val: u8 = *source.get(x as usize).unwrap();
let val = (val as f32) / (std::u8::MAX as f32);
let dest = destination.get_mut(x as usize).unwrap();
*dest = val;
}
}
cursor_offset.0 += bitmap.width as u32;
debug_assert!(cursor_offset.0 <= texture_width);
}
Ok((character, CharacterInfos {
tex_size: (bitmap.width as f32, bitmap.rows as f32),
tex_coords: (offset_x_before_copy as f32, cursor_offset.1 as f32),
size: (bitmap.width as f32, bitmap.rows as f32),
left_padding: h_metrics.left_side_bearing as f32,
right_padding: (h_metrics.advance_width
- bitmap.width as f32
- h_metrics.left_side_bearing as f32) as f32 / 64.0,
height_over_line: -bb.min.y as f32,
}))
}).collect::<Result<Vec<_>, Error>>()?;
{
let current_height = texture_data.len() as u32 / texture_width;
let requested_height = get_nearest_po2(current_height);
texture_data.extend(iter::repeat(0.0).take((texture_width * (requested_height - current_height)) as usize));
}
assert!((texture_data.len() as u32 % texture_width) == 0);
let texture_height = (texture_data.len() as u32 / texture_width) as f32;
let float_texture_width = texture_width as f32;
let mut characters_infos = characters_infos.into_iter().map(|mut chr| {
chr.1.tex_size.0 /= float_texture_width;
chr.1.tex_size.1 /= texture_height;
chr.1.tex_coords.0 /= float_texture_width;
chr.1.tex_coords.1 /= texture_height;
chr.1.size.0 /= em_pixels;
chr.1.size.1 /= em_pixels;
chr.1.left_padding /= em_pixels;
chr.1.right_padding /= em_pixels;
chr.1.height_over_line /= em_pixels;
chr
}).collect::<HashMap<_, _>>();
characters_infos.shrink_to_fit();
Ok((TextureData {
data: texture_data,
width: texture_width,
height: texture_height as u32,
}, characters_infos))
}
fn get_nearest_po2(mut x: u32) -> u32 {
assert!(x > 0);
x -= 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
x + 1
}