logo
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use std::collections::HashMap;

use glam::{Mat4, Vec3, Vec3A};
use ttf_parser::{Face, GlyphId};

use crate::{
    error::MeshTextError,
    util::{
        raster_to_mesh, raster_to_mesh_indexed, text_mesh_from_data, text_mesh_from_data_indexed,
        GlyphOutlineBuilder,
    },
    BoundingBox, Glyph, IndexedMeshText, MeshText, QualitySettings, TextSection,
};

type Mesh = (Vec<Vec3A>, BoundingBox);
type IndexedMesh = (Vec<u32>, Vec<Vec3A>, BoundingBox);

/// A [MeshGenerator] handles rasterizing individual glyphs.
///
/// Each [MeshGenerator] will handle exactly one font. This means
/// if you need support for multiple fonts, you will need to create
/// multiple instances (one per font) of this generator.
pub struct MeshGenerator {
    /// Cached non-indexed glyphs are stored in this [HashMap].
    ///
    /// The key is the character itself, however because each
    /// character can have a 2D and a 3D variant, in the 3D
    /// variant each character is prefixed with an `_`.
    #[allow(unused)]
    cache: HashMap<String, Mesh>,

    /// The current [Face].
    font: Face<'static>,

    /// Cached indexed glyphs are stored in this [HashMap].
    ///
    /// The key is the character itself, however because each
    /// character can have a 2D and a 3D variant, in the 3D
    /// variant each character is prefixed with an `_`.
    #[allow(unused)]
    indexed_cache: HashMap<String, IndexedMesh>,

    /// Quality settings for generating the text meshes.
    quality: QualitySettings,

    /// Controls wether the generator will automatically
    /// cache glyphs.
    #[allow(unused)]
    use_cache: bool,
}

impl MeshGenerator {
    /// Creates a new [MeshGenerator].
    ///
    /// Arguments:
    ///
    /// * `font`: The font that will be used for rasterizing.
    pub fn new(font: &'static [u8]) -> Self {
        let face = Face::from_slice(font, 0).expect("Failed to generate font from data.");

        Self {
            cache: HashMap::new(),
            font: face,
            indexed_cache: HashMap::new(),
            quality: QualitySettings::default(),
            use_cache: true,
        }
    }

    /// Creates a new [MeshGenerator] with custom quality settings.
    ///
    /// Arguments:
    ///
    /// * `font`: The font that will be used for rasterizing.
    /// * `quality`: The [QualitySettings] that should be used.
    pub fn new_with_quality(font: &'static [u8], quality: QualitySettings) -> Self {
        let face = Face::from_slice(font, 0).expect("Failed to generate font from data.");

        Self {
            cache: HashMap::new(),
            font: face,
            indexed_cache: HashMap::new(),
            quality: quality,
            use_cache: true,
        }
    }

    /// Creates a new [MeshGenerator] with custom quality settings and no caching.
    ///
    /// Arguments:
    ///
    /// * `font`: The font that will be used for rasterizing.
    /// * `quality`: The [QualitySettings] that should be used.
    pub fn new_without_cache(font: &'static [u8], quality: QualitySettings) -> Self {
        let face = Face::from_slice(font, 0).expect("Failed to generate font from data.");

        Self {
            cache: HashMap::new(),
            font: face,
            indexed_cache: HashMap::new(),
            quality: quality,
            use_cache: false,
        }
    }

