aboutsummaryrefslogtreecommitdiffstats
path: root/dev/MinGfx/src/text_shader.h
blob: a075cd295d1cf30acbffd9c55bfe689a65892017 (plain) (blame)
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
/*
 This file is part of the MinGfx Project.
 
 Copyright (c) 2017,2018 Regents of the University of Minnesota.
 All Rights Reserved.
 
 Original Author(s) of this File:
	Dan Keefe, 2018, University of Minnesota
	
 Author(s) of Significant Updates/Modifications to the File:
	...
 */

#ifndef SRC_TEXT_SHADER_H_
#define SRC_TEXT_SHADER_H_

#include <string>
#include <map>

#include "matrix4.h"
#include "mesh.h"
#include "shader_program.h"
#include "texture2d.h"

// disable warnings for this 3rd party code
#pragma warning ( push, 0 )
#include <stb_truetype.h>
#pragma warning ( pop )

namespace mingfx {
    


/**
 */
class TextShader {
public:
    TextShader();
    virtual ~TextShader();
    
    /// Call this from within the InitOpenGL() function since it will initialize
    /// not just the Font's internal data but also an OpenGL texture to be
    /// stored on the graphics card.  Internally, this uses the stb_truetype
    /// library to load true type fonts (files with a .ttf extension).
    bool Init(const std::string &font_file, int native_font_size);
    
    enum class HorizAlign {
        HORIZ_ALIGN_LEFT,
        HORIZ_ALIGN_CENTER,
        HORIZ_ALIGN_RIGHT
    };

    enum class VertAlign {
        VERT_ALIGN_TOP,
        VERT_ALIGN_CENTER,
        VERT_ALIGN_BASELINE,
        VERT_ALIGN_BOTTOM
    };
    
    class TextFormat {
    public:
        // constructor sets defaults
        TextFormat() :
            size(0.1f),
            color(1,1,1,1),
            h_align(HorizAlign::HORIZ_ALIGN_CENTER),
            v_align(VertAlign::VERT_ALIGN_BASELINE) {}
        
        float size;
        Color color;
        HorizAlign h_align;
        VertAlign v_align;
    };
    

    //void Draw2D(const Point2 &pos,
    //            const std::string &text, TextFormat format, bool cache=false);

    
    void Draw3D(const Matrix4 &model, const Matrix4 &view, const Matrix4 &projection,
                const std::string &text, TextFormat format, bool cache=false);

    
    Vector2 TextExtents(const std::string &text, TextFormat format, bool cache=false);
    
    float native_font_size();
    
private:
    Texture2D atlas_;
    float native_font_size_;
    
    stbtt_packedchar chardata_[128];
    
    struct MeshData {
        Mesh mesh;
        Point2 min;
        Point2 max;
    };
    
    void SetTextMesh(const std::string &text, MeshData *md);

    std::map<std::string, MeshData> cache_;
    MeshData tmp_md_;

    ShaderProgram shader_;
};
    
} // end namespace

#endif