Debian Codegraph @

src/LomiriMetrics/bitmaptext.cpp

raw
1 // Copyright © 2016 Canonical Ltd.
2 // Author: Loïc Molinari <[email protected]>
3 //
4 // This file is part of Lomiri UI Toolkit.
5 //
6 // Lomiri UI Toolkit is free software: you can redistribute it and/or modify it
7 // under the terms of the GNU Lesser General Public License as published by the
8 // Free Software Foundation; version 3.
9 //
10 // Lomiri UI Toolkit is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
13 // for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public License
16 // along with Lomiri UI Toolkit. If not, see <http://www.gnu.org/licenses/>.
17
18 #include <math.h>
19
20 #include <QtCore/QtGlobal>
21 #include <QtCore/QPoint>
22 #include <QtCore/QSize>
23
24 #include "bitmaptext_p.h"
25 #include "bitmaptextfont_p.h"
26 #include "lomirimetricsglobal_p.h"
27
28 static const GLchar* bitmapTextVertexShaderSource =
29 // See "The OpenGL® ES Shading Language", section 3.4 Preprocessor,
30 // for "GL_ES" macro.
31 // https://www.khronos.org/registry/OpenGL/specs/es/2.0/GLSL_ES_Specification_1.00.pdf
32 "#ifndef GL_ES \n"
33 "# define highp \n"
34 "# define mediump \n"
35 "# define lowp \n"
36 "#endif \n"
37 "attribute highp vec4 positionAttrib; \n"
38 "attribute mediump vec2 textureCoordAttrib; \n"
39 "varying mediump vec2 textureCoord; \n"
40 "uniform highp vec4 transform; \n"
41 "void main(void) \n"
42 "{ \n"
43 " gl_Position = vec4((positionAttrib.xy * transform.xy) + transform.zw, 0.0, 1.0); \n"
44 " textureCoord = textureCoordAttrib; \n"
45 "} \n";
46
47 static const GLchar* bitmapTextFragmentShaderSource =
48 "#ifndef GL_ES \n"
49 "# define highp \n"
50 "# define mediump \n"
51 "# define lowp \n"
52 "#endif \n"
53 "varying mediump vec2 textureCoord; \n"
54 "uniform sampler2D texture; \n"
55 "uniform lowp float opacity; \n"
56 "void main() \n"
57 "{ \n"
58 " gl_FragColor = texture2D(texture, textureCoord) * vec4(opacity); \n"
59 "} \n";
60
61 const int bitmapTextDefaultFontSize = 16;
62 const float bitmapTextDefaultOpacity = 1.0f;
63 const float bitmapTextCarriageReturnHeight = 1.5f;
64
65 BitmapText::BitmapText()
66 : m_functions(nullptr)
67 #if !defined QT_NO_DEBUG
68 , m_context(nullptr)
69 #endif
70 , m_vertexBuffer(nullptr)
71 , m_textToVertexBuffer(nullptr)
72 , m_textLength(0)
73 , m_characterCount(0)
74 , m_flags(0)
75 {
76 // Set current font based on requested font size.
77 const int fontSize = qBound(
78 static_cast<int>(g_bitmapTextFont.font[0].size), bitmapTextDefaultFontSize & (INT_MAX - 1),
79 static_cast<int>(g_bitmapTextFont.font[g_bitmapTextFont.fontCount-1].size));
80 for (int i = 0; i < g_bitmapTextFont.fontCount; i++) {
81 if (static_cast<int>(g_bitmapTextFont.font[i].size) == fontSize) {
82 m_currentFont = i;
83 break;
84 }
85 }
86 }
87
88 BitmapText::~BitmapText()
89 {
90 delete [] m_vertexBuffer;
91 delete [] m_textToVertexBuffer;
92 }
93
94 static GLuint createProgram(QOpenGLFunctions* functions, const char* vertexShaderSource,
95 const char* fragmentShaderSource, GLuint* vertexShaderObject,
96 GLuint* fragmentShaderObject)
97 {
98 GLuint program;
99 GLuint vertexShader;
100 GLuint fragmentShader;
101 GLint status;
102
103 vertexShader = functions->glCreateShader(GL_VERTEX_SHADER);
104 fragmentShader = functions->glCreateShader(GL_FRAGMENT_SHADER);
105 if (vertexShader == 0 || fragmentShader == 0) {
106 WARN("ApplicationMonitor: glCreateShader() failed (OpenGL error: %d).", functions->glGetError());
107 return 0;
108 }
109
110 functions->glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
111 functions->glCompileShader(vertexShader);
112 functions->glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
113 if (status == GL_FALSE) {
114 #if !defined(QT_NO_DEBUG)
115 char infoLog[2048];
116 functions->glGetShaderInfoLog(vertexShader, 2048, nullptr, infoLog);
117 WARN("ApplicationMonitor: Vertex shader compilation failed:\n%s", infoLog);
118 #endif
119 return 0;
120 }
121
122 functions->glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr);
123 functions->glCompileShader(fragmentShader);
124 functions->glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
125 if (status == GL_FALSE) {
126 #if !defined(QT_NO_DEBUG)
127 char infoLog[2048];
128 functions->glGetShaderInfoLog(fragmentShader, 2048, nullptr, infoLog);
129 WARN("ApplicationMonitor: Fragment shader compilation failed:\n%s", infoLog);
130 #endif
131 return 0;
132 }
133
134 program = functions->glCreateProgram();
135 functions->glAttachShader(program, vertexShader);
136 functions->glAttachShader(program, fragmentShader);
137 functions->glLinkProgram(program);
138 functions->glGetProgramiv(program, GL_LINK_STATUS, &status);
139 if (status == GL_FALSE) {
140 #if !defined(QT_NO_DEBUG)
141 char infoLog[2048];
142 functions->glGetProgramInfoLog(program, 2048, nullptr, infoLog);
143 WARN("ApplicationMonitor: Shader linking failed:\n%s", infoLog);
144 #endif
145 return 0;
146 }
147
148 *vertexShaderObject = vertexShader;
149 *fragmentShaderObject = fragmentShader;
150
151 return program;
152 }
153
154 bool BitmapText::initialize()
155 {
156 DASSERT(!(m_flags & Initialized));
157 DASSERT(QOpenGLContext::currentContext());
158
159 m_functions = QOpenGLContext::currentContext()->functions();
160 #if !defined QT_NO_DEBUG
161 m_context = QOpenGLContext::currentContext();
162 #endif
163
164 m_functions->glGenTextures(1, &m_texture);
165 m_functions->glBindTexture(GL_TEXTURE_2D, m_texture);
166 m_functions->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, g_bitmapTextFont.textureWidth,
167 g_bitmapTextFont.textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE,
168 g_bitmapTextFont.textureData);
169 m_functions->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
170 m_functions->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
171 m_functions->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
172 m_functions->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
173
174 m_program = createProgram(
175 m_functions, bitmapTextVertexShaderSource, bitmapTextFragmentShaderSource,
176 &m_vertexShaderObject, &m_fragmentShaderObject);
177 if (m_program != 0) {
178 m_functions->glBindAttribLocation(m_program, 0, "positionAttrib");
179 m_functions->glBindAttribLocation(m_program, 1, "textureCoordAttrib");
180 m_functions->glUniform1i(m_functions->glGetUniformLocation(m_program, "texture"), 0);
181 m_programTransform = m_functions->glGetUniformLocation(m_program, "transform");
182 m_programOpacity = m_functions->glGetUniformLocation(m_program, "opacity");
183 m_functions->glUniform1f(m_programOpacity, bitmapTextDefaultOpacity);
184 }
185
186 m_functions->glGenBuffers(1, &m_indexBuffer);
187
188 if (m_texture && m_program && m_indexBuffer) {
189 #if !defined QT_NO_DEBUG
190 m_flags |= Initialized;
191 #endif
192 return true;
193 } else {
194 return false;
195 }
196 }
197
198 void BitmapText::finalize()
199 {
200 DASSERT(m_flags & Initialized);
201 DASSERT(m_context == QOpenGLContext::currentContext());
202
203 if (m_texture) {
204 m_functions->glDeleteTextures(1, &m_texture);
205 m_texture = 0;
206 }
207
208 if (m_program) {
209 m_functions->glDeleteProgram(m_program);
210 m_functions->glDeleteShader(m_vertexShaderObject);
211 m_functions->glDeleteShader(m_fragmentShaderObject);
212 m_program = 0;
213 m_vertexShaderObject = 0;
214 m_fragmentShaderObject = 0;
215 }
216
217 if (m_indexBuffer) {
218 m_functions->glDeleteBuffers(1, &m_indexBuffer);
219 m_indexBuffer = 0;
220 }
221
222 m_functions = nullptr;
223 #if !defined QT_NO_DEBUG
224 m_context = nullptr;
225 m_flags &= ~Initialized;
226 #endif
227 }
228
229 void BitmapText::setText(const char* text)
230 {
231 DASSERT(m_flags & Initialized);
232
233 int textLength = 0;
234 int characterCount = 0;
235
236 // Count the number of printable characters and get the given text length.
237 if (text) {
238 while (text[textLength] != '\0') {
239 const char character = text[textLength++];
240 if (character >= 32 && character <= 126) { // Printable characters.
241 characterCount++;
242 }
243 }
244 }
245
246 // Clean up and update info.
247 if (m_characterCount) {
248 delete [] m_vertexBuffer;
249 delete [] m_textToVertexBuffer;
250 }
251 if (characterCount) {
252 m_textLength = textLength;
253 m_characterCount = characterCount;
254 m_flags |= NotEmpty;
255 } else {
256 // Early exit if the given text is null, empty or filled with non
257 // printable characters.
258 m_vertexBuffer = nullptr;
259 m_textToVertexBuffer = nullptr;
260 m_textLength = 0;
261 m_characterCount = 0;
262 m_flags &= ~NotEmpty;
263 return;
264 }
265
266 // Fill the index buffer. The GL_TRIANGLES primitive mode requires 3 indices
267 // per triangle, so 6 per character.
268 GLushort* indices = new GLushort [6 * characterCount];
269 for (int i = 0; i < characterCount; i++) {
270 const GLushort currentIndex = i * 6;
271 const GLushort currentVertex = i * 4;
272 indices[currentIndex] = currentVertex;
273 indices[currentIndex+1] = currentVertex + 1;
274 indices[currentIndex+2] = currentVertex + 2;
275 indices[currentIndex+3] = currentVertex + 2;
276 indices[currentIndex+4] = currentVertex + 1;
277 indices[currentIndex+5] = currentVertex + 3;
278 }
279 m_functions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
280 m_functions->glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * characterCount * sizeof(GLushort),
281 indices, GL_STATIC_DRAW); // Deletes and replaces the old data.
282 delete [] indices;
283
284 // Allocate and fill the vertex buffer and the text to vertex buffer array.
285 m_vertexBuffer = new Vertex [characterCount * 4];
286 m_textToVertexBuffer = new int [textLength];
287 const float fontY = static_cast<float>(g_bitmapTextFont.font[m_currentFont].y);
288 const float fontWidth = static_cast<float>(g_bitmapTextFont.font[m_currentFont].width);
289 const float fontHeight = static_cast<float>(g_bitmapTextFont.font[m_currentFont].height);
290 const float fontWidthNormalized = fontWidth / g_bitmapTextFont.textureWidth;
291 const float fontHeightNormalized = fontHeight / g_bitmapTextFont.textureHeight;
292 const float t1 = fontY / g_bitmapTextFont.textureHeight;
293 const float t2 = (fontHeight + fontY) / g_bitmapTextFont.textureHeight;
294 float x = 0.0f;
295 float y = 0.0f;
296 characterCount = 0;
297 for (int i = 0; i < textLength; i++) {
298 char character = text[i];
299 if (character >= ' ' && character <= '~') { // Printable characters.
300 const int index = characterCount * 4;
301 // The atlas stores 2 lines per font size, second line starts at
302 // ASCII character 80 at position 49 in the bitmap.
303 const float s = ((character - ' ') % '0') * fontWidthNormalized;
304 const float t = (character < 80) ? t1 : t2;
305 m_vertexBuffer[index].x = x;
306 m_vertexBuffer[index].y = y;
307 m_vertexBuffer[index].s = s;
308 m_vertexBuffer[index].t = t;
309 m_vertexBuffer[index+1].x = x;
310 m_vertexBuffer[index+1].y = y + 1.0f;
311 m_vertexBuffer[index+1].s = s;
312 m_vertexBuffer[index+1].t = t + fontHeightNormalized;
313 m_vertexBuffer[index+2].x = x + 1.0f;
314 m_vertexBuffer[index+2].y = y;
315 m_vertexBuffer[index+2].s = s + fontWidthNormalized;
316 m_vertexBuffer[index+2].t = t;
317 m_vertexBuffer[index+3].x = x + 1.0f;
318 m_vertexBuffer[index+3].y = y + 1.0f;
319 m_vertexBuffer[index+3].s = s + fontWidthNormalized;
320 m_vertexBuffer[index+3].t = t + fontHeightNormalized;
321 x += 1.0f;
322 m_textToVertexBuffer[i] = characterCount++;
323 } else if (character == '\n') {
324 x = 0.0f;
325 y += 1.0f;
326 m_textToVertexBuffer[i] = -1;
327 } else if (character == '\r') {
328 x = 0.0f;
329 y += bitmapTextCarriageReturnHeight;
330 m_textToVertexBuffer[i] = -1;
331 } else {
332 m_textToVertexBuffer[i] = -1;
333 }
334 }
335 }
336
337 void BitmapText::updateText(const char* text, int index, int length)
338 {
339 DASSERT(m_flags & Initialized);
340 DASSERT(text);
341 DASSERT(index >= 0 && index <= m_textLength);
342 DASSERT(index + length <= m_textLength);
343
344 const float fontY = static_cast<float>(g_bitmapTextFont.font[m_currentFont].y);
345 const float fontWidth = static_cast<float>(g_bitmapTextFont.font[m_currentFont].width);
346 const float fontHeight = static_cast<float>(g_bitmapTextFont.font[m_currentFont].height);
347 const float fontWidthNormalized = fontWidth / g_bitmapTextFont.textureWidth;
348 const float fontHeightNormalized = fontHeight / g_bitmapTextFont.textureHeight;
349 const float t1 = fontY / g_bitmapTextFont.textureHeight;
350 const float t2 = (fontHeight + fontY) / g_bitmapTextFont.textureHeight;
351
352 for (int i = index, j = 0; i < index + length; i++, j++) {
353 int vertexBufferIndex = m_textToVertexBuffer[i];
354 const char character = text[j];
355 if (vertexBufferIndex != -1 && character >= 32 && character <= 126) {
356 const float s = ((character - ' ') % '0') * fontWidthNormalized;
357 const float t = (character < 80) ? t1 : t2;
358 vertexBufferIndex *= 4;
359 m_vertexBuffer[vertexBufferIndex].s = s;
360 m_vertexBuffer[vertexBufferIndex].t = t;
361 m_vertexBuffer[vertexBufferIndex+1].s = s;
362 m_vertexBuffer[vertexBufferIndex+1].t = t + fontHeightNormalized;
363 m_vertexBuffer[vertexBufferIndex+2].s = s + fontWidthNormalized;
364 m_vertexBuffer[vertexBufferIndex+2].t = t;
365 m_vertexBuffer[vertexBufferIndex+3].s = s + fontWidthNormalized;
366 m_vertexBuffer[vertexBufferIndex+3].t = t + fontHeightNormalized;
367 }
368 }
369 }
370
371 void BitmapText::bindProgram()
372 {
373 DASSERT(m_context == QOpenGLContext::currentContext());
374 DASSERT(m_flags & Initialized);
375
376 m_functions->glUseProgram(m_program);
377 }
378
379 void BitmapText::setTransform(const QSize& viewportSize, const QPointF& position)
380 {
381 DASSERT(m_context == QOpenGLContext::currentContext());
382 DASSERT(m_flags & Initialized);
383 DASSERT(viewportSize.width() > 0.0f);
384 DASSERT(viewportSize.height() > 0.0f);
385 DASSERT(!qIsNaN(position.x()));
386 DASSERT(!qIsNaN(position.y()));
387
388 // The transform stores a scale (in (x, y)) and translate (in (z, w)) used
389 // to put vertices in the right space ((-1, 1), (-1, 1)), at the right
390 // position.
391 const float transform[4] = {
392 (2.0f * g_bitmapTextFont.font[m_currentFont].width) / viewportSize.width(),
393 -(2.0f * g_bitmapTextFont.font[m_currentFont].height) / viewportSize.height(),
394 ((2.0f * roundf(position.x())) / viewportSize.width()) - 1.0f,
395 ((2.0f * -roundf(position.y())) / viewportSize.height()) + 1.0f
396 };
397 m_functions->glUniform4fv(m_programTransform, 1, transform);
398 }
399
400 void BitmapText::setOpacity(float opacity)
401 {
402 DASSERT(m_context == QOpenGLContext::currentContext());
403 DASSERT(m_flags & Initialized);
404 DASSERT(opacity >= 0.0f && opacity <= 1.0f);
405
406 m_functions->glUniform1f(m_programOpacity, opacity);
407 }
408
409 void BitmapText::render()
410 {
411 DASSERT(m_context == QOpenGLContext::currentContext());
412 DASSERT(m_flags & Initialized);
413
414 if (m_flags & NotEmpty) {
415 m_functions->glVertexAttribPointer(
416 0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), reinterpret_cast<char*>(m_vertexBuffer));
417 m_functions->glVertexAttribPointer(
418 1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
419 reinterpret_cast<char*>(m_vertexBuffer) + (2 * sizeof(float)));
420 m_functions->glEnableVertexAttribArray(0);
421 m_functions->glEnableVertexAttribArray(1);
422 m_functions->glBindTexture(GL_TEXTURE_2D, m_texture);
423 m_functions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
424 m_functions->glDisable(GL_DEPTH_TEST); // QtQuick renderers restore that at each draw call.
425 m_functions->glEnable(GL_BLEND);
426 m_functions->glDrawElements(GL_TRIANGLES, 6 * m_characterCount, GL_UNSIGNED_SHORT, 0);
427 }
428 }