Sign in to follow this  
swinchen

OpenGL OpenGL SDL_ttf font rendering problems.

Recommended Posts

swinchen    224
Hello, I have been hacking at the SDL_ttf glfont.c example (included with the SDL_ttf source code) file in order to improve performance by pre-caching the ogl textures. As it stands right now it seems to render 'i' and 'l' correctly but all other glyphs show up as white or gray rectangles. Any help you might be able to offer would be greatly appreciated. I am not sure if this is an SDL problem I am having or an OpenGL... Here is the nice color coded version: http://paste.lisp.org/display/29373 Or see the attached code Thanks, Sam
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_opengl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

#define PI 3.141592653589793238462643

typedef struct
{
	int minx, maxx, miny, maxy, advance;
	GLfloat texcoord[4];
	GLuint texid;
} t_glyph;

typedef struct
{
	int style, pointsize, height, ascent, descent, lineskip;
	SDL_Color color;
	t_glyph glyphs[128];
} t_font;

int build_font(char* filename, t_font* font);
void print_glstr(int x, int y, t_font* font, char* str);
void set_perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
void SDL_GL_Enter2DMode();
void SDL_GL_Leave2DMode();
static int power_of_two(int input);
GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord);

int main(int argc, char* argv[])
{
	t_font font;
	SDL_Surface* screen;
	
	SDL_Color white = {0xFF, 0xFF, 0xFF, 0x00};
	
	if ( SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0 )
	{
		fprintf(stderr, "ERROR Initializing SDL: %s\n", SDL_GetError());
		return -1;		
	}
	atexit(SDL_Quit);
	
	if ( TTF_Init() < 0 )
	{
		fprintf(stderr, "ERROR Initializing TTF Engine: %s\n", TTF_GetError());
		return -1;
	}
	atexit(TTF_Quit);
	
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL);
	if ( screen == NULL )
	{
		fprintf(stderr, "ERROR Couldn't set video mode: %s\n", SDL_GetError());
		return -1;
	}
	
	glViewport(0, 0, screen->w, screen->h);
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	
	set_perspective(45.0f, (GLdouble) screen->w / screen->h, 1.0f, 100.0f);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glShadeModel(GL_SMOOTH);
	glClearColor(0.0, 0.0, 0.0, 1.0);
	
	
	font.pointsize = 20;
	font.style = TTF_STYLE_NORMAL;
	memcpy(&(font.color), &white, sizeof(SDL_Color));
	if ( build_font("MONACO.TTF",&font) < 0)
	{
		fprintf(stderr, "ERROR building font: %s\n", TTF_GetError());
		return -1;		
	}
	
	while ( SDL_GetTicks() < 5000 )
	{
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glTranslated(0.0, 0.0, -5.0);
		
		glBegin(GL_POINTS);
			glVertex3d(0.0,0.0,0.0);
		glEnd();
		
		SDL_GL_Enter2DMode();
		print_glstr(100, 500, &font, "abcdefghijklmnopqrstuvwxyz");
		SDL_GL_Leave2DMode();		
			
		SDL_GL_SwapBuffers();
	}
	
	SDL_FreeSurface(screen);
	return 0;
}

int build_font(char* filename, t_font* font)
{
	TTF_Font* ttffont;
	SDL_Surface* surf;
	int i;
	GLenum gl_error;
	
	ttffont = TTF_OpenFont(filename, font->pointsize);
	if (ttffont == NULL)
	{
		TTF_SetError("ERROR opening font: %s\n", TTF_GetError());
		return -1;
	}
	
	TTF_SetFontStyle(ttffont, font->style);
	
	font->ascent = TTF_FontAscent(ttffont);
	font->descent = TTF_FontDescent(ttffont);
	font->height = TTF_FontHeight(ttffont);
	font->lineskip = TTF_FontLineSkip(ttffont);
	
	for ( i = ' '; i <= '~'; i++ )
	{
		surf = TTF_RenderGlyph_Blended(ttffont, i, font->color);
		if ( surf == NULL )
		{
			TTF_SetError("ERROR rendering glyph %c: %s\n", (char)i,
				TTF_GetError());
			TTF_CloseFont(ttffont);
			return -1;			
		}
		
		TTF_GlyphMetrics(ttffont, i, &(font->glyphs[i].minx), 
			&(font->glyphs[i].maxx), &(font->glyphs[i].miny),
			&(font->glyphs[i].maxy), &(font->glyphs[i].advance));
		
		font->glyphs[i].texid = SDL_GL_LoadTexture(surf,
			font->glyphs[i].texcoord);
		
		if ( (gl_error = glGetError()) != GL_NO_ERROR ) {
			/* If this failed, the text may exceed texture size limits */
			TTF_SetError("Warning: Couldn't create texture: 0x%x\n", gl_error);
			SDL_FreeSurface(surf);
			TTF_CloseFont(ttffont);
			return -1;
		}		
		SDL_FreeSurface(surf);
	}
	
	TTF_CloseFont(ttffont);
	return 0;
}

