I'm learning the OpenGL library with Python, so I use PyOpenGL 3.1.0 with Python 3.6.4 (and pygame 1.9.4 for windowing)
I watched some videos to learn how to render basic triangles with VBOs and VAOs, and so I writed the following code, but I don't understand why my code does not render a simple rectangle from the vertices array...
I think that I missed something about array attribution in vbo but I'm not sure.. Anyone ?
import pygame,numpy
from OpenGL.GL import *
from OpenGL.GLU import *
display = (800,600)
#pygame
pygame.init()
pygame.display.set_mode(display,pygame.DOUBLEBUF|pygame.OPENGL)
#opengl
"""
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 4000)"""
vertices = [-0.5,0.5,0,
-0.5,-0.5,0,
0.5,-0.5,0,
0.5,-0.5,0,
0.5,0.5,0,
-0.5,0.5,0]
vertices = numpy.array(vertices,dtype=numpy.float32)
vao = GLuint()
glGenVertexArrays(1,vao)
glBindVertexArray(vao)
vbo = GLuint()
glGenBuffers(1,vbo)
glBindBuffer(GL_ARRAY_BUFFER,vbo)
glBufferData(GL_ARRAY_BUFFER,len(vertices)*4,vertices,GL_STATIC_DRAW)
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0)
glBindBuffer(GL_ARRAY_BUFFER,0)
glBindVertexArray(0)
a=1
while a:
for event in pygame.event.get():
if event.type == pygame.QUIT:
a = 0
glClearColor(0, 0, 1, 0)
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )
glBindVertexArray(vao)
glEnableVertexAttribArray(0)
glDrawArrays(GL_TRIANGLES,0,len(vertices)//3)
glDisableVertexAttribArray(0)
glBindVertexArray(0)
pygame.display.flip()
pygame.time.wait(10)
pygame.quit()
The issue is the call to glVertexAttribPointer
.
If a named array buffer object is bound then the last parameter (6th parameter) is treated as a byte offset into the buffer object's data store. The data type of the parameter has to be ctypes.c_void_p
.
This means you have to use a ctypes.cast
:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.cast(0, ctypes.c_void_p))
or None
:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
Thoes days it is common to use a shader program.
If you don't use a shader program, then yuo have to use fixed function attributes (glEnableClientState
, glVertexPointer
...).
The only exception is vertex attribute 0. Setting the vertex attribute 0 is completely equivalent to setting the fixed function vertex coordinate array (glVertexPointer
).
See also What are the Attribute locations for fixed function pipeline in OpenGL 4.0++ core profile?.