    /// Generates the [BasicMeshText] of a single character with a custom transformation.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be converted to a mesh.
    /// * `flat`: Set this to `true` for 2D meshes, or to `false` in order
    /// to generate a mesh with a depth of `1.0` units.
    /// * `transform`: The 4x4 homogenous transformation matrix in column
    /// major order that will be applied to this text.
    ///
    /// Returns:
    ///
    /// The desired [MeshText] or an [MeshTextError] if anything went wrong in the
    /// process.
    fn generate_glyph(
        &mut self,
        glyph: char,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<MeshText, Box<dyn MeshTextError>> {
        let mut mesh = self.load_from_cache(glyph, flat)?;

        if let Some(value) = transform {
            let transform = Mat4::from_cols_array(value);

            for v in mesh.0.iter_mut() {
                *v = transform.transform_point3a(*v);
            }
            mesh.1.transform(&transform);
        }

        Ok(text_mesh_from_data(mesh))
    }

    /// Generates the [IndexedMeshText] of a single character with a custom transformation.
    ///
    /// This function generates a mesh with indices and vertices.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be converted to a mesh.
    /// * `flat`: Set this to `true` for 2D meshes, or to `false` in order
    /// to generate a mesh with a depth of `1.0` units.
    /// * `transform`: The 4x4 homogenous transformation matrix in column
    /// major order that will be applied to this text.
    ///
    /// Returns:
    ///
    /// The desired [IndexedMeshText] or an [MeshTextError] if anything went wrong in the
    /// process.
    fn generate_glyph_indexed(
        &mut self,
        glyph: char,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<IndexedMeshText, Box<dyn MeshTextError>> {
        let mut mesh = self.load_from_cache_indexed(glyph, flat)?;

        if let Some(value) = transform {
            let transform = Mat4::from_cols_array(value);

            for v in mesh.1.iter_mut() {
                *v = transform.transform_point3a(*v);
            }
            mesh.2.transform(&transform);
        }

        Ok(text_mesh_from_data_indexed(mesh))
    }

    /// Generates the [Mesh] of a single character with a custom transformation given
    /// as a [Mat4].
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be converted to a mesh.
    /// * `flat`: Set this to `true` for 2D meshes, or to `false` in order
    /// to generate a mesh with a depth of `1.0` units.
    /// * `transform`: The 4x4 homogenous transformation matrix.
    ///
    /// Returns:
    ///
    /// The desired [Mesh] or an [MeshTextError] if anything went wrong in the
    /// process.
    pub(crate) fn generate_glyph_with_glam_transform(
        &mut self,
        glyph: char,
        flat: bool,
        transform: &Mat4,
    ) -> Result<Mesh, Box<dyn MeshTextError>> {
        let mut mesh = self.load_from_cache(glyph, flat)?;

        for v in mesh.0.iter_mut() {
            *v = transform.transform_point3a(*v);
        }
        mesh.1.transform(&transform);

        Ok(mesh)
    }

    /// Generates the [IndexedMesh] of a single character with a custom transformation given
    /// as a [Mat4].
    ///
    /// This function handles indexed meshes.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be converted to a mesh.
    /// * `flat`: Set this to `true` for 2D meshes, or to `false` in order
    /// to generate a mesh with a depth of `1.0` units.
    /// * `transform`: The 4x4 homogenous transformation matrix.
    ///
    /// Returns:
    ///
    /// The desired [IndexedMesh] or an [MeshTextError] if anything went wrong in the
    /// process.
    pub(crate) fn generate_glyph_with_glam_transform_indexed(
        &mut self,
        glyph: char,
        flat: bool,
        transform: &Mat4,
    ) -> Result<IndexedMesh, Box<dyn MeshTextError>> {
        let mut mesh = self.load_from_cache_indexed(glyph, flat)?;

        for v in mesh.1.iter_mut() {
            *v = transform.transform_point3a(*v);
        }
        mesh.2.transform(&transform);

        Ok(mesh)
    }

    /// Generates the [MeshText] of a given text section.
    ///
    /// Arguments:
    ///
    /// * `text`: The text that should be converted to a mesh.
    /// * `flat`: Set this to `true` for 2D meshes, or to `false` in order
    /// to generate a mesh with a depth of `1.0` units.
    /// * `transform`: The optional 4x4 homogenous transformation matrix in column
    /// major order that will be applied to this text.
    ///
    /// Returns:
    ///
    /// The desired [MeshText] or an [MeshTextError] if anything went wrong in the
    /// process.
    fn generate_text_section(
        &mut self,
        text: &String,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<MeshText, Box<dyn MeshTextError>> {
        let base_transform = match transform {
            Some(value) => Mat4::from_cols_array(value),
            None => Mat4::IDENTITY,
        };

        let mut mesh = (Vec::new(), BoundingBox::empty());
        let mut overall_advance = 0f32;

        let mut chars_iter = text.chars();

        // The first char will be handled differently if present.
        if let Some(first_glyph) = chars_iter.next() {
            let x_advance = self
                .font
                .glyph_hor_advance(self.glyph_id_of_char(first_glyph))
                .unwrap_or(0) as f32
                / self.font.height() as f32;

            let transform =
                base_transform * Mat4::from_translation(Vec3::new(overall_advance, 0f32, 0f32));
            let mut glyph_mesh =
                self.generate_glyph_with_glam_transform(first_glyph, flat, &transform)?;

            // Add vertices and replace bbox.
            mesh.0.append(&mut glyph_mesh.0);
            mesh = (mesh.0, glyph_mesh.1);

            overall_advance += x_advance;
        }

        for glyph in chars_iter {
            let x_advance = self
                .font
                .glyph_hor_advance(self.glyph_id_of_char(glyph))
                .unwrap_or(0) as f32
                / self.font.height() as f32;

            let transform =
                base_transform * Mat4::from_translation(Vec3::new(overall_advance, 0f32, 0f32));
            let mut glyph_mesh =
                self.generate_glyph_with_glam_transform(glyph, flat, &transform)?;

            // Add vertices and adjust bbox.
            mesh.0.append(&mut glyph_mesh.0);
            mesh = (mesh.0, mesh.1.combine(&glyph_mesh.1));

            overall_advance += x_advance;
        }

        Ok(text_mesh_from_data(mesh))
    }

    /// Generates the [MeshText] of a given text section.
    ///
    /// This function handles indexed meshes.
    ///
    /// Arguments:
    ///
    /// * `text`: The text that should be converted to a mesh.
    /// * `flat`: Set this to `true` for 2D meshes, or to `false` in order
    /// to generate a mesh with a depth of `1.0` units.
    /// * `transform`: The optional 4x4 homogenous transformation matrix in column
    /// major order that will be applied to this text.
    ///
    /// Returns:
    ///
    /// The desired [MeshText] or an [MeshTextError] if anything went wrong in the
    /// process.
    fn generate_text_section_indexed(
        &mut self,
        text: &String,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<IndexedMeshText, Box<dyn MeshTextError>> {
        let base_transform = match transform {
            Some(value) => Mat4::from_cols_array(value),
            None => Mat4::IDENTITY,
        };

        let mut mesh = (Vec::new(), Vec::new(), BoundingBox::empty());
        let mut overall_advance = 0f32;
        let mut index_offset = 0;

        let mut chars_iter = text.chars();

        // The first char will be handled differently if present.
        if let Some(first_glyph) = chars_iter.next() {
            let x_advance = self
                .font
                .glyph_hor_advance(self.glyph_id_of_char(first_glyph))
                .unwrap_or(0) as f32
                / self.font.height() as f32;

            let transform =
                base_transform * Mat4::from_translation(Vec3::new(overall_advance, 0f32, 0f32));
            let mut glyph_mesh =
                self.generate_glyph_with_glam_transform_indexed(first_glyph, flat, &transform)?;

            // Update index offset (note that glyph meshes can be empty).
            if let Some(max) = glyph_mesh.0.iter().max() {
                index_offset = *max + 1;
            }

            // Add vertices and replace bbox.
            mesh.0.append(&mut glyph_mesh.0);
            mesh.1.append(&mut glyph_mesh.1);
            mesh = (mesh.0, mesh.1, glyph_mesh.2);

            overall_advance += x_advance;
        }

        for glyph in chars_iter {
            let x_advance = self
                .font
                .glyph_hor_advance(self.glyph_id_of_char(glyph))
                .unwrap_or(0) as f32
                / self.font.height() as f32;

            let transform =
                base_transform * Mat4::from_translation(Vec3::new(overall_advance, 0f32, 0f32));
            let mut glyph_mesh =
                self.generate_glyph_with_glam_transform_indexed(glyph, flat, &transform)?;

            // Offset indices.
            for i in glyph_mesh.0.iter_mut() {
                *i += index_offset;
            }

            // Update index offset (note that glyph meshes can be empty).
            if let Some(max) = glyph_mesh.0.iter().max() {
                index_offset = *max + 1;
            }

            // Add vertices and indices and adjust bbox.
            mesh.0.append(&mut glyph_mesh.0);
            mesh.1.append(&mut glyph_mesh.1);
            mesh = (mesh.0, mesh.1, mesh.2.combine(&glyph_mesh.2));

            overall_advance += x_advance;
        }

        Ok(text_mesh_from_data_indexed(mesh))
    }

    /// Loads the given glyph from the cache or adds it.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be loaded.
    /// * `flat`: Wether the character should be laid out in a 2D mesh.
    ///
    /// Returns:
    ///
    /// A [Result] containing the [Mesh] if successful, otherwise an [MeshTextError].
    fn load_from_cache(&mut self, glyph: char, flat: bool) -> Result<Mesh, Box<dyn MeshTextError>> {
        if flat {
            match self.cache.get(&glyph.to_string()) {
                Some(glyph_mesh) => Ok(glyph_mesh.to_owned()),
                None => self.insert_into_cache(glyph, flat),
            }
        } else {
            match self.cache.get(&format!("_{}", glyph)) {
                Some(glyph_mesh) => Ok(glyph_mesh.to_owned()),
                None => self.insert_into_cache(glyph, flat),
            }
        }
    }

    /// Loads the given glyph from the cache or adds it.
    ///
    /// This function deals with indexed meshes.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be loaded.
    /// * `flat`: Wether the character should be laid out in a 2D mesh.
    ///
    /// Returns:
    ///
    /// A [Result] containing the [IndexedMesh] if successful, otherwise an [MeshTextError].
    fn load_from_cache_indexed(
        &mut self,
        glyph: char,
        flat: bool,
    ) -> Result<IndexedMesh, Box<dyn MeshTextError>> {
        if flat {
            match self.indexed_cache.get(&glyph.to_string()) {
                Some(glyph_mesh) => Ok(glyph_mesh.to_owned()),
                None => self.insert_into_cache_indexed(glyph, flat),
            }
        } else {
            match self.indexed_cache.get(&format!("_{}", glyph)) {
                Some(glyph_mesh) => Ok(glyph_mesh.to_owned()),
                None => self.insert_into_cache_indexed(glyph, flat),
            }
        }
    }

    /// Generates a new [Mesh] from the loaded font and the given `glyph`
    /// and inserts it into the internal `cache`.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be loaded.
    /// * `flat`: Wether the character should be laid out in a 2D mesh.
    ///
    /// Returns:
    ///
    /// A [Result] containing the [Mesh] if successful, otherwise an [MeshTextError].
    fn insert_into_cache(
        &mut self,
        glyph: char,
        flat: bool,
    ) -> Result<Mesh, Box<dyn MeshTextError>> {
        let font_height = self.font.height() as f32;
        let mut builder = GlyphOutlineBuilder::new(font_height, self.quality);

        let glyph_index = self.glyph_id_of_char(glyph);

        let mut depth = (0.5f32, -0.5f32);
        let (rect, mesh) = match self.font.outline_glyph(glyph_index, &mut builder) {
            Some(bbox) => {
                let mesh = raster_to_mesh(&builder.get_glyph_outline(), flat)?;
                (bbox, mesh)
            }
            None => {
                // The glyph has no outline so it is most likely a space or any other
                // charcter that can not be displayed.
                // An empty mesh is cached for simplicity nevertheless.
                depth = (0f32, 0f32);
                (
                    ttf_parser::Rect {
                        x_min: 0,
                        y_min: 0,
                        x_max: 0,
                        y_max: 0,
                    },
                    Vec::new(),
                )
            }
        };

        // Add mesh to cache.
        let bbox;
        if flat {
            bbox = BoundingBox {
                max: Vec3A::new(
                    rect.x_max as f32 / font_height,
                    rect.y_max as f32 / font_height,
                    0f32,
                ),
                min: Vec3A::new(
                    rect.x_min as f32 / font_height,
                    rect.y_min as f32 / font_height,
                    0f32,
                ),
            };
            self.cache.insert(glyph.to_string(), (mesh.clone(), bbox));
        } else {
            bbox = BoundingBox {
                max: Vec3A::new(
                    rect.x_max as f32 / font_height,
                    rect.y_max as f32 / font_height,
                    depth.0,
                ),
                min: Vec3A::new(
                    rect.x_min as f32 / font_height,
                    rect.y_min as f32 / font_height,
                    depth.1,
                ),
            };
            self.cache
                .insert(format!("_{}", glyph), (mesh.clone(), bbox));
        }

        Ok((mesh, bbox))
    }

    /// Generates a new [IndexedMesh] from the loaded font and the given `glyph`
    /// and inserts it into the internal `cache`.
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character that should be loaded.
    /// * `flat`: Wether the character should be laid out in a 2D mesh.
    ///
    /// Returns:
    ///
    /// A [Result] containing the [IndexedMesh] if successful, otherwise an [MeshTextError].
    fn insert_into_cache_indexed(
        &mut self,
        glyph: char,
        flat: bool,
    ) -> Result<IndexedMesh, Box<dyn MeshTextError>> {
        let font_height = self.font.height() as f32;
        let mut builder = GlyphOutlineBuilder::new(font_height, self.quality);

        let glyph_index = self.glyph_id_of_char(glyph);

        let mut depth = (0.5f32, -0.5f32);
        let (rect, vertices, indices) = match self.font.outline_glyph(glyph_index, &mut builder) {
            Some(bbox) => {
                let mesh = raster_to_mesh_indexed(&builder.get_glyph_outline(), flat)?;
                (bbox, mesh.0, mesh.1)
            }
            None => {
                // The glyph has no outline so it is most likely a space or any other
                // charcter that can not be displayed.
                // An empty mesh is cached for simplicity nevertheless.
                depth = (0f32, 0f32);
                (
                    ttf_parser::Rect {
                        x_min: 0,
                        y_min: 0,
                        x_max: 0,
                        y_max: 0,
                    },
                    Vec::new(),
                    Vec::new(),
                )
            }
        };

        // Add mesh to cache.
        let bbox;
        if flat {
            bbox = BoundingBox {
                max: Vec3A::new(
                    rect.x_max as f32 / font_height,
                    rect.y_max as f32 / font_height,
                    0f32,
                ),
                min: Vec3A::new(
                    rect.x_min as f32 / font_height,
                    rect.y_min as f32 / font_height,
                    0f32,
                ),
            };
            self.indexed_cache
                .insert(glyph.to_string(), (indices.clone(), vertices.clone(), bbox));
        } else {
            bbox = BoundingBox {
                max: Vec3A::new(
                    rect.x_max as f32 / font_height,
                    rect.y_max as f32 / font_height,
                    depth.0,
                ),
                min: Vec3A::new(
                    rect.x_min as f32 / font_height,
                    rect.y_min as f32 / font_height,
                    depth.1,
                ),
            };
            self.indexed_cache.insert(
                format!("_{}", glyph),
                (indices.clone(), vertices.clone(), bbox),
            );
        }

        Ok((indices, vertices, bbox))
    }

    /// Finds the [GlyphId] of a certain [char].
    ///
    /// Arguments:
    ///
    /// * `glyph`: The character of which the id is determined.
    ///
    /// Returns:
    ///
    /// The corresponding [GlyphId].
    fn glyph_id_of_char(&self, glyph: char) -> GlyphId {
        self.font
            .glyph_index(glyph)
            .unwrap_or(ttf_parser::GlyphId(0))
    }
}

impl TextSection<MeshText> for MeshGenerator {
    fn generate_section(
        &mut self,
        text: &String,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<MeshText, Box<dyn MeshTextError>> {
        self.generate_text_section(text, flat, transform)
    }
}

impl TextSection<IndexedMeshText> for MeshGenerator {
    fn generate_section(
        &mut self,
        text: &String,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<IndexedMeshText, Box<dyn MeshTextError>> {
        self.generate_text_section_indexed(text, flat, transform)
    }
}

impl Glyph<MeshText> for MeshGenerator {
    fn generate_glyph(
        &mut self,
        glyph: char,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<MeshText, Box<dyn MeshTextError>> {
        self.generate_glyph(glyph, flat, transform)
    }
}

impl Glyph<IndexedMeshText> for MeshGenerator {
    fn generate_glyph(
        &mut self,
        glyph: char,
        flat: bool,
        transform: Option<&[f32; 16]>,
    ) -> Result<IndexedMeshText, Box<dyn MeshTextError>> {
        self.generate_glyph_indexed(glyph, flat, transform)
    }
}