void print_glstr(int x, int y, t_font* font, char* str)
{
	int texMinX, texMaxX, texMinY, texMaxY, i, w, h;
	
	while (*str != 0)
	{
		i = (int)*str;
		texMinX = font->glyphs[i].texcoord[0];
		texMinY = font->glyphs[i].texcoord[1];
		texMaxX = font->glyphs[i].texcoord[2];
		texMaxY = font->glyphs[i].texcoord[3];
		w = font->glyphs[i].maxx;
		h = font->glyphs[i].maxy;
		
		glBindTexture(GL_TEXTURE_2D, font->glyphs[i].texid);
		glBegin(GL_TRIANGLE_STRIP);
			glTexCoord2f(texMinX, texMinY); glVertex2i(x,   y  );
			glTexCoord2f(texMaxX, texMinY); glVertex2i(x+w, y  );
			glTexCoord2f(texMinX, texMaxY); glVertex2i(x,   y+h);
			glTexCoord2f(texMaxX, texMaxY); glVertex2i(x+w, y+h);
		glEnd();
		
		x += font->glyphs[i].advance;
		str++;
	}
}

void set_perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
{
   GLdouble ymax;
   ymax = zNear * tan(fovy * PI / 360.0f);
   glFrustum(-ymax*aspect, ymax*aspect, -ymax, ymax, zNear, zFar);
}

void SDL_GL_Enter2DMode()
{
	SDL_Surface *screen = SDL_GetVideoSurface();

	/* Note, there may be other things you need to change,
	   depending on how you have your OpenGL state set up.
	*/
	glPushAttrib(GL_ENABLE_BIT);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
	glEnable(GL_TEXTURE_2D);

	/* This allows alpha blending of 2D textures with the scene */
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glViewport(0, 0, screen->w, screen->h);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	glOrtho(0.0, (GLdouble)screen->w, (GLdouble)screen->h, 0.0, 0.0, 1.0);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}

void SDL_GL_Leave2DMode()
{
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glPopAttrib();
}

/* Quick utility function for texture creation */
static int power_of_two(int input)
{
	int value = 1;

	while ( value < input ) {
		value <<= 1;
	}
	return value;
}

GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord)
{
	GLuint texture;
	int w, h;
	SDL_Surface *image;
	SDL_Rect area;
	Uint32 saved_flags;
	Uint8  saved_alpha;

	/* Use the surface width and height expanded to powers of 2 */
	w = power_of_two(surface->w);
	h = power_of_two(surface->h);
	texcoord[0] = 0.0f;			/* Min X */
	texcoord[1] = 0.0f;			/* Min Y */
	texcoord[2] = (GLfloat)surface->w / w;	/* Max X */
	texcoord[3] = (GLfloat)surface->h / h;	/* Max Y */

	image = SDL_CreateRGBSurface(
			SDL_SWSURFACE,
			w, h,
			32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
			0x000000FF, 
			0x0000FF00, 
			0x00FF0000, 
			0xFF000000
#else
			0xFF000000,
			0x00FF0000, 
			0x0000FF00, 
			0x000000FF
#endif
		       );
	if ( image == NULL ) {
		return 0;
	}

	/* Save the alpha blending attributes */
	saved_flags = surface->flags&(SDL_SRCALPHA|SDL_RLEACCELOK);
	saved_alpha = surface->format->alpha;
	if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
		SDL_SetAlpha(surface, 0, 0);
	}

	/* Copy the surface into the GL texture image */
	area.x = 0;
	area.y = 0;
	area.w = surface->w;
	area.h = surface->h;
	SDL_BlitSurface(surface, &area, image, &area);

	/* Restore the alpha blending attributes */
	if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
		SDL_SetAlpha(surface, saved_flags, saved_alpha);
	}

	/* Create an OpenGL texture for the image */
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D,
		     0,
		     GL_RGBA,
		     w, h,
		     0,
		     GL_RGBA,
		     GL_UNSIGNED_BYTE,
		     image->pixels);
	SDL_FreeSurface(image); /* No longer needed */

	return texture;
}


