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
//! Text rendering functionality.
//!
//! Mostly just a wrapper/integration layer for rusttype.

use crate::gl;
use crate::gl::types::*;
use crate::image::Image;
use crate::renderer::{DrawCallHandle, DrawCallParameters, Renderer, Shaders};
use rusttype::gpu_cache::Cache;
use rusttype::*;
use std::cell::RefCell;
use std::error::Error;
use unicode_normalization::UnicodeNormalization;

pub(crate) const GLYPH_CACHE_WIDTH: u32 = 1024;
pub(crate) const GLYPH_CACHE_HEIGHT: u32 = 1024;

const DEFAULT_TEXT_SHADERS: Shaders = Shaders {
    vertex_shader_110: include_str!("shaders/legacy/texquad.vert"),
    fragment_shader_110: include_str!("shaders/legacy/text.frag"),
    vertex_shader_330: include_str!("shaders/texquad.vert"),
    fragment_shader_330: include_str!("shaders/text.frag"),
};

/// Defines the alignment of text.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug)]
pub enum Alignment {
    /// Text is aligned to the left.
    Left,
    /// Text is aligned to the right.
    Right,
    /// Text is centered.
    Center,
}

struct TextRender {
    glyphs: Vec<SizedGlyph>,
    clip_area: Option<(f32, f32, f32, f32)>,
    z: f32,
}

#[derive(Clone)]
struct SizedGlyph {
    glyph: PositionedGlyph<'static>,
    width: f32,
}

/// Holds the state required for text rendering, such as the font, and
/// a text draw call queue.
pub struct TextRenderer {
    font: Font<'static>,
    cache: RefCell<Cache<'static>>,
    cached_text: Vec<TextRender>,
    dpi_factor: f32,
    draw_call: DrawCallHandle,
}

impl TextRenderer {
    /// Creates a new text renderer.
    ///
    /// - `font_data`: The bytes that consist a .ttf file. See the `rusttype` crate's documentation for what kinds of fonts are supported.
    ///
    /// - `subpixel_accurate`: If true, glyphs will be rendered if
    /// their subpixel position differs by very small amounts, to
    /// render the font more accurately for that position. In
    /// practice, I haven't seen any difference, so I'd recommend
    /// setting this to false. (Internally this maps to `rusttype`'s
    /// `CacheBuilder`'s position tolerance value, true = 0.1, false =
    /// 1.0).
    pub fn create(
        font_data: Vec<u8>,
        subpixel_accurate: bool,
        renderer: &mut Renderer,
    ) -> Result<TextRenderer, Box<Error>> {
        let glyph_cache_image =
            Image::from_color(GLYPH_CACHE_WIDTH as i32, GLYPH_CACHE_HEIGHT as i32, &[0])
                .format(gl::RED);
        let params = DrawCallParameters {
            image: Some(glyph_cache_image),
            shaders: Some(DEFAULT_TEXT_SHADERS),
            ..Default::default()
        };
        let draw_call = renderer.create_draw_call(params);
        let position_tolerance = if subpixel_accurate { 0.1 } else { 1.0 };

        Ok(TextRenderer {
            font: Font::from_bytes(font_data)?,
            cache: RefCell::new(
                Cache::builder()
                    .dimensions(GLYPH_CACHE_WIDTH, GLYPH_CACHE_HEIGHT)
                    .position_tolerance(position_tolerance)
                    .build(),
            ),
            cached_text: Vec::new(),
            dpi_factor: 1.0,
            draw_call,
        })
    }

    /// Updates the DPI factor that will be taken into account during
    /// text rendering. If the window DPI changes, this should be
    /// called with the new factor before new text draw calls.
    pub fn update_dpi_factor(&mut self, dpi_factor: f32) {
        self.dpi_factor = dpi_factor;
    }

