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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Fast GPU cached text rendering using gfx-rs & rusttype.
//!
//! Makes use of three kinds of caching to optimise frame performance.
//!
//! * Caching of glyph positioning output to avoid repeated cost of identical text
//! rendering on sequential frames.
//! * Caches draw calculations to avoid repeated cost of identical text rendering on
//! sequential frames.
//! * GPU cache logic to dynamically maintain a GPU texture of rendered glyphs.
//!
//! # Example
//!
//! ```no_run
//! # extern crate gfx;
//! # extern crate gfx_window_glutin;
//! # extern crate glutin;
//! extern crate gfx_glyph;
//! use gfx_glyph::{Section, GlyphBrushBuilder};
//! # fn main() {
//! # let events_loop = glutin::EventsLoop::new();
//! # let (_window, _device, mut gfx_factory, gfx_color, gfx_depth) =
//! #     gfx_window_glutin::init::<gfx::format::Srgba8, gfx::format::Depth>(
//! #         glutin::WindowBuilder::new(),
//! #         glutin::ContextBuilder::new(),
//! #         &events_loop);
//! # let mut gfx_encoder: gfx::Encoder<_, _> = gfx_factory.create_command_buffer().into();
//!
//! let dejavu: &[u8] = include_bytes!("../examples/DejaVuSans.ttf");
//! let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu)
//!     .build(gfx_factory.clone());
//!
//! # let some_other_section = Section { text: "another", ..Section::default() };
//! let section = Section {
//!     text: "Hello gfx_glyph",
//!     ..Section::default()
//! };
//!
//! glyph_brush.queue(section);
//! glyph_brush.queue(some_other_section);
//!
//! glyph_brush.draw_queued(&mut gfx_encoder, &gfx_color, &gfx_depth).unwrap();
//! # }
//! ```
#![allow(unknown_lints)]
#![warn(clippy)]
#![cfg_attr(feature = "bench", feature(test))]
#[cfg(test)]
#[macro_use]
extern crate approx;
#[cfg(test)]
extern crate env_logger;
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "bench")]
extern crate test;

extern crate backtrace;
#[macro_use]
extern crate gfx;
extern crate gfx_core;
#[macro_use]
extern crate log;
extern crate ordered_float;
extern crate rusttype;
extern crate twox_hash;
extern crate unicode_normalization;
extern crate xi_unicode;

mod section;
mod layout;
mod linebreak;
mod pipe;
mod builder;
#[macro_use]
mod trace;
mod glyph_calculator;
mod owned_section;
#[cfg(feature = "performance_stats")]
mod performance_stats;

pub use builder::*;
pub use glyph_calculator::*;
pub use layout::*;
pub use linebreak::*;
pub use owned_section::*;
pub use section::*;

use gfx::{format, handle, texture};
use gfx::traits::FactoryExt;
use gfx_core::memory::Typed;
use pipe::*;
use rusttype::{point, vector};
use rusttype::gpu_cache::{Cache, CacheBuilder};
use std::{fmt, iter, slice};
use std::borrow::{Borrow, Cow};
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::error::Error;
use std::hash::{Hash, Hasher};
use std::i32;

/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type Font<'a> = rusttype::Font<'a>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type Scale = rusttype::Scale;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type Rect<T> = rusttype::Rect<T>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type Point<T> = rusttype::Point<T>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type PositionedGlyph<'font> = rusttype::PositionedGlyph<'font>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type ScaledGlyph<'font> = rusttype::ScaledGlyph<'font>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type Glyph<'font> = rusttype::Glyph<'font>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type SharedBytes<'a> = rusttype::SharedBytes<'a>;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type HMetrics = rusttype::HMetrics;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type VMetrics = rusttype::VMetrics;
/// Aliased type to allow lib usage without declaring underlying **rusttype** lib
pub type GlyphId = rusttype::GlyphId;

