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
use glin::gl;
use glin::CreationContext;
use gl::types::GLenum;

use rin_graphics::Mesh;
use rin_graphics::Vertex2DTex;
use rin_graphics::projection::CoordinateOrigin;
use rin_graphics as graphics;
use rin_math::{Rect, Vec3, Vec2, Pnt2, vec3};
pub use rin_graphics::ttf::{Shape, BoxCoordinatesX, BoxCoordinatesY, BoxFlags, BoxMesh};

use color::{ToRgba,Rgba};

use std::f32;
use std::rc::Rc;

use rin_util::{Result, Error};
use glin::RenderSurface;
use glin::uniforms;
use std::cell::{RefCell, Ref, Cell};

use super::{CreationProxy, Renderer};

// FIXME: implement drop we need TextureFont free impl
pub struct Ttf{
    ttf: graphics::Ttf,
    gamma: f32,
    texture: Rc<RefCell<glin::Texture>>,
    pixel: Vec3,
    used: Cell<usize>,
    context: CreationProxy,
}

pub struct Builder<'a>{
    ttf_builder: graphics::ttf::Builder<'a>,
    context: CreationProxy,
    gamma: f32,
}

impl<'a> Builder<'a>{
    pub(crate) fn new(context: CreationProxy, path: &'a str, pt_height: f32) -> Builder<'a>{
        Builder{
            ttf_builder: graphics::ttf::Builder::new(path, pt_height),
            context,
            gamma: 1.0,
        }
    }

    pub(crate) fn from_bytes(context: CreationProxy, bytes: &'a [u8], pt_height: f32) -> Builder<'a>{
        Builder{
            ttf_builder: graphics::ttf::Builder::from_bytes(bytes, pt_height),
            context,
            gamma: 1.0,
        }
    }

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

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

    pub fn build(self) -> Result<Ttf>{
        let ttf = self.ttf_builder.build()?;
        let texture = Ttf::texture_for(&self.context, &ttf)?;

        let vgamma = if ttf.antialiasing_type() == graphics::ttf::Antialiasing::LCD && self.gamma>-0.01 && self.gamma<0.01 {
            0.01
        }else{
            self.gamma
        };

        let pixel = if vgamma>-0.01 && vgamma<0.01{
            vec3!(0.0)
        }else{
            vec3(1.0/texture.width() as f32, 1.0/texture.height() as f32, ttf.antialiasing_type() as i32 as f32)
        };

        let used = ttf.freetypegl().atlas().used();

        Ok( Ttf{
            ttf,
            gamma: vgamma,
            texture:  Rc::new(RefCell::new(texture)),
            pixel,
            used: Cell::new(used),
            context: self.context,
        })
    }
}

impl Ttf{

    /// distance between baselines
    pub fn line_height(&self) -> f32{
        self.ttf.line_height()
    }

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

    /// distance between the baseline and bottom of the lowest character in the
    /// font
    pub fn descender(&self) -> f32{
        self.ttf.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.ttf.line_gap()
    }

    /// level of antialiasing, this value should be read by renderers and
    /// applied on rendering, doesn't affect the loaded glyphs, default is 1.0
    pub fn gamma(&self) -> f32{
        self.gamma
    }

    /// returns the type of antialiasing of this font
    pub fn antialiasing_type(&self) -> graphics::ttf::Antialiasing{
        self.ttf.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, pos: &Pnt2, coordinate_origin: CoordinateOrigin) -> Mesh<Vertex2DTex>{
        self.ttf.mesh(string, pos, coordinate_origin)
    }

    // 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, pos: &Pnt2, coordinate_origin: CoordinateOrigin) -> Rect<f32>{
        self.ttf.bounding_box(string, pos, coordinate_origin)
    }

    /// returns the mesh of a text so it fits in a box of the size and position
    /// passed as parameters, if h is some height, it will stop drawing the text
    /// before the next line overflows the specified height. Otherwise it won't
    /// adjust for height
    pub fn box_mesh<H>(
        &self,
        string: &str,
        pos: &Pnt2,
        w: BoxCoordinatesX,
        h: H,
        coordinate_origin: CoordinateOrigin,
        flags: BoxFlags) -> BoxMesh<Vertex2DTex>
    where H: Into<Option<BoxCoordinatesY>>
    {
        self.ttf.box_mesh(string, pos, w, h, coordinate_origin, flags)
    }

    /// returns the total height of a box of text with width w
    pub fn box_size(&self, string: &str, w: BoxCoordinatesX) -> Vec2{
        self.ttf.box_size(string, w)
    }

    /// 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, pos: &Pnt2, coordinate_origin: CoordinateOrigin) -> Pnt2 {
        self.ttf.next_pos(string, pos, 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_iter<'a>(
        &'a self,
        string: &'a str,
        pos: &'a Pnt2,
        coordinate_origin: CoordinateOrigin) -> impl Iterator<Item = Shape> + 'a
    {
        self.ttf.shape_iter(string, pos, coordinate_origin)
    }

    /// 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_iter<'a, H>(
        &'a self,
        string: &'a str,
        pos: &Pnt2,
        w: BoxCoordinatesX,
        h: H,
        coordinate_origin: CoordinateOrigin,
        flags: BoxFlags) -> impl Iterator<Item = Shape> + 'a
    where H: Into<Option<BoxCoordinatesY>> + 'a
    {
        self.ttf.box_shape_iter(string, pos, w, h, coordinate_origin, flags)
    }

