10

I have to use two different shader programs in OpenGL for different objects.

I found that I have to use glUseProgram() to switch between different shader programs, but not much information on that.

How does generating and binding VAOs and VBOs work for each shader program (how & when) given that I have two different shader programs I use for different objects?

2
  • 2
    I'll try to put this delicately... you said "I am pretty familiar with OpenGL overall by now," but it might help to approach the subject with more humility. Modern OpenGL builds on a foundation of running shader programs, and most techniques are built on top of that foundation. Oct 7, 2016 at 18:38
  • @DietrichEpp Well with pretty familiar I meant I did several Projects in University, of which some were pretty complex. But the thing is we always had to code base or it was not modern openGL. So I am facing this specific part the first time, and this is how I asked this question.
    – nurgan
    Oct 7, 2016 at 22:01

2 Answers 2

16

When you render objects in OpenGL, your code will look like this:

  • Bind program with glUseProgram, set uniforms with glUniform4fv, glUniformMatrix4fv, etc.

  • Bind the vertex array with glBindVertexArray.

  • Bind any textures you need with glActiveTexture and glBindTexture.

  • Change any other state, e.g., glEnable, glDisable, glBlendFunc.

  • Draw with glDrawArrays or glDrawElements.

  • If you want, reset state back to defaults.

These are all the things that you tend to do in vanilla OpenGL 3 code. You should already have this part working.

If you need to write multiple objects with different shader programs, you just do the above steps multiple times. State changes can be omitted if you are going to use the same state for multiple programs (except uniforms, which are saved separately for each program). For example, you might use the same VAO, the same textures, the same blending function, et cetera.

There are many tutorials on how OpenGL 3 drawing commands work, if you are looking for more detailed examples.

15
  • 2
    In addition: If you want to use the same VAO with different shaders, you have to make sure that the input variables have the same location in both shaders
    – BDL
    Oct 7, 2016 at 19:48
  • @DietrichEpp So if I render different objects in two different VAOs, I just bind the program and bind the VAO for the one objects and shaders, and then do the same for the other objects and shaders? Just for clearification. If so it is very straight forward and I don't know what confused me that much, since I actually have the part working you mentioned I should have...
    – nurgan
    Oct 7, 2016 at 22:05
  • You're asking if you have two VAOs and two programs? Yes, you would bind one program + VAO, draw, then bind the other program + VAO, then draw. It is of course also possible to have one VAO and two programs, or two VAOs and one program. Oct 8, 2016 at 0:27
  • Program objects retain their arguments from last time they were set. See my answer. Nov 29, 2018 at 11:15
  • @enigmaticPhysicist: When you say "arguments" my guess is that you are talking about uniforms? Good catch, I've clarified that the uniforms are per-program. Nov 29, 2018 at 16:10
1

It is possible to switch program objects without having to specify their arguments all over again. In order for it to work, though, you must pre-assign the values of your vertex attribute array indices before compiling and linking, using glBindAttribLocation, making sure each of your programs uses separate indices. If you don't, then the same VBO may go to both programs. The VBOs being used by both programs must all be in the same VAO, which must be bound while the programs are active and the Draw commands are executed.

Here's an example:

// HELPER FUNCTIONS
// ================
// Read a file to a string.
char *load(const char *fn)
{
    int fd = open(fn, O_RDONLY);
    assert(fd != -1);

    off_t size = lseek(fd, 0, SEEK_END);
    assert(size != -1);
    off_t res = lseek(fd, 0, SEEK_SET);
    assert(res != -1);

    size++;  // null terminator
    char *buf = (char *)malloc(size);

    char *p = buf;
    for (;;) {
        // File has gotten bigger since we started? Fuck that.
        assert(p - buf < size);
        ssize_t nread = read(fd, (char *)p, 0x10000);
        assert(nread != -1);
        if (nread == 0) {
            *p = '\0';
            break;
        }

#ifndef NDEBUG
        // Null character? Fuck that shit.
        void *nullbyte = memchr((char *)p, '\0', nread);
        assert(nullbyte == NULL);
#endif

        p += nread;
    }
    int cres = close(fd);
    assert(cres == 0);

    return buf;
}