/// An iterator over `PositionedGlyph`s from the `GlyphBrush`
pub type PositionedGlyphIter<'a, 'font> = iter::FlatMap<
    slice::Iter<'a, GlyphedSectionText<'font>>,
    slice::Iter<'a, rusttype::PositionedGlyph<'font>>,
    fn(&'a GlyphedSectionText<'font>) -> slice::Iter<'a, PositionedGlyph<'font>>,
>;

pub(crate) type Color = [f32; 4];

// Type for the generated glyph cache texture
type TexForm = format::U8Norm;
type TexSurface = <TexForm as format::Formatted>::Surface;
type TexChannel = <TexForm as format::Formatted>::Channel;
type TexFormView = <TexForm as format::Formatted>::View;
type TexSurfaceHandle<R> = handle::Texture<R, TexSurface>;
type TexShaderView<R> = handle::ShaderResourceView<R, TexFormView>;

const IDENTITY_MATRIX4: [[f32; 4]; 4] = [
    [1.0, 0.0, 0.0, 0.0],
    [0.0, 1.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 0.0],
    [0.0, 0.0, 0.0, 1.0],
];

fn xxhash<H: Hash>(hashable: &H) -> u64 {
    let mut s = twox_hash::XxHash::default();
    hashable.hash(&mut s);
    s.finish()
}

/// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing,
/// glyph draw caching & efficient GPU texture cache updating and re-sizing on demand.
///
/// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html).
///
/// # Example
///
/// ```no_run
/// # extern crate gfx;
/// # extern crate gfx_window_glutin;
/// # extern crate glutin;
/// extern crate gfx_glyph;
/// # use gfx_glyph::{GlyphBrushBuilder};
/// use gfx_glyph::Section;
/// # fn main() {
/// # let events_loop = glutin::EventsLoop::new();
/// # let (_window, _device, mut gfx_factory, gfx_color, gfx_depth) =
/// #     gfx_window_glutin::init::<gfx::format::Srgba8, gfx::format::Depth>(
/// #         glutin::WindowBuilder::new(),
/// #         glutin::ContextBuilder::new(),
/// #         &events_loop);
/// # let mut gfx_encoder: gfx::Encoder<_, _> = gfx_factory.create_command_buffer().into();
///
/// # let dejavu: &[u8] = include_bytes!("../examples/DejaVuSans.ttf");
/// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu)
/// #     .build(gfx_factory.clone());
///
/// # let some_other_section = Section { text: "another", ..Section::default() };
/// let section = Section {
///     text: "Hello gfx_glyph",
///     ..Section::default()
/// };
///
/// glyph_brush.queue(section);
/// glyph_brush.queue(some_other_section);
///
/// glyph_brush.draw_queued(&mut gfx_encoder, &gfx_color, &gfx_depth).unwrap();
/// # }
/// ```
///
/// # Caching behaviour
///
/// Calls to [`GlyphBrush::queue`](#method.queue),
/// [`GlyphBrush::pixel_bounds`](#method.pixel_bounds), [`GlyphBrush::glyphs`](#method.glyphs)
/// calculate the positioned glyphs for a section.
/// This is cached so future calls to any of the methods for the same section are much
/// cheaper. In the case of [`GlyphBrush::queue`](#method.queue) the calculations will also be
/// used for actual drawing.
///
/// The cache for a section will be **cleared** after a
/// [`GlyphBrush::draw_queued`](#method.draw_queued) call when that section has not been used since
/// the previous draw call.
pub struct GlyphBrush<'font, R: gfx::Resources, F: gfx::Factory<R>> {
    fonts: HashMap<FontId, rusttype::Font<'font>>,
    font_cache: Cache<'font>,
    font_cache_tex: (
        gfx::handle::Texture<R, TexSurface>,
        gfx_core::handle::ShaderResourceView<R, f32>,
    ),
    texture_filter_method: texture::FilterMethod,
    factory: F,
    draw_cache: Option<DrawnGlyphBrush<R>>,

    // cache of section-layout hash -> computed glyphs, this avoid repeated glyph computation
    // for identical layout/sections common to repeated frame rendering
    calculate_glyph_cache: HashMap<u64, GlyphedSection<'font>>,

    // buffer of section-layout hashs (that must exist in the calculate_glyph_cache)
    // to be rendered on the next `draw_queued` call
    section_buffer: Vec<u64>,

    // Set of section hashs to keep in the glyph cache this frame even if they haven't been drawn
    keep_in_cache: HashSet<u64>,

    // config
    gpu_cache_scale_tolerance: f32,
    gpu_cache_position_tolerance: f32,
    cache_glyph_positioning: bool,
    cache_glyph_drawing: bool,

    depth_test: gfx::state::Depth,

    #[cfg(feature = "performance_stats")]
    perf: performance_stats::PerformanceStats,
}