    pub fn texture(&self) -> Ref<glin::Texture> {
        self.texture.borrow()
    }

    pub fn material<C: ToRgba>(&self, color: &C) -> Material{
        let color: Rgba<f32> = color.to_rgba().to_standard();
        let mut uniforms = uniforms!{
            font_color: color,
            font_texture: &*self.texture.borrow(),
        };
        if self.gamma.abs()>0.01{
            uniforms.push(glin::program::uniform("gamma", &self.gamma));
            uniforms.push(glin::program::uniform("pixel", &self.pixel));
        }
        self.update_texture();
        Material{
            texture: self.texture.clone(),
            color: Some(color),
            gamma: self.gamma,
            pixel: self.pixel,
            uniforms,
            used: self.used.get(),
        }
    }

    pub fn material_no_color(&self) -> Material{
        let mut uniforms = uniforms!{
            font_texture: &*self.texture.borrow(),
        };
        if self.gamma.abs()>0.01{
            uniforms.push(glin::program::uniform("gamma", &self.gamma));
            uniforms.push(glin::program::uniform("pixel", &self.pixel));
        }
        self.update_texture();
        Material{
            texture: self.texture.clone(),
            color: None,
            gamma: self.gamma,
            pixel: self.pixel,
            uniforms,
            used: self.used.get(),
        }
    }

    #[cfg(not(any(feature="gles", feature="webgl")))]
    fn texture_internal_for_aa(aa: graphics::ttf::Antialiasing) -> GLenum{
        match aa{
            graphics::ttf::Antialiasing::None => gl::R8,
            graphics::ttf::Antialiasing::Gray => gl::R8,
            graphics::ttf::Antialiasing::LCD  => gl::RGB8
        }
    }

    #[cfg(any(feature="gles", feature="webgl"))]
    fn texture_internal_for_aa(aa: graphics::ttf::Antialiasing) -> GLenum{
        match aa{
            graphics::ttf::Antialiasing::None => gl::LUMINANCE,
            graphics::ttf::Antialiasing::Gray => gl::LUMINANCE,
            graphics::ttf::Antialiasing::LCD  => gl::RGB
        }
    }