Share this post


Link to post
Share on other sites
swinchen    224
Hmmm, if no one sees the problem right away maybe you could give me some tips on debugging applications with OpenGL? If I used a software renderer like MESA maybe I could use traditional debugging techniques? Right now I am staring at the code saying "Well, it looks like it should work!"


Thanks,
Sam

Share this post


Link to post
Share on other sites
Grudzio    122
In print_glstr function set w to font->glyphs[i].advance and h to font->height,
since maxx and maxy don't give glyph width and height. Another possibility is the call to TTF_RenderGlyph_Blended. Replace it with TTF_RenderGlyph_Solid.

I would also suggest putting all glyphs in one big OpenGL texture. Something like in NeHe tutorial #17 (textured fonts).

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Doh! I figured it out. In the print_glstr function I declared texMinX and friends as int... they should have been GLfloat. Also, I fixed the font alignment...

Now you mentioned using one texture to hold all of the font information. What are the reasons/benefits of doing this?

If I did store them as one texture I could just render one surface that contains all printable characters, and then "chop" the texture into display lists using the glyph metrics correct?

Thanks!

Sam


#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <GL/glew.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

#define PI 3.141592653589793238462643

typedef struct
{
int minx, maxx, miny, maxy, advance;
GLfloat texcoord[4];
GLuint texid;
} t_glyph;

typedef struct
{
int style, pointsize, height, ascent, descent, lineskip;
SDL_Color color;
t_glyph glyphs[128];
} t_font;

int build_font(char* filename, t_font* font);
void print_glstr(int x, int y, t_font* font, char* str);
void set_perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
void SDL_GL_Enter2DMode();
void SDL_GL_Leave2DMode();
static int power_of_two(int input);
GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord);

int main(int argc, char* argv[])
{
t_font font;
SDL_Surface* screen;
GLenum glerr;
char buffer[256];
unsigned int frame_cnt, old_ticks;
GLfloat frame_rate;

SDL_Color white = {0xFF, 0xFF, 0xFF, 0x00};

if ( SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "ERROR Initializing SDL: %s\n", SDL_GetError());
return -1;
}
atexit(SDL_Quit);

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
screen = SDL_SetVideoMode(1024, 768, 32, SDL_OPENGL | SDL_FULLSCREEN);
if ( screen == NULL )
{
fprintf(stderr, "ERROR Couldn't set video mode: %s\n", SDL_GetError());
return -1;
}

SDL_WM_SetCaption("Sam's Font Example", 0);

if ( TTF_Init() < 0 )
{
fprintf(stderr, "ERROR Initializing TTF Engine: %s\n", TTF_GetError());
return -1;
}
atexit(TTF_Quit);

glerr = glewInit();
if ( glerr != GLEW_OK )
{
fprintf(stderr, "ERROR Initializing GLEW: %s\n", glewGetErrorString(glerr));
return -1;
}

