Search code examples
c++imageopenglgraphicstextures

How does OpenGL know which image unit to attach to a uniform?


When loading textures to texture units I usually have to find the location of a texture unit and load the unit to teh unform, in which looks somehow like this:

glActiveTexture(GL_TEXTURE0 + texture_unit);
glBindTexture(target, textureID);
//Get the uniform location in the program and attach the texture unit
GLuint location = program->get_uniform_location(uniform);
glUniform1i(location,texture_unit);

However I have a program that is using image3D and the only line that I call to bind the texture to the image is:

glBindImageTexture(image_unit, textureID, 0, GL_TRUE, 0, GL_READ_WRITE, GL_RGBA8);

And then in the shader I sample it as:

uniform layout(rgba8) image3D image;

vec3 c = vec3(imageLoad(image, ivec3(v_uv,0)));

This outputs the expected values, regardless of what changes I make, so it seems to work just fine. This leads me to my question, how is OpenGL able to determine that the uniform uniform layout(rgba8) image3D image; is to be attached to the image unit through the use of:

glBindImageTexture(image_unit, textureID, 0, GL_TRUE, 0, GL_READ_WRITE, GL_RGBA8);

What would happen if I had multiple images?


Solution

  • The image unit assigned to image in your shader is 0, since this is the default for any uniform whose value you do not provide. And you didn't. In your case, 0 is probably the value of your image_unit variable. So it all works out.

    It's best to do this correctly, by assigning a binding to the image variable. If you're using modern OpenGL, you can put this in the shader with the binding layout qualifier. Otherwise, you have to do exactly what you did for textures (which, BTW, you could also assign in shaders with the binding qualifier): change the value of the uniform with glUniform1i.