Search code examples
pythonopenglglm-mathopengl-compat

Error when using glLoadMatrix and glm.value_ptr()


I'm currently working on an FPS-style camera module in python using OpenGL and GLM. Using glm, I generate a view matrix with gluLookAt(). When I try to load it to OpenGL using glm.value_ptr(), it returns an error:

AttributeError: ("'CtypesPointerHandler' object has no attribute 'arrayByteCount'", <function asArrayTypeSize.<locals>.asArraySize at 0x0000021D3BD0CD08>)

Here's my code:

viewMatrix = glm.lookAt(self.position, self.position + self.front, self.upVector)
glMatrixMode(GL_MODELVIEW)
glLoadMatrixf(glm.value_ptr(viewMatrix))

Please tell me what I'm doing wrong, and maybe explain what glm.value_ptr() returns exactly? Thanks in advance!


Solution

  • When you use PyOpenGL, then you have to convert the matrix to a list. See PyOpenGL - glLoadMatrix:

    viewMatrix = glm.lookAt(self.position, self.position + self.front, self.upVector)
    
    matList = [viewMatrix[i][j] for i in range(4) for j in range(4)]
    
    glMatrixMode(GL_MODELVIEW)
    glLoadMatrixf(matList)
    

    Alternatively glLoadMatrix accepts a ctypes.c_float array. See ctypes - Data types e.g:

    matArray = (ctypes.c_float *16).from_buffer(viewMatrix)
    
    glMatrixMode(GL_MODELVIEW)
    glLoadMatrixf(matArray)
    

    It is even possible to use a numpy.array

    matArray = np.array(viewMatrix, dtype=np.float32)
    
    glMatrixMode(GL_MODELVIEW)
    glLoadMatrixf(matArray)