Search code examples
c++qtopenglglslshader

Can't load texture uniform with glUniform1i function


I try to follow the tutorial on YT on 'The Cherno' channel about OpenGL (you can find my code here). I have two uniforms u_Color and u_Texture that I load using glUniform1i function called from Shader.cpp file. For u_Color everything's alright but when I try to load u_Texture I obtain error code

0x502 (GL_INVALID_OPERATION; Qt debugging stops printing out "Illegal operation" error).

I tried to remove unused calls to "u_Color" uniform in shader AND cpp code, I've tried to use the function outside of GLCall macro and some other stuff but it simply doesn't want to work. I am sure location of the texture is alright (unsigned int) and I think my code looks exactly the same as the one from tutorial that actually works!

I work on Linux system (18.04), with Intel graphic card, and I'm using Qt Creator (Qt Creator 4.11.2 based on Qt 5.14.2) with g++ compiler (7.5.0).

If somebody could check it out I'd really appreciate it.

That's the problematic part of the code from "Shader.cpp"

GLuint uniformlocation = static_cast<GLuint>(glGetUniformLocation(m_rendererID, "u_Texture"));
glUniform1f(uniformLocation, value);

And here's fragment shader that uses u_Texture

#version 330 core

layout(location = 0) out vec4 color;

in vec2 v_TexCoord;

uniform vec4 u_Color;
uniform sampler2D u_Texture;

void main()
{
    vec4 texColor = texture2D(u_Texture, v_TexCoord);
    color = texColor;
}

Solution

  • glUniform1f sets a value of a uniform of the currently installed program, thus the program has to be installed by glUseProgram, before:

    GLuint uniformlocation = static_cast<GLuint>(glGetUniformLocation(m_rendererID, "u_Texture"));
    glUseProgram(m_rendererID);
    glUniform1f(uniformLocation, value);
    

    respectively:

    shader.bind();
    shader.setUniform1i("u_Texture", 0);
    

    The GL_INVALID_OPERATION is caused, by the fact, that there is no current program object.


    Alternatively you can use glProgramUniform to specify the value of a uniform variable for a specified program object