'Failing to get any PyOpenGL functions working, keeps getting error 1282 invalid operation on Windows

I've been searching in Google and Stackoverflow for days now trying to solve this peculiar problem... tried out over 50+ ways suggested by the OpenGL/Python community. My 1st time trying to use PyOpenGL within PyCharm IDE... or Python cmd line.

  • Windows 10 OS
  • no GPU, just Intel UHD 64-bit graphics latest driver and tested OK with OpenGL v4
  • installed Python 3.10
  • installed latest pyopensl, pygame, etc into PyCharm and C:\Python310\
  • even tried installing PyOpenGL via wheel file... PyOpenGL-3.1.6-cp310-cp310-win_amd64.whl and PyOpenGL_accelerate-3.1.6-cp310-cp310-win_amd64.whl

The following simple std codes I got from the WWW community keeps throwing...

OpenGL.error.GLError: GLError(
    err = 1282,
    description = b'invalid operation',
    baseOperation = glGenTextures,
    pyArgs = (
        1,
        <object object at 0x000001E4412E72A0>,
    ),

Here the full codes...

import os
import pygame
from OpenGL.GL import *

class OBJ:
    generate_on_init = True
    @classmethod
    def loadTexture(cls, imagefile):
        surf = pygame.image.load(imagefile)
        image = pygame.image.tostring(surf, 'RGBA', 1)
        ix, iy = surf.get_rect().size
        # Creating Texture
        texid = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, texid)
        # texture wrapping params
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # texture filtering params
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)

        return texid

    @classmethod
    def loadMaterial(cls, filename):
        contents = {}
        mtl = None
        dirname = os.path.dirname(filename)

        for line in open(filename, "r"):
            if line.startswith('#'): continue
            values = line.split()
            if not values: continue
            if values[0] == 'newmtl':
                mtl = contents[values[1]] = {}
            elif mtl is None:
                raise ValueError("mtl file doesn't start with newmtl stmt")
            elif values[0] == 'map_Kd':
                # load the texture referred to by this declaration
                mtl[values[0]] = values[1]
                imagefile = os.path.join(dirname, mtl['map_Kd'])
                print("imagefile=", imagefile)
                mtl['texture_Kd'] = cls.loadTexture(imagefile)
            elif values[0] == 'map_Bump':
                # ignore, do nothing
                print("ignoring... ", values[0])
            else:
                print(values[1:])
                mtl[values[0]] = list(map(float, values[1:]))
        return contents

    def __init__(self, filename, swapyz=False):
        """Loads a Wavefront OBJ file. """
        self.vertices = []
        self.normals = []
        self.texcoords = []
        self.faces = []
        self.gl_list = 0
        dirname = os.path.dirname(filename)

        material = None
        for line in open(filename, "r"):
            if line.startswith('#'): continue
            values = line.split()
            if not values: continue
            if values[0] == 'v':
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.vertices.append(v)
            elif values[0] == 'vn':
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.normals.append(v)
            elif values[0] == 'vt':
                self.texcoords.append(list(map(float, values[1:3])))
            elif values[0] in ('usemtl', 'usemat'):
                material = values[1]
            elif values[0] == 'mtllib':
                self.mtl = self.loadMaterial(os.path.join(dirname, values[1]))
            elif values[0] == 'f':
                face = []
                texcoords = []
                norms = []
                for v in values[1:]:
                    w = v.split('/')
                    face.append(int(w[0]))
                    if len(w) >= 2 and len(w[1]) > 0:
                        texcoords.append(int(w[1]))
                    else:
                        texcoords.append(0)
                    if len(w) >= 3 and len(w[2]) > 0:
                        norms.append(int(w[2]))
                    else:
                        norms.append(0)
                self.faces.append((face, norms, texcoords, material))
        if self.generate_on_init:
            self.generate()

    def generate(self):
        self.gl_list = glGenLists(1)
        glNewList(self.gl_list, GL_COMPILE)
        glEnable(GL_TEXTURE_2D)
        glFrontFace(GL_CCW)
        for face in self.faces:
            vertices, normals, texture_coords, material = face

            mtl = self.mtl[material]
            if 'texture_Kd' in mtl:
                # use diffuse texmap
                glBindTexture(GL_TEXTURE_2D, mtl['texture_Kd'])
            else:
                # just use diffuse colour
                glColor(*mtl['Kd'])

            glBegin(GL_POLYGON)
            for i in range(len(vertices)):
                if normals[i] > 0:
                    glNormal3fv(self.normals[normals[i] - 1])
                if texture_coords[i] > 0:
                    glTexCoord2fv(self.texcoords[texture_coords[i] - 1])
                glVertex3fv(self.vertices[vertices[i] - 1])
            glEnd()
        glDisable(GL_TEXTURE_2D)
        glEndList()

    def render(self):
        glCallList(self.gl_list)

    def free(self):
        glDeleteLists([self.gl_list])

dir_name = os.getcwd()
OBJ(os.path.join(dir_name, 'models/earth.obj'), swapyz=True)

I narrowed down to the "1282 invalid operation" complaint from running ANY glXXXXX() functions. If I removed any glXXXXX() function, it will complain the next glXXXXX() until all of them are removed. I cant even have the simple... texid = glGenTextures(1)

The "earth.obj" I have all its mtl, texture, bump 2D jpg files in same dir as this py file. I tested these 3D/2D files using 3D viewer online to be OK.

Anyone can please give some pointers what is wrong with my OS or graphics driver or packages? Thanks a bunch!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source