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
extern crate freetypegl;

use self::freetypegl::{TextureFont, TextureGlyph};

use mesh::Mesh;
use vertex::Vertex2DTex;
use projection::CoordinateOrigin;

use na::*;
use io::read_asset;
use math::Rect;

use util::{Result, Error};
use std::f32;

/// antialiasing types
///
/// NoAA   -> no antialiasing
/// GrayAA -> normal antialiasing
/// LCDAA  -> subpixel antialiasing
///
/// the antialiasing should be applied by the renderer, but
/// the LCD type loads a 3 channels texture instead of 1
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum Antialiasing{
    None=0,
    Gray=1,
    LCD=3
}

// FIXME: implement drop we need TextureFont free impl
pub struct Ttf{
    font: TextureFont,
    antialiasing_type: Antialiasing,
}

pub struct Builder<'a>{
    path: Option<&'a str>,
    bytes: Option<&'a [u8]>,
    pt_height: f32,
    antialiasing: Antialiasing,
}

impl<'a> Builder<'a>{
    pub fn new(path: &'a str, pt_height: f32) -> Builder<'a>{
        Builder{
            path: Some(path),
            bytes: None,
            pt_height,
            antialiasing: Antialiasing::LCD,
        }
    }

    pub fn from_bytes(bytes: &'a [u8], pt_height: f32) -> Builder<'a>{
        Builder{
            path: None,
            bytes: Some(bytes),
            pt_height,
            antialiasing: Antialiasing::LCD,
        }
    }

    pub fn antialiasing(mut self, antialiasing: Antialiasing) -> Builder<'a>{
        self.antialiasing = antialiasing;
        self
    }

    pub fn create(self) -> Result<Ttf>{
        let buffer = if let Some(path) = self.path{
    		match read_asset(path){
    		    Ok(buffer) => buffer,
    		    Err(err) => return Err(Error::with_cause("Error openning font file", err)),
    		}
        }else{
            self.bytes.unwrap().to_vec()
        };

        let tex_font = TextureFont::load_from_memory(buffer, self.pt_height, self.antialiasing as usize);

        Ok( Ttf{
            font: tex_font,
            antialiasing_type: self.antialiasing,
        })
    }
}

impl Ttf{
    /// distance between baselines
    pub fn line_height(&self) -> f32{
        self.font.height()
    }

    /// distance between baseline and top of highest character in the font
    pub fn ascender(&self) -> f32{
        self.font.ascender()
    }

    /// distance between the baseline and bottom of the lowest character in the
    /// font
    pub fn descender(&self) -> f32{
        self.font.descender()
    }

    /// distance between the bottom of the lowest character in the font and the
    /// top of the highest character if they were put in consecutive lines.
    /// separation between 2 lines
    pub fn line_gap(&self) -> f32{
        self.font.linegap()
    }

    /// returns the type of antialiasing of this font
    pub fn antialiasing_type(&self) -> Antialiasing{
        self.antialiasing_type
    }

    /// returns the mesh for the string passed, put this mesh in a vao when
    /// drawing the same text for a long time or use a renderer draw_string
    /// function if it changes very often
    pub fn mesh(&self, string: &str, x: f32, y: f32, coordinate_origin: CoordinateOrigin) -> Mesh<Vertex2DTex>{
        let mut mesh = Mesh::default();

        self.shape(string,x,y,coordinate_origin, |bl, tr, glyph|{
            append_glyph(&mut mesh,bl,tr,glyph);
        });
        mesh
    }

    // pub fn vao(&self, string: &str, x: f32, y: f32, coordinate_origin: CoordinateOrigin) -> glin::Result<glin::SimpleVao<Vertex2DTexture>>{
    //     self.mesh(string, x, y, coordinate_origin)
    //         .to_simple_vao(&self.context, &::default_attribute_bindings(), gl::STATIC_DRAW)
    // }

    /// returns the bounding box of a text drawn from a mesh returned by like
    /// the mesh function like gl::draw_string or other renderers do
    pub fn bounding_box(&self, string: &str, x: f32, y: f32, coordinate_origin: CoordinateOrigin) -> Rect<f32>{
        if string.is_empty(){
            Rect{pos: pnt2(x,y), width: 0., height: 0.}
        }else{
            let mut min = pnt2(f32::MAX as f32, f32::MAX as f32);
            let mut max = pnt2(f32::MIN as f32, f32::MIN as f32);
            self.shape(string,x,y,coordinate_origin, |bl, tr, _glyph|{
                min.x = min.x.min(bl.x);
                min.y = min.y.min(bl.y);
                max.x = max.x.max(tr.x);
                max.y = max.y.max(tr.y);
            });
            Rect{pos: min, width: max.x-min.x, height: max.y-min.y}
        }
    }