impl<'font, R: gfx::Resources, F: gfx::Factory<R>> fmt::Debug for GlyphBrush<'font, R, F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "GlyphBrush")
    }
}

impl<'font, R: gfx::Resources, F: gfx::Factory<R>> GlyphCruncher<'font>
    for GlyphBrush<'font, R, F>
{
    fn pixel_bounds_custom_layout<'a, S, L>(
        &mut self,
        section: S,
        custom_layout: &L,
    ) -> Option<Rect<i32>>
    where
        L: GlyphPositioner + Hash,
        S: Into<Cow<'a, VariedSection<'a>>>,
    {
        let section = section.into();
        let mut x = (0, 0);
        let mut y = (0, 0);
        let mut no_match = true;

        let section_hash = self.cache_glyphs(section.borrow(), custom_layout);
        self.keep_in_cache.insert(section_hash);

        for g in self.calculate_glyph_cache[&section_hash]
            .glyphs
            .iter()
            .flat_map(|&GlyphedSectionText(ref g, ..)| g.iter())
        {
            if let Some(Rect { min, max }) = g.pixel_bounding_box() {
                if no_match || min.x < x.0 {
                    x.0 = min.x;
                }
                if no_match || min.y < y.0 {
                    y.0 = min.y;
                }
                if no_match || max.x > x.1 {
                    x.1 = max.x;
                }
                if no_match || max.y > y.1 {
                    y.1 = max.y;
                }

                no_match = false;
            }
        }

        if no_match {
            None
        }
        else {
            Some(Rect {
                min: Point { x: x.0, y: y.0 },
                max: Point { x: x.1, y: y.1 },
            })
        }
    }

    fn glyphs_custom_layout<'a, 'b, S, L>(
        &'b mut self,
        section: S,
        custom_layout: &L,
    ) -> PositionedGlyphIter<'b, 'font>
    where
        L: GlyphPositioner + Hash,
        S: Into<Cow<'a, VariedSection<'a>>>,
    {
        let section = section.into();
        let section_hash = self.cache_glyphs(section.borrow(), custom_layout);
        self.keep_in_cache.insert(section_hash);
        self.calculate_glyph_cache[&section_hash]
            .glyphs
            .iter()
            .flat_map(|&GlyphedSectionText(ref g, ..)| g.iter())
    }
}

