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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use std::cmp;
use std::fmt;
use std::path;
use std::collections::BTreeMap;
use std::io::Read;
use rusttype;
use image;
use super::*;
pub enum Font {
TTFFont {
font: rusttype::Font<'static>,
points: u32,
scale: rusttype::Scale,
},
BitmapFont {
bytes: Vec<u8>,
width: usize,
height: usize,
glyphs: BTreeMap<char, usize>,
glyph_width: usize,
},
}
impl Font {
pub fn new<P>(context: &mut Context, path: P, points: u32) -> GameResult<Font>
where P: AsRef<path::Path> + fmt::Debug
{
let mut stream = context.filesystem.open(path.as_ref())?;
let mut buf = Vec::new();
stream.read_to_end(&mut buf)?;
let name = format!("{:?}", path);
let (_diag_dpi, x_dpi, y_dpi) = context.gfx_context.dpi;
Font::from_bytes(&name, &buf, points, (x_dpi, y_dpi))
}
pub fn from_bytes(name: &str, bytes: &[u8], points: u32, dpi: (f32, f32)) -> GameResult<Font> {
let collection = rusttype::FontCollection::from_bytes(bytes.to_vec());
let font_err = GameError::ResourceLoadError(format!("Could not load font collection for \
font {:?}",
name));
let font = collection.into_font().ok_or(font_err)?;
let (x_dpi, y_dpi) = dpi;
let scale = display_independent_scale(points, x_dpi, y_dpi);
Ok(Font::TTFFont {
font: font,
points: points,
scale: scale,
})
}
pub fn new_bitmap<P: AsRef<path::Path>>(context: &mut Context,
path: P,
glyphs: &str)
-> GameResult<Font> {
let img = {
let mut buf = Vec::new();
let mut reader = context.filesystem.open(path)?;
reader.read_to_end(&mut buf)?;
image::load_from_memory(&buf)?.to_rgba()
};
let (image_width, image_height) = img.dimensions();
let glyph_width = (image_width as usize) / glyphs.len();
let mut glyphs_map: BTreeMap<char, usize> = BTreeMap::new();
for (i, c) in glyphs.chars().enumerate() {
glyphs_map.insert(c, i * glyph_width);
}
Ok(Font::BitmapFont {
bytes: img.into_vec(),
width: image_width as usize,
height: image_height as usize,
glyphs: glyphs_map,
glyph_width: glyph_width,
})
}
pub fn default_font() -> GameResult<Self> {
let size = 16;
let buf = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/DejaVuSerif.ttf"));
Font::from_bytes("default", &buf[..], size, (75.0, 75.0))
}
pub fn get_height(&self) -> usize {
match *self {
Font::BitmapFont{ height, .. } => height,
Font::TTFFont{ scale, .. } => {
scale.y.ceil() as usize
},
}
}
pub fn get_width(&self, text: &str) -> usize {
match *self {
Font::BitmapFont{ width, .. } => width * text.len(),
Font::TTFFont{ref font, scale, .. } => {
let v_metrics = font.v_metrics(scale);
let offset = rusttype::point(0.0, v_metrics.ascent);
let glyphs: Vec<rusttype::PositionedGlyph> = font.layout(text, scale, offset).collect();
text_width(&glyphs) as usize
},
}
}
pub fn get_wrap(&self, text: &str, wrap_limit: usize) -> (usize, Vec<String>) {
let mut broken_lines = Vec::new();
let mut max_line_length = 0;
let whitespace_width = self.get_width("x");
for line in text.lines() {
let mut current_line = Vec::new();
let mut current_line_length = 0;
for word in line.split_whitespace() {
let mut prospective_line = current_line.clone();
prospective_line.push(word);
let text = prospective_line.join(" ");
let prospective_line_width = self.get_width(&text);
if prospective_line_width > wrap_limit {
broken_lines.push(current_line.join(" "));
current_line.clear();
current_line.push(word);
} else {
current_line.push(word);
}
}
broken_lines.push(current_line.join(" "));
}
let max_line_length = broken_lines
.iter()
.map(|line| self.get_width(line))
.max()
.unwrap_or(1);
(max_line_length, broken_lines)
}
}
impl fmt::Debug for Font {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Font::TTFFont { .. } => write!(f, "<TTFFont: {:p}>", &self),
Font::BitmapFont { .. } => write!(f, "<BitmapFont: {:p}>", &self),
}
}
}
pub struct Text {
texture: Image,
contents: String,
}
fn display_independent_scale(points: u32, dpi_w: f32, dpi_h: f32) -> rusttype::Scale {
let points = points as f32;
let points_per_inch = 72.0;
let pixels_per_point_w = dpi_w * (1.0 / points_per_inch);
let pixels_per_point_h = dpi_h * (1.0 / points_per_inch);
rusttype::Scale {
x: pixels_per_point_w * points,
y: pixels_per_point_h * points,
}
}
fn text_width(glyphs: &[rusttype::PositionedGlyph]) -> f32 {
glyphs
.iter()
.rev()
.filter_map(|g| {
g.pixel_bounding_box()
.map(|b| {
b.min.x as f32 + g.unpositioned().h_metrics().advance_width
})
})
.next()
.unwrap_or(0.0)
}
fn render_ttf(context: &mut Context,
text: &str,
font: &rusttype::Font<'static>,
scale: rusttype::Scale)
-> GameResult<Text> {
let text_height_pixels = scale.y.ceil() as usize;
let v_metrics = font.v_metrics(scale);
let offset = rusttype::point(0.0, v_metrics.ascent);
let glyphs: Vec<rusttype::PositionedGlyph> = font.layout(text, scale, offset).collect();
let text_width_pixels = text_width(&glyphs).ceil() as usize;
let bytes_per_pixel = 4;
let mut pixel_data = vec![0; text_width_pixels * text_height_pixels * bytes_per_pixel];
let pitch = text_width_pixels * bytes_per_pixel;
for g in glyphs {
if let Some(bb) = g.pixel_bounding_box() {
g.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = x as i32 + bb.min.x;
let y = y as i32 + bb.min.y;
if x >= 0 && x < text_width_pixels as i32 && y >= 0 &&
y < text_height_pixels as i32 {
let x = x as usize * bytes_per_pixel;
let y = y as usize;
pixel_data[(x + y * pitch + 0)] = 255;
pixel_data[(x + y * pitch + 1)] = 255;
pixel_data[(x + y * pitch + 2)] = 255;
pixel_data[(x + y * pitch + 3)] = c;
}
})
}
}
assert!(text_width_pixels < u16::MAX as usize);
assert!(text_height_pixels < u16::MAX as usize);
let image = Image::from_rgba8(context,
text_width_pixels as u16,
text_height_pixels as u16,
&pixel_data)?;
let text_string = text.to_string();
Ok(Text {
texture: image,
contents: text_string,
})
}
#[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
fn blit(dst: &mut [u8],
dst_dims: (usize, usize),
dst_point: (usize, usize),
src: &[u8],
src_dims: (usize, usize),
src_point: (usize, usize),
rect_size: (usize, usize),
pitch: usize) {
let area_row_width = rect_size.0 * pitch;
let src_row_width = src_dims.0 * pitch;
let dst_row_width = dst_dims.0 * pitch;
for row_idx in 0..rect_size.1 {
let src_row = row_idx + src_point.1;
let dst_row = row_idx + dst_point.1;
let src_offset = src_row * src_row_width + (src_point.0 * pitch);
let dst_offset = dst_row * dst_row_width + (dst_point.0 * pitch);
let dst_slice = &mut dst[dst_offset..(dst_offset + area_row_width)];
let src_slice = &src[src_offset..(src_offset + area_row_width)];
dst_slice.copy_from_slice(src_slice);
}
}
fn render_bitmap(context: &mut Context,
text: &str,
bytes: &[u8],
width: usize,
height: usize,
glyphs_map: &BTreeMap<char, usize>,
glyph_width: usize)
-> GameResult<Text> {
let text_length = text.len();
let glyph_height = height;
let buf_len = text_length * glyph_width * glyph_height * 4;
let mut dest_buf = Vec::with_capacity(buf_len);
dest_buf.resize(buf_len, 0u8);
for (i, c) in text.chars().enumerate() {
let error = GameError::FontError(format!("Character '{}' not in bitmap font!", c));
let source_offset = *glyphs_map
.get(&c)
.ok_or(error)?;
let dest_offset = glyph_width * i;
blit(&mut dest_buf,
(text_length * glyph_width, glyph_height),
(dest_offset, 0),
bytes,
(width, height),
(source_offset, 0),
(glyph_width, glyph_height),
4);
}
let image = Image::from_rgba8(context,
(text_length * glyph_width) as u16,
glyph_height as u16,
&dest_buf)?;
let text_string = text.to_string();
Ok(Text {
texture: image,
contents: text_string,
})
}
impl Text {
pub fn new(context: &mut Context, text: &str, font: &Font) -> GameResult<Text> {
match *font {
Font::TTFFont {
font: ref f,
scale,
..
} => render_ttf(context, text, f, scale),
Font::BitmapFont {
ref bytes,
width,
height,
glyph_width,
ref glyphs,
} => render_bitmap(context, text, bytes, width, height, glyphs, glyph_width),
}
}
pub fn width(&self) -> u32 {
self.texture.width()
}
pub fn height(&self) -> u32 {
self.texture.height()
}
pub fn contents(&self) -> &str {
&self.contents
}
pub fn get_dimensions(&self) -> Rect {
self.texture.get_dimensions()
}
pub fn get_filter(&self) -> FilterMode {
self.texture.get_filter()
}
pub fn set_filter(&mut self, mode: FilterMode) {
self.texture.set_filter(mode);
}
}
impl Drawable for Text {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
draw_ex(ctx, &self.texture, param)
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"<Text: {}x{}, {:p}>",
self.texture.width,
self.texture.height,
&self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_blit() {
let dst = &mut [0; 125][..];
let src = &[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9,
1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 1, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[..];
assert_eq!(src.len(), 25 * 5);
let rect_dims = (25, 5);
blit(dst, rect_dims, (0, 0), src, rect_dims, (0, 0), (25, 5), 1);
assert_eq!(dst, src);
for i in 0..dst.len() {
dst[i] = 0;
}
let rect_dims = (5, 5);
blit(dst, rect_dims, (0, 0), src, rect_dims, (0, 0), (5, 5), 5);
assert_eq!(dst, src);
}
#[test]
fn test_metrics() {
let f = Font::default_font().unwrap();
assert_eq!(f.get_height(), 17);
assert_eq!(f.get_width("Foo!"), 33);
let text_to_wrap = "Walk on car leaving trail of paw prints on hood and windshield sniff other cat's butt and hang jaw half open thereafter for give attitude. Annoy kitten\nbrother with poking. Mrow toy mouse squeak roll over. Human give me attention meow.";
let (len, v) = f.get_wrap(text_to_wrap, 250);
println!("{} {:?}", len, v);
assert_eq!(len, 249);
let wrapped_text = vec![
"Walk on car leaving trail of paw",
"prints on hood and windshield",
"sniff other cat\'s butt and hang jaw",
"half open thereafter for give",
"attitude. Annoy kitten",
"brother with poking. Mrow toy",
"mouse squeak roll over. Human",
"give me attention meow."
];
assert_eq!(&v, &wrapped_text);
}
fn test_wrapping() {
use conf;
let c = conf::Conf::new();
let ctx = &mut Context::load_from_conf("test_wrapping", "ggez", c).unwrap();
let font = Font::default_font().unwrap();
let text_to_wrap = "Walk on car leaving trail of paw prints on hood and windshield sniff other cat's butt and hang jaw half open thereafter for give attitude. Annoy kitten\nbrother with poking. Mrow toy mouse squeak roll over. Human give me attention meow.";
let wrap_length = 250;
let (len, v) = font.get_wrap(text_to_wrap, wrap_length);
assert!(len < wrap_length);
for line in &v {
let t = Text::new(ctx, line, &font).unwrap();
println!("Width is claimed to be <= {}, should be <= {}, is {}", len, wrap_length, t.width());
assert!(t.width() as usize <= wrap_length);
}
}
}