glViewport(0, 0, screen->w, screen->h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();

set_perspective(45.0f, (GLdouble) screen->w / screen->h, 1.0f, 1000.0f);

glMatrixMode( GL_MODELVIEW );
glLoadIdentity( );
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glShadeModel(GL_SMOOTH);

font.pointsize = 20;
font.style = TTF_STYLE_NORMAL;
memcpy(&(font.color), &white, sizeof(SDL_Color));
if ( build_font(argv[1],&font) < 0 )
{
fprintf(stderr, "ERROR building font: %s\n", TTF_GetError());
return -1;
}

frame_cnt = 0;
old_ticks = SDL_GetTicks();
frame_rate = 0.0;
while ( SDL_GetTicks() < 10000 )
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

glTranslated(0.0, 0.0, -5.0);

SDL_GL_Enter2DMode();

sprintf(buffer, "Frame Rate - %f", frame_rate);
print_glstr(0, font.height, &font, buffer);

// print_glstr(0, 100, &font, " !\"#$%&'()*+,-./0123456789:;<=>?@");
// print_glstr(0, 200, &font, "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`");
// print_glstr(0, 300, &font, "abcdefghijklmnopqrstuvwxyz{|}~");

SDL_GL_Leave2DMode();
SDL_GL_SwapBuffers();

frame_cnt++;

if (frame_cnt >= 100)
{
frame_rate = (GLfloat)frame_cnt/((GLfloat)(SDL_GetTicks() - old_ticks)/1000.0f);
old_ticks = SDL_GetTicks();
frame_cnt = 0;
}
}

SDL_FreeSurface(screen);
return 0;
}

int build_font(char* filename, t_font* font)
{
TTF_Font* ttffont;
SDL_Surface* surf;
int i;
GLenum gl_error;

ttffont = TTF_OpenFont(filename, font->pointsize);
if (ttffont == NULL)
{
TTF_SetError("ERROR opening font: %s\n", TTF_GetError());
return -1;
}

TTF_SetFontStyle(ttffont, font->style);

font->ascent = TTF_FontAscent(ttffont);
font->descent = TTF_FontDescent(ttffont);
font->height = TTF_FontHeight(ttffont);
font->lineskip = TTF_FontLineSkip(ttffont);

for ( i = ' '; i <= '~'; i++ )
{
surf = TTF_RenderGlyph_Blended(ttffont, i, font->color);
if ( surf == NULL )
{
TTF_SetError("ERROR rendering glyph %c: %s\n", (char)i,
TTF_GetError());
TTF_CloseFont(ttffont);
return -1;
}

TTF_GlyphMetrics(ttffont, i, &(font->glyphs[i].minx),
&(font->glyphs[i].maxx), &(font->glyphs[i].miny),
&(font->glyphs[i].maxy), &(font->glyphs[i].advance));

font->glyphs[i].texid = SDL_GL_LoadTexture(surf,
font->glyphs[i].texcoord);

if ( (gl_error = glGetError()) != GL_NO_ERROR ) {
/* If this failed, the text may exceed texture size limits */
TTF_SetError("Warning: Couldn't create texture: 0x%x\n", gl_error);
SDL_FreeSurface(surf);
TTF_CloseFont(ttffont);
return -1;
}
SDL_FreeSurface(surf);
}

TTF_CloseFont(ttffont);
return 0;
}

void print_glstr(int x, int y, t_font* font, char* str)
{
GLfloat texMinX, texMaxX, texMinY, texMaxY;
GLfloat left, right, top, bottom;
t_glyph* g;

while (*str != 0)
{
g = &(font->glyphs[(int)*str]);

texMinX = g->texcoord[0];
texMinY = g->texcoord[1];
texMaxX = g->texcoord[2];
texMaxY = g->texcoord[3];
left = x + g->minx;
right = x + g->maxx - g->minx;
top = y - g->maxy;
bottom = y - g->miny;

glBindTexture(GL_TEXTURE_2D, g->texid);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(texMinX, texMinY); glVertex2f( left, top);
glTexCoord2f(texMaxX, texMinY); glVertex2f(right, top);
glTexCoord2f(texMinX, texMaxY); glVertex2f( left, bottom);
glTexCoord2f(texMaxX, texMaxY); glVertex2f(right, bottom);
glEnd();

x += g->advance;
str++;
}
}

void set_perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
{
GLdouble ymax;
ymax = zNear * tan(fovy * PI / 360.0f);
glFrustum(-ymax*aspect, ymax*aspect, -ymax, ymax, zNear, zFar);
}

void SDL_GL_Enter2DMode()
{
SDL_Surface *screen = SDL_GetVideoSurface();

/* Note, there may be other things you need to change,
depending on how you have your OpenGL state set up.
*/

glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);

/* This allows alpha blending of 2D textures with the scene */
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glViewport(0, 0, screen->w, screen->h);

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();

glOrtho(0.0, (GLdouble)screen->w, (GLdouble)screen->h, 0.0, 0.0, 1.0);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}

