summaryrefslogtreecommitdiff
path: root/Runtime/GUI/UITextMesh.cpp
blob: 7fc261468bcbe411ed8dd4df2eebd2b7a03e017a (plain)
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
#include "../Graphics/CustomVertexLayout.h"
#include "Runtime/Utilities/StaticInitiator.h"
#include "../Math/Math.h"
#include "../Graphics/Color.h"
#include "UITextMesh.h"
#include "../Graphics/DefaultVertexLayout.h"
#include "Runtime/Debug/Log.h"
#include <vector>
#include <unordered_map>
#include "Runtime/Graphics/GfxDevice.h"

using namespace std;

struct TextMeshVBOLayout
{
	Vector2 position;
	Vector2 uv;
	Color32 color;
};

static CustomVertexLayout s_TextMeshVBOLayout;

static unsigned int s_VertexPerText;
static unsigned int s_SizePerVertex;
static unsigned int s_SizePerText;
static unsigned int s_SizePerIndex;
static unsigned int s_IndicesPerText;

struct TextInfo {
	const Character* ch;
	float offset;
    int line; // 从0开始
};

static unordered_map<unsigned int, vector<TextInfo>> s_TextInfos;

InitializeStaticVariables([]() {
	VertexAttributeDescriptor POSITION = VertexAttributeDescriptor(0, 2, VertexAttrFormat_Float, sizeof(TextMeshVBOLayout));
	VertexAttributeDescriptor UV = VertexAttributeDescriptor(sizeof(Vector2), 2, VertexAttrFormat_Float, sizeof(TextMeshVBOLayout));
	VertexAttributeDescriptor COLOR = VertexAttributeDescriptor(sizeof(Vector2)*2, 4, VertexAttrFormat_Unsigned_Byte, sizeof(TextMeshVBOLayout), true);
	s_TextMeshVBOLayout.attributes.push_back(POSITION);
	s_TextMeshVBOLayout.attributes.push_back(UV);
	s_TextMeshVBOLayout.attributes.push_back(COLOR);

	s_VertexPerText = 4;
	s_SizePerVertex = sizeof(TextMeshVBOLayout);

    s_IndicesPerText = 6;
    s_SizePerIndex = VertexLayout::GetDefaultIndexSize();

	s_SizePerText = sizeof(TextMeshVBOLayout) * 4;
});

// 一段文字里面的网格可能会来自不同的atlas,在生成UITextMesh时做好合批

// 需要支持
// * 大小
// * 锚点
// * 对齐方式
// * 换行
// * 颜色

