4
votes

I've been trying to have text rendering in my OpenGL scene using SDL2. The tutorial I came across is this one Rendering text

I followed the same code, and I get text rendering fine. However the issue I'm having is that there is obviously a "conflict" between the OpenGL rendering and the SDL_Renderer used in the code. When I run my scene the text displays but everything else keeps flickering. The following gif shows the issue:

enter image description here

Any idea on how to overcome this while still just using SDL2 and OpenGL, not another library or anything.

1
Maybe this answer could help you: stackoverflow.com/a/5289823/1175077jpw
@jpw I'm using SDL2, so restricted to using SDL_CreateWindow rather than SDL_SetVideoModeKakalokia

1 Answers

1
votes

Try render SDL text in texture like:

SDL_Texture* renderText(const std::string &message, const std::string &fontFile,
    SDL_Color color, int fontSize, SDL_Renderer *renderer)
{
    //Open the font
    TTF_Font *font = TTF_OpenFont(fontFile.c_str(), fontSize);
    if (font == nullptr){
        logSDLError(std::cout, "TTF_OpenFont");
        return nullptr;
    }   
    //We need to first render to a surface as that's what TTF_RenderText
    //returns, then load that surface into a texture
    SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color);
    if (surf == nullptr){
        TTF_CloseFont(font);
        logSDLError(std::cout, "TTF_RenderText");
        return nullptr;
    }
    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf);
    if (texture == nullptr){
        logSDLError(std::cout, "CreateTexture");
    }
    //Clean up the surface and font
    SDL_FreeSurface(surf);
    TTF_CloseFont(font);
    return texture;
}

See http://www.willusher.io/sdl2%20tutorials/2013/12/18/lesson-6-true-type-fonts-with-sdl_ttf/

Bind SDL_Texture

void SDL_BindTexture(SDL_Texture *t)
{
  glBindTexture(GL_TEXTURE_2D, t->id);
}

And draw using glDrawArrays() like:

const GLfloat quadVertices[] = { -1.0f, 1.0f, 0.0f, 
    1.0f, 1.0f, 0.0f, 
    1.0f,-1.0f, 0.0f,
    -1.0f,-1.0f, 0.0f
}; 

glVertexPointer(3, GL_FLOAT, 0, quadVertices);
glDrawArrays(GL_QUADS, 0, 4);