impl<'font, R: gfx::Resources, F: gfx::Factory<R>> GlyphBrush<'font, R, F> {
    /// Queues a section/layout to be drawn by the next call of
    /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be called multiple times
    /// to queue multiple sections for drawing.
    ///
    /// Used to provide custom `GlyphPositioner` logic, if using built-in
    /// [`Layout`](enum.Layout.html) simply use [`queue`](struct.GlyphBrush.html#method.queue)
    ///
    /// Benefits from caching, see [caching behaviour](#caching-behaviour).
    pub fn queue_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G)
    where
        G: GlyphPositioner,
        S: Into<Cow<'a, VariedSection<'a>>>,
    {
        let section = section.into();
        if cfg!(debug_assertions) {
            for text in &section.text {
                assert!(self.fonts.contains_key(&text.font_id));
            }
        }
        let section_hash = self.cache_glyphs(&section, custom_layout);
        self.section_buffer.push(section_hash);
    }

    /// Queues a section/layout to be drawn by the next call of
    /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be called multiple times
    /// to queue multiple sections for drawing.
    ///
    /// Benefits from caching, see [caching behaviour](#caching-behaviour).
    pub fn queue<'a, S>(&mut self, section: S)
    where
        S: Into<Cow<'a, VariedSection<'a>>>,
    {
        let section = section.into();
        let layout = section.layout;
        self.queue_custom_layout(section, &layout)
    }

    /// Returns the calculate_glyph_cache key for this sections glyphs
    fn cache_glyphs<L>(&mut self, section: &VariedSection, layout: &L) -> u64
    where
        L: GlyphPositioner,
    {
        let section_hash = xxhash(&(section, layout));

        if self.cache_glyph_positioning {
            if let Entry::Vacant(entry) = self.calculate_glyph_cache.entry(section_hash) {
                #[cfg(feature = "performance_stats")]
                self.perf.layout_start();
                entry.insert(GlyphedSection {
                    bounds: layout.bounds_rect(section),
                    glyphs: layout.calculate_glyphs(&self.fonts, section),
                    z: section.z,
                });
                #[cfg(feature = "performance_stats")]
                self.perf.layout_finished();
            }
        }
        else {
            #[cfg(feature = "performance_stats")]
            self.perf.layout_start();
            self.calculate_glyph_cache.insert(
                section_hash,
                GlyphedSection {
                    bounds: layout.bounds_rect(section),
                    glyphs: layout.calculate_glyphs(&self.fonts, section),
                    z: section.z,
                },
            );
            #[cfg(feature = "performance_stats")]
            self.perf.layout_finished();
        }
        section_hash
    }

    /// Draws all queued sections onto a render target, applying a position transform (e.g.
    /// a projection).
    /// See [`queue`](struct.GlyphBrush.html#method.queue).
    ///
    /// Trims the cache, see [caching behaviour](#caching-behaviour).
    pub fn draw_queued<C, T, D>(
        &mut self,
        encoder: &mut gfx::Encoder<R, C>,
        target: &gfx::handle::RenderTargetView<R, T>,
        depth_target: &gfx::handle::DepthStencilView<R, D>,
    ) -> Result<(), String>
    where
        C: gfx::CommandBuffer<R>,
        T: format::RenderFormat,
        D: format::DepthFormat,
    {
        self.draw_queued_with_transform(IDENTITY_MATRIX4, encoder, target, depth_target)
    }

    /// Draws all queued sections onto a render target, applying a position transform (e.g.
    /// a projection).
    /// See [`queue`](struct.GlyphBrush.html#method.queue).
    ///
    /// Trims the cache, see [caching behaviour](#caching-behaviour).
    pub fn draw_queued_with_transform<C, T, D>(
        &mut self,
        transform: [[f32; 4]; 4],
        mut encoder: &mut gfx::Encoder<R, C>,
        target: &gfx::handle::RenderTargetView<R, T>,
        depth_target: &gfx::handle::DepthStencilView<R, D>,
    ) -> Result<(), String>
    where
        C: gfx::CommandBuffer<R>,
        T: format::RenderFormat,
        D: format::DepthFormat,
    {
        #[cfg(feature = "performance_stats")]
        self.perf.draw_start();

        let (screen_width, screen_height, ..) = target.get_dimensions();
        let (screen_width, screen_height) = (u32::from(screen_width), u32::from(screen_height));

        let current_text_state = xxhash(&(&self.section_buffer, screen_width, screen_height));

        if !self.cache_glyph_drawing || self.draw_cache.is_none()
            || self.draw_cache.as_ref().unwrap().texture_updated
            || self.draw_cache.as_ref().unwrap().last_text_state != current_text_state
        {
            loop {
                let mut no_text = true;

                for section_hash in &self.section_buffer {
                    let GlyphedSection { ref glyphs, .. } =
                        self.calculate_glyph_cache[section_hash];
                    for &GlyphedSectionText(ref glyphs, _, font_id) in glyphs {
                        for glyph in glyphs {
                            self.font_cache.queue_glyph(font_id.0, glyph.clone());
                            no_text = false;
                        }
                    }
                }

                if no_text {
                    self.clear_section_buffer();
                    return Ok(());
                }

                let tex = self.font_cache_tex.0.clone();
                if let Err(err) = self.font_cache.cache_queued(|rect, tex_data| {
                    let offset = [rect.min.x as u16, rect.min.y as u16];
                    let size = [rect.width() as u16, rect.height() as u16];
                    update_texture(&mut encoder, &tex, offset, size, tex_data);
                }) {
                    let (width, height) = self.font_cache.dimensions();
                    let (new_width, new_height) = (width * 2, height * 2);

                    if let Some(ref mut cache) = self.draw_cache {
                        cache.texture_updated = true;
                    }

                    if log_enabled!(log::Level::Warn) {
                        warn!(
                            "Increasing glyph texture size {old:?} -> {new:?}, as {reason:?}. \
                             Consider building with `.initial_cache_size({new:?})` to avoid \
                             resizing. Called from:\n{trace}",
                            old = (width, height),
                            new = (new_width, new_height),
                            reason = err,
                            trace = outer_backtrace!()
                        );
                    }

                    let new_cache = CacheBuilder {
                        width: new_width,
                        height: new_height,
                        scale_tolerance: self.gpu_cache_scale_tolerance,
                        position_tolerance: self.gpu_cache_position_tolerance,
                        ..CacheBuilder::default()
                    }.build();

                    match create_texture(&mut self.factory, new_width, new_height) {
                        Ok((new_tex, tex_view)) => {
                            self.font_cache = new_cache;
                            self.font_cache_tex.1 = tex_view;
                            self.font_cache_tex.0 = new_tex;
                            continue;
                        }
                        Err(_) => {
                            self.section_buffer.clear();
                            return Err(format!(
                                "Failed to create {}x{} glyph texture",
                                new_width, new_height
                            ));
                        }
                    }
                }

                break;
            }
            #[cfg(feature = "performance_stats")]
            self.perf.gpu_cache_done();

            let verts: Vec<GlyphVertex> = {
                let sections: Vec<_> = self.section_buffer
                    .iter()
                    .map(|hash| &self.calculate_glyph_cache[hash])
                    .collect();

                let mut verts = Vec::with_capacity(
                    sections
                        .iter()
                        .flat_map(|section| section.glyphs.iter().map(|glyphs| glyphs.0.len()))
                        .sum::<usize>() * VERTICES_PER_GLYPH,
                );

                for &GlyphedSection {
                    ref glyphs,
                    bounds,
                    z,
                } in sections
                {
                    for v in glyphs.iter().flat_map(
                        |&GlyphedSectionText(ref glyphs, color, font_id)| {
                            text_vertices(
                                glyphs,
                                color,
                                font_id,
                                &self.font_cache,
                                bounds,
                                z,
                                (screen_width as f32, screen_height as f32),
                            )
                        },
                    ) {
                        verts.push(v)
                    }
                }
                verts
            };
            #[cfg(feature = "performance_stats")]
            self.perf.vertex_generation_done();

            let (vbuf, slice) = self.factory.create_vertex_buffer_with_slice(&verts, ());

            let draw_cache = if self.draw_cache.is_some() {
                let mut cache = self.draw_cache.take().unwrap();
                cache.pipe_data.vbuf = vbuf;
                cache.pipe_data.out = target.raw().clone();
                cache.pipe_data.out_depth = depth_target.raw().clone();
                if cache.pso.0 != T::get_format() {
                    cache.pso = (
                        T::get_format(),
                        self.pso_using(T::get_format(), D::get_format()),
                    );
                }
                cache.slice = slice;
                cache.last_text_state = current_text_state;
                if cache.texture_updated {
                    cache.pipe_data.font_tex.0 = self.font_cache_tex.1.clone();
                    cache.texture_updated = false;
                }
                cache
            }
            else {
                DrawnGlyphBrush {
                    pipe_data: {
                        let sampler = self.factory.create_sampler(texture::SamplerInfo::new(
                            self.texture_filter_method,
                            texture::WrapMode::Clamp,
                        ));
                        glyph_pipe::Data {
                            vbuf,
                            font_tex: (self.font_cache_tex.1.clone(), sampler),
                            transform,
                            out: target.raw().clone(),
                            out_depth: depth_target.raw().clone(),
                        }
                    },
                    pso: (
                        T::get_format(),
                        self.pso_using(T::get_format(), D::get_format()),
                    ),
                    slice,
                    last_text_state: 0,
                    texture_updated: false,
                }
            };

            self.draw_cache = Some(draw_cache);
        }

        if let Some(&mut DrawnGlyphBrush {
            ref pso,
            ref slice,
            ref mut pipe_data,
            ..
        }) = self.draw_cache.as_mut()
        {
            pipe_data.transform = transform;
            encoder.draw(slice, &pso.1, pipe_data);
        }

        self.clear_section_buffer();

        #[cfg(feature = "performance_stats")]
        {
            self.perf.draw_finished();
            self.perf.log_sluggishness();
        }

        Ok(())
    }

    /// Returns `FontId` -> `Font` map of available fonts.
    pub fn fonts(&self) -> &HashMap<FontId, Font<'font>> {
        &self.fonts
    }

    fn clear_section_buffer(&mut self) {
        if self.cache_glyph_positioning {
            // clear section_buffer & trim calculate_glyph_cache to active sections
            let mut active =
                HashSet::with_capacity(self.section_buffer.len() + self.keep_in_cache.len());

            for h in self.section_buffer.drain(..) {
                active.insert(h);
            }
            for h in self.keep_in_cache.drain() {
                active.insert(h);
            }
            self.calculate_glyph_cache
                .retain(|key, _| active.contains(key));
        }
        else {
            self.section_buffer.clear();
            self.calculate_glyph_cache.clear();
            self.keep_in_cache.clear();
        }
    }

    fn pso_using(
        &mut self,
        color_format: gfx::format::Format,
        depth_format: gfx::format::Format,
    ) -> gfx::PipelineState<R, glyph_pipe::Meta> {
        self.factory
            .create_pipeline_simple(
                include_bytes!("shader/vert.glsl"),
                include_bytes!("shader/frag.glsl"),
                glyph_pipe::Init::new(color_format, depth_format, self.depth_test),
            )
            .unwrap()
    }

    /// Adds an additional font to the one(s) initially added on build.
    ///
    /// Returns a new [`FontId`](struct.FontId.html) to reference this font.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # extern crate gfx;
    /// # extern crate gfx_window_glutin;
    /// # extern crate glutin;
    /// extern crate gfx_glyph;
    /// use gfx_glyph::{Section, GlyphBrushBuilder};
    /// # fn main() {
    /// # let events_loop = glutin::EventsLoop::new();
    /// # let (_window, _device, mut gfx_factory, gfx_color, gfx_depth) =
    /// #     gfx_window_glutin::init::<gfx::format::Srgba8, gfx::format::Depth>(
    /// #         glutin::WindowBuilder::new(),
    /// #         glutin::ContextBuilder::new(),
    /// #         &events_loop);
    /// # let mut gfx_encoder: gfx::Encoder<_, _> = gfx_factory.create_command_buffer().into();
    ///
    /// // dejavu is built as default `FontId(0)`
    /// let dejavu: &[u8] = include_bytes!("../examples/DejaVuSans.ttf");
    /// let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu)
    ///     .build(gfx_factory.clone());
    ///
    /// // some time later, add another font referenced by a new `FontId`
    /// let open_sans_italic: &[u8] = include_bytes!("../examples/OpenSans-Italic.ttf");
    /// let open_sans_italic_id = glyph_brush.add_font_bytes(open_sans_italic);
    /// # glyph_brush.draw_queued(&mut gfx_encoder, &gfx_color, &gfx_depth).unwrap();
    /// # let _ = open_sans_italic_id;
    /// # }
    /// ```
    pub fn add_font_bytes<'a: 'font, B: Into<SharedBytes<'a>>>(&mut self, font_data: B) -> FontId {
        self.add_font(Font::from_bytes(font_data.into()).unwrap())
    }

    /// Adds an additional font to the one(s) initially added on build.
    ///
    /// Returns a new [`FontId`](struct.FontId.html) to reference this font.
    pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId {
        let next_id = FontId(self.fonts.keys().max().unwrap().0 + 1);
        self.fonts.insert(next_id, font_data);
        next_id
    }
}

