SDL: my own font function uses tons of memory..

Started by
4 comments, last by Feidias 19 years, 5 months ago
I am very new to SDL and still learning c++ so please forgive me if this is a stupid question. I made my own function for writing text on the screen using a bitmap I made. It is for a game a friend and I are making as a school project, in case you are wondering. It works well except that it hogs tons of memory and the whole program becomes very unstable when I print any text using the function. Here is the whole function:

void DrawText( char *str, SDL_Surface *screen, int xpos, int ypos )
{
    SDL_Surface *text = SDL_LoadBMP("bitmaps/font.bmp");

    SDL_SetColorKey(text, SDL_SRCCOLORKEY, 
                       SDL_MapRGB(text->format, 0, 255, 0));

    SDL_Rect dest;
    SDL_Rect source;
    source.w = 31; // width
    source.h = 31; // height
    int xsource; // x position in font.bmp
    int ysource; // y position in font.bmp
    for ( int x=0, y=0; *str; x++ )
    {
        // if there are over 20 symbols, go down one row
        if ( x >= 20 )
        {
            x=0;
            y++;
        }
        dest.x = xpos+(x*32);
        dest.y = ypos+(y*32);

        ysource=0;
        xsource=((int)*str)-' ';
        // change row in font.bmp automatically
        while ( xsource >= 16 )
        {
            xsource-=16;
            ysource++;
        }    

        source.x = (xsource*32)+1;
        source.y = (ysource*32)+1;
   
        SDL_BlitSurface(text, &source, screen, &dest);
        str++;
    }
}

Any help is appreciated. Thanks.
Advertisement
You aren't freeing the bitmap.
HxRender | Cornerstone SDL TutorialsCurrently picking on: Hedos, Programmer One
If you plan on using that function multiple times throughout your game, why not load the font bitmap while initializing everything? My sdl font engine class inherits an sdl image class, which frees the surface when destructed, so I don't have to worry about it!

When I initialize my game I simply create an object of type CFont (my font class) and use it until the end of the game. When the game ends, my destructor is called, and the surface is freed. Anyways, just an idea for you to consider.
Thanks guys. I will get right into it as soon as I get home from school.
you could also try making an counter:

int count;
while(count<5)
{
count++;
}

if(count==6);
{
count=0;
}


if(printmsg ==true && count = 5)
{
your_printfunction();
}

I would think that will give you less lag...
What is that count stuff? Anyway, the routine is using very strange way to calculate the font position.. better use pre-calculation for the font positions in the source image or divide & remainder to get the row and column position of the font source.

This topic is closed to new replies.

Advertisement