void SDL_GL_Leave2DMode()
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix();

glMatrixMode(GL_PROJECTION);
glPopMatrix();

glPopAttrib();
}

/* Quick utility function for texture creation */
static int power_of_two(int input)
{
int value = 1;

while ( value < input ) {
value <<= 1;
}
return value;
}

GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord)
{
GLuint texture;
int w, h;
SDL_Surface *image;
SDL_Rect area;
Uint32 saved_flags;
Uint8 saved_alpha;

/* Use the surface width and height expanded to powers of 2 */
w = power_of_two(surface->w);
h = power_of_two(surface->h);
texcoord[0] = 0.0f; /* Min X */
texcoord[1] = 0.0f; /* Min Y */
texcoord[2] = (GLfloat)surface->w / w; /* Max X */
texcoord[3] = (GLfloat)surface->h / h; /* Max Y */

image = SDL_CreateRGBSurface(
SDL_SWSURFACE,
w, h,
32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
0x000000FF,
0x0000FF00,
0x00FF0000,
0xFF000000
#else
0xFF000000,
0x00FF0000,
0x0000FF00,
0x000000FF
#endif
);
if ( image == NULL ) {
return 0;
}

/* Save the alpha blending attributes */
saved_flags = surface->flags&(SDL_SRCALPHA|SDL_RLEACCELOK);
saved_alpha = surface->format->alpha;
if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
SDL_SetAlpha(surface, 0, 0);
}

/* Copy the surface into the GL texture image */
area.x = 0;
area.y = 0;
area.w = surface->w;
area.h = surface->h;
SDL_BlitSurface(surface, &area, image, &area);

/* Restore the alpha blending attributes */
if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
SDL_SetAlpha(surface, saved_flags, saved_alpha);
}

/* Create an OpenGL texture for the image */
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
w, h,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image->pixels);
SDL_FreeSurface(image); /* No longer needed */

return texture;
}

Share this post


Link to post
Share on other sites
swinchen    224
Doh! I figured it out. In the print_glstr function I declared texMinX and friends as int... they should have been GLfloat. Also, I fixed the font alignment...

Now you mentioned using one texture to hold all of the font information. What are the reasons/benefits of doing this?

If I did store them as one texture I could just render one surface that contains all printable characters, and then "chop" the texture into display lists using the glyph metrics correct?

Thanks!

Sam


#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <GL/glew.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

#define PI 3.141592653589793238462643

typedef struct
{
int minx, maxx, miny, maxy, advance;
GLfloat texcoord[4];
GLuint texid;
} t_glyph;

typedef struct
{
int style, pointsize, height, ascent, descent, lineskip;
SDL_Color color;
t_glyph glyphs[128];
} t_font;

int build_font(char* filename, t_font* font);
void print_glstr(int x, int y, t_font* font, char* str);
void set_perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
void SDL_GL_Enter2DMode();
void SDL_GL_Leave2DMode();
static int power_of_two(int input);
GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord);

int main(int argc, char* argv[])
{
t_font font;
SDL_Surface* screen;
GLenum glerr;
char buffer[256];
unsigned int frame_cnt, old_ticks;
GLfloat frame_rate;

SDL_Color white = {0xFF, 0xFF, 0xFF, 0x00};

if ( SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "ERROR Initializing SDL: %s\n", SDL_GetError());
return -1;
}
atexit(SDL_Quit);

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
screen = SDL_SetVideoMode(1024, 768, 32, SDL_OPENGL | SDL_FULLSCREEN);
if ( screen == NULL )
{
fprintf(stderr, "ERROR Couldn't set video mode: %s\n", SDL_GetError());
return -1;
}

SDL_WM_SetCaption("Sam's Font Example", 0);

if ( TTF_Init() < 0 )
{
fprintf(stderr, "ERROR Initializing TTF Engine: %s\n", TTF_GetError());
return -1;
}
atexit(TTF_Quit);

glerr = glewInit();
if ( glerr != GLEW_OK )
{
fprintf(stderr, "ERROR Initializing GLEW: %s\n", glewGetErrorString(glerr));
return -1;
}

