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
use super::geometry::{Curve, Line, Rect};
use super::shape::{AllocatedShape, Segment, Shape};
use super::texture::{Texture, TextureViewAllocator};
use cgmath::Point2;
use rusttype::{Contour, Scale, Segment as FontSegment};
use rusttype::{Error as RustTypeError, Font as RustTypeFont};
use std::collections::HashMap;
use std::iter::{once, FromIterator};
use std::mem::replace;
use std::sync::{Arc, Mutex};

#[derive(Debug)]
pub enum FontError {
    CannotLoadFont,
}

impl From<RustTypeError> for FontError {
    fn from(_error: RustTypeError) -> Self {
        FontError::CannotLoadFont
    }
}

struct GlyphInfo {
    texture_id: u32,
    texture_view: Rect<f32>,
}

pub struct GlyphLayout {
    pub texture_id: u32,
    pub screen_coord: Rect<f32>,
    pub texture_coord: Rect<f32>,
}

pub struct TextBlockLayout {
    pub font_size: u8,
    pub shadow_size: u8,
    pub bounding_box: Rect<f32>,
    pub glyph_layouts: Vec<GlyphLayout>,
}

pub struct TextureRenderBatch {
    pub texture_id: u32,
    pub texture: Arc<Mutex<Texture>>,
    pub allocated_shapes: Vec<AllocatedShape>,
}

struct TextureMetadata {
    texture: Arc<Mutex<Texture>>,
    allocator: TextureViewAllocator,
    allocated_shapes: Vec<AllocatedShape>,
}

pub struct Font {
    texture_metadatas: Vec<TextureMetadata>,
    free_texture_index: u32,
    texture_width: u32,
    texture_height: u32,
    font_size: u8,
    shadow_size: u8,
    font: RustTypeFont<'static>,
    glyphs: HashMap<char, Option<GlyphInfo>>,
}

impl Font {
    pub fn new(
        texture_width: u32,
        texture_height: u32,
        font_size: u8,
        shadow_size: u8,
        font_data: Vec<u8>,
    ) -> Result<Self, FontError> {
        let font = RustTypeFont::from_bytes(font_data)?;
        let (texture, allocator) = Texture::new(texture_width, texture_height);
        let texture_metadatas = vec![TextureMetadata {
            texture: Arc::new(Mutex::new(texture)),
            allocator,
            allocated_shapes: Vec::new(),
        }];

        Ok(Font {
            texture_metadatas,
            free_texture_index: 0,
            texture_width,
            texture_height,
            font_size,
            shadow_size,
            font,
            glyphs: HashMap::new(),
        })
    }

    pub fn invalidate(&mut self) {
        let (texture, allocator) = Texture::new(self.texture_width, self.texture_height);
        let texture_metadatas = vec![TextureMetadata {
            texture: Arc::new(Mutex::new(texture)),
            allocator,
            allocated_shapes: Vec::new(),
        }];

        self.texture_metadatas = texture_metadatas;
        self.free_texture_index = 0;
        self.glyphs = HashMap::new();
    }

    pub fn allocate_glyph(&mut self, c: char) {
        if self.glyphs.contains_key(&c) {
            return;
        }

        let glyph = self.font.glyph(c);
        let allocated_shape =
            if let Some(shape) = glyph.scaled(Scale::uniform(self.font_size as f32)).shape() {
                loop {
                    let allocated_shape = {
                        let texture_allocator =
                            &mut self.texture_metadatas[self.free_texture_index as usize].allocator;
                        AllocatedShape::new(
                            shape.as_slice().into(),
                            texture_allocator,
                            self.shadow_size as f32,
                        )
                    };

                    if let Some(s) = allocated_shape {
                        break Some(s);
                    } else {
                        let (texture, allocator) =
                            Texture::new(self.texture_width, self.texture_height);

                        self.texture_metadatas.push(TextureMetadata {
                            texture: Arc::new(Mutex::new(texture)),
                            allocated_shapes: Vec::new(),
                            allocator,
                        });

                        self.free_texture_index += 1;
                    }
                }
            } else {
                None
            };

        let glyph_info = allocated_shape.map(|allocated_shape| {
            let texture_view = allocated_shape.texture_view.get_view();
            let texture_id = self.free_texture_index;

            self.texture_metadatas[texture_id as usize]
                .allocated_shapes
                .push(allocated_shape);

            GlyphInfo {
                texture_id,
                texture_view: Rect::new(
                    texture_view.min.x as f32 / self.texture_width as f32,
                    texture_view.min.y as f32 / self.texture_height as f32,
                    texture_view.max.x as f32 / self.texture_width as f32,
                    texture_view.max.y as f32 / self.texture_height as f32,
                ),
            }
        });

        self.glyphs.insert(c, glyph_info);
    }

    pub fn allocate_glyphs(&mut self, text: &str) {
        text.chars().for_each(|c| self.allocate_glyph(c));
    }

    pub fn get_texture(&self, texture_id: u32) -> Arc<Mutex<Texture>> {
        self.texture_metadatas[texture_id as usize].texture.clone()
    }

