Text rendering with OpenGL and C++


, , , , , , , , , , , , ,

Most words are drivel, a substitute for beautiful space. One can never say ‘horse radish’ enough, true, though putting devious pickles to one side we are left cupping hot air. Someone’s hot filthy air, stinking of the last egg sandwich.

But not so with the Oculus Rift virtual reality headset! Slip it on and one yearns for words to shape our virtual world.

Lucky that Learn OpenGL article Text Rendering is at hand.

I cranked up my C++ Microsoft Visual Studio application (with the Oculus SDK for Windows and OpenGL graphics library) and added some text to a TV screen:

The pixels on my headset tell me that the pixels on the virtual TV set say “Number of coins: 0”. That’s no good. One is impotent in a virtual land without a purse bulging with treasure.

Thankfully there is a pig at hand, floating in the air. If I munch it I will receive a coin. Don’t ask why, just revel in a double benefit:

It has worked! The text rendering code has dynamically updated to “Number of coins: 1”.

As the Learn OpenGL article demonstrates, rendering the text is no trivial matter.

First we must download FreeType to help us. I also copy the Arial font from the C:\Windows\Fonts folder into my application folder, for consumption.

We need to turn on OpenGL Blending so that each character of our text stands out from its background.

Since I am rendering text in a 3D world I also incorporate its Z position into the code, adding it to the view and projection matrix I am sending to the shaders:

Matrix4f combined = proj * view * Matrix4f::Translation(Vector3f(0.0, 0.0, textPos.z));

All that’s left is to plop the text on top of the TV screen on each render cycle, dynamically adjusting it to the number of coins we currently possess:

std::string coinsText = "Number of coins: " + std::to_string(possessionClient->GetCoins());

Of course, rendering text in VR has some specific considerations, as outlined in article Modern Game UI with the Oculus Rift – Part 2

Still. Vital words. Clean words. World turns without a gallon of oil on its hinges.