Text-Rendering.html (24833B)
1 <h1 id="content-title">Text Rendering</h1> 2 <h1 id="content-url" style='display:none;'>In-Practice/Text-Rendering</h1> 3 <p> 4 At some stage of your graphics adventures you will want to draw text in OpenGL. Contrary to what you may expect, getting a simple string to render on screen is all but easy with a low-level API like OpenGL. If you don't care about rendering more than 128 different same-sized characters, then it's probably not too difficult. Things are getting difficult as soon as each character has a different width, height, and margin. Based on where you live, you may also need more than 128 characters, and what if you want to express special symbols for like mathematical expressions or sheet music symbols, and what about rendering text from top to bottom? Once you think about all these complicated matters of text, it wouldn't surprise you that this probably doesn't belong in a low-level API like OpenGL. 5 </p> 6 7 <p> 8 Since there is no support for text capabilities within OpenGL, it is up to us to define a system for rendering text to the screen. There are no graphical primitives for text characters, we have to get creative. Some example techniques are: drawing letter shapes via <var>GL_LINES</var>, create 3D meshes of letters, or render character textures to 2D quads in a 3D environment. 9 </p> 10 11 <p> 12 Most developers choose to render character textures onto quads. Rendering textured quads by itself shouldn't be too difficult, but getting the relevant character(s) onto a texture could prove challenging. In this chapter we'll explore several methods and implement a more advanced, but flexible technique for rendering text using the FreeType library. 13 </p> 14 15 <h2>Classical text rendering: bitmap fonts</h2> 16 <p> 17 In the early days, rendering text involved selecting a font (or create one yourself) you'd like for your application and extracting all relevant characters out of this font to place them within a single large texture. Such a texture, that we call a <def>bitmap font</def>, contains all character symbols we want to use in predefined regions of the texture. These character symbols of the font are known as <def>glyphs</def>. Each glyph has a specific region of texture coordinates associated with them. Whenever you want to render a character, you select the corresponding glyph by rendering this section of the bitmap font to a 2D quad. 18 </p> 19 20 <img src="/img/in-practice/bitmapfont.png" alt="Sprite sheet of characters"/> 21 22 <p> 23 Here you can see how we would render the text 'OpenGL' by taking a bitmap font and sampling the corresponding glyphs from the texture (carefully choosing the texture coordinates) that we render on top of several quads. By enabling <a href="https://learnopengl.com/Advanced-OpenGL/Blending" target="_blank">blending</a> and keeping the background transparent, we will end up with just a string of characters rendered to the screen. This particular bitmap font was generated using Codehead's Bitmap <a href="http://www.codehead.co.uk/cbfg/" target="_blank">Font Generator</a>. 24 </p> 25 26 <p> 27 This approach has several advantages and disadvantages. It is relatively easy to implement and because bitmap fonts are pre-rasterized, they're quite efficient. However, it is not particularly flexible. When you want to use a different font, you need to recompile a complete new bitmap font and the system is limited to a single resolution; zooming will quickly show pixelated edges. Furthermore, it is limited to a small character set, so Extended or Unicode characters are often out of the question. 28 </p> 29 30 <p> 31 This approach was quite popular back in the day (and still is) since it is fast and works on any platform, but as of today more flexible approaches exist. One of these approaches is loading TrueType fonts using the FreeType library. 32 </p> 33 34 <h2>Modern text rendering: FreeType</h2> 35 <p> 36 FreeType is a software development library that is able to load fonts, render them to bitmaps, and provide support for several font-related operations. It is a popular library used by Mac OS X, Java, PlayStation, Linux, and Android to name a few. What makes FreeType particularly attractive is that it is able to load TrueType fonts. 37 </p> 38 39 <p> 40 A TrueType font is a collection of character glyphs not defined by pixels or any other non-scalable solution, but by mathematical equations (combinations of splines). Similar to vector images, the rasterized font images can be procedurally generated based on the preferred font height you'd like to obtain them in. By using TrueType fonts you can easily render character glyphs of various sizes without any loss of quality. 41 </p> 42 43 <p> 44 FreeType can be downloaded from their <a href="http://www.freetype.org/" target="_blank">website</a>. You can choose to compile the library yourself or use one of their precompiled libraries if your target platform is listed. Be sure to link to <code>freetype.lib</code> and make sure your compiler knows where to find the header files. 45 </p> 46 47 <p> 48 Then include the appropriate headers: 49 </p> 50 51 <pre><code> 52 #include <ft2build.h> 53 #include FT_FREETYPE_H 54 </code></pre> 55 56 <warning> 57 Due to how FreeType is developed (at least at the time of this writing), you cannot put their header files in a new directory; they should be located at the root of your include directories. Including FreeType like <code>#include <FreeType/ft2build.h></code> will likely cause several header conflicts. 58 </warning> 59 60 <p> 61 FreeType loads these TrueType fonts and, for each glyph, generates a bitmap image and calculates several metrics. We can extract these bitmap images for generating textures and position each character glyph appropriately using the loaded metrics. 62 </p> 63 64 <p> 65 To load a font, all we have to do is initialize the FreeType library and load the font as a <def>face</def> as FreeType likes to call it. Here we load the <code>arial.ttf</code> TrueType font file that was copied from the <code>Windows/Fonts</code> directory: 66 </p> 67 68 <pre><code> 69 FT_Library ft; 70 if (FT_Init_FreeType(&ft)) 71 { 72 std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; 73 return -1; 74 } 75 76 FT_Face face; 77 if (FT_New_Face(ft, "fonts/arial.ttf", 0, &face)) 78 { 79 std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl; 80 return -1; 81 } 82 </code></pre> 83 84 <p> 85 Each of these FreeType functions returns a non-zero integer whenever an error occurred. 86 </p> 87 88 <p> 89 Once we've loaded the face, we should define the pixel font size we'd like to extract from this face: 90 </p> 91 92 <pre class="cpp"><code> 93 FT_Set_Pixel_Sizes(face, 0, 48); 94 </code></pre> 95 96 <p> 97 The function sets the font's width and height parameters. Setting the width to <code>0</code> lets the face dynamically calculate the width based on the given height. 98 </p> 99 100 <p> 101 A FreeType face hosts a collection of glyphs. We can set one of those glyphs as the active glyph by calling <fun>FT_Load_Char</fun>. Here we choose to load the character glyph 'X': 102 </p> 103 104 <pre><code> 105 if (FT_Load_Char(face, 'X', FT_LOAD_RENDER)) 106 { 107 std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl; 108 return -1; 109 } 110 </code></pre> 111 112 <p> 113 By setting <var>FT_LOAD_RENDER</var> as one of the loading flags, we tell FreeType to create an 8-bit grayscale bitmap image for us that we can access via <code>face->glyph->bitmap</code>. 114 </p> 115 116 <p> 117 Each of the glyphs we load with FreeType however, do not have the same size (as we had with bitmap fonts). The bitmap image generated by FreeType is just large enough to contain the visible part of a character. For example, the bitmap image of the dot character '.' is much smaller in dimensions than the bitmap image of the character 'X'. For this reason, FreeType also loads several metrics that specify how large each character should be and how to properly position them. Next is an image from FreeType that shows all of the metrics it calculates for each character glyph: 118 </p> 119 120 <img src="/img/in-practice/glyph.png" alt="Image of metrics of a Glyph as loaded by FreeType"/> 121 122 <p> 123 Each of the glyphs reside on a horizontal <def>baseline</def> (as depicted by the horizontal arrow) where some glyphs sit exactly on top of this baseline (like 'X') or some slightly below the baseline (like 'g' or 'p'). These metrics define the exact offsets to properly position each glyph on the baseline, how large each glyph should be, and how many pixels we need to advance to render the next glyph. Next is a small list of the properties we'll be needing: 124 </p> 125 126 <ul> 127 <li><strong>width</strong>: the width (in pixels) of the bitmap accessed via <code>face->glyph->bitmap.width</code>.</li> 128 <li><strong>height</strong>: the height (in pixels) of the bitmap accessed via <code>face->glyph->bitmap.rows</code>.</li> 129 <li><strong>bearingX</strong>: the horizontal bearing e.g. the horizontal position (in pixels) of the bitmap relative to the origin accessed via <code>face->glyph->bitmap_left</code>.</li> 130 <li><strong>bearingY</strong>: the vertical bearing e.g. the vertical position (in pixels) of the bitmap relative to the baseline accessed via <code>face->glyph->bitmap_top</code>.</li> 131 <li><strong>advance</strong>: the horizontal advance e.g. the horizontal distance (in 1/64th pixels) from the origin to the origin of the next glyph. Accessed via <code>face->glyph->advance.x</code>.</li> 132 </ul> 133 134 <p> 135 We could load a character glyph, retrieve its metrics, and generate a texture each time we want to render a character to the screen, but it would be inefficient to do this each frame. We'd rather store the generated data somewhere in the application and query it whenever we want to render a character. We'll define a convenient <code>struct</code> that we'll store in a <fun>map</fun>: 136 </p> 137 138 <pre><code> 139 struct Character { 140 unsigned int TextureID; // ID handle of the glyph texture 141 glm::ivec2 Size; // Size of glyph 142 glm::ivec2 Bearing; // Offset from baseline to left/top of glyph 143 unsigned int Advance; // Offset to advance to next glyph 144 }; 145 146 std::map<char, Character> Characters; 147 </code></pre> 148 149 <p> 150 For this chapter we'll keep things simple by restricting ourselves to the first 128 characters of the ASCII character set. For each character, we generate a texture and store its relevant data into a <fun>Character</fun> struct that we add to the <var>Characters</var> map. This way, all data required to render each character is stored for later use. 151 </p> 152 153 <pre><code> 154 glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // disable byte-alignment restriction 155 156 for (unsigned char c = 0; c < 128; c++) 157 { 158 // load character glyph 159 if (FT_Load_Char(face, c, FT_LOAD_RENDER)) 160 { 161 std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl; 162 continue; 163 } 164 // generate texture 165 unsigned int texture; 166 <function id='50'>glGenTextures</function>(1, &texture); 167 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, texture); 168 <function id='52'>glTexImage2D</function>( 169 GL_TEXTURE_2D, 170 0, 171 GL_RED, 172 face->glyph->bitmap.width, 173 face->glyph->bitmap.rows, 174 0, 175 GL_RED, 176 GL_UNSIGNED_BYTE, 177 face->glyph->bitmap.buffer 178 ); 179 // set texture options 180 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 181 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 182 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 183 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 184 // now store character for later use 185 Character character = { 186 texture, 187 glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), 188 glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), 189 face->glyph->advance.x 190 }; 191 Characters.insert(std::pair<char, Character>(c, character)); 192 } 193 </code></pre> 194 195 <p> 196 Within the for loop we list over all the 128 characters of the ASCII set and retrieve their corresponding character glyphs. For each character: we generate a texture, set its options, and store its metrics. What is interesting to note here is that we use <var>GL_RED</var> as the texture's <code>internalFormat</code> and <code>format</code> arguments. The bitmap generated from the glyph is a grayscale 8-bit image where each color is represented by a single byte. For this reason we'd like to store each byte of the bitmap buffer as the texture's single color value. We accomplish this by creating a texture where each byte corresponds to the texture color's red component (first byte of its color vector). If we use a single byte to represent the colors of a texture we do need to take care of a restriction of OpenGL: 197 </p> 198 199 <pre class="cpp"><code> 200 glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 201 </code></pre> 202 203 <p> 204 OpenGL requires that textures all have a 4-byte alignment e.g. their size is always a multiple of 4 bytes. Normally this won't be a problem since most textures have a width that is a multiple of 4 and/or use 4 bytes per pixel, but since we now only use a single byte per pixel, the texture can have any possible width. By setting its unpack alignment to <code>1</code> we ensure there are no alignment issues (which could cause segmentation faults). 205 </p> 206 207 <p> 208 Be sure to clear FreeType's resources once you're finished processing the glyphs: 209 </p> 210 211 <pre><code> 212 FT_Done_Face(face); 213 FT_Done_FreeType(ft); 214 </code></pre> 215 216 <h3>Shaders</h3> 217 <p> 218 To render the glyphs we'll be using the following vertex shader: 219 </p> 220 221 <pre><code> 222 #version 330 core 223 layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex> 224 out vec2 TexCoords; 225 226 uniform mat4 projection; 227 228 void main() 229 { 230 gl_Position = projection * vec4(vertex.xy, 0.0, 1.0); 231 TexCoords = vertex.zw; 232 } 233 </code></pre> 234 235 <p> 236 We combine both the position and texture coordinate data into one <fun>vec4</fun>. The vertex shader multiplies the coordinates with a projection matrix and forwards the texture coordinates to the fragment shader: 237 </p> 238 239 <pre><code> 240 #version 330 core 241 in vec2 TexCoords; 242 out vec4 color; 243 244 uniform sampler2D text; 245 uniform vec3 textColor; 246 247 void main() 248 { 249 vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r); 250 color = vec4(textColor, 1.0) * sampled; 251 } 252 </code></pre> 253 254 <p> 255 The fragment shader takes two uniforms: one is the mono-colored bitmap image of the glyph, and the other is a color uniform for adjusting the text's final color. We first sample the color value of the bitmap texture. Because the texture's data is stored in just its red component, we sample the <code>r</code> component of the texture as the sampled alpha value. By varying the output color's alpha value, the resulting pixel will be transparent for all the glyph's background colors and non-transparent for the actual character pixels. We also multiply the RGB colors by the <var>textColor</var> uniform to vary the text color. 256 </p> 257 258 <p> 259 We do need to enable <a href="https://learnopengl.com/Advanced-OpenGL/Blending" target="_blank">blending</a> for this to work though: 260 </p> 261 262 <pre><code> 263 <function id='60'>glEnable</function>(GL_BLEND); 264 <function id='70'>glBlendFunc</function>(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 265 </code></pre> 266 267 <p> 268 For the projection matrix we'll be using an orthographic projection matrix. For rendering text we (usually) do not need perspective, and using an orthographic projection matrix also allows us to specify all vertex coordinates in screen coordinates if we set it up as follows: 269 </p> 270 271 <pre><code> 272 glm::mat4 projection = <function id='59'>glm::ortho</function>(0.0f, 800.0f, 0.0f, 600.0f); 273 </code></pre> 274 275 <p> 276 We set the projection matrix's bottom parameter to <code>0.0f</code> and its top parameter equal to the window's height. The result is that we specify coordinates with <code>y</code> values ranging from the bottom part of the screen (<code>0.0f</code>) to the top part of the screen (<code>600.0f</code>). This means that the point (<code>0.0</code>, <code>0.0</code>) now corresponds to the bottom-left corner. 277 </p> 278 279 <p> 280 Last up is creating a VBO and VAO for rendering the quads. For now we reserve enough memory when initiating the VBO so that we can later update the VBO's memory when rendering characters: 281 </p> 282 283 <pre><code> 284 unsigned int VAO, VBO; 285 <function id='33'>glGenVertexArrays</function>(1, &VAO); 286 <function id='12'>glGenBuffers</function>(1, &VBO); 287 <function id='27'>glBindVertexArray</function>(VAO); 288 <function id='32'>glBindBuffer</function>(GL_ARRAY_BUFFER, VBO); 289 <function id='31'>glBufferData</function>(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW); 290 <function id='29'><function id='60'>glEnable</function>VertexAttribArray</function>(0); 291 <function id='30'>glVertexAttribPointer</function>(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); 292 <function id='32'>glBindBuffer</function>(GL_ARRAY_BUFFER, 0); 293 <function id='27'>glBindVertexArray</function>(0); 294 </code></pre> 295 296 <p> 297 The 2D quad requires <code>6</code> vertices of <code>4</code> floats each, so we reserve <code>6 * 4</code> floats of memory. Because we'll be updating the content of the VBO's memory quite often we'll allocate the memory with <var>GL_DYNAMIC_DRAW</var>. 298 </p> 299 300 <h3>Render line of text</h3> 301 <p> 302 To render a character, we extract the corresponding <fun>Character</fun> struct of the <var>Characters</var> map and calculate the quad's dimensions using the character's metrics. With the quad's calculated dimensions we dynamically generate a set of 6 vertices that we use to update the content of the memory managed by the VBO using <fun><function id='90'>glBufferSubData</function></fun>. 303 </p> 304 305 <p> 306 We create a function called <fun>RenderText</fun> that renders a string of characters: 307 </p> 308 309 <pre><code> 310 void RenderText(Shader &s, std::string text, float x, float y, float scale, glm::vec3 color) 311 { 312 // activate corresponding render state 313 s.Use(); 314 <function id='44'>glUniform</function>3f(<function id='45'>glGetUniformLocation</function>(s.Program, "textColor"), color.x, color.y, color.z); 315 <function id='49'>glActiveTexture</function>(GL_TEXTURE0); 316 <function id='27'>glBindVertexArray</function>(VAO); 317 318 // iterate through all characters 319 std::string::const_iterator c; 320 for (c = text.begin(); c != text.end(); c++) 321 { 322 Character ch = Characters[*c]; 323 324 float xpos = x + ch.Bearing.x * scale; 325 float ypos = y - (ch.Size.y - ch.Bearing.y) * scale; 326 327 float w = ch.Size.x * scale; 328 float h = ch.Size.y * scale; 329 // update VBO for each character 330 float vertices[6][4] = { 331 { xpos, ypos + h, 0.0f, 0.0f }, 332 { xpos, ypos, 0.0f, 1.0f }, 333 { xpos + w, ypos, 1.0f, 1.0f }, 334 335 { xpos, ypos + h, 0.0f, 0.0f }, 336 { xpos + w, ypos, 1.0f, 1.0f }, 337 { xpos + w, ypos + h, 1.0f, 0.0f } 338 }; 339 // render glyph texture over quad 340 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, ch.textureID); 341 // update content of VBO memory 342 <function id='32'>glBindBuffer</function>(GL_ARRAY_BUFFER, VBO); 343 <function id='90'>glBufferSubData</function>(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); 344 <function id='32'>glBindBuffer</function>(GL_ARRAY_BUFFER, 0); 345 // render quad 346 <function id='1'>glDrawArrays</function>(GL_TRIANGLES, 0, 6); 347 // now advance cursors for next glyph (note that advance is number of 1/64 pixels) 348 x += (ch.Advance >> 6) * scale; // bitshift by 6 to get value in pixels (2^6 = 64) 349 } 350 <function id='27'>glBindVertexArray</function>(0); 351 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, 0); 352 } 353 </code></pre> 354 355 <p> 356 Most of the content of the function should be relatively self-explanatory: we first calculate the origin position of the quad (as <var>xpos</var> and <var>ypos</var>) and the quad's size (as <var>w</var> and <var>h</var>) and generate a set of 6 vertices to form the 2D quad; note that we scale each metric by <var>scale</var>. We then update the content of the VBO and render the quad. 357 </p> 358 359 <p> 360 The following line of code requires some extra attention though: 361 </p> 362 363 <pre><code> 364 float ypos = y - (ch.Size.y - ch.Bearing.y); 365 </code></pre> 366 367 <p> 368 Some characters (like 'p' or 'g') are rendered slightly below the baseline, so the quad should also be positioned slightly below <fun>RenderText</fun>'s <var>y</var> value. The exact amount we need to offset <var>ypos</var> below the baseline can be figured out from the glyph metrics: 369 </p> 370 371 <img src="/img/in-practice/glyph_offset.png" alt="Offset below baseline of glyph to position 2D quad"/> 372 373 <p> 374 To calculate this distance e.g. offset we need to figure out the distance a glyph extends below the baseline; this distance is indicated by the red arrow. As you can see from the glyph metrics, we can calculate the length of this vector by subtracting <code>bearingY</code> from the glyph's (bitmap) height. This value is then <code>0.0</code> for characters that rest on the baseline (like 'X') and positive for characters that reside slightly below the baseline (like 'g' or 'j'). 375 </p> 376 377 <p> 378 If you did everything correct you should now be able to successfully render strings of text with the following statements: 379 </p> 380 381 <pre><code> 382 RenderText(shader, "This is sample text", 25.0f, 25.0f, 1.0f, glm::vec3(0.5, 0.8f, 0.2f)); 383 RenderText(shader, "(C) LearnOpenGL.com", 540.0f, 570.0f, 0.5f, glm::vec3(0.3, 0.7f, 0.9f)); 384 </code></pre> 385 386 <p> 387 This should then look similar to the following image: 388 </p> 389 390 <img src="/img/in-practice/text_rendering.png" class="clean" alt="Image of text rendering with OpenGL using FreeType"/> 391 392 <p> 393 You can find the code of this example <a href="/code_viewer_gh.php?code=src/7.in_practice/2.text_rendering/text_rendering.cpp" target="_blank">here</a>. 394 </p> 395 396 <p> 397 To give you a feel for how we calculated the quad's vertices, we can disable blending to see what the actual rendered quads look like: 398 </p> 399 400 <img src="/img/in-practice/text_rendering_quads.png" class="clean" alt="Image of quads without transparency for text rendering in OpenGL"/> 401 402 <p> 403 Here you can clearly see most quads resting on the (imaginary) baseline while the quads that corresponds to glyphs like 'p' or '(' are shifted downwards. 404 </p> 405 406 <h2>Going further</h2> 407 <p> 408 This chapter demonstrated a text rendering technique with TrueType fonts using the FreeType library. The approach is flexible, scalable, and works with many character encodings. However, this approach is likely going to be overkill for your application as we generate and render textures for each glyph. Performance-wise, bitmap fonts are preferable as we only need one texture for all our glyphs. The best approach would be to combine the two approaches by dynamically generating a bitmap font texture featuring all character glyphs as loaded with FreeType. This saves the renderer from a significant amount of texture switches and, based on how tight each glyph is packed, could save quite some performance. 409 </p> 410 411 <p> 412 Another issue with FreeType font bitmaps is that the glyph textures are stored with a fixed font size, so a significant amount of scaling may introduce jagged edges. Furthermore, rotations applied to the glyphs will cause them to appear blurry. This can be mitigated by, instead of storing the actual rasterized pixel colors, storing the distance to the closest glyph outline per pixel. This technique is called <def>signed distance field fonts</def> and Valve published a <a href="https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf" target="_blank">paper</a> a few years ago about their implementation of this technique which works surprisingly well for 3D rendering applications. 413 </p> 414 415 <h2>Further reading</h2> 416 <ul> 417 <li><a href="https://www.websiteplanet.com/blog/best-free-fonts/" target="_blank">70+ Best Free Fonts for Designers</a>: summarized list of a large group of fonts to use in your project for personal or commercial use.</li> 418 </ul> 419 420 </div> 421 422 <div id="hover"> 423 HI 424 </div> 425 <!-- 728x90/320x50 sticky footer --> 426 <div id="waldo-tag-6196"></div> 427 428 <div id="disqus_thread"></div> 429 430 431 432 433 </div> <!-- container div --> 434 435 436 </div> <!-- super container div --> 437 </body> 438 </html>