    /// Draws text.
    ///
    /// - `text`: The rendered text.
    /// - `(x, y, z)`: The position (top-left) of the rendered text
    /// area.
    /// - `font_size`: The size of the font.
    /// - `max_row_width`: The width at which the text will wrap. An
    /// effort is made to break lines at word boundaries.
    /// - `clip_area`: The area which defines where the text will be
    /// rendered. Text outside the area will be cut off. For an
    /// example use case, think editable text boxes: the clip area
    /// would be the text box.
    pub fn draw_text(
        &mut self,
        text: &str,
        (x, y, z): (f32, f32, f32),
        font_size: f32,
        alignment: Alignment,
        max_row_width: Option<f32>,
        clip_area: Option<(f32, f32, f32, f32)>,
    ) {
        let rows = self.collect_glyphs(x, y, max_row_width, font_size, text);
        let dpi = self.dpi_factor;

        let mut final_glyphs = Vec::with_capacity(text.len());

        // Collect the rows and offset them according to the alignment
        if let Some(width) = max_row_width {
            match alignment {
                Alignment::Right => {
                    for row in rows {
                        let row = if let Some((row_width, _)) = measure_text(&row, dpi) {
                            let offset = width - row_width;
                            offset_glyphs(row, offset, 0.0, dpi)
                        } else {
                            row
                        };
                        final_glyphs.extend_from_slice(&row);
                    }
                }

                Alignment::Center => {
                    for row in rows {
                        let row = if let Some((row_width, _)) = measure_text(&row, dpi) {
                            let offset = (width - row_width) / 2.0;
                            offset_glyphs(row, offset, 0.0, dpi)
                        } else {
                            row
                        };
                        final_glyphs.extend_from_slice(&row);
                    }
                }

                Alignment::Left => {
                    for row in rows {
                        final_glyphs.extend_from_slice(&row);
                    }
                }
            }
        } else {
            for row in rows {
                final_glyphs.extend_from_slice(&row);
            }
        }

        self.cached_text.push(TextRender {
            glyphs: final_glyphs,
            clip_area,
            z,
        });
    }

    fn collect_glyphs(
        &self,
        x: f32,
        y: f32,
        width: Option<f32>,
        font_size: f32,
        text: &str,
    ) -> Vec<Vec<SizedGlyph>> {
        let dpi = self.dpi_factor;
        let scale = Scale::uniform(font_size * dpi);
        let x = x * dpi;
        let y = y * dpi;

        let mut rows = Vec::new();
        rows.push(Vec::with_capacity(text.len()));
        let v_metrics = self.font.v_metrics(scale);
        let advance_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
        let mut caret = point(x, y + v_metrics.ascent);
        let mut last_glyph_id = None;

        let next_row = |caret: &mut Point<f32>, rows: &mut Vec<Vec<SizedGlyph>>| {
            *caret = point(x, caret.y + advance_height);
            // Pre-allocate based on the last row's length
            let len = rows.last().unwrap().len();
            rows.push(Vec::with_capacity(len));
        };

        let chars: Vec<char> = text.nfc().collect();
        let mut i = 0;
        let mut current_word_length = 0;
        while i < chars.len() {
            let c = chars[i];
            i += 1;
            if c.is_control() {
                if c == '\n' {
                    next_row(&mut caret, &mut rows);
                }
                continue;
            }
            if c == ' ' {
                current_word_length = 0;
            } else {
                current_word_length += 1;
            }

            let glyph = self.font.glyph(c);
            if let Some(id) = last_glyph_id.take() {
                caret.x += self.font.pair_kerning(scale, id, glyph.id());
            }

            if width.is_some() && caret.x > (x + width.unwrap()) * dpi {
                if let Some(ref mut last_row) = rows.last_mut() {
                    let len = last_row.len();
                    if current_word_length < len {
                        last_row.truncate(len - current_word_length);
                        i -= current_word_length;
                    } else {
                        i -= 1;
                    }
                    current_word_length = 0;
                }
                next_row(&mut caret, &mut rows);
                continue;
            } else {
                last_glyph_id = Some(glyph.id());
            }

            let glyph = glyph.scaled(scale).positioned(caret);
            let advance_width = glyph.unpositioned().h_metrics().advance_width;
            caret.x += advance_width;

            rows.last_mut().unwrap().push(SizedGlyph {
                glyph,
                width: advance_width,
            });
        }
        rows
    }

