-1
\$\begingroup\$

Simple question:

What is the fastest way to retrieve a texture ID, given an enum value? Say I have 100 textures, what would be the fastest way to get one texture ID?

Make a texture manager with a HashMap<TextureEnum, int> so I can call TextureManager.get(TextureEnum.button_hover)? (example, I know hashmaps are slow).

\$\endgroup\$
2
  • \$\begingroup\$ There is rarely a universally best way to do something. Questions like this just invite opinions. Since your requirements are poorly defined, there are lots of strategies that would work. \$\endgroup\$
    – House
    Jul 16, 2013 at 14:15
  • \$\begingroup\$ Agreed. Changed the question. \$\endgroup\$
    – Basaa
    Jul 16, 2013 at 14:22

1 Answer 1

1
\$\begingroup\$

First of all, why do you think hash maps are slow? For run time data they are quite fast!

An easy and good to start with approach is using a std::unordered_map which maps GLuint texture ids to std::string names.

#include <string>
#include <unordered_map>
using namespace std;

unordered_map<string, GLuint> textures;

Then you could expand this to an easy manager by providing functions to create, get and delete textures. I wrote down this three functions without testing, but I think it is helpful anyway.

Function to create a new texture, load image data to it and add it to the system.

void TextureCreate(string Name, string ImagePath, bool Mipmapping = false;)
{
    // load image file from disk
    // ...

    GLuint id;
    // create OpenGL texture
    // ...

    textures.insert(make_pair(Name, id));
}

Function to get a created texture.

GLuint TextureGet(string Name)
{
    auto i = textures.find(Name);
    if(i == textures.end())
    {
        cout << "Texture with this name doesn't exist." << endl;
        return 0;
    }

    return i.second;
}

Function to delete a texture from the system.

void TextureDelete(string Name)
{
    auto i = textures.find(Name);
    if(i == textures.end())
    {
        cout << "Texture with this name doesn't exist." << endl;
        return;
    }

    GLuint id = i.second;
    // delete OpenGL texture
    // ...

    textures.erase(i);
}

Use case example.

// initialization
TextureCreate("button", "images/button/default.png");
TextureCreate("button hover", "images/button/hover.png");
Button.texture = TextureGet("button");

// on hover event
Button.texture = TextureGet("button hover");

// on blur event
Button.texture = TextureGet("button");
\$\endgroup\$
1
  • \$\begingroup\$ Thank you for your answer. Actually I'm using Java, but I get the point. \$\endgroup\$
    – Basaa
    Jul 16, 2013 at 13:31

Not the answer you're looking for? Browse other questions tagged .