    /// returns the mesh of a text so it fits in a box of the size and position
    /// passed as parameters, if h<0 it won't adjust for height, if not it'll
    /// stop drawing the text before the next line overflows the specified
    /// height
    pub fn box_mesh(&self, string: &str, x: f32, y: f32, w: f32, h: f32, coordinate_origin: CoordinateOrigin) -> Mesh<Vertex2DTex>{
        let mut mesh = Mesh::default();

        self.box_shape(string,x,y,w,h,coordinate_origin,|word,x_word,y_word|{
            self.shape(word,x_word,y_word,coordinate_origin, |bl, tr, glyph|{
                append_glyph(&mut mesh,bl,tr,glyph);
            });
        });
        mesh
    }

    /// returns the total height of a box of text with width w
    pub fn box_height(&self, string: &str, w: f32) -> f32{
        self.box_shape(string,0.0,0.0,w,-1.0,CoordinateOrigin::TopLeft,|_,_,_|())
    }

    /// returns the position where a text should be drawn to correctly appear
    /// next to the one passed as parameter. the kerning with the next character
    /// is of course not added since we don't know which will be that next
    /// character yet, and should be added when rendering the next string
    pub fn next_pos(&self, string: &str, x: f32, y: f32, coordinate_origin: CoordinateOrigin) -> Vec2{
        self.shape(string,x,y,coordinate_origin,|_,_,_|())
    }

    /// useful for advanced layout, calls back the f closure for each glyph
    /// passing the bottom left and top right corners where it should be drawn
    /// after applying kerning and the glyph itself which contains information
    /// like it's ascendent, descendent, offset, width...
    /// http://www.freetype.org/freetype2/docs/tutorial/step2.html#section-1
    pub fn shape<F>(&self, string: &str, x: f32, y: f32, coordinate_origin: CoordinateOrigin, mut f: F) -> Vec2
		where F: FnMut(Vec2, Vec2, &TextureGlyph){ //Fn(bottom_left,top_right,glyph)
        let mut xpos = x;
        let mut ypos = match coordinate_origin{
			CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp => y,
			CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown => y - self.line_height(),
		};
        let line_height = match coordinate_origin{
			CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp => self.line_height(),
			CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown => -self.line_height(),
		};

        for l in string.lines(){
        	xpos = x;
        	ypos -= line_height;
        	let mut prevc = '\0';
        	for (i,c) in l.chars().enumerate(){
	            let glyph = self.font.glyph(c);

	            if i > 0 {
	                xpos+= glyph.kerning(prevc);
	            }

		        let (bl,tr) = match coordinate_origin{
					CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp => {
			            let x0  = ( xpos + glyph.offset_x() as f32 ) as i32 as f32;
			            let y1  = ( ypos + glyph.offset_y() as f32 ) as i32 as f32;
			            let x1  = ( x0 + glyph.width() as f32 ) as i32 as f32;
			            let y0  = ( y1 - glyph.height() as f32 ) as i32 as f32;
			            (vec2(x0,y0),vec2(x1,y1))
					}
					CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown => {
			            let x0  = ( xpos + glyph.offset_x() as f32 ) as i32 as f32;
			            let y0  = ( ypos - glyph.offset_y() as f32 ) as i32 as f32;
			            let x1  = ( x0 + glyph.width() as f32 ) as i32 as f32;
			            let y1  = ( y0 + glyph.height() as f32 ) as i32 as f32;
			            (vec2(x0,y1),vec2(x1,y0))
					}
				};

	            f(bl,tr,&glyph);

	            xpos += glyph.advance_x();
	            prevc = c;
	        }
        }
        vec2(xpos,ypos)
    }