    #[cfg(not(any(feature="gles", feature="webgl")))]
    fn texture_format_for_aa(aa: graphics::ttf::Antialiasing) -> GLenum{
        match aa{
            graphics::ttf::Antialiasing::None => gl::RED,
            graphics::ttf::Antialiasing::Gray => gl::RED,
            graphics::ttf::Antialiasing::LCD  => gl::RGB
        }
    }

    #[cfg(any(feature="gles", feature="webgl"))]
    fn texture_format_for_aa(aa: graphics::ttf::Antialiasing) -> GLenum{
        match aa{
            graphics::ttf::Antialiasing::None => gl::LUMINANCE,
            graphics::ttf::Antialiasing::Gray => gl::LUMINANCE,
            graphics::ttf::Antialiasing::LCD  => gl::RGB
        }
    }

    pub fn texture_for(context: &CreationProxy, ttf: &graphics::Ttf) -> Result<glin::Texture>{
        let tex_internal = Ttf::texture_internal_for_aa(ttf.antialiasing_type());
        let mut texture = context.new_texture()
            .from_format(glin::texture::Format::new(
                tex_internal,
                ttf.freetypegl().atlas().width() as u32,
                ttf.freetypegl().atlas().height() as u32
            )).map_err(|e| Error::with_cause("Error creating texture", e))?;

        texture
            .load_data(ttf.freetypegl().atlas().data(), Default::default())
            .map_err(|e| Error::with_cause("Error uploading texture", e))?;
        Ok(texture)
    }

    fn update_texture(&self) {
        if self.used.get() != self.ttf.freetypegl().atlas().used() {
            if self.ttf.freetypegl().atlas().width() != self.texture.borrow().width() as usize
                || self.ttf.freetypegl().atlas().width() != self.texture.borrow().height() as usize
            {
                *self.texture.borrow_mut() = Ttf::texture_for(&self.context, &self.ttf).unwrap();
            }else{
                self.texture.borrow_mut()
                    .load_data(self.ttf.freetypegl().atlas().data(), Default::default())
                    .unwrap();
            }
            self.used.set(self.ttf.freetypegl().atlas().used());
        }
    }
}

pub struct MaterialBuilder<'a>{
    context: CreationProxy,
    color: Option<Rgba<f32>>,
    gamma: f32,
    ttf: &'a graphics::Ttf
}

impl<'a> MaterialBuilder<'a>{
    pub(super) fn new(context: CreationProxy, ttf: &graphics::Ttf) -> MaterialBuilder{
        MaterialBuilder{
            context,
            color: None,
            gamma: 1.0,
            ttf,
        }
    }

    pub fn color<C: ToRgba>(&mut self, color: &C) -> &mut MaterialBuilder<'a>{
        self.color = Some(color.to_rgba().to_standard());
        self
    }

    pub fn gamma(&mut self, gamma: f32) -> &mut MaterialBuilder<'a>{
        self.gamma = gamma;
        self
    }

    pub fn build(&mut self) -> Result<Material>{
        Ttf::texture_for(&self.context, self.ttf).map(|texture|{
            let gamma = self.gamma;
            let pixel = vec3(
                1.0/texture.width() as f32,
                1.0/texture.height() as f32,
                self.ttf.antialiasing_type() as i32 as f32);

            let uniforms = if let Some(color) = self.color {
                uniforms!{
                    font_color: color,
                    font_texture: texture,
                    gamma: gamma,
                    pixel: pixel,
                }
            }else{
                uniforms!{
                    font_texture: texture,
                    gamma: gamma,
                    pixel: pixel,
                }
            };

            Material{
                color: self.color,
                gamma: self.gamma,
                pixel,
                texture: Rc::new(RefCell::new(texture)),
                uniforms,
                used: self.ttf.freetypegl().atlas().used(),
            }
        })
    }
}

pub struct Material{
    color: Option<Rgba<f32>>,
    gamma: f32,
    pixel: Vec3,
    texture: Rc<RefCell<glin::Texture>>,
    uniforms: Vec<glin::program::Uniform>,
    used: usize,
}

