Can I test wether a texture has been already loaded?


My problem is this:
I’m reading in the paths to files containing textures (TGA-format), and then I’m loading the textures. The thing is, that sometimes I’m loading the same image (texture) twice or more, which of course is a waste of memory. Due to the structure of my program, it is not so easy just to test wether a certain path has already been used. Doing that would reduce the problem somewhat, but not entirely. So my question is this: Can I ask OpenGL wether a texture has already been loaded?

Well, how would OpenGL know the filename?

Yeah, I know it’s a long shot, but I was just hoping, that it could be done in some clever way, since it would be the easiest solution in this case.

Put this inside your texture loading implementation, and make sure you use MaybeLoadTexture() from the rest of your program:

static map<string,GLuint> loadedTextures;

static GLuint ReallyLoadTexture( char const * path )
// open TGA, generate texture ID, blah blah blah

GLuint MaybeLoadTexture( string path )
// you might want to make the string all lowercase first …

// here, see if we already loaded it
map<string,GLuint>::iterator ptr( loadedTextures.find( path ) );
if( ptr != loadedTextures.end() ) {
return (*ptr).second;
GLuint ret = ReallyLoadTexture( path.c_str() );
loadedTextures[ path ] = ret;
return ret;

To push things even further, it could happen that the same image is in two different files !

In this case, you could load the file and compare it to the already loaded textures byte by byte…

OK, just kidding !