0
\$\begingroup\$

Is it possible to setup something sort of like a class in C++ but in c in the simplest terms? I want to avoid using c++ but I would like to create a simple struct that has glsl shader program.

for example

struct shader_program
{
     GLuint shader;
     void (*create_shader)(const char* vss, const char* fss);
     void (*enableShader)(void);
     GLuint (*getUniformLoc(struct shader_program* sp, char* name);
     void (*disableShader)(void);

}

sample usage.

struct shader_program simple_shader = create_shader(.., ..);
struct shader_program advanced_shader = create_shader(.., ..);


draaw()
{
 simple_shader->enableShader();
 //...bind vai, draw, etc..
 simple_shader->disableShader();

 advanced_shader->enableShader();
 //draw
 advanced_shader->disableShader();

}

the main question is how would i set this up in a header and source file so that I can use a struct like this to do my rendering?

\$\endgroup\$
2
  • \$\begingroup\$ You are going to need function pointers. The struct defined in the header will be defined with function pointer members, and when you create objects of this type you will have to set those members to point at the functions you want them to use. \$\endgroup\$ Commented Jul 12, 2015 at 20:34
  • \$\begingroup\$ simple_shader->enableShader() is going to be impossible. The closest you could get is simple_shader->enableShader(simple_shader). That's because C does not have a this keyword. That means functions (even if pointed to by the data of the struct) have no frame of reference to the variable you're using to call them, unless you explicitly pass it. I personally would recommend the approach of Honeybunchs answer, unless you have a reason to do simple_shader->enableShader(simple_shader) (the C version of a virtual function, effectively) \$\endgroup\$ Commented Jul 13, 2015 at 19:43

1 Answer 1

0
\$\begingroup\$

If you want to aim for a real class, I would recommend C++ if that's how you want to organize your project. However C is still totally appropriate for OpenGL. If I'm not mistaken a totally appropriate C way of doing something class-like would be:

// Shader.h
struct Shader{
    GLuint id;
}

Shader* createShader(char* vertexSource, char* pixelSource);
void bindShader(Shader* shader);
void unbindShader();


//Shader.c
Shader* createShader(char* vertexSource, char* pixelSource{
    //Load shader or whatever
    return new Shader(shaderID);
}

void bindShader(Shader* shader){
    glBindShader(shader->id);
}
void unbindShader(){
    glBindShader(0);
}


//Application.c
void init(){
    shader = createShader("vert source", "pixel source);
}

void draw(){
    bindShader(shader);
}
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.