impl Material{
    pub fn texture(&self) -> Ref<glin::Texture>{
        self.texture.borrow()
    }

    pub fn set_color<C: ToRgba>(&mut self, color: &C){
        self.color = Some(color.to_rgba().to_standard());
        self.regenerate_uniforms();
    }

    pub fn no_color(&mut self){
        self.color = None;
        self.regenerate_uniforms();
    }

    pub fn set_gamma(&mut self, gamma: f32){
        self.gamma = gamma;
        self.regenerate_uniforms();
    }

    pub fn update(&mut self, ttf: &graphics::Ttf) -> Result<()> {
        if self.used != ttf.freetypegl().atlas().used(){
            if ttf.freetypegl().atlas().width() != self.texture.borrow().width() as usize
                || ttf.freetypegl().atlas().width() != self.texture.borrow().height() as usize
            {
                return Err(Error::new("The font used to update a ttf Material, has different dimensions than the one used originally"))
            }

            let tex_format = Ttf::texture_format_for_aa(ttf.antialiasing_type());
            self.texture.borrow_mut()
                .load_data(ttf.freetypegl().atlas().data(), Default::default())
                .map_err(|e| Error::with_cause("Error uploading texture", e))?;
            self.used = ttf.freetypegl().atlas().used();
        }

        Ok(())
    }

    fn regenerate_uniforms(&mut self){
        self.uniforms.clear();

        if let Some(color) = self.color.as_ref() {
            self.uniforms.push(glin::program::uniform("font_color", color));
        }

        self.uniforms.push(glin::program::uniform("font_texture", &*self.texture.borrow()));

        if self.gamma.abs()>0.01{
            self.uniforms.push(glin::program::uniform("gamma", &self.gamma));
            self.uniforms.push(glin::program::uniform("pixel", &self.pixel));
        }
    }
}

impl crate::Material for Material{
    fn program<R: RenderSurface>(&self, renderer: &Renderer<R>) -> &glin::Program{
        if self.color.is_some(){
            shaders::get_ttf_program(renderer)
        }else{
            shaders::get_ttf_program_no_global_color(renderer)
        }
    }

    fn uniforms<R: RenderSurface>(&self, _gl: &Renderer<R>) -> &[glin::program::Uniform]{
        &self.uniforms
    }

    fn properties(&self) -> &[glin::Property]{
    	&[
    		glin::Property::Blend(true),
            glin::Property::BlendFuncSeparate(
                gl::SRC_ALPHA,
                gl::ONE_MINUS_SRC_ALPHA,
                gl::ONE,
                gl::ONE_MINUS_SRC_ALPHA,
            )
    	]
    }
}

#[cfg(not(any(feature="gles", feature="webgl")))]
mod shaders{
    program_cache!("shaders/vertex_ttf.glsl", "shaders/fragment_ttf.glsl", get_ttf_program, SHADER_TTF);
    program_cache!(glin::program::Settings{
        version: crate::default_glsl_version(),
        extensions: vec![],
        precision: glin::program::ShaderPrecision::High,
        defines: vec![
            ("USE_GLOBAL_COLOR",  "0"),
        ],
        shaders: vec![
            (glin::gl::VERTEX_SHADER, include_str!("shaders/vertex_ttf.glsl")),
            (glin::gl::FRAGMENT_SHADER, include_str!("shaders/fragment_ttf.glsl")),
        ],
        bindings: crate::default_attribute_bindings().clone(),
        base_path: "",
        .. Default::default()
    }, get_ttf_program_no_global_color, SHADER_TTF_NO_GLOBAL_COLOR);
}

#[cfg(any(feature="gles", feature="webgl"))]
mod shaders{
    program_cache!("shaders/vertex_ttf_gles.glsl", "shaders/fragment_ttf_gles.glsl", get_ttf_program, SHADER_TTF);
}