struct DrawnGlyphBrush<R: gfx::Resources> {
    pipe_data: glyph_pipe::Data<R>,
    pso: (gfx::format::Format, gfx::PipelineState<R, glyph_pipe::Meta>),
    slice: gfx::Slice<R>,
    last_text_state: u64,
    texture_updated: bool,
}

#[derive(Clone)]
struct GlyphedSection<'font> {
    bounds: Rect<f32>,
    glyphs: Vec<GlyphedSectionText<'font>>,
    z: f32,
}

#[derive(Clone)]
pub struct GlyphedSectionText<'font>(pub Vec<PositionedGlyph<'font>>, pub Color, pub FontId);

/// Returns a Font from font bytes info or an error reason.
#[deprecated(since = "0.10.0", note = "please use `Font::from_bytes` instead")]
pub fn font<'a, B: Into<SharedBytes<'a>>>(font_bytes: B) -> Result<Font<'a>, &'static str> {
    let font_bytes = font_bytes.into();
    if font_bytes.is_empty() {
        return Err("Empty font data");
    }
    Font::from_bytes(font_bytes).map_err(|_| "Font not supported by rusttype")
}

const VERTICES_PER_GLYPH: usize = 6;

#[inline]
fn text_vertices(
    glyphs: &[PositionedGlyph],
    color: Color,
    font_id: FontId,
    cache: &Cache,
    bounds: Rect<f32>,
    z: f32,
    (screen_width, screen_height): (f32, f32),
) -> Vec<GlyphVertex> {
    let origin = point(0.0, 0.0);
    let mut vertices = Vec::with_capacity(glyphs.len() * VERTICES_PER_GLYPH);

    let gl_bounds = Rect {
        min: origin
            + (vector(
                bounds.min.x as f32 / screen_width - 0.5,
                1.0 - bounds.min.y as f32 / screen_height - 0.5,
            )) * 2.0,
        max: origin
            + (vector(
                bounds.max.x as f32 / screen_width - 0.5,
                1.0 - bounds.max.y as f32 / screen_height - 0.5,
            )) * 2.0,
    };

    for g in glyphs {
        let rect = cache.rect_for(font_id.0, g);
        if let Ok(Some((mut uv_rect, screen_rect))) = rect {
            if screen_rect.min.x as f32 > bounds.max.x || screen_rect.min.y as f32 > bounds.max.y
                || bounds.min.x > screen_rect.max.x as f32
                || bounds.min.y > screen_rect.max.y as f32
            {
                // glyph is totally outside the bounds
                continue;
            }

            let mut gl_rect = Rect {
                min: origin
                    + (vector(
                        screen_rect.min.x as f32 / screen_width - 0.5,
                        1.0 - screen_rect.min.y as f32 / screen_height - 0.5,
                    )) * 2.0,
                max: origin
                    + (vector(
                        screen_rect.max.x as f32 / screen_width - 0.5,
                        1.0 - screen_rect.max.y as f32 / screen_height - 0.5,
                    )) * 2.0,
            };

            // handle overlapping bounds, modify uv_rect to preserve texture aspect
            if gl_rect.max.x > gl_bounds.max.x {
                let old_width = gl_rect.width();
                gl_rect.max.x = gl_bounds.max.x;
                uv_rect.max.x = uv_rect.min.x + uv_rect.width() * gl_rect.width() / old_width;
            }
            if gl_rect.min.x < gl_bounds.min.x {
                let old_width = gl_rect.width();
                gl_rect.min.x = gl_bounds.min.x;
                uv_rect.min.x = uv_rect.max.x - uv_rect.width() * gl_rect.width() / old_width;
            }
            // note: y access is flipped gl compared with screen,
            // texture is not flipped (ie is a headache)
            if gl_rect.max.y < gl_bounds.max.y {
                let old_height = gl_rect.height();
                gl_rect.max.y = gl_bounds.max.y;
                uv_rect.max.y = uv_rect.min.y + uv_rect.height() * gl_rect.height() / old_height;
            }
            if gl_rect.min.y > gl_bounds.min.y {
                let old_height = gl_rect.height();
                gl_rect.min.y = gl_bounds.min.y;
                uv_rect.min.y = uv_rect.max.y - uv_rect.height() * gl_rect.height() / old_height;
            }

            vertices.push(GlyphVertex {
                pos: [gl_rect.min.x, gl_rect.max.y, z],
                tex_pos: [uv_rect.min.x, uv_rect.max.y],
                color,
            });
            vertices.push(GlyphVertex {
                pos: [gl_rect.min.x, gl_rect.min.y, z],
                tex_pos: [uv_rect.min.x, uv_rect.min.y],
                color,
            });
            vertices.push(GlyphVertex {
                pos: [gl_rect.max.x, gl_rect.min.y, z],
                tex_pos: [uv_rect.max.x, uv_rect.min.y],
                color,
            });
            vertices.push(GlyphVertex {
                pos: [gl_rect.max.x, gl_rect.min.y, z],
                tex_pos: [uv_rect.max.x, uv_rect.min.y],
                color,
            });
            vertices.push(GlyphVertex {
                pos: [gl_rect.max.x, gl_rect.max.y, z],
                tex_pos: [uv_rect.max.x, uv_rect.max.y],
                color,
            });
            vertices.push(GlyphVertex {
                pos: [gl_rect.min.x, gl_rect.max.y, z],
                tex_pos: [uv_rect.min.x, uv_rect.max.y],
                color,
            });
        }
        else if rect.is_err() {
            warn!("Cache miss?: {:?}", rect);
        }
    }
    vertices
}