glViewport(0, 0, screen->w, screen->h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();

set_perspective(45.0f, (GLdouble) screen->w / screen->h, 1.0f, 1000.0f);

glMatrixMode( GL_MODELVIEW );
glLoadIdentity( );
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glShadeModel(GL_SMOOTH);

font.pointsize = 20;
font.style = TTF_STYLE_NORMAL;
memcpy(&(font.color), &white, sizeof(SDL_Color));
if ( build_font(argv[1],&font) < 0 )
{
fprintf(stderr, "ERROR building font: %s\n", TTF_GetError());
return -1;
}

frame_cnt = 0;
old_ticks = SDL_GetTicks();
frame_rate = 0.0;
while ( SDL_GetTicks() < 10000 )
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

glTranslated(0.0, 0.0, -5.0);

SDL_GL_Enter2DMode();

sprintf(buffer, "Frame Rate - %f", frame_rate);
print_glstr(0, font.height, &font, buffer);

// print_glstr(0, 100, &font, " !\"#$%&'()*+,-./0123456789:;<=>?@");
// print_glstr(0, 200, &font, "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`");
// print_glstr(0, 300, &font, "abcdefghijklmnopqrstuvwxyz{|}~");

SDL_GL_Leave2DMode();
SDL_GL_SwapBuffers();

frame_cnt++;

if (frame_cnt >= 100)
{
frame_rate = (GLfloat)frame_cnt/((GLfloat)(SDL_GetTicks() - old_ticks)/1000.0f);
old_ticks = SDL_GetTicks();
frame_cnt = 0;
}
}

SDL_FreeSurface(screen);
return 0;
}

int build_font(char* filename, t_font* font)
{
TTF_Font* ttffont;
SDL_Surface* surf;
int i;
GLenum gl_error;

ttffont = TTF_OpenFont(filename, font->pointsize);
if (ttffont == NULL)
{
TTF_SetError("ERROR opening font: %s\n", TTF_GetError());
return -1;
}

TTF_SetFontStyle(ttffont, font->style);

font->ascent = TTF_FontAscent(ttffont);
font->descent = TTF_FontDescent(ttffont);
font->height = TTF_FontHeight(ttffont);
font->lineskip = TTF_FontLineSkip(ttffont);

for ( i = ' '; i <= '~'; i++ )
{
surf = TTF_RenderGlyph_Blended(ttffont, i, font->color);
if ( surf == NULL )
{
TTF_SetError("ERROR rendering glyph %c: %s\n", (char)i,
TTF_GetError());
TTF_CloseFont(ttffont);
return -1;
}

TTF_GlyphMetrics(ttffont, i, &(font->glyphs[i].minx),
&(font->glyphs[i].maxx), &(font->glyphs[i].miny),
&(font->glyphs[i].maxy), &(font->glyphs[i].advance));

font->glyphs[i].texid = SDL_GL_LoadTexture(surf,
font->glyphs[i].texcoord);

if ( (gl_error = glGetError()) != GL_NO_ERROR ) {
/* If this failed, the text may exceed texture size limits */
TTF_SetError("Warning: Couldn't create texture: 0x%x\n", gl_error);
SDL_FreeSurface(surf);
TTF_CloseFont(ttffont);
return -1;
}
SDL_FreeSurface(surf);
}

TTF_CloseFont(ttffont);
return 0;
}

void print_glstr(int x, int y, t_font* font, char* str)
{
GLfloat texMinX, texMaxX, texMinY, texMaxY;
GLfloat left, right, top, bottom;
t_glyph* g;

while (*str != 0)
{
g = &(font->glyphs[(int)*str]);

texMinX = g->texcoord[0];
texMinY = g->texcoord[1];
texMaxX = g->texcoord[2];
texMaxY = g->texcoord[3];
left = x + g->minx;
right = x + g->maxx - g->minx;
top = y - g->maxy;
bottom = y - g->miny;

glBindTexture(GL_TEXTURE_2D, g->texid);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(texMinX, texMinY); glVertex2f( left, top);
glTexCoord2f(texMaxX, texMinY); glVertex2f(right, top);
glTexCoord2f(texMinX, texMaxY); glVertex2f( left, bottom);
glTexCoord2f(texMaxX, texMaxY); glVertex2f(right, bottom);
glEnd();

x += g->advance;
str++;
}
}