    /// useful for advanced layout, calls back the f closure for each glyph
    /// passing the bottom left and top right corners where it should be drawn
    /// after applying kerning and the glyph itself which contains information
    /// like it's ascendent, descendent, offset, width...
    /// http://www.freetype.org/freetype2/docs/tutorial/step2.html#section-1
    pub fn shape_iter<'a>(&'a self, string: &'a str, x: f32, y: f32, coordinate_origin: CoordinateOrigin) -> ShapeIter<'a> {
        let mut xpos = x;
        let mut ypos = match coordinate_origin{
			CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp => y,
			CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown => y - self.line_height(),
		};
        let line_height = match coordinate_origin{
			CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp => self.line_height(),
			CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown => -self.line_height(),
		};

        let iter = Box::new(string.lines().flat_map(move |l|{
        	xpos = x;
        	ypos -= line_height;
        	let mut prevc = '\0';
        	l.chars().enumerate().map(move |(i,c)|{
	            let glyph = self.font.glyph(c);

	            if i > 0 {
	                xpos+= glyph.kerning(prevc);
	            }

		        let (bl,tr) = match coordinate_origin{
					CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp => {
			            let x0  = ( xpos + glyph.offset_x() as f32 ) as i32 as f32;
			            let y1  = ( ypos + glyph.offset_y() as f32 ) as i32 as f32;
			            let x1  = ( x0 + glyph.width() as f32 ) as i32 as f32;
			            let y0  = ( y1 - glyph.height() as f32 ) as i32 as f32;
			            (pnt2(x0,y0), pnt2(x1,y1))
					}
					CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown => {
			            let x0  = ( xpos + glyph.offset_x() as f32 ) as i32 as f32;
			            let y0  = ( ypos - glyph.offset_y() as f32 ) as i32 as f32;
			            let x1  = ( x0 + glyph.width() as f32 ) as i32 as f32;
			            let y1  = ( y0 + glyph.height() as f32 ) as i32 as f32;
			            (pnt2(x0,y1), pnt2(x1,y0))
					}
				};

	            xpos += glyph.advance_x();
	            prevc = c;

                Shape{
                    rect: Rect{ pos: bl, width: tr.x - bl.x, height: tr.y - bl.y},
                    glyph,
                    character: c
                }
	        })
        }));

        ShapeIter{ iter }
    }


    /// useful for advanced box layout, calculates the layout of text fitted in
    /// a box of w x h and calls back the f closure for each word passing the x
    /// and y coordinates where it should be drawn, combined with shape it
    /// can be used to calculate the layout for each glyph on the text.
    /// returns the final height of the bounding box for the resulting text
    pub fn box_shape<F>(&self, string: &str, x: f32, y: f32, w: f32, h: f32, coordinate_origin: CoordinateOrigin, mut f: F) -> f32
		where F: FnMut(&str, f32, f32) { //Fn(word, x, y)
        let line_height = self.line_height();
        let mut ypos = y;
        let mut xpos = x;
        let mut first_char = true;
        let space_glyph = self.font.glyph(' ');

        ypos -= self.ascender();

        for paragraph in string.lines(){
            for word in paragraph.split_whitespace(){
                let word_width = self.next_pos(word,0.0,0.0,coordinate_origin).x;
                if !first_char && xpos + word_width > x + w + 1.0{
                    ypos -= line_height;
                    if h>0.0 && ypos < y - h as f32{
                        ypos -= self.descender();
                        return y - ypos;
                    }
                    xpos = x;
                }
                first_char = false;

                f(vec!(word.to_string(), " ".to_string()).concat().as_ref(),xpos,ypos);

                xpos += word_width + space_glyph.advance_x();
                //TODO: do we need to calculate the kerning of the first char
                //of the next word with the space? perhaps pass previous char to
                //shape?
            }

            ypos -= line_height;
            xpos = x;
            first_char = true;
            if h>0.0 && ypos < y - h as f32{
                break;
            }
        }

        ypos -= self.descender();

        // return final height of the box layout
        y - ypos
    }

    pub fn freetypegl(&self) -> &TextureFont{
        &self.font
    }
}

pub struct Shape{
    pub rect: Rect<f32>,
    pub glyph: TextureGlyph,
    pub character: char,
}

pub struct ShapeIter<'a>{
    iter: Box<Iterator<Item=Shape> + 'a>
}

impl<'a> Iterator for ShapeIter<'a>{
    type Item = Shape;
    fn next(&mut self) -> Option<Shape>{
        self.iter.next()
    }
}


pub fn append_glyph(mesh: &mut Mesh<Vertex2DTex>, bl: Vec2, tr: Vec2, glyph: &TextureGlyph){
    mesh.push(Vertex2DTex{ position: bl, texcoord: vec2(glyph.s0(), glyph.t1()) });
    mesh.push(Vertex2DTex{ position: vec2(tr.x, bl.y), texcoord: vec2(glyph.s1(), glyph.t1()) });
    mesh.push(Vertex2DTex{ position: tr, texcoord: vec2(glyph.s1(), glyph.t0()) });

    mesh.push(Vertex2DTex{ position: bl, texcoord: vec2(glyph.s0(), glyph.t1()) });
    mesh.push(Vertex2DTex{ position: tr, texcoord: vec2(glyph.s1(), glyph.t0()) });
    mesh.push(Vertex2DTex{ position: vec2(bl.x,tr.y), texcoord: vec2(glyph.s0(), glyph.t0()) });
}