Sign in to follow this  
nitro404

OpenGL Issues with OpenGL / SDL / SDL_TTF

Recommended Posts

nitro404    103
Okay, so I'm attempting to create dynamic font loading from TTF files using SDL_TTF / SDL / OpenGL. (Also note I am using the QtCore library as well.) The general idea of what my code is doing is as follows:

Loading:
1) Generate font path and attempt to load the font using SDL_TTF
2) Render 128 characters to individual SDL_Surfaces, from character 32 to 160
3) Keep track of the size of the largest characters
4) Create a new surface to render all 128 characters onto based on the largest width and height (also make sure it is a power of 2 to prevent scaling)
5) Iterate over all 128 of the characters, rendering to them to the full surface (16x8)
6) Create an OpenGL texture from the data contained in the full surface
7) Create an OpenGL list of all of the characters for ease of use when rendering text later

Rendering:
1) Generate output text data based on format string and arguments passed in
2) Use glCallLists to render the string using the previously generated font data

It's been somewhat successful so far, but I have hit two major snags:

1) SDL_Surfaces store pixel data upside down. I've read about this issue online, but have not found any simple solutions to this. I ultimately did find some code to flip the texture upside-down, but it seemed like an unnecessary amount of code to do so - and it still didn't fix the problem. In short, if I blit to an SDL_Surface, then attempt to make an OpenGL texture out of it, the image is upside-down when rendered. And since I'm generating the image on runtime, having an upside-down input file is not an option.

2) The text shows up yellow instead of white, as specified by the SDL_Color struct. I also found others online who had this same issue, but have not managed to find a solution. When the temp SDL_Surface is allocated, I had to change the RGBA masks to BGRA instead of the usual RGBA / ABGR depending on what endian SDL is using in order to have anything show up at all. I'm not sure if I horribly messed this up or not, but it's the only thing that produces any results thus far. I also tried SDL_DisplayFormat on the surface I was generating, but no matter what I change the RGBA masks to after that, there is no output.

I have attached a quad displaying the full image output at the bottom as well as relevant source code. If anyone has any advice / tips / hints / suggestions / solutions / etc. to this problem, they would be tremendously appreciated. I'll gladly surf around the forums and help other people out as well afterwards, seeing as how this is my first post. Thanks so much!

Edit: I just realized the texture co-ordinates are semi wrong when generating the lists, they're for a 16x16 grid, but the one I'm using is 16x8. They also don't account for non-perfect fit textures (ie. whitespace on the "top" and "right" to make the texture a power of 2, to prevent automatic scaling).

Font Loading:
[code]
bool Font::load() {
if(m_loaded) { return true; }

QString fontPath = QString(Game::settings->dataDirectory);
fontPath.append("/Fonts/");
fontPath.append(m_filename);

QFileInfo fontFile(fontPath);
if(!fontFile.exists()) { return false; }

QByteArray bytes = fontPath.toLocal8Bit();

TTF_Font * fontData;
if(!(fontData = TTF_OpenFont(bytes.data(), m_size))) {
return false;
}

SDL_Color colour = {255, 255, 255, 255};

SDL_Surface * character;
QVector<SDL_Surface *> characters;
int maxWidth = -1;
int maxHeight = -1;
char data[2];
data[1] = '\0';
for(int i=0;i<128;i++ ) {
data[0] = (char) (i + 32);
character = TTF_RenderText_Blended(fontData, data, colour);
characters.push_back(character);
if(maxWidth < 0 || maxWidth < character->w) { maxWidth = character->w; }
if(maxHeight < 0 || maxHeight < character->h) { maxHeight = character->h; }
}

int width = 1, tempWidth = maxWidth * 16;
int height = 1, tempHeight = maxHeight * 8;
while(width < tempWidth) { width *= 2; }
while(height < tempHeight) { height *= 2; }

SDL_Surface * temp = SDL_CreateRGBSurface(0, width, height, 32, 0x0000ff00, 0x00ff0000, 0xff000000, 0x000000ff);

SDL_Rect sourceArea, destArea;
int x = 0;
int y = 0;
for(int i=0;i<128;i++) {
sourceArea.x = 0;
sourceArea.y = 0;
sourceArea.w = characters[i]->w;
sourceArea.h = characters[i]->h;

destArea.x = maxWidth * x;
destArea.y = maxHeight * y;
destArea.w = characters[i]->w;
destArea.h = characters[i]->h;

SDL_BlitSurface(characters[i], &sourceArea, temp, &destArea);

x++;
if(x == 16) {
x = 0;
y++;
}
}

glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

m_font = glGenLists(128);

float cx, cy;
for(int i=0;i<128;i++) {
cx = (float) (i % 16) / 16.0f;
cy = (float) (i / 16) / 16.0f;

glNewList(m_font + i, GL_COMPILE);

glBegin(GL_QUADS);
glTexCoord2f(cx, 1 - cy - 0.0625f); glVertex2i(0, m_size);
glTexCoord2f(cx + 0.0625f, 1 - cy - 0.0625f); glVertex2i(m_size, m_size);
glTexCoord2f(cx + 0.0625f, 1 - cy ); glVertex2i(m_size, 0 );
glTexCoord2f(cx, 1 - cy ); glVertex2i(0, 0 );

glEnd();

glTranslated(10, 0, 0);

glEndList();
}

for(int i=0;i<128;i++) {
SDL_FreeSurface(characters[i]);
}
SDL_FreeSurface(temp);

m_loaded = true;

return true;
}
[/code]

