Search code examples
pythonopenglglutpyopenglfreeglut

My texture is being displayed as completely black in pyOpenGL


I was trying to display a texture in pyOpenGL with the following methods. Instead of the texture being rendered correctly, the entire object was black. The texture is being loaded with PIL in an RGBA format.

I try to load in the texture using this method:

@classmethod
def load_texture(cls, file_name: str):
    try:
        img = Image.open(f"{sys.path[0]}/res/{file_name}.png")
    except Exception as e:
        print(e)
        raise SystemExit
    try:
        ix, iy, image = img.size[0], img.size[1], img.tobytes("raw", "RGBA", 0, -1)
    except SystemError:
        ix, iy, image = img.size[0], img.size[1], img.tobytes("raw", "RGBX", 0, -1)
    texture_id = glGenTextures(1)             # generate a texture texture_id
    cls.__textures.append(texture_id)
    glBindTexture(GL_TEXTURE_2D, texture_id)  # make it current
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    # copy the texture into the current texture texture_id
    glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
    return texture_id

And display it with this method:

@staticmethod
def render(model: TexturedModel):
    raw_model = model.get_raw_model()
    glBindVertexArray(raw_model.get_vao_id())                    # bind the desired VAO to be able to use it
    glEnableVertexAttribArray(0)                             # we have put the indices in the 0th address
    glEnableVertexAttribArray(1)                             # we have put the textures in the 1st address
    glActiveTexture(GL_TEXTURE0)
    glBindTexture(GL_TEXTURE_2D, model.get_texture().get_id())
    glDrawElements(GL_TRIANGLES, raw_model.get_vertex_count(), GL_UNSIGNED_INT, None)
    glDisableVertexAttribArray(0)                            # disable the attributeList after using it
    glDisableVertexAttribArray(1)                            # disable the attributeList after using it
    glBindVertexArray(0)                                     # unbind the VAO

What exactly is going wrong? I suppose the texture isn't getting loaded in right as it's displayed black.


Solution

  • In loader.py I needed to include:

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    

    in the load_texture method before the glTexImage2D call.