Using SDL_ttf with OpenGL

Khedesh picture Khedesh · Mar 13, 2011 · Viewed 12.4k times · Source

I'm using OpenGL and SDL to create a window in my program.

How do I use SDL_ttf with an OpenGL window?

For example I want to load a font and render some text. I want to draw the text using an SDL OpenGL surface.

Answer

Antti picture Antti · Mar 13, 2011

Here's how to do it:

  1. Initialize SDL and SDL_ttf, and create a window using SDL_SetVideoMode(). Make sure you pass the SDL_OPENGL flag.
  2. Initialize your OpenGL scene (glViewport(), glMatrixMode() etc.).
  3. Render your text with SDL_ttf using e.g. TTF_RenderUTF8_Blended(). The render functions return an SDL_surface, which you have to convert into an OpenGL texture by passing a pointer to the data (surface->pixels) to OpenGL as well as the format of the data. Like this:

    colors = surface->format->BytesPerPixel;
    if (colors == 4) {   // alpha
        if (surface->format->Rmask == 0x000000ff)
            texture_format = GL_RGBA;
        else
            texture_format = GL_BGRA;
    } else {             // no alpha
        if (surface->format->Rmask == 0x000000ff)
            texture_format = GL_RGB;
        else
            texture_format = GL_BGR;
    }
    
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture); 
    glTexImage2D(GL_TEXTURE_2D, 0, colors, surface->w, surface->h, 0,
                        texture_format, GL_UNSIGNED_BYTE, surface->pixels);
    
  4. Then you can use the texture in OpenGL using glBindTexture() etc. Make sure to call SDL_GL_SwapBuffers() when you're done with drawing.