void set_perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
{
GLdouble ymax;
ymax = zNear * tan(fovy * PI / 360.0f);
glFrustum(-ymax*aspect, ymax*aspect, -ymax, ymax, zNear, zFar);
}

void SDL_GL_Enter2DMode()
{
SDL_Surface *screen = SDL_GetVideoSurface();

/* Note, there may be other things you need to change,
depending on how you have your OpenGL state set up.
*/

glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);

/* This allows alpha blending of 2D textures with the scene */
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glViewport(0, 0, screen->w, screen->h);

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();

glOrtho(0.0, (GLdouble)screen->w, (GLdouble)screen->h, 0.0, 0.0, 1.0);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}

void SDL_GL_Leave2DMode()
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix();

glMatrixMode(GL_PROJECTION);
glPopMatrix();

glPopAttrib();
}

/* Quick utility function for texture creation */
static int power_of_two(int input)
{
int value = 1;

while ( value < input ) {
value <<= 1;
}
return value;
}

GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord)
{
GLuint texture;
int w, h;
SDL_Surface *image;
SDL_Rect area;
Uint32 saved_flags;
Uint8 saved_alpha;

/* Use the surface width and height expanded to powers of 2 */
w = power_of_two(surface->w);
h = power_of_two(surface->h);
texcoord[0] = 0.0f; /* Min X */
texcoord[1] = 0.0f; /* Min Y */
texcoord[2] = (GLfloat)surface->w / w; /* Max X */
texcoord[3] = (GLfloat)surface->h / h; /* Max Y */

image = SDL_CreateRGBSurface(
SDL_SWSURFACE,
w, h,
32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
0x000000FF,
0x0000FF00,
0x00FF0000,
0xFF000000
#else
0xFF000000,
0x00FF0000,
0x0000FF00,
0x000000FF
#endif
);
if ( image == NULL ) {
return 0;
}

/* Save the alpha blending attributes */
saved_flags = surface->flags&(SDL_SRCALPHA|SDL_RLEACCELOK);
saved_alpha = surface->format->alpha;
if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
SDL_SetAlpha(surface, 0, 0);
}

/* Copy the surface into the GL texture image */
area.x = 0;
area.y = 0;
area.w = surface->w;
area.h = surface->h;
SDL_BlitSurface(surface, &area, image, &area);

/* Restore the alpha blending attributes */
if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
SDL_SetAlpha(surface, saved_flags, saved_alpha);
}

/* Create an OpenGL texture for the image */
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
w, h,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image->pixels);
SDL_FreeSurface(image); /* No longer needed */

return texture;
}

Share this post


Link to post
Share on other sites
Grudzio    122
Quote:

If I did store them as one texture I could just render one surface that contains all printable characters, and then "chop" the texture into display lists using the glyph metrics correct?

Exactly. Also you call glBindTexture only once - for whole printed string and not for each char.

I know very little about OpenGL texture management but I believe that it is better to use one big texture then lots of small ones.

Share this post


Link to post
Share on other sites
swinchen    224
Alright thanks. I can render all printable characters, but in order to make my life easier I am trying to draw lines and points while in SDL_GL_Enter2DMode(); (you know, just so I can see if I am chopping at the right point) but I can not draw anything while in 2D mode. Do you know any reason why I wouldn't be able to? Thanks,

Sam

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 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.
    • By markshaw001
      Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.
       
    • By KarimIO
      Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
      GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats = gbufferCFs.data(); gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!
    • By Adrianensis
      Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
      This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
      This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
      I'm available for a good conversation about Game Engine / Graphics Programming
    • By C0dR
      I would like to introduce the first version of my physically based camera rendering library, written in C++, called PhysiCam.
      Physicam is an open source OpenGL C++ library, which provides physically based camera rendering and parameters. It is based on OpenGL and designed to be used as either static library or dynamic library and can be integrated in existing applications.
       
      The following features are implemented:
      Physically based sensor and focal length calculation Autoexposure Manual exposure Lense distortion Bloom (influenced by ISO, Shutter Speed, Sensor type etc.) Bokeh (influenced by Aperture, Sensor type and focal length) Tonemapping  
      You can find the repository at https://github.com/0x2A/physicam
       
      I would be happy about feedback, suggestions or contributions.

  • Popular Now