Drawing text seems like it should be a free lunch, but it’s not. Simplest way is to draw a character per quad, but a naive implementation will have each character a seperate draw call. This might be fine for some simple text like ‘Level Up’ but when you have a screen of text this becomes problematic. You really want to be able to batch your calls somehow. This is how I’ve been doing it, there are other techniques out there so don’t consider this a definitive guide to text batching. Also I’m not going into how to render the text in any detail, as that really is another topic.
What I’ve done in Terminal to render text is to push all the data into a texture, use the geometry buffer to build the quad in the correct place with the correct scale, and then in the fragment shader lookup the font glyph.
This is the most expensive step, we need to build a texture with all the data inside it, and potentially update each frame.
Use this data as texture data, but we aren’t going to use GL_RGBA as our pixel format as we wont get the same data backvout of the texture. Instead we will build our texture with GL_RGBA32F, this way our values will not get clipped.
Since we are using the Geometry shader to generate the quads, we need to pass the geo shader some way to index the data texture. We could have a vertex format with an ‘id’, and generate a large vertex buffer of points, However there is a nice feature in OpenGL we can use. If you render a bunch of nothings, the vertex shader will still get called with unique gl_VertexID. We can pass this along to the geo shader to use as an index into our data texture.
Calling this (With your data texture bound of course).
We can can get the vertex id in the vertex shader (notice no input).
And pass it straight to the geo shader.
In the geometry shader we can use the vertex id combined with texelFetch (which takes an x,y co-ord into a texture) to get the information from the texture for the quads we need.
Now we can just sample from the texture that contains all the character glyphs.
Text is a big topic I purposely avoided talking about UTF-8, and the actual rendering processes as those are their own topics. Being able to batch text like this is pretty cool, I don’t see a reason why this couldn’t be extended to Sprites.