// Creates a gfx texture with the given data
fn create_texture<F, R>(
    factory: &mut F,
    width: u32,
    height: u32,
) -> Result<(TexSurfaceHandle<R>, TexShaderView<R>), Box<Error>>
where
    R: gfx::Resources,
    F: gfx::Factory<R>,
{
    let kind = texture::Kind::D2(
        width as texture::Size,
        height as texture::Size,
        texture::AaMode::Single,
    );

    let tex = factory.create_texture(
        kind,
        1 as texture::Level,
        gfx::memory::Bind::SHADER_RESOURCE,
        gfx::memory::Usage::Dynamic,
        Some(<TexChannel as format::ChannelTyped>::get_channel_type()),
    )?;

    let view =
        factory.view_texture_as_shader_resource::<TexForm>(&tex, (0, 0), format::Swizzle::new())?;

    Ok((tex, view))
}

// Updates a texture with the given data (used for updating the GlyphCache texture)
fn update_texture<R, C>(
    encoder: &mut gfx::Encoder<R, C>,
    texture: &handle::Texture<R, TexSurface>,
    offset: [u16; 2],
    size: [u16; 2],
    data: &[u8],
) where
    R: gfx::Resources,
    C: gfx::CommandBuffer<R>,
{
    let info = texture::ImageInfoCommon {
        xoffset: offset[0],
        yoffset: offset[1],
        zoffset: 0,
        width: size[0],
        height: size[1],
        depth: 0,
        format: (),
        mipmap: 0,
    };
    encoder
        .update_texture::<TexSurface, TexForm>(texture, None, info, data)
        .unwrap();
}