// Compile the "type" shader named "filename" and attach it to
// "shader_program".
static void compile_shader(GLenum type, const char *filename,
        GLuint shader_program)
{
    GLuint shader = glCreateShader(type);
    char *source = load(filename);
    glShaderSource(shader, 1, &source, 0);
    glCompileShader(shader);
#ifndef NDEBUG
    GLint success;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
    if (!success) {
        GLint log_length;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
        char *log = (char *)malloc(log_length);
        glGetShaderInfoLog(shader, log_length, NULL, log);
        fprintf(stderr, "Failed to compile %s:\n%s", filename, log);
        abort();
    }
#endif
    glAttachShader(shader_program, shader);
}
// Return a shader program with vertex shader "vertfile" and the fragment
// shader "fragfile". The program is not linked, in case stuff still needs to
// be added.
GLuint compile_shader_program(const char *vertfile, const char *fragfile)
{
    GLuint p = glCreateProgram();
    compile_shader(GL_VERTEX_SHADER, vertfile, p);
    compile_shader(GL_FRAGMENT_SHADER, fragfile, p);
    return p;
}


// . . . 


// INIT
// ====

// Make and bind the VAO, shared between both programs.
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

// Init one_program.
float square[] = {0.f, 0.f,  1.f, 0.f,  0.f, 1.f,  1.f, 1.f};
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(square), square, GL_STATIC_DRAW);
// Make sure these indices are unique among all VBOs you are using to render.
GLuint attr = 0;
glEnableVertexAttribArray(attr);
glVertexAttribPointer(attr, 2, GL_FLOAT, GL_FALSE, 0, NULL);

GLuint one_program = compile_shader_program("glsl/2d.vert", "glsl/white.frag");
glBindAttribLocation(one_program, attr, "vertex_pos");
glLinkProgram(one_program);

// Set uniforms.
// . . .

// Do the same thing for the_other_program.
float triangle[] = {0.f, 0.f,  1.f, 0.f,  0.f, 1.f};
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(square), square, GL_STATIC_DRAW);
attr++;
glEnableVertexAttribArray(attr);
glVertexAttribPointer(attr, 2, GL_FLOAT, GL_FALSE, 0, NULL);

GLuint the_other_program =
    compile_shader_program("glsl/2d.vert", "glsl/chrome.frag");
glBindAttribLocation(the_other_program, attr, "vertex_pos");
glLinkProgram(the_other_program);

// Set uniforms.
// . . .



// RENDER ONE FRAME
// ================
glUseProgram(one_program);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glUseProgram(the_other_program);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
12
  • This code looks like it’s from an older version of OpenGL than the question is asking about. The question mentions VAOs, which are mandatory in core profiles since version 3.2, but it appears that the code in this answer does not use VAOs at all and might be from an older version of OpenGL (2.1). Nov 30, 2018 at 8:45
  • Oh. I didn't know VAOs were manditory since 3.2. But there's a good chance this will still work. I can't test this because I don't have a computer that supports opengl 3.2, if you can believe that. I bet you could get it working, though. Nov 30, 2018 at 10:41
  • I just found out my computer actually does support VAOs even though it's only opengl2.1 (through the extension GL_ARB_vertex_array_object), so I was able to test these ideas on VAOs. It still works. I'm updating my answer now. Nov 30, 2018 at 12:06
  • How old is your computer? OpenGL 3.2 is actually very old now, and if your computer has a discrete graphics card manufactured after 2007, or a CPU manufactured after 2010, then it probably supports OpenGL 3.3 or newer. However, you might need to request a “core context” during context creation to get something newer than OpenGL 2.1. This is true for both macOS and true for any Linux system which uses Mesa (which is true if you haven’t installed closed-source drivers). Nov 30, 2018 at 15:08
  • Note that there is at least one major problem with this answer—there is a maximum value for attribute array indexes, and it can be quite small! The most common value for GL_MAX_VERTEX_ATTRIBS is 16, so you might only get 16 different unique indexes. Nov 30, 2018 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.