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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use crate::layout::GlyphRasterConfig;
use crate::math::{Geometry, Line};
use crate::platform::{as_i32, ceil, floor, fract, is_negative};
use crate::raster::Raster;
use crate::unicode;
use crate::FontResult;
use alloc::string::String;
use alloc::vec;
use alloc::vec::*;
use core::mem;
use core::num::NonZeroU16;
use core::ops::Deref;
use hashbrown::HashMap;
use ttf_parser::{Face, FaceParsingError};
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct OutlineBounds {
pub xmin: f32,
pub ymin: f32,
pub width: f32,
pub height: f32,
}
impl Default for OutlineBounds {
fn default() -> Self {
Self {
xmin: 0.0,
ymin: 0.0,
width: 0.0,
height: 0.0,
}
}
}
impl OutlineBounds {
#[inline(always)]
pub fn scale(&self, scale: f32) -> OutlineBounds {
OutlineBounds {
xmin: self.xmin * scale,
ymin: self.ymin * scale,
width: self.width * scale,
height: self.height * scale,
}
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Metrics {
pub xmin: i32,
pub ymin: i32,
pub width: usize,
pub height: usize,
pub advance_width: f32,
pub advance_height: f32,
pub bounds: OutlineBounds,
}
impl Default for Metrics {
fn default() -> Self {
Metrics {
xmin: 0,
ymin: 0,
width: 0,
height: 0,
advance_width: 0.0,
advance_height: 0.0,
bounds: OutlineBounds::default(),
}
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct LineMetrics {
pub ascent: f32,
pub descent: f32,
pub line_gap: f32,
pub new_line_size: f32,
}
impl LineMetrics {
fn new(ascent: i16, descent: i16, line_gap: i16) -> LineMetrics {
let (ascent, descent, line_gap) = (ascent as i32, descent as i32, line_gap as i32);
LineMetrics {
ascent: ascent as f32,
descent: descent as f32,
line_gap: line_gap as f32,
new_line_size: (ascent - descent + line_gap) as f32,
}
}
#[inline(always)]
fn scale(&self, scale: f32) -> LineMetrics {
LineMetrics {
ascent: self.ascent * scale,
descent: self.descent * scale,
line_gap: self.line_gap * scale,
new_line_size: self.new_line_size * scale,
}
}
}
#[derive(Clone)]
pub(crate) struct Glyph {
pub v_lines: Vec<Line>,
pub m_lines: Vec<Line>,
advance_width: f32,
advance_height: f32,
pub bounds: OutlineBounds,
}
impl Default for Glyph {
fn default() -> Self {
Glyph {
v_lines: Vec::new(),
m_lines: Vec::new(),
advance_width: 0.0,
advance_height: 0.0,
bounds: OutlineBounds::default(),
}
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct FontSettings {
pub collection_index: u32,
pub scale: f32,
}
impl Default for FontSettings {
fn default() -> FontSettings {
FontSettings {
collection_index: 0,
scale: 40.0,
}
}
}
#[derive(Clone)]
pub struct Font {
name: Option<String>,
units_per_em: f32,
glyphs: Vec<Glyph>,
char_to_glyph: HashMap<u32, NonZeroU16>,
horizontal_line_metrics: Option<LineMetrics>,
vertical_line_metrics: Option<LineMetrics>,
settings: FontSettings,
}
impl core::fmt::Debug for Font {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Font")
.field("name", &self.name)
.field("settings", &self.settings)
.field("units_per_em", &self.units_per_em)
.finish()
}
}
fn convert_error(error: FaceParsingError) -> &'static str {
use FaceParsingError::*;
match error {
MalformedFont => "An attempt to read out of bounds detected.",
UnknownMagic => "Face data must start with 0x00010000, 0x74727565, 0x4F54544F or 0x74746366.",
FaceIndexOutOfBounds => "The face index is larger than the number of faces in the font.",
NoHeadTable => "The head table is missing or malformed.",
NoHheaTable => "The hhea table is missing or malformed.",
NoMaxpTable => "The maxp table is missing or malformed.",
}
}
fn convert_name(face: &Face) -> Option<String> {
for name in face.names() {
if name.name_id() == 4 && name.is_unicode() {
return Some(unicode::decode_utf16(name.name()));
}
}
None
}
impl Font {
pub fn from_bytes<Data: Deref<Target = [u8]>>(data: Data, settings: FontSettings) -> FontResult<Font> {
use ttf_parser::GlyphId;
let face = match Face::from_slice(&data, settings.collection_index) {
Ok(f) => f,
Err(e) => return Err(convert_error(e)),
};
let name = convert_name(&face);
let mut char_to_glyph = HashMap::new();
for subtable in face.character_mapping_subtables() {
subtable.codepoints(|codepoint| {
let mapping = match subtable.glyph_index(codepoint) {
Some(id) => id.0,
None => 0,
};
char_to_glyph.insert(codepoint, unsafe { NonZeroU16::new_unchecked(mapping) });
});
}
let units_per_em = face.units_per_em().unwrap_or(1000) as f32;
let glyph_count = face.number_of_glyphs() as usize;
let mut glyphs: Vec<Glyph> = vec::from_elem(Glyph::default(), glyph_count);
for (_, mapping) in &char_to_glyph {
let mapping = unsafe { mem::transmute::<NonZeroU16, u16>(*mapping) as usize };
if mapping as usize >= glyph_count {
return Err("Attempted to map a codepoint out of bounds.");
}
let glyph_id = GlyphId(mapping as u16);
let glyph = &mut glyphs[mapping];
if let Some(advance_width) = face.glyph_hor_advance(glyph_id) {
glyph.advance_width = advance_width as f32;
}
if let Some(advance_height) = face.glyph_ver_advance(glyph_id) {
glyph.advance_height = advance_height as f32;
}
let mut geometry = Geometry::new(settings.scale, units_per_em);
face.outline_glyph(glyph_id, &mut geometry);
geometry.finalize(glyph);
}
let horizontal_line_metrics =
Some(LineMetrics::new(face.ascender(), face.descender(), face.line_gap()));
let vertical_line_metrics = if let Some(ascender) = face.vertical_ascender() {
Some(LineMetrics::new(
ascender,
face.vertical_descender().unwrap_or(0),
face.vertical_line_gap().unwrap_or(0),
))
} else {
None
};
Ok(Font {
name,
glyphs,
char_to_glyph,
units_per_em,
horizontal_line_metrics,
vertical_line_metrics,
settings,
})
}
pub fn horizontal_line_metrics(&self, px: f32) -> Option<LineMetrics> {
if let Some(metrics) = self.horizontal_line_metrics {
Some(metrics.scale(self.scale_factor(px)))
} else {
None
}
}
pub fn vertical_line_metrics(&self, px: f32) -> Option<LineMetrics> {
if let Some(metrics) = self.vertical_line_metrics {
Some(metrics.scale(self.scale_factor(px)))
} else {
None
}
}
#[inline(always)]
pub fn units_per_em(&self) -> f32 {
self.units_per_em
}
#[inline(always)]
pub fn scale_factor(&self, px: f32) -> f32 {
px / self.units_per_em
}
#[inline]
pub fn metrics(&self, character: char, px: f32) -> Metrics {
self.metrics_indexed(self.lookup_glyph_index(character), px)
}
pub fn metrics_indexed(&self, index: usize, px: f32) -> Metrics {
let glyph = &self.glyphs[index];
let scale = self.scale_factor(px);
let (metrics, _, _) = self.metrics_raw(scale, glyph, 0.0);
metrics
}
fn metrics_raw(&self, scale: f32, glyph: &Glyph, offset: f32) -> (Metrics, f32, f32) {
let bounds = glyph.bounds.scale(scale);
let mut offset_x = fract(bounds.xmin + offset);
let mut offset_y = fract(1.0 - fract(bounds.height) - fract(bounds.ymin));
if is_negative(offset_x) {
offset_x += 1.0;
}
if is_negative(offset_y) {
offset_y += 1.0;
}
let metrics = Metrics {
xmin: as_i32(floor(bounds.xmin)),
ymin: as_i32(floor(bounds.ymin)),
width: as_i32(ceil(bounds.width + offset_x)) as usize,
height: as_i32(ceil(bounds.height + offset_y)) as usize,
advance_width: scale * glyph.advance_width,
advance_height: scale * glyph.advance_height,
bounds,
};
(metrics, offset_x, offset_y)
}
#[inline]
pub fn rasterize_config(&self, config: GlyphRasterConfig) -> (Metrics, Vec<u8>) {
self.rasterize_indexed(config.glyph_index as usize, config.px)
}
#[inline]
pub fn rasterize(&self, character: char, px: f32) -> (Metrics, Vec<u8>) {
self.rasterize_indexed(self.lookup_glyph_index(character), px)
}
#[inline]
pub fn rasterize_config_subpixel(&self, config: GlyphRasterConfig) -> (Metrics, Vec<u8>) {
self.rasterize_indexed_subpixel(config.glyph_index as usize, config.px)
}
#[inline]
pub fn rasterize_subpixel(&self, character: char, px: f32) -> (Metrics, Vec<u8>) {
self.rasterize_indexed_subpixel(self.lookup_glyph_index(character), px)
}
pub fn rasterize_indexed(&self, index: usize, px: f32) -> (Metrics, Vec<u8>) {
let glyph = &self.glyphs[index];
let scale = self.scale_factor(px);
let (metrics, offset_x, offset_y) = self.metrics_raw(scale, glyph, 0.0);
let mut canvas = Raster::new(metrics.width, metrics.height);
canvas.draw(&glyph, scale, scale, offset_x, offset_y);
(metrics, canvas.get_bitmap())
}
pub fn rasterize_indexed_subpixel(&self, index: usize, px: f32) -> (Metrics, Vec<u8>) {
let glyph = &self.glyphs[index];
let scale = self.scale_factor(px);
let (metrics, offset_x, offset_y) = self.metrics_raw(scale, glyph, 0.0);
let mut canvas = Raster::new(metrics.width * 3, metrics.height);
canvas.draw(&glyph, scale * 3.0, scale, offset_x, offset_y);
(metrics, canvas.get_bitmap())
}
#[inline]
pub fn lookup_glyph_index(&self, character: char) -> usize {
unsafe {
mem::transmute::<Option<NonZeroU16>, u16>(self.char_to_glyph.get(&(character as u32)).copied())
as usize
}
}
pub fn glyph_count(&self) -> usize {
self.glyphs.len()
}
}