Text Drawing:
[code]
void Font::drawText(int x, int y, const char * format, ...) const {
if(!m_loaded) { return; }

char text[256];
va_list args;
va_start(args, format);
vsprintf_s(text, 256, format, args);
va_end(args);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

glBindTexture(GL_TEXTURE_2D, m_texture);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();

glLoadIdentity();

glTranslated(x, y, 0);
glListBase(m_font - 32);
glCallLists(strlen(text), GL_BYTE, text);

glPopMatrix();
}
[/code]

Output:
[attachment=4116:font_texture.png]

Share this post


Link to post
Share on other sites
nitro404    103
Finally solved all of the problems I was having after much frustration. Here's my solution code to anyone who has run into the same problems I have - hopefully it is helpful:

Font.h
[code]
#ifndef FONT_H
#define FONT_H

#include "SDL/SDL.h"
#include "SDL/SDL_OpenGL.h"
#include "SDL/SDL_TTF.h"
#include "Utilities.h"

class Font {
public:
Font(const char * id, const char * filename, int size);
Font(const Font & f);
Font & operator = (const Font & f);
virtual ~Font();

const char * getID() const;
const char * getFilename() const;
int getSize() const;
int getHorizontalSpacing();
int getVerticalSpacing();

void drawText(int x, int y, const char * format, ...) const;

bool load();
bool unload();
bool isLoaded() const;

bool operator == (const Font & f) const;
bool operator != (const Font & f) const;

protected:
char * m_id;
char * m_filename;
int m_size;
int m_horizontalSpacing;
int m_verticalSpacing;
GLuint m_texture;
GLuint m_font;
bool m_loaded;
};

#endif // FONT_H
[/code]

Font.cpp
[code]
#include "Game.h"
#include "Font.h"

Font::Font(const char * id, const char * filename, int size) : m_loaded(false) {
if(id == NULL) {
m_id = new char[1];
m_id[0] = '\0';
}
else {
m_id = strtrimcpy(id);
}

if(filename == NULL) {
m_filename = new char[1];
m_filename[0] = '\0';
}
else {
m_filename = strtrimcpy(filename);
}

m_size = (size < 1) ? 1 : size;
}

Font::Font(const Font & f) {
m_id = new char[strlen(f.m_id) + 1];
strcpy_s(m_id, strlen(f.m_id) + 1, f.m_id);

m_filename = new char[strlen(f.m_filename) + 1];
strcpy_s(m_filename, strlen(f.m_filename) + 1, f.m_filename);

m_size = f.m_size;
}

Font & Font::operator = (const Font & f) {
unload();
delete [] m_id;
delete [] m_filename;

m_id = new char[strlen(f.m_id) + 1];
strcpy_s(m_id, strlen(f.m_id) + 1, f.m_id);

m_filename = new char[strlen(f.m_filename) + 1];
strcpy_s(m_filename, strlen(f.m_filename) + 1, f.m_filename);

m_size = f.m_size;

return *this;
}

Font::~Font() {
unload();
delete [] m_id;
delete [] m_filename;
}

const char * Font::getID() const {
return m_id;
}

const char * Font::getFilename() const {
return m_filename;
}

int Font::getSize() const {
return m_size;
}

int Font::getHorizontalSpacing() {
return m_horizontalSpacing;
}

int Font::getVerticalSpacing() {
return m_verticalSpacing;
}

void Font::drawText(int x, int y, const char * format, ...) const {
if(!m_loaded) { return; }

char text[256];
va_list args;
va_start(args, format);
vsprintf_s(text, 256, format, args);
va_end(args);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

glBindTexture(GL_TEXTURE_2D, m_texture);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();

glLoadIdentity();

glTranslated(x, y, 0);
glListBase(m_font - 32);
glCallLists(strlen(text), GL_BYTE, text);

glPopMatrix();
}

