OpenGL对象包装器中的自动绑定

Mor*_*son 4 c++ opengl

我倾向于将OpenGL对象包装在自己的类中.在OpenGL中有绑定的概念,你绑定你的对象,用它做一些事情,然后取消绑定它.例如,纹理:

 glBindTexture(GL_TEXTURE_2D, TextureColorbufferName);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);
 glBindTexture(GL_TEXTURE_2D, 0);
Run Code Online (Sandbox Code Playgroud)

包装这将是这样的:

texture->bind();
    texture->setParameter(...);
    texture->setParameter(...);
texture->unBind();
Run Code Online (Sandbox Code Playgroud)

这里的问题是,我想避免使用bind()和unBind()函数,而只是能够调用set方法,GLObject将自动绑定.

我可以在每个方法实现中做到这一点:

public void Texture::setParameter(...)
{
    this.bind();
    // do something
    this.unBind();
}
Run Code Online (Sandbox Code Playgroud)

虽然我必须为每一个添加的方法做到这一点!有没有更好的方法,所以它是在每个方法添加之前和之后自动完成的?

Con*_*ius 5

也许上下文对象可能在这里有帮助.考虑这个小对象:

class TextureContext {
public:
    TextureContext(char* texname) {
        glBindTexture(GL_TEXTURE_2D, texname);
    }
    ~TextureContext() {
        glBindTexture(GL_TEXTURE_2D, 0);
    }
};
Run Code Online (Sandbox Code Playgroud)

此对象现在在范围内使用:

{
    TextureContext mycont(textname);
    mytexture->setParameter(...);
    mytexture->setParameter(...);
    mytexture->setParameter(...);
}
Run Code Online (Sandbox Code Playgroud)

对象mycont只存在于作用域中,并在保留作用域后自动调用其析构函数(分别为ant unbind方法).

编辑:

也许你可以调整TextureContext类来Texture在构造函数中取代你的实例,并在绑定纹理之前检索纹理名称本身.