    pub fn get_texture_width(&self) -> u32 {
        self.texture_width
    }

    pub fn get_texture_height(&self) -> u32 {
        self.texture_height
    }

    pub fn set_texture_size(&mut self, width: u32, height: u32) {
        self.texture_width = width;
        self.texture_height = height;
        self.invalidate();
    }

    pub fn get_shadow_size(&self) -> u8 {
        self.shadow_size
    }

    pub fn set_shadow_size(&mut self, shadow_size: u8) {
        self.shadow_size = shadow_size;
        self.invalidate();
    }

    pub fn get_font_size(&self) -> u8 {
        self.font_size
    }

    pub fn set_font_size(&mut self, font_size: u8) {
        self.font_size = font_size;
        self.invalidate();
    }

    pub fn get_ascent(&self) -> f32 {
        let scale = Scale::uniform(1.0);
        let v_metrics = self.font.v_metrics(scale);
        v_metrics.ascent
    }

    pub fn get_descent(&self) -> f32 {
        let scale = Scale::uniform(1.0);
        let v_metrics = self.font.v_metrics(scale);
        v_metrics.descent
    }

    pub fn get_line_gap(&self) -> f32 {
        let scale = Scale::uniform(1.0);
        let v_metrics = self.font.v_metrics(scale);
        v_metrics.line_gap
    }

    pub fn get_texture_render_batches(&mut self) -> Vec<TextureRenderBatch> {
        let mut batches = Vec::new();

        for (texture_id, texture_metadata) in self.texture_metadatas.iter_mut().enumerate() {
            if !texture_metadata.allocated_shapes.is_empty() {
                let allocated_shapes = replace(&mut texture_metadata.allocated_shapes, Vec::new());

                batches.push(TextureRenderBatch {
                    texture_id: texture_id as u32,
                    texture: texture_metadata.texture.clone(),
                    allocated_shapes,
                })
            }
        }

        batches
    }

    pub fn layout_text_block(&mut self, text: &str) -> TextBlockLayout {
        self.allocate_glyphs(text);

        let mut glyph_layouts = Vec::new();

        let mut bb_min_x = 0.0;
        let mut bb_min_y = 0.0;
        let mut bb_max_x = 0.0;
        let mut bb_max_y = 0.0;

        let shadow = self.shadow_size as f32 / self.font_size as f32;
        let scale = Scale::uniform(1.0);
        let v_metrics = self.font.v_metrics(scale);

        let mut last_glyph = None;
        let mut offset_x = 0.0;
        let mut offset_y = 0.0;

        for c in text.chars() {
            if c == '\n' {
                offset_x = 0.0;
                last_glyph = None;
                offset_y -= v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
                continue;
            }

            let glyph = self.font.glyph(c).scaled(scale);
            let glyph_info = self.glyphs.get(&c).unwrap();

            if let Some(last_glyph) = last_glyph {
                offset_x += self.font.pair_kerning(scale, last_glyph, glyph.id());
            }

            let advance_width = glyph.h_metrics().advance_width;

            if let Some(bb) = glyph.exact_bounding_box() {
                let min_x = offset_x + bb.min.x;
                let min_y = offset_y - bb.max.y;
                let max_x = offset_x + bb.max.x;
                let max_y = offset_y - bb.min.y;

                bb_min_x = min_x.min(bb_min_x);
                bb_min_y = min_y.min(bb_min_y);
                bb_max_x = max_x.max(bb_max_x);
                bb_max_y = max_y.max(bb_max_y);

                if let Some(glyph_info) = glyph_info {
                    glyph_layouts.push(GlyphLayout {
                        texture_id: glyph_info.texture_id,
                        screen_coord: Rect::new(
                            min_x - shadow,
                            min_y - shadow,
                            max_x + shadow,
                            max_y + shadow,
                        ),
                        texture_coord: glyph_info.texture_view,
                    });
                }
            }

            offset_x += advance_width;
            last_glyph = Some(glyph.id());
        }

        TextBlockLayout {
            font_size: self.font_size,
            shadow_size: self.shadow_size,
            bounding_box: Rect::new(bb_min_x, bb_min_y, bb_max_x, bb_max_y),
            glyph_layouts,
        }
    }
}

impl<'a> From<&'a [Contour]> for Shape {
    fn from(contours: &'a [Contour]) -> Shape {
        let segments = contours.iter().flat_map(|contour| {
            once(Segment::Start {
                count: contour.segments.len(),
            })
            .chain(contour.segments.iter().map(|segment| match segment {
                FontSegment::Line(line) => Segment::Line {
                    line: Line {
                        p0: Point2::new(line.p[0].x, line.p[0].y),
                        p1: Point2::new(line.p[1].x, line.p[1].y),
                    },
                },
                FontSegment::Curve(curve) => Segment::Curve {
                    curve: Curve {
                        p0: Point2::new(curve.p[0].x, curve.p[0].y),
                        p1: Point2::new(curve.p[1].x, curve.p[1].y),
                        p2: Point2::new(curve.p[2].x, curve.p[2].y),
                    },
                },
            }))
        });

        Shape::from_iter(segments)
    }
}