bool Font::load() {
if(m_loaded) { return true; }

QString fontPath = QString(Game::settings->dataDirectory);
fontPath.append("/Fonts/");
fontPath.append(m_filename);

QFileInfo fontFile(fontPath);
if(!fontFile.exists()) { return false; }

QByteArray bytes = fontPath.toLocal8Bit();

TTF_Font * fontData;
if(!(fontData = TTF_OpenFont(bytes.data(), m_size))) {
return false;
}

SDL_Color colour = {255, 255, 255, 255};

SDL_Surface * character;
QVector<SDL_Surface *> characters;
int maxWidth = -1;
int maxHeight = -1;
char data[2];
data[1] = '\0';
for(int i=0;i<128;i++ ) {
data[0] = (char) (i + 32);
character = TTF_RenderText_Blended(fontData, data, colour);
characters.push_back(character);
if(maxWidth < 0 || maxWidth < character->w) { maxWidth = character->w; }
if(maxHeight < 0 || maxHeight < character->h) { maxHeight = character->h; }
}

m_horizontalSpacing = maxWidth;
m_verticalSpacing = maxHeight;

int width = 1, tempWidth = maxWidth * 16;
int height = 1, tempHeight = maxHeight * 8;
while(width < tempWidth) { width *= 2; }
while(height < tempHeight) { height *= 2; }

SDL_Surface * temp = SDL_CreateRGBSurface(0, width, height, 32,
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
#else
0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
#endif
);

SDL_Rect sourceArea, destArea;
int x = 0;
int y = 0;
for(int i=0;i<128;i++) {
sourceArea.x = 0;
sourceArea.y = 0;
sourceArea.w = characters[i]->w;
sourceArea.h = characters[i]->h;

destArea.x = maxWidth * x;
destArea.y = maxHeight * y;
destArea.w = characters[i]->w;
destArea.h = characters[i]->h;

SDL_SetAlpha(characters[i], 0, 0);
SDL_BlitSurface(characters[i], &sourceArea, temp, &destArea);

x++;
if(x == 16) {
x = 0;
y++;
}
}

glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

m_font = glGenLists(128);

x = 0;
y = 0;
float w = (float) maxWidth / (float) (temp->w);
float h = (float) maxHeight / (float) (temp->h);
for(int i=0;i<128;i++) {

glNewList(m_font + i, GL_COMPILE);

glBegin(GL_QUADS);
glTexCoord2f((w * x), ((h * y))); glVertex2i(0, 0);
glTexCoord2f((w * x) + w, ((h * y))); glVertex2i(maxWidth, 0);
glTexCoord2f((w * x) + w, ((h * y) + h)); glVertex2i(maxWidth, maxHeight);
glTexCoord2f((w * x), ((h * y) + h)); glVertex2i(0, maxHeight);
glEnd();

glTranslated(maxWidth, 0, 0);

glEndList();

x++;
if(x == 16) {
x = 0;
y++;
}
}

for(int i=0;i<128;i++) {
SDL_FreeSurface(characters[i]);
}
SDL_FreeSurface(temp);

m_loaded = true;

return true;
}

bool Font::unload() {
if(!m_loaded) { return true; }

glDeleteLists(m_font, 128);
glDeleteTextures(1, &m_texture);

m_loaded = false;

return true;
}

bool Font::isLoaded() const {
return m_loaded;
}

bool Font::operator == (const Font & f) const {
return _stricmp(m_id, f.m_id) == 0 &&
_stricmp(m_filename, f.m_filename) == 0 &&
m_size == f.m_size;
}

bool Font::operator != (const Font & f) const {
return !operator == (f);
}
[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By povilaslt2
      Hello. I'm Programmer who is in search of 2D game project who preferably uses OpenGL and C++. You can see my projects in GitHub. Project genre doesn't matter (except MMO's :D).
    • By ZeldaFan555
      Hello, My name is Matt. I am a programmer. I mostly use Java, but can use C++ and various other languages. I'm looking for someone to partner up with for random projects, preferably using OpenGL, though I'd be open to just about anything. If you're interested you can contact me on Skype or on here, thank you!
      Skype: Mangodoor408
    • By tyhender
      Hello, my name is Mark. I'm hobby programmer. 
      So recently,I thought that it's good idea to find people to create a full 3D engine. I'm looking for people experienced in scripting 3D shaders and implementing physics into engine(game)(we are going to use the React physics engine). 
      And,ye,no money =D I'm just looking for hobbyists that will be proud of their work. If engine(or game) will have financial succes,well,then maybe =D
      Sorry for late replies.
      I mostly give more information when people PM me,but this post is REALLY short,even for me =D
      So here's few more points:
      Engine will use openGL and SDL for graphics. It will use React3D physics library for physics simulation. Engine(most probably,atleast for the first part) won't have graphical fron-end,it will be a framework . I think final engine should be enough to set up an FPS in a couple of minutes. A bit about my self:
      I've been programming for 7 years total. I learned very slowly it as "secondary interesting thing" for like 3 years, but then began to script more seriously.  My primary language is C++,which we are going to use for the engine. Yes,I did 3D graphics with physics simulation before. No, my portfolio isn't very impressive. I'm working on that No,I wasn't employed officially. If anybody need to know more PM me. 
       
    • By Zaphyk
      I am developing my engine using the OpenGL 3.3 compatibility profile. It runs as expected on my NVIDIA card and on my Intel Card however when I tried it on an AMD setup it ran 3 times worse than on the other setups. Could this be a AMD driver thing or is this probably a problem with my OGL code? Could a different code standard create such bad performance?
    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      Question:
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
       
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
  • Popular Now