    /// Makes the `draw_text` calls called before this function
    /// render. Should be called every frame before rendering.
    pub fn compose_draw_call(&mut self, renderer: &mut Renderer) {
        let &mut TextRenderer {
            dpi_factor,
            ref draw_call,
            ..
        } = self;
        let mut cache = self.cache.borrow_mut();

        for text in &self.cached_text {
            for glyph in &text.glyphs {
                cache.queue_glyph(0, glyph.glyph.clone());
            }
        }

        let tex = renderer.get_texture(draw_call);
        unsafe {
            gl::BindTexture(gl::TEXTURE_2D, tex);
            gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
        }

        let upload_new_texture = |rect: Rect<u32>, data: &[u8]| unsafe {
            gl::TexSubImage2D(
                gl::TEXTURE_2D,
                0,
                rect.min.x as GLint,
                rect.min.y as GLint,
                rect.width() as GLint,
                rect.height() as GLint,
                gl::RED as GLuint,
                gl::UNSIGNED_BYTE,
                data.as_ptr() as *const _,
            );
        };
        cache.cache_queued(upload_new_texture).ok();

        for text in &self.cached_text {
            let z = text.z;

            let clip_coords;
            let clipped;
            if let Some(clip_area) = text.clip_area {
                clip_coords = clip_area;
                clipped = true;
            } else {
                clip_coords = (0.0, 0.0, 0.0, 0.0);
                clipped = false;
            }
            for glyph in &text.glyphs {
                if let Ok(Some((uv_rect, screen_rect))) = cache.rect_for(0, &glyph.glyph) {
                    let coords = (
                        screen_rect.min.x as f32 / dpi_factor,
                        screen_rect.min.y as f32 / dpi_factor,
                        screen_rect.max.x as f32 / dpi_factor,
                        screen_rect.max.y as f32 / dpi_factor,
                    );
                    let texcoords = (uv_rect.min.x, uv_rect.min.y, uv_rect.max.x, uv_rect.max.y);
                    if clipped {
                        renderer.draw_quad_clipped(
                            clip_coords,
                            coords,
                            texcoords,
                            (0.0, 0.0, 0.0, 1.0),
                            (0.0, 0.0, 0.0),
                            z,
                            draw_call,
                        );
                    } else {
                        renderer.draw_quad(
                            coords,
                            texcoords,
                            (0.0, 0.0, 0.0, 1.0),
                            (0.0, 0.0, 0.0),
                            z,
                            draw_call,
                        );
                    };
                }
            }
        }

        self.cached_text.clear();
    }
}

/// Will only return `None` when `index >= glyphs.len()`.
fn measure_text_at_index(
    glyphs: &[SizedGlyph],
    index: usize,
    dpi: f32,
) -> Option<(f32, f32, f32, f32)> {
    if index >= glyphs.len() {
        return None;
    }

    let width = glyphs[index].width;
    let glyph = &glyphs[index].glyph;
    let position = glyph.position();
    if let Some(rect) = glyph.pixel_bounding_box() {
        return Some((
            rect.min.x as f32 / dpi,
            rect.min.y as f32 / dpi,
            rect.max.x as f32 / dpi,
            rect.max.y as f32 / dpi,
        ));
    } else {
        let (x, y) = (position.x / dpi, position.y / dpi);
        return Some((x, y, x + width / dpi, y + 1.0));
    }
}

fn measure_text(glyphs: &[SizedGlyph], dpi: f32) -> Option<(f32, f32)> {
    let mut result: Option<(f32, f32, f32, f32)> = None;

    for i in 0..glyphs.len() {
        if let Some(glyph_rect) = measure_text_at_index(glyphs, i, dpi) {
            if let Some(ref mut rect) = result {
                *rect = (
                    rect.0.min(glyph_rect.0),
                    rect.1.min(glyph_rect.1),
                    rect.2.max(glyph_rect.2),
                    rect.3.max(glyph_rect.3),
                );
            } else {
                result = Some(glyph_rect);
            }
        }
    }

    if let Some(rect) = result {
        Some((rect.2 - rect.0, rect.3 - rect.1))
    } else {
        None
    }
}

fn offset_glyphs(glyphs: Vec<SizedGlyph>, x: f32, y: f32, dpi: f32) -> Vec<SizedGlyph> {
    glyphs
        .into_iter()
        .map(|glyph| offset_glyph(glyph, x, y, dpi))
        .collect()
}

fn offset_glyph(glyph: SizedGlyph, x: f32, y: f32, dpi: f32) -> SizedGlyph {
    let width = glyph.width;
    let glyph = glyph.glyph;
    let position = glyph.position() + vector(x, y) * dpi;
    SizedGlyph {
        width,
        glyph: glyph.into_unpositioned().positioned(position),
    }
}