Cross-Platform Game Programming with gameplay3d/Text and Fonts

Importing fonts into gameplay3d edit

Gameplay3d supports TrueType fonts, but these must first be converted to a gameplay bundle file (see Cross-Platform Game Programming with gameplay3d/gameplay3d_Design_Concepts#Creating_and_importing_assets) before use in your project.

Use the following steps to import a font into your project:

  • Find or create a TrueType font file (.ttf).
  • Pass the .ttf file to the gameplay-encoder command line tool and specify the size you want. A pre-compiled version of gameplay-encoder is available under GamePlay/bin:

gameplay-encoder -s 28 myfont.ttf

  • The gameplay-encoder will output a .gpb file.
  • Copy the .gpb file to your game's resource directory. (The .ttf file does not need to be included.)
  • Import your font into your project as follows:

// Create a font from the gpb file
Font* _font = Font::create("res/myfont.gpb");

Drawing text with a Font edit

To render using a font:

  • first, call Font::start() on your font instance to start text drawing;
  • second, call Font::drawText() to draw some text at a defined location. There are four different overloads for this function, the parameters for which can be found in Font.h; and
  • finally, call Font::start() to finish text batching for the relevant font and render all drawn text.

Here is an example of loading a font and using it to render the game's frame rate on the screen.

void MyGame::initialize()
{
    // Create a font from the gpb file
    _font = Font::create("res/myfont.gpb");
}

void MyGame::render(float elapsedTime)
{
    // Clear the frame buffer
    clear(CLEAR_COLOR_DEPTH, Vector4(0, 0, 0, 1), 1.0f, 0);

    // Draw the text at position 20,20 using red color
    _font->start();
    char text[1024];
    sprintf(text, "FPS:%d", Game::getFrameRate());
    _font->drawText(text, 20, 20, Vector4(1, 0, 0, 1), _font->getSize());
    _font->finish();
}

void MyGame::finalize()
{
    // Use built-in macros to clean up our resources.
    SAFE_RELEASE(_font);
}

Batching edit

It is possible to call Font::drawText() multiple times between Font::start() and Font::finish() in order to draw different text in different places with the same font.

High-quality text using distance fields edit

Since version 2.0.0, gameplay3d supports distance field fonts. You can read more about distance field fonts in the Valve paper Improved Alpha-Tested Magnification for Vector Textures and Special Effects but, in short, distance fonts look a lot better than bitmap fonts, particularly at high magnification!

To create a distance field font, use the -f:d option parameter when running gameplay-encoder, e.g.:

gameplay-encoder -s 50 -f:d myfont.ttf