// lineheight 用来处理换行、锚点
// wordwrap 自动换行
// preferredSize 自动换行区域大小
UITextMesh::UITextMesh(const UnicodeString& str, Font* font, int pixelSize, int lineHeight, ETextAnchor anchor, ETextAlignment alignment, bool wordwrap, float preferred)
{
	s_TextInfos.clear();

    // 记录文本每行的长度
    static unordered_map<int, int> s_LineWidths;
    s_LineWidths.clear();

    // 记录每行的偏移长度
    static unordered_map<int, int> s_LineOffsets;
    s_LineOffsets.clear();

    m_Font = font;
    const Vector2 atlasSize = font->GetAtlasSize();

    //-----------------------------------------------------------------
    // 处理了换行和自动换行之后的文本区域大小
    Vector2 textRegion;
    // 按照不同的atlas分类到s_TextInfos
	float offset = 0;
    int line = 0;
	for (int i = 0; i < str.length; ++i)
	{
		character::Unicode c = str.str[i];
		const Character* ch = font->GetCharacter(c, pixelSize);
        if (ch == NULL)
            continue;

        if (wordwrap) // 自动换行
        {
            if (offset + ch->bearing.x + ch->position.width > preferred)
            {
                
                ++line;
                offset = 0;
            }
        }

		unsigned int atlasIndex = ch->atlas;
        if (atlasIndex != FONT_NOT_IN_ATLAS_PLACEHOLDER) //非空格
        {

// 换行符Unix'\n', Windows'\r\n', MacOS '\r'
#define CHECK_BREAKS() \
            if (c == '\n' || c == '\r')                                                       \
            {                                                                                 \
                ++line;                                                                       \
                offset = 0;                                                                   \
                if (c == '\r' && ((i + 1) < str.length && str.str[i + 1] == '\n')) /*skip\n*/ \
                    ++i;                                                                      \
                continue;                                                                     \
            }

            CHECK_BREAKS();

            TextInfo info;
            info.ch = ch;
            info.offset = offset;
            info.line = line;

            auto list = s_TextInfos.find(atlasIndex);
            if (list == s_TextInfos.end())
                s_TextInfos.insert(std::pair<unsigned int, vector<TextInfo>>(atlasIndex, vector<TextInfo>()));

            vector<TextInfo>& v = s_TextInfos[atlasIndex];
            v.push_back(info);
        }
        else
        {
            // 有些字体换行没有字形,所以也需要在这里处理
            CHECK_BREAKS();
        }

		offset += ch->advance;

        textRegion.x = max(offset, textRegion.x);

        if (s_LineWidths.count(line) == 0)
            s_LineWidths.insert(std::pair<int, int>(line, 0));
        s_LineWidths[line] = max(offset, s_LineWidths[line]);
	}

    textRegion.y = (line + 1) * lineHeight;

	if (s_TextInfos.size() == 0)
		return;

    Vector2i textOffset;
    Vector2 halfRegion = Vector2(textRegion.x/ 2.f, textRegion.y / 2.f);
    switch (anchor)
    {
        case TextAnchor_UpperLeft:    textOffset.Set(0,             0);             break;
        case TextAnchor_UpperCenter:  textOffset.Set(-halfRegion.x, 0);             break;
        case TextAnchor_UpperRight:   textOffset.Set(-textRegion.x, 0);             break;
        case TextAnchor_MiddleLeft:   textOffset.Set(0,             -halfRegion.y); break;
        case TextAnchor_MiddleCenter: textOffset.Set(-halfRegion.x, -halfRegion.y); break;
        case TextAnchor_MiddleRight:  textOffset.Set(-textRegion.x, -halfRegion.y); break;
        case TextAnchor_LowerLeft:    textOffset.Set(0,             -textRegion.y); break;
        case TextAnchor_LowerCenter:  textOffset.Set(-halfRegion.x, -textRegion.y); break;
        case TextAnchor_LowerRight:   textOffset.Set(-textRegion.x, -textRegion.y); break;
    }

    for (int i = 0; i < line; ++i)
    {
        int lineLen = s_LineWidths.count(i) != 0 ? s_LineWidths[i] : 0;
        int lineOffset = 0;
        switch (alignment)
        {
            case TextAlignment_Left: lineOffset = 0; break;
            case TextAlignment_Center: lineOffset = (textRegion.x - lineLen)/2.f; break;
            case TextAlignment_Right: lineOffset = textRegion.x - lineLen; break;
        }
        s_LineOffsets.insert(std::pair<int, int>(i, lineOffset));
    }

    //-----------------------------------------------------------------

    // 填充VBO和IBO
	for (auto iter : s_TextInfos) {
		unsigned int atlasIndex = iter.first; // atlas atlasIndex
		vector<TextInfo>& texts = iter.second;
		int textCount = texts.size();

		VertexBuffer* vb = new VertexBuffer(textCount * s_SizePerText, textCount * s_IndicesPerText * s_SizePerIndex, VertexBuffer::VertexBufferType_Static);
        void* pVB;
        uint16* pIB;

        vb->GetChunk(s_SizePerVertex, s_SizePerIndex, s_VertexPerText * textCount, s_IndicesPerText * textCount, EPrimitive::Primitive_Triangle, &pVB,(void**) &pIB);

        TextMeshVBOLayout* dst = (TextMeshVBOLayout*)pVB;
        for (int i = 0; i < textCount; ++i)
        {
            TextInfo& text = texts[i];

            int vOff = i * s_VertexPerText;
            int lineXOff = s_LineOffsets.count(text.line) ? s_LineOffsets[text.line] : 0;
            int lineYOff = text.line * lineHeight;
			// 左上角是原点
            float pos[] = {
				textOffset.x + lineXOff + text.offset + text.ch->bearing.x,                           textOffset.y + lineYOff + pixelSize - text.ch->bearing.y + text.ch->position.height, // bottom-left
				textOffset.x + lineXOff + text.offset + text.ch->bearing.x + text.ch->position.width, textOffset.y + lineYOff + pixelSize - text.ch->bearing.y + text.ch->position.height, // bottom-right 
				textOffset.x + lineXOff + text.offset + text.ch->bearing.x + text.ch->position.width, textOffset.y + lineYOff + pixelSize - text.ch->bearing.y,                            // top-right 
				textOffset.x + lineXOff + text.offset + text.ch->bearing.x,                           textOffset.y + lineYOff + pixelSize - text.ch->bearing.y,                            // top-left 
            };
            Vector4 uvQuad = Vector4(text.ch->position.x / atlasSize.x, text.ch->position.y / atlasSize.y, text.ch->position.width / atlasSize.x, text.ch->position.height / atlasSize.y);
            float uv[] = {
                uvQuad.x,            uvQuad.y + uvQuad.w,
                uvQuad.x + uvQuad.z, uvQuad.y + uvQuad.w,
                uvQuad.x + uvQuad.z, uvQuad.y,
                uvQuad.x,            uvQuad.y,
            };
            for (int j = 0; j < s_VertexPerText; ++j)
            {
                dst[vOff + j].position.Set(pos[2 * j], pos[2 * j + 1]);
                dst[vOff + j].uv.Set(uv[2 * j], uv[2 * j + 1]);
                dst[vOff + j].color.Set(255 , 255, 255, 255);
            }

            int iOff = i * s_IndicesPerText;
            int indices[] = {
                0, 1, 3, // right-top  
                1, 2, 3, // left-bottom
            };
            for (int j = 0; j < s_IndicesPerText; ++j)
                pIB[iOff + j] = vOff + indices[j];
        }

        vb->FlushChunk(s_VertexPerText * textCount, s_IndicesPerText * textCount);

        m_VBOs.insert(std::pair<int, VertexBuffer*>(atlasIndex, vb));
	}

    WipeGLError();
}

void UITextMesh::Draw()
{
    for (auto subText : m_VBOs)
    {
        int atlasIndex = subText.first; // atlasIndex of atlas
        VertexBuffer* vbo = subText.second; 

        const GlyphAtals* atlas = m_Font->GetGlyphAtlas(atlasIndex);
        if (atlas == NULL)
        {
            log_error("Render text failed, no glyph atlas.");
            continue;
        }

        g_GfxDevice.SetUniformTexture("gamelab_main_tex", atlas->altas);

        WipeGLError();
        vbo->Draw(s_TextMeshVBOLayout);

        WipeGLError();
        g_GfxDevice.ResetUniformsState();
    }
}