Parashoo
Parashoo

Reputation: 325

glm's value_ptr in PyOpenGL returns error when used with glUniformMatrix4fv

I'm using shaders on PyOpenGL to render things, and now I want to use matrices to transform my vertices by passing them to the shaders. For this, I define a transformation matrix in my main code using glm, and then I try to pass it as a uniform to my vertex shader using glUniformMatrix4fv and glm.value_ptr.

When I try to run my code, it returns me an invalid operation error:

OpenGL.error.GLError: GLError(
    err = 1282,
    description = b'invalid operation',
    baseOperation = glUniformMatrix4fv,
    pyArgs = (
        3,
        1,
        GL_FALSE,
        <glfw.LP_c_float object at 0x7f40928b8b70>,
    ),
    cArgs = (
        3,
        1,
        GL_FALSE,
        <glfw.LP_c_float object at 0x7f40928b8b70>,
    ),
    cArguments = (
        3,
        1,
        GL_FALSE,
        <glfw.LP_c_float object at 0x7f40928b8b70>,
    )
)

Here's the relevant code section:

    trans = glm.mat4(1.0)
    trans = glm.rotate(trans, glm.radians(90), glm.vec3(0, 0, 1))
    trans = glm.scale(trans, glm.vec3(0.5, 0.5, 0.5))

    shaderProgram = shaderUtils.shader(vert_shader_file, frag_shader_file)
    shaderProgram.compile()

    transformLocation = glGetUniformLocation(shaderProgram.getID(), 'transform')
    glUniformMatrix4fv(transformLocation, 1, GL_FALSE, glm.value_ptr(trans))

And here's my vertex shader:

#version 450 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 TexCoord;

uniform mat4 transform;

void main() {
        gl_Position = transform * vec4(aPos, 1.0);
        TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}

I had already experienced a similar error when using glLoadMatrix and glm.value_ptr. I had worked around it by turning the matrix into a list using a list comprehension, and I suspect it would work also in this case.

I was wondering if glm.value_ptr is just generally broken in Python, or if I'm just using it wrong? Thanks!

Upvotes: 1

Views: 999

Answers (1)

Rabbid76
Rabbid76

Reputation: 210908

The issue is not caused by glm.value_ptr. You do not get a type error, you ge the OpenGL error "invalid operation".

The error is caused, because you missed to install the shaderProgram before glUniformMatrix4fv.

glUseProgram(shaderProgram.getID())
glUniformMatrix4fv(transformLocation, 1, GL_FALSE, glm.value_ptr(trans))

Note, glUniform* sets a value to a uniform in the default uniform block of the currently installed program and causes a GL_INVALID_OPERATION error, if there is no current program object.

Upvotes: 1

Related Questions