def __init__(self, data): self.data = data self.vbo_id = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo_id) rawGlBufferData(gl.GL_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), gl.GL_DYNAMIC_DRAW) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
def __init__(self, data, usage): self.buffer = GLuint(0) glGenBuffers(1, self.buffer) self.buffer = self.buffer.value glBindBuffer(GL_ARRAY_BUFFER, self.buffer) glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage)
def set_buffers(self): color_as_attribute = hasattr(self, 'colors') if self.vao == -1: self.vao = glGenVertexArrays(1) self.vbo = glGenBuffers(3 if color_as_attribute else 2) glBindVertexArray(self.vao) glBindBuffer(GL_ARRAY_BUFFER, self.vbo[0]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.vertices), self.vertices, GL_STATIC_DRAW) glVertexAttribPointer(glGetAttribLocation(self.shader, 'pos'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) # glEnable(GL_ELEMENT_ARRAY_BUFFER) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vbo[1]) # glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(self.indices)*4, (ctypes.c_uint * len(self.indices))(*self.indices), GL_STATIC_DRAW) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.indices), self.indices, GL_STATIC_DRAW) if color_as_attribute: glBindBuffer(GL_ARRAY_BUFFER, self.vbo[2]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.colors), self.colors, GL_STATIC_DRAW) glVertexAttribPointer(glGetAttribLocation(self.shader, 'color'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindVertexArray(0)
def glBufferSubData( baseOperation, target, offset, size=None, data=None ): """Copy subset of data into the currently bound vertex-buffer-data object target -- the symbolic constant indicating which buffer type is intended offset -- offset from beginning of buffer at which to copy bytes size -- the count-in-bytes of the array (if an int/long), if None, calculate size from data, if an array and data is None, use as data (i.e. the parameter can be omitted and calculated) data -- data-pointer to be used, may be None to initialize without copying over a data-set Note that if size is not an int/long it is considered to be data *iff* data is None """ if size is None: if data is None: raise TypeError( "Need data or size" ) elif (not isinstance( size, integer_types)) and (data is None): data = size size = None try: if size is not None: size = int( size ) except TypeError: if data is not None: raise TypeError( """Expect an integer size *or* a data-array, not both""" ) data = size size = None data = ArrayDatatype.asArray( data ) if size is None: size = ArrayDatatype.arrayByteCount( data ) return baseOperation( target, offset, size, data )
def glBufferSubData(baseOperation, target, offset, size=None, data=None): """Copy subset of data into the currently bound vertex-buffer-data object target -- the symbolic constant indicating which buffer type is intended offset -- offset from beginning of buffer at which to copy bytes size -- the count-in-bytes of the array (if an int/long), if None, calculate size from data, if an array and data is None, use as data (i.e. the parameter can be omitted and calculated) data -- data-pointer to be used, may be None to initialize without copying over a data-set Note that if size is not an int/long it is considered to be data *iff* data is None """ if size is None: if data is None: raise TypeError("Need data or size") elif (not isinstance(size, int)) and (data is None): data = size size = None try: if size is not None: size = int(size) except TypeError as err: if data is not None: raise TypeError( """Expect an integer size *or* a data-array, not both""") data = size size = None data = ArrayDatatype.asArray(data) if size is None: size = ArrayDatatype.arrayByteCount(data) return baseOperation(target, offset, size, data)
def __init__(self, data, usage): self.buffer = GL.GLuint(0) glGenBuffers(1) # self.buffer) self.buffer = self.buffer.value glBindBuffer(GL_ARRAY_BUFFER_ARB, self.buffer) glBufferData(GL_ARRAY_BUFFER_ARB, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage)
def __init__(self, vertbuffer, indexbuffer): self.buffer = glGenBuffers(1) self.indexbuffer = indexbuffer glBindBuffer(GL_ARRAY_BUFFER, self.buffer) self.numverts = len(vertbuffer) vertbuffer = convertbuffer(vertbuffer) glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(vertbuffer), ADT.voidDataPointer(vertbuffer), GL_STATIC_DRAW)
def __init__(self, vertices): vertexBufferData = numpy.array(vertices, dtype=numpy.float32) self.num_vertices = len(vertices) self.vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vbo) glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(vertexBufferData), ADT.voidDataPointer(vertexBufferData), GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0)
def set_data(self, data, target): self.data = data self.target = target glBindBuffer(self.target, self.vbo) glBufferData(self.target, ArrayDatatype.arrayByteCount(self.data), ArrayDatatype.voidDataPointer(self.data), GL_STATIC_DRAW) glBindBuffer(self.target, 0)
def __init__(self, data, usage=GL_STATIC_DRAW): """ Initiate the vertex buffer object on the CPU """ self.buffer = GLuint(0) glGenBuffers(1, self.buffer) self.buffer = self.buffer.value glBindBuffer(GL_ARRAY_BUFFER, self.buffer) glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage)
def draw(self): """Render the textbox""" # Reload the texture coordinate buffer if anything changed if self._dirty: # Bind and load the buffer glBindBufferARB(GL_ARRAY_BUFFER_ARB, self.__texCoordBuffer) glBufferDataARB(GL_ARRAY_BUFFER_ARB, ArrayDatatype.arrayByteCount(self._texCoordArray), ArrayDatatype.voidDataPointer(self._texCoordArray), GL_DYNAMIC_DRAW) glBindBufferARB(GL_ARRAY_BUFFER, 0) self._dirty = False # Set up transformations glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(self._pos[0], self._pos[1], 0) glScalef(0.25, 0.25, 1) # Set up the foreground color glColor4f(*self._color) # Set up the texture glEnable(GL_TEXTURE_2D) self._charset.bind() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) # Enable vertex and texture arrays glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Set the vertex buffer for rendering glBindBufferARB(GL_ARRAY_BUFFER_ARB, self.__vertexBuffer) glVertexPointer(3, GL_FLOAT, 0, None) # Set the texture coordinate buffer for rendering glBindBufferARB(GL_ARRAY_BUFFER_ARB, self.__texCoordBuffer) glTexCoordPointer(2, GL_FLOAT, 0, None) # Unbind the active buffer--pointers are already specified glBindBufferARB(GL_ARRAY_BUFFER, 0) # Render over everything else glDisable(GL_DEPTH_TEST) # Render glDrawArrays(GL_QUADS, 0, self._cols * self._rows * 4) # Disable vertex and texture arrays glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY)
def initBuffers(self): self.num= len(self.result) self.vertices = numpy.ndarray((self.num/4, 4), dtype=numpy.float32) for i in range(self.num): self.vertices[i/4,i%4] = self.result[i] from OpenGL.arrays import ArrayDatatype as ADT self.bufferVertices = GLuint(0) self.bufferVertices = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER_ARB, self.bufferVertices) glBufferData(GL_ARRAY_BUFFER_ARB, ADT.arrayByteCount(self.vertices), ADT.voidDataPointer(self.vertices), GL_STATIC_DRAW_ARB)
def __init__(self, data, usage): self.buffer = GLuint(0) self.buffer = glGenBuffers(1) self.usage = usage self.data = data # Add a little warning if data.dtype == np.float: Warning('This float array is 64 bit') glBindBuffer(GL_ARRAY_BUFFER, self.buffer) glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage) glBindBuffer(GL_ARRAY_BUFFER, 0)
def __init__(self, v, i): self.__T = mat4() v_buff = numpy.array(v, dtype=numpy.float32) i_buff = numpy.array(i, dtype=numpy.int16) self.__v_hdl = glGenBuffers(1) self.__i_hdl = glGenBuffers(1) self.__i_size = adt.arrayByteCount(i_buff) * 2 glBindBuffer(GL_ARRAY_BUFFER, self.__v_hdl) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__i_hdl) glBufferData(GL_ARRAY_BUFFER, adt.arrayByteCount(v_buff), adt.voidDataPointer(v_buff), GL_STATIC_DRAW) glBufferData(GL_ELEMENT_ARRAY_BUFFER, adt.arrayByteCount(i_buff), adt.voidDataPointer(i_buff), GL_STATIC_DRAW) if glGetError() != GL_NO_ERROR: raise RuntimeError('mesh create error!') Engine.get().add_object(Engine.get(), self)
def bind_buffer(vbo_vertices, vertices_vec, vbo_normals, normals_vec, vbo_indices, indices_vec): glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertices_vec), vertices_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo_normals) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_vec), normals_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) pass
def __init__(self, fragment_shader_path, vertex_shader_path): self.fragment_shader_path = fragment_shader_path self.vertex_shader_path = vertex_shader_path self.vertex_data = np.array( [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0]).astype(dtype=np.float32, order='C') self.vertex_byte_count = ArrayDatatype.arrayByteCount(self.vertex_data) self.index_data = np.array([0, 1, 2, 0, 2, 3]).astype(dtype=np.uint32, order='C') self.index_byte_count = ArrayDatatype.arrayByteCount(self.index_data) self.texture_data = np.array([0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]).astype(dtype=np.float32, order='C') self.texture_byte_count = ArrayDatatype.arrayByteCount( self.texture_data) self.image_loaded = False
def calculateVBOList(self, image = None): ''' Create the VBO list to be passed on to the module for drawing vbolist could possibly be a multi-layered tuple, one tuple per layer. So that it doesn't have to be recalculated every time one single image is changed. ''' if len(self.layers) > 0 and len(self.vbolist) > 2 and image != None: if image.layer == self.layers[0]: self.vbolist.insert(2, image.offset) #note the reversed order here self.vbolist.insert(2, image.textureId) glmod.setVBO(tuple(self.vbolist)) return elif image.layer == self.layers[-1]: self.vbolist.append(image.textureId) self.vbolist.append(image.offset) glmod.setVBO(tuple(self.vbolist)) return self.vbolist = [self.VBO, ADT.arrayByteCount(numpy.zeros((2, 2), 'f'))] for layer in self.layers: for img in self.images[layer]: if img.hidden: continue self.vbolist.append(img.textureId) self.vbolist.append(img.offset) if len(self.vbolist) > 2: glmod.setVBO(tuple(self.vbolist))
def fillBuffers(self, image = None): ''' ALSO FILL IN LATER...PLOX ''' size = 0 vertByteCount = ADT.arrayByteCount(numpy.zeros((8, 2), 'f')) for layer in self.layers: size += len(self.images[layer]) glBindBufferARB(GL_ARRAY_BUFFER_ARB, self.VBO) if self.VBOBuffer <= size or image == None: self.VBOBuffer = nextPowerOfTwo(size+1) glBufferDataARB(GL_ARRAY_BUFFER_ARB, self.VBOBuffer*vertByteCount, None, GL_STATIC_DRAW_ARB) self.offset = 0 for layer in self.layers: for img in self.images[layer]: img.offset = int(float(self.offset)/vertByteCount*4) VBOData = img.getVBOData() glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, self.offset, vertByteCount, VBOData) self.offset += vertByteCount else: image.offset = int(float(self.offset)/vertByteCount*4) VBOData = image.getVBOData() glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, self.offset, vertByteCount, VBOData) self.offset += vertByteCount
def create_grad(rows, cols, size): # y = 5*x + z*z vertices_list = [] def der_x(x): return math.sin(x) def der_z(z): return math.cos(z) for z in range(0, 50): for x in range(0, 50): d_x = der_x(x) d_z = der_z(z) vertices_list.append([x, 0.0, z]) vertices_list.append([x + d_x, 0.0, z + d_z]) vertices_vec = np.array(vertices_list, dtype=np.float32) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertices_vec), vertices_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindVertexArray(0) return (vao, len(vertices_list))
def reserveVBOSize(self, size): ''' Does not work yet. If this function is called, it makes glGenTextures fail ''' return if Globals.vbos and size > self.VBOBuffer: self.VBOBuffer = size vertByteCount = ADT.arrayByteCount(numpy.zeros((8, 2), 'f')) glBufferDataARB(GL_ARRAY_BUFFER_ARB, self.VBOBuffer*vertByteCount, None, GL_STATIC_DRAW_ARB) self.offset = 0 for layer in self.layers: for img in self.images[layer]: img.offset = int(float(self.offset)/vertByteCount*4) VBOData = img.getVBOData() glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, self.offset, vertByteCount, VBOData) self.offset += vertByteCount glBindBuffer(GL_ARRAY_BUFFER_ARB, 0) self.calculateVBOList()
def __init__(self, parent): QGLWidget.__init__(self, parent) self.setMinimumSize(640, 480) self.w = 640 self.h = 480 self.images = dict() self.lastMousePos = [0, 0] self.camera = [0, 0] self.layers = [] self.zoom = 1 self.VBO = None self.vbos = False self.VBOBuffer = 0 self.offset = 0 self.ctrl = False self.shift = False self.qimages = {} self.texext = GL_TEXTURE_2D self.npot = 3 self.lines = dict() self.error = False self.texts = [] self.textid = 0 self.vertByteCount = ADT.arrayByteCount(numpy.zeros((8, 2), 'f')) self.leftMouse = False self.setFocusPolicy(Qt.StrongFocus) self.setMouseTracking(True) #this may be the fix for a weird problem with leaveevents
def __init__(self, parent): QGLWidget.__init__(self, parent) self.setMinimumSize(320, 240) self.w = 640 self.h = 480 self.images = dict() self.lastMousePos = [0, 0] self.camera = [0, 0] self.layers = [] self.zoom = 1 self.VBO = None self.vbos = False self.VBOBuffer = 0 self.offset = 0 self.ctrl = False self.shift = False self.qimages = {} self.texext = GL_TEXTURE_2D self.error = False self.texts = [] self.textid = 0 self.vertByteCount = ADT.arrayByteCount(numpy.zeros((8, 2), 'f')) self.movecam = False #default settings, though overriden in initializeGL by fieldtemp self.npot = 3 self.anifilt = 0 self.compress = False self.magfilter = GL_NEAREST self.mipminfilter = GL_NEAREST_MIPMAP_NEAREST self.minfilter = GL_NEAREST self.setFocusPolicy(Qt.StrongFocus) self.setMouseTracking(True) #this may be the fix for a weird problem with leaveevents
def __init__(self, v, i): self.__T = mat4() self.__verts = numpy.array(v, dtype=numpy.float32) self.__ndx = numpy.array(i, dtype=numpy.int16) self.__id = glGenBuffers(2) glBindBuffer(GL_ARRAY_BUFFER, self.__id[0]) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__id[1]) glBufferData(GL_ARRAY_BUFFER, ARR.arrayByteCount(self.__verts), ARR.voidDataPointer(self.__verts), GL_STATIC_DRAW) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ARR.arrayByteCount(self.__ndx), ARR.voidDataPointer(self.__ndx), GL_STATIC_DRAW) if glGetError() != GL_NO_ERROR: raise RuntimeError('mesh vbo error!')
def vao_update(self,data): if data.size: self.vao_data=data # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) # Now go ahead and fill this bound buffer with some data glBufferSubData(GL_ARRAY_BUFFER,0, ArrayDatatype.arrayByteCount(self.vao_data), self.vao_data)
def read_ply(): plydata = PlyData.read('cloud.ply') vertices_list = [] normal_list = [] color_list = [] for data in plydata.elements[0].data: vertices_list.append([data[0],data[1],data[2]]) normal_list.append([data[3],data[4],data[5]]) color_list.append([data[6], data[7], data[8]]) vector_vertices = np.array(vertices_list, dtype=np.float32) vector_normal = np.array(normal_list, dtype=np.float32) vector_color = np.array(color_list, dtype=np.float32) vector_color /= 255.0 vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_normals = glGenBuffers(1) vbo_colors = glGenBuffers(1) glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_vertices), vector_vertices.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo_normals) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_normal), vector_normal.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, vbo_colors) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_color), vector_color.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(2) glBindVertexArray(0) return vao, len(vertices_list)
def setDrawRect(self, drawRect): self.drawRect = drawRect if Globals.vbos: VBOData = self.getVBOData() vertByteCount = ADT.arrayByteCount(VBOData) glBindBuffer(GL_ARRAY_BUFFER_ARB, self.VBO) glBufferSubData(GL_ARRAY_BUFFER_ARB, int(self.offset*vertByteCount/4), vertByteCount, VBOData)
def setDrawRect(self, drawRect): self.drawRect = drawRect if Globals.vbos: VBOData = self.getVBOData() vertByteCount = ADT.arrayByteCount(VBOData) glBindBuffer(GL_ARRAY_BUFFER_ARB, Globals.glwidget.VBO) glBufferSubData(GL_ARRAY_BUFFER_ARB, int(self.offset*vertByteCount/4), vertByteCount, VBOData)
def __init__(self, ui, pos, rows, cols, color=COLOR_WHITE): """Initialize the vertex buffer, text array, and texture coordinate array""" self._pos = pos self._rows = rows self._cols = cols self._color = color self._charset = ui.characterSet # Set up the vertex buffer self.__vertexBuffer = glGenBuffersARB(1) glBindBufferARB(GL_ARRAY_BUFFER_ARB, self.__vertexBuffer) # Generate the vertices vertices = [] for row in xrange(rows): for col in xrange(cols): vertices.append((col * self.SCALEX, -row, 0)) vertices.append(((col + 1) * self.SCALEX, -row, 0)) vertices.append(((col + 1) * self.SCALEX, -row + 1, 0)) vertices.append((col * self.SCALEX, -row + 1, 0)) vertexArray = numpy.array(vertices, dtype=numpy.float32) # Load the vertices into the vertex buffer glBufferDataARB(GL_ARRAY_BUFFER_ARB, ArrayDatatype.arrayByteCount(vertexArray), ArrayDatatype.voidDataPointer(vertexArray), GL_STATIC_DRAW) # Initialize the text array self._textArray = numpy.zeros((rows, cols), dtype=numpy.uint8) # Set up the texture coordinate buffer self.__texCoordBuffer = glGenBuffersARB(1) glBindBufferARB(GL_ARRAY_BUFFER_ARB, self.__texCoordBuffer) # Initialize all texture coordinates to zero self._texCoordArray = numpy.zeros((rows, cols, 4, 2), dtype=numpy.float32) # Force the buffer to be reloaded on the next draw self._dirty = True
def initialize(self): self.vertices = igl.eigen.MatrixXd() self.faces = igl.eigen.MatrixXi() try: if not igl.read_triangle_mesh(self.mesh_path, self.vertices, self.faces): print("failed to read mesh\n") except: traceback.print_exc(file=sys.stdout) sys.exit(-1) self.face_normals = igl.eigen.MatrixXd() igl.per_face_normals(self.vertices, self.faces, self.face_normals) self.vertex_normals = igl.eigen.MatrixXd() igl.per_vertex_normals(self.vertices, self.faces, igl.PER_VERTEX_NORMALS_WEIGHTING_TYPE_AREA, self.vertex_normals) self.vertex_data = e2p(self.vertices).astype(dtype=np.float32, order='C') self.index_data = e2p(self.faces).astype(dtype=np.uint32, order='C') self.face_normal_data = e2p(self.face_normals).astype(dtype=np.float32, order='C') self.vertex_normal_data = e2p(self.vertex_normals).astype( dtype=np.float32, order='C') self.num_faces = self.index_data.shape[0] self.num_vertices = self.vertex_data.shape[0] self.center = np.mean(self.vertex_data, axis=0) self.max_vals = np.max(self.vertex_data, axis=0) self.min_vals = np.min(self.vertex_data, axis=0) self.extents = self.max_vals - self.min_vals print("min = %s, max = %s, extents = %s" % (self.min_vals, self.max_vals, self.extents)) self.vertex_data = (self.vertex_data - self.center) / self.extents self.vertex_byte_count = ArrayDatatype.arrayByteCount(self.vertex_data) self.vertex_normal_byte_count = ArrayDatatype.arrayByteCount( self.vertex_normal_data) self.index_byte_count = ArrayDatatype.arrayByteCount(self.index_data)
def vao_update(self, data): if data.size: self.vao_data = data # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) # Now go ahead and fill this bound buffer with some data glBufferSubData(GL_ARRAY_BUFFER, 0, ArrayDatatype.arrayByteCount(self.vao_data), self.vao_data)
def createVertexAndTextureBuffers(self, vertices, tcoords, opacity = None): ''' Allocate hardware buffers for vertices, texture coordinates, and optionally opacity. ''' if self.flipHorizontal: vertices[:,0] = -vertices[:,0] if self.flipVertical: vertices[:,1] = -vertices[:,1] GL.glEnableClientState (GL.GL_VERTEX_ARRAY) #vertex buffer in hardware self.gl_vb = GL.GLuint() GL.glGenBuffers(1 , self.gl_vb) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_vb) GL.glBufferData(GL.GL_ARRAY_BUFFER, ADT.arrayByteCount(vertices), ADT.voidDataPointer(vertices), GL.GL_STATIC_DRAW) #vertex buffer tdata in hardware self.gl_tb = GL.GLuint() GL.glGenBuffers(1 , self.gl_tb) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_tb) GL.glBufferData(GL.GL_ARRAY_BUFFER, ADT.arrayByteCount(tcoords), ADT.voidDataPointer(tcoords), GL.GL_STATIC_DRAW) # opacity buffer in hardware (only for warp files) if opacity is not None: self.gl_color = GL.GLuint() GL.glGenBuffers(1 , self.gl_color) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_color) #convert opacity to RGBA, one point for each corner of the quad GL.glBufferData(GL.GL_ARRAY_BUFFER, ADT.arrayByteCount(opacity), ADT.voidDataPointer(opacity), GL.GL_STATIC_DRAW) else: self.gl_color = None GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glDisableClientState(GL.GL_VERTEX_ARRAY)
def glBufferDataARB( baseOperation, target, size, data=None, usage=None ): """Copy given data into the currently bound vertex-buffer-data object target -- the symbolic constant indicating which buffer type is intended size -- if provided, the count-in-bytes of the array data -- data-pointer to be used, may be None to initialize without copying over a data-set usage -- hint to the driver as to how to set up access to the buffer Note: parameter "size" can be omitted, which makes the signature glBufferData( target, data, usage ) instead of: glBufferData( target, size, data, usage ) """ if usage is None: usage = data data = size size = None data = ArrayDatatype.asArray( data ) if size is None: size = ArrayDatatype.arrayByteCount( data ) return baseOperation( target, size, data, usage )
def initializeGL(self): ''' Initialize GL ''' global mod if not hasGLExtension("GL_ARB_framebuffer_object"): print "GL_ARB_framebuffer_object not supported, switching to GL_GENERATE_MIPMAP" self.npot = 2 version = glGetString(GL_VERSION) if int(version[0]) == 1 and int(version[2]) < 4: #no opengl 1.4 support print "GL_GENERATE_MIPMAP not supported, not using mipmapping" self.npot = 1 if not hasGLExtension("GL_ARB_texture_non_power_of_two"): print "GL_ARB_texture_non_power_of_two not supported, switching to GL_ARB_texture_rectangle" self.texext = GL_TEXTURE_RECTANGLE_ARB self.npot = 1 if not hasGLExtension("GL_ARB_texture_rectangle"): print "GL_TEXTURE_RECTANGLE_ARB not supported, switching to GL_TEXTURE_2D" self.texext = GL_TEXTURE_2D self.npot = 0 glEnable(self.texext) glEnable(GL_BLEND) glDisable(GL_DEPTH_TEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glViewport(0, 0, self.width(), self.height()) glClearColor(0.0, 0.0, 0.0, 0.0) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST) initok = False if mod: ret = glmod.init(self.texext) if ret == -1: print "Something terrible went wrong in initializing glmod" mod = False elif ret == -2: print "using gl module without VBO support" else: initok = True print "using gl module with VBO support" if mod and initok: if glInitVertexBufferObjectARB() and bool(glBindBufferARB): self.vbos = True print "VBO support initialised succesfully" self.VBO = int(glGenBuffersARB(1)) glmod.initVBO(self.VBO, ADT.arrayByteCount(numpy.zeros((2, 2), 'f'))) else: print "VBO support initialisation failed, continuing without"
def setTextureRect(self, textureRect): self.textureRect = textureRect if Globals.glwidget.texext == GL_TEXTURE_2D: x = float(textureRect[0])/float(self.qimg.width()) y = float(textureRect[1])/float(self.qimg.height()) w = float(textureRect[2])/float(self.qimg.width()) h = float(textureRect[3])/float(self.qimg.height()) self.textureRect = [x, y, w, h] if Globals.vbos: VBOData = self.getVBOData() vertByteCount = ADT.arrayByteCount(VBOData) glBindBuffer(GL_ARRAY_BUFFER_ARB, Globals.glwidget.VBO) glBufferSubData(GL_ARRAY_BUFFER_ARB, int(self.offset*vertByteCount/4), vertByteCount, VBOData)
def Init(): vao = glGenVertexArrays(1) glBindVertexArray(vao) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) # Each point has 3 coordinates, each coordinate is a float, which has 4 bytes glBufferData(GL_ARRAY_BUFFER, MAX_NUM_POINTS * 12, None, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferSubData(GL_ARRAY_BUFFER, 0, ArrayDatatype.arrayByteCount(array), array) program = ShaderProgram(fragment=fragment_shader, vertex=vertex_shader) glUseProgram(program.program_id) return vao, vbo, program
def draw(self): glUseProgram(self.__material.id) glBindBuffer(GL_ARRAY_BUFFER, self.__id[0]) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__id[1]) t = glGetUniformLocation(self.__material.id, 'time') if t != -1: glUniform1f(t, Engine.get_time()) if self.__material.mv != -1: glUniformMatrix4fv(self.__material.mv, 1, GL_FALSE, self.__T.ptr) if self.__material.pv != -1: glUniformMatrix4fv(self.__material.pv, 1, GL_FALSE, Engine.camera.ptr) glVertexAttribPointer(self.__material.pos, 3, GL_FLOAT, GL_FALSE, 20, None) glEnableVertexAttribArray(self.__material.pos) glVertexAttribPointer(self.__material.tex, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12)) glEnableVertexAttribArray(self.__material.tex) glDrawElements(GL_TRIANGLES, ARR.arrayByteCount(self.__ndx) * 2, GL_UNSIGNED_SHORT, None) if glGetError() != GL_NO_ERROR: raise RuntimeError('draw error!')
def Mouse(button, state, x, y): if button is GLUT_LEFT_BUTTON: if state is GLUT_DOWN: print("MOUSE CLICK (%d, %d)\n", x, y) xc = x / (float)(WINDOW_SIZE / 2) yc = y / (float)(-WINDOW_SIZE / 2) xc -= 1 yc += 1 print("MOUSE CLICK (%f, %f)\n", xc, yc) # Create a class point array = np.concatenate([array, (xc, yc, 0)]).astype(np.float32) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferSubData(GL_ARRAY_BUFFER, 0, ArrayDatatype.arrayByteCount(array), array) glutPostRedisplay() elif GLUT_RIGHT_BUTTON: if state is GLUT_DOWN: glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, MAX_NUM_POINTS * 12, None, GL_STATIC_DRAW)
def __init__(self, parent): QGLWidget.__init__(self, parent) self.setMinimumSize(640, 480) self.w = 640 self.h = 480 self.images = dict() self.lastMousePos = [0, 0] self.camera = [0, 0] self.layers = [] self.zoom = 1 self.VBO = None self.vbos = False self.VBOBuffer = 0 self.offset = 0 self.ctrl = False self.shift = False self.qimages = {} self.texext = GL_TEXTURE_2D self.error = False self.texts = [] self.textid = 0 self.vertByteCount = ADT.arrayByteCount(numpy.zeros((8, 2), 'f')) self.movecam = False #default settings, though overriden in initializeGL by fieldtemp self.npot = 3 self.anifilt = 0 self.compress = False self.magfilter = GL_NEAREST self.mipminfilter = GL_NEAREST_MIPMAP_NEAREST self.minfilter = GL_NEAREST self.setFocusPolicy(Qt.StrongFocus) self.setMouseTracking( True) #this may be the fix for a weird problem with leaveevents
# Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data vbo_id = glGenBuffers(2) # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # Now go ahead and fill this bound buffer with some data glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) # Now specify how the shader program will be receiving this data # In this case the data from this buffer will be # available in the shader as the vin_position vertex attribute glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) # Turn on this vertex attribute in the shader glEnableVertexAttribArray(0) # Now do the same for the other vertex buffer glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data),
def initializeGL(self): ''' Initialize GL ''' global mod #stuff used as defaults for storing user settings. #Removed that feature since I'm lazy and didn't want to import too much from my other projects. self.fieldtemp = ["GL_COMPRESSED_RG_RGTC2", 4.0, "GL_LINEAR", "GL_LINEAR", "GL_LINEAR_MIPMAP_LINEAR", "On", "On", "Magic"] #mipmap support and NPOT texture support block if not hasGLExtension("GL_ARB_framebuffer_object"): print "GL_ARB_framebuffer_object not supported, switching to GL_GENERATE_MIPMAP" self.npot = 2 version = glGetString(GL_VERSION) if int(version[0]) == 1 and int(version[2]) < 4: #no opengl 1.4 support print "GL_GENERATE_MIPMAP not supported, not using mipmapping" self.npot = 1 if not hasGLExtension("GL_ARB_texture_non_power_of_two"): print "GL_ARB_texture_non_power_of_two not supported, switching to GL_ARB_texture_rectangle" self.texext = GL_TEXTURE_RECTANGLE_ARB self.npot = 1 if not hasGLExtension("GL_ARB_texture_rectangle"): print "GL_TEXTURE_RECTANGLE_ARB not supported, switching to GL_TEXTURE_2D" self.texext = GL_TEXTURE_2D self.npot = 0 #assorted settings block if hasGLExtension("GL_EXT_texture_compression_rgtc") and self.fieldtemp[0] != "None": self.compress = self.interpretString(self.fieldtemp[0]) # print "using " + self.fieldtemp[0] + " texture compression" if hasGLExtension("GL_EXT_texture_filter_anisotropic") and self.fieldtemp[1] > 1.0: self.anifilt = self.fieldtemp[1] print "using " + str(self.fieldtemp[1]) + "x anisotropic texture filtering. max: " + str(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)) self.minfilter = self.interpretString(self.fieldtemp[2]) self.magfilter = self.interpretString(self.fieldtemp[3]) self.mipminfilter = self.interpretString(self.fieldtemp[4]) if self.mipminfilter == "Off": self.mipminfilter = -1 if self.format().sampleBuffers() and self.fieldtemp[5] == "On": print "enabling " + str(self.format().samples()) + "x FSAA" glEnable(GL_MULTISAMPLE) else: print "FSAA not supported and/or disabled" glEnable(self.texext) glEnable(GL_BLEND) glDisable(GL_DEPTH_TEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glViewport(0, 0, self.width(), self.height()) glClearColor(0.0, 0.0, 0.0, 0.0) initok = False if mod: ret = glmod.init(self.texext) if ret == -1: print "Something terrible went wrong in initializing glmod" mod = False elif ret == -2: if self.fieldtemp[6] == "On": print "using gl module, VBO support requested but not available" else: print "using gl module, VBO support not requested" else: initok = True if self.fieldtemp[6] == "On": print "using gl module, VBO support requested and available" else: print "using gl module, VBO support not requested" if mod and initok and self.fieldtemp[6] == "On": if glInitVertexBufferObjectARB() and bool(glBindBufferARB): self.vbos = True print "VBO support initialised succesfully" self.VBO = int(glGenBuffersARB(1)) glmod.initVBO(self.VBO, ADT.arrayByteCount(numpy.zeros((2, 2), 'f'))) else: print "VBO support initialisation failed, continuing without"
def main(): pg.init() display = (1680, 1050) pg.display.set_mode(display, DOUBLEBUF|OPENGL) # If everything went well the following calls # will display the version of opengl being used print('Vendor: %s' % (glGetString(GL_VENDOR))) print('Opengl version: %s' % (glGetString(GL_VERSION))) print('GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION))) print('Renderer: %s' % (glGetString(GL_RENDERER))) glClearColor(0.95, 1.0, 0.95, 0) # Lets compile our shaders since the use of shaders is now # mandatory. We need at least a vertex and fragment shader # begore we can draw anything program = ShaderProgram(fragment=fragment, vertex=vertex) # Lets create a VAO and bind it # Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data vbo_id = glGenBuffers(2) # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # Now go ahead and fill this bound buffer with some data glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) # Now specify how the shader program will be receiving this data # In this case the data from this buffer will be available in the shader as the vin_position vertex attribute glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) # Turn on this vertex attribute in the shader glEnableVertexAttribArray(0) # Now do the same for the other vertex buffer glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # Lets unbind our vbo and vao state # We will bind these again in the draw loop glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() glClear(GL_COLOR_BUFFER_BIT) # Specify shader to be used glUseProgram(program.program_id) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls glBindVertexArray(vao_id) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glDrawArrays(GL_TRIANGLES, 0, 3) # Lets unbind the shader and vertex array state glUseProgram(0) glBindVertexArray(0) # Now lets show our master piece on the screen pg.display.flip() pg.time.wait(10)
def __init__(self, data, usage): self.vbo_id = glGenBuffers(2) self.buffer = self.vbo_id[0] glBindBuffer(GL_ARRAY_BUFFER, self.buffer) glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage)
def Init(self): global program, vao, matrix, scale vbo = vbo = 0 vao = glGenVertexArrays(1) glBindVertexArray(vao) self.vertices = np.array([ -0.5, -0.5, -0.5, 1.0, -0.5, -0.5, 0.5, 1.0, -0.5, 0.5, 0.5, 1.0, 0.5, 0.5, -0.5, 1.0, -0.5, -0.5, -0.5, 1.0, -0.5, 0.5, -0.5, 1.0, 0.5, -0.5, 0.5, 1.0, -0.5, -0.5, -0.5, 1.0, 0.5, -0.5, -0.5, 1.0, 0.5, 0.5, -0.5, 1.0, 0.5, -0.5, -0.5, 1.0, -0.5, -0.5, -0.5, 1.0, -0.5, -0.5, -0.5, 1.0, -0.5, 0.5, 0.5, 1.0, -0.5, 0.5, -0.5, 1.0, 0.5, -0.5, 0.5, 1.0, -0.5, -0.5, 0.5, 1.0, -0.5, -0.5, -0.5, 1.0, -0.5, 0.5, 0.5, 1.0, -0.5, -0.5, 0.5, 1.0, 0.5, -0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, -0.5, -0.5, 1.0, 0.5, 0.5, -0.5, 1.0, 0.5, -0.5, -0.5, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, -0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 0.5, -0.5, 1.0, -0.5, 0.5, -0.5, 1.0, 0.5, 0.5, 0.5, 1.0, -0.5, 0.5, -0.5, 1.0, -0.5, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 1.0, -0.5, 0.5, 0.5, 1.0, 0.5, -0.5, 0.5, 1.0 ], dtype=np.float32) self.colors = np.array( [ 1.0, 1.0, 1.0, 1.0, # Face 0.1 - White 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, # Face 1.1 - Yellow 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.2, 0.2, 0.2, 1.0, # Face 2.1 - Grey 0.2, 0.2, 0.2, 1.0, 0.2, 0.2, 0.2, 1.0, 1.0, 1.0, 0.0, 1.0, # Face 1.2 - Yellow 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, # Face 0.2 - White 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.2, 0.2, 0.2, 1.0, # Face 2.2 - Grey 0.2, 0.2, 0.2, 1.0, 0.2, 0.2, 0.2, 1.0, 1.0, 0.0, 0.0, 1.0, # Face 4.1 - Red 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, # Face 5.1 - Green 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, # Face 5.2 - Green 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, # Face 3.1 - Blue 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, # Face 3.2 - Blue 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, # Face 4.2 - Red 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, ], dtype=np.float32) self.object = Object() self.matrix = glm.mat4(1) self.object.height = 1 self.object.width = 1 self.object.depth = 1 # Create vertex buffer object (vbo) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.vertices), self.vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) # Create color buffer object (CBO) cbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, cbo) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.colors), self.colors, GL_STATIC_DRAW) glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # Load and compile shaders. self.program = ShaderProgram(vertex_shader, fragment_shader) glUseProgram(self.program.program_id) # Compute a fix transformation matrix. self.matrix = glm.mat4(1) self.set_perspective() scale = 0.3 # Scale for easier observation self.matrix = glm.scale(self.matrix, glm.vec3(scale, scale, scale)) # Bind transformation matrix. transformLoc = glGetUniformLocation(self.program.program_id, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm.value_ptr(self.matrix)) # Enable depth test glEnable(GL_DEPTH_TEST)
print 'GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)) print 'Renderer: %s' % (glGetString(GL_RENDERER)) glClearColor(0.95, 1.0, 0.95, 0) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) program = ShaderProgram(fragment=fragment, vertex=vertex) vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) vbo_id = glGenBuffers(2) glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_voidp(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_voidp(0)) glEnableVertexAttribArray(1) displacement_loc = program.uniform_location('vu_displacement') glProgramUniform3fv(program.program_id, displacement_loc, 2, displacement_data) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) running = True
def update_data(self, data, usage): glBindBuffer(GL_ARRAY_BUFFER_ARB, self.buffer) glBufferData(GL_ARRAY_BUFFER_ARB, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage)
program = ShaderProgram(fragment=fragment, vertex=vertex) fragment_color_location = glGetFragDataLocation(program.program_id, "fragment_color") print("fragment_color_location = %d" % fragment_color_location) # Generate VAOs. vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) # Generate VBOs. vbo_id = glGenBuffers(3) # Setup the vertex data in VBO. vertex_location = program.attribute_location('vertex_position') vertex_byte_count = ArrayDatatype.arrayByteCount(vertex_data) print("vertex_location = ", vertex_location) print("vertex_byte_count = ", vertex_byte_count) glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) glBufferData(GL_ARRAY_BUFFER, vertex_byte_count, vertex_data, GL_STATIC_DRAW) glVertexAttribPointer(vertex_location, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(vertex_location) # Setup the normal data in VBO. vertex_normal_location = program.attribute_location('vertex_normal') vertex_normal_byte_count = ArrayDatatype.arrayByteCount(vertex_normal_data) print("normal_location = ", vertex_normal_location) print("normal_byte_count = ", vertex_normal_byte_count) glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, vertex_normal_byte_count, vertex_normal_data,
return baseOperation( target, size, data, usage ) @lazy( glBufferSubDataARB ) def glBufferSubDataARB( baseOperation, target, offset, size, data=None ): """Copy subset of data into the currently bound vertex-buffer-data object target -- the symbolic constant indicating which buffer type is intended offset -- offset from beginning of buffer at which to copy bytes size -- the count-in-bytes of the array (if an int/long), if None, calculate size from data, if an array and data is None, use as data (i.e. the parameter can be omitted and calculated) data -- data-pointer to be used, may be None to initialize without copying over a data-set Note that if size is not an int/long it is considered to be data """ try: if size is not None: size = int( size ) except TypeError, err: if data is not None: raise TypeError( """Expect an integer size *or* a data-array, not both""" ) data = size size = None data = ArrayDatatype.asArray( data ) if size is None: size = ArrayDatatype.arrayByteCount( data ) return baseOperation( target, offset, size, data )
def create_index_buffer(self, data, usage=GL_STATIC_DRAW): self.index_buffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.index_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), usage)
def set_data(self, data): self.bind() glBufferData(GL_ARRAY_BUFFER, ADT.arrayByteCount(data), ADT.voidDataPointer(data), self.usage) self.unbind()
def main(): global width global height global camera width = 1024 height = 1024 delta_time = 0.0 last_frame = 0.0 if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, GL_FALSE) window = glfw.create_window(width, height, "opengl_lab1", None, None) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mousemove_callback) glfw.set_mouse_button_callback(window, mouseclick_callback) if not window: glfw.terminate() return glfw.make_context_current(window) fun1 = lambda x, z: math.sin(x+z) fun2 = lambda x, z: math.exp(-x*x - z*z) fun3 = lambda x, z: (x**2 + z**2) / (x*z) contour_plot = lambda x, z: 0.0 heightmap_dummy_fun = lambda x, z: 0.0 surface_size = 50 (fun_vao1, ind_fun1) = create_surface(100, 100, surface_size, fun1, False) (fun_vao2, ind_fun2) = create_surface(100, 100, surface_size, fun2, False) (fun_vao3, ind_fun3) = create_surface(100, 100, surface_size, fun3, False) (grad_vao, grad_point_count) = create_grad(100, 100, surface_size) (contour_plot_vao, ind_con, vec_lines, vector_line_indexes) = create_surface(100, 100, surface_size, 0, False, True) (heightmap_vao, ind_hm) = create_surface(100,100, surface_size, heightmap_dummy_fun, True) (sphere_vao, sphere_ind, normals_for_glyph) = uv_sphere(22, 11) (torus_vao, torus_ind) = uv_torus(5, 10, 100, 100) (cm_vao, ind_cm) = create_surface(100, 100, surface_size, heightmap_dummy_fun, True) (cloud_vao, points_count) = read_ply() (perlin_vao, ind_perlin) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False) (div_vao, ind_div) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False) (traj_vao, ind_traj) = simple_cube() fun_shader_sources = [(GL_VERTEX_SHADER, "shaders/functions.vert"), (GL_FRAGMENT_SHADER, "shaders/functions.frag")] fun_program = ShaderProgram(fun_shader_sources) hm_shader_sources = [(GL_VERTEX_SHADER, "shaders/heightmap.vert"), (GL_FRAGMENT_SHADER, "shaders/heightmap.frag")] hm_program = ShaderProgram(hm_shader_sources) hm_texture = read_texture("1.jpg") contour_plot_shader_sources = [(GL_VERTEX_SHADER, "shaders/contourplot.vert"), (GL_FRAGMENT_SHADER, "shaders/contourplot.frag")] contour_plot_program = ShaderProgram(contour_plot_shader_sources) sphere_shader_sources = [(GL_VERTEX_SHADER, "shaders/sphere.vert"), (GL_FRAGMENT_SHADER, "shaders/sphere.frag")] sphere_program = ShaderProgram(sphere_shader_sources) glyph_shader_sources = [(GL_VERTEX_SHADER, "shaders/glyph.vert"), (GL_GEOMETRY_SHADER, "shaders/glyph.geom"), (GL_FRAGMENT_SHADER, "shaders/glyph.frag")] glyph_program = ShaderProgram(glyph_shader_sources) grad_shader_sources = [(GL_VERTEX_SHADER, "shaders/grad.vert"), (GL_GEOMETRY_SHADER, "shaders/grad.geom"), (GL_FRAGMENT_SHADER, "shaders/grad.frag")] grad_program = ShaderProgram(grad_shader_sources) cm_shader_sources = [(GL_VERTEX_SHADER, "shaders/colormap.vert"), (GL_FRAGMENT_SHADER, "shaders/colormap.frag")] cm_program = ShaderProgram( cm_shader_sources ) perlin_shader_sources = [(GL_VERTEX_SHADER, "shaders/perlin.vert"), (GL_FRAGMENT_SHADER, "shaders/perlin.frag")] perlin_program = ShaderProgram(perlin_shader_sources) cloud_shader_sources = [(GL_VERTEX_SHADER, "shaders/ply.vert"), (GL_FRAGMENT_SHADER, "shaders/ply.frag")] cloud_program = ShaderProgram(cloud_shader_sources) vf_shader_sources = [(GL_VERTEX_SHADER, "shaders/vector_field.vert"), (GL_FRAGMENT_SHADER, "shaders/vector_field.frag")] vf_program = ShaderProgram(vf_shader_sources) traj_shader_sources = [(GL_VERTEX_SHADER, "shaders/trajectory.vert"), (GL_FRAGMENT_SHADER, "shaders/trajectory.frag")] traj_program = ShaderProgram(traj_shader_sources) check_gl_errors() projection = projectionMatrixTransposed(60.0, float(width) / float(height), 1, 1000.0) HDR_TEXTURES_AMOUNT = 33 cm_textures = read_cm_textures(HDR_TEXTURES_AMOUNT) cm_texture_num = 0 cm_change_counter = 0 hdr_textures_speed = 6 perlin_time = 0.0 perlin_time_step = 0.03 cube_multiplier = 1.0 cube_center = [0.0, 0.0, 0.0] traj_points_list = [ cube_center ] cube_edge_length = 2.0 * cube_multiplier offset = cube_edge_length / 10 left_cube_pos = -25 * cube_edge_length cube_steps = -left_cube_pos / offset - 10 traj_points_count = int(cube_steps) for i in range(traj_points_count): traj_points_list.append( [0.5*cube_edge_length * i, 0.0, 0.0] ) traj_part_index = 0 while not glfw.window_should_close(window): current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame glfw.poll_events() doCameraMovement(camera, delta_time) model = translateM4x4(np.array([0.0, 0.0, 0.0])) view = camera.get_view_matrix() glClearColor(0.5, 0.5, 0.5, 1.0) glViewport(0, 0, width, height) glEnable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) fun_program.bindProgram() glUniform3fv(fun_program.uniformLocation("col"), 1 , [1.0, 0, 0] ) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(fun_vao1) glDrawElements(GL_TRIANGLE_STRIP, ind_fun1, GL_UNSIGNED_INT, None) model = translateM4x4(np.array([-1.5*surface_size,0.0 ,0.0 ])) glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0]) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glBindVertexArray(fun_vao2) glDrawElements(GL_TRIANGLE_STRIP, ind_fun2, GL_UNSIGNED_INT, None) model = translateM4x4(np.array([1.5 * surface_size, 0.0, 0.0])) glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 0.0, 1.0]) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glBindVertexArray(fun_vao3) glDrawElements(GL_TRIANGLE_STRIP, ind_fun3, GL_UNSIGNED_INT, None) cloud_program.bindProgram() translate_cloud = translateM4x4(np.array([-2.5*surface_size,0.0 ,0.0 ])) # rotate_cloud = rotateYM4x4(math.radians(180)) model = translate_cloud # glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0]) glUniformMatrix4fv(cloud_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(cloud_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(cloud_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(cloud_vao) glDrawArrays(GL_POINTS, 0, points_count) sphere_program.bindProgram() sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius])) sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size])) glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten()) glUniformMatrix4fv(sphere_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(sphere_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(sphere_vao) glDrawElements(GL_TRIANGLES, sphere_ind, GL_UNSIGNED_INT, None) torus_translate = translateM4x4(np.array([0.0, 0.0, 3.0 * surface_size])) glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(torus_translate + sph_scale).flatten()) glBindVertexArray(torus_vao) glDrawElements(GL_TRIANGLES, torus_ind, GL_UNSIGNED_INT, None) glyph_program.bindProgram() sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius])) sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size])) glUniformMatrix4fv(glyph_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten()) glUniformMatrix4fv(glyph_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(glyph_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) vao = glGenVertexArrays(1) glBindVertexArray(vao) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_for_glyph), normals_for_glyph.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glDrawArrays(GL_POINTS, 0, 10000) glBindVertexArray(0) contour_plot_program.bindProgram() model = translateM4x4(np.array([-1.5 * surface_size, 0.0, -1.5 * surface_size])) glUniformMatrix4fv(contour_plot_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(contour_plot_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(contour_plot_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(contour_plot_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_con, GL_UNSIGNED_INT, None) fun_program.bindProgram() lines_vao = glGenVertexArrays(1) glBindVertexArray(lines_vao) vbo_lines = glGenBuffers(1) vbo_indices = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo_lines) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vec_lines), vec_lines.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_line_indexes), vector_line_indexes.flatten(), GL_STATIC_DRAW) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(lines_vao) glDrawElements(GL_LINES, vector_line_indexes.size, GL_UNSIGNED_INT, None) hm_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -1.5 * surface_size])) bindTexture(0, hm_texture) glUniform1i(hm_program.uniformLocation("tex"), 0) glUniformMatrix4fv(hm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(hm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(hm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(heightmap_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_hm, GL_UNSIGNED_INT, None) cm_program.bindProgram() model = translateM4x4(np.array([1.5 * surface_size, 0.0, -1.5 * surface_size])) cur_cm_texture = cm_textures[cm_texture_num % HDR_TEXTURES_AMOUNT] bindTexture(1, cur_cm_texture) if cm_change_counter % hdr_textures_speed == 0: cm_texture_num += 1 cm_change_counter += 1 glUniform1i(cm_program.uniformLocation("cm_switch"), False) glUniform1i(cm_program.uniformLocation("tex"), 1) glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(cm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(cm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(cm_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None) # draw second animated hdr on the same shader model = translateM4x4(np.array([2.5 * surface_size, 0.0, -2.5 * surface_size])) glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniform1i(cm_program.uniformLocation("cm_switch"), True) glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None) perlin_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -3.5 * surface_size])) glUniformMatrix4fv(perlin_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(perlin_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(perlin_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glUniform1f(perlin_program.uniformLocation("time"), perlin_time) perlin_time += perlin_time_step glBindVertexArray(perlin_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_perlin, GL_UNSIGNED_INT, None) grad_program.bindProgram() model = translateM4x4(np.array([-25.0, 0.0, -7.0 * surface_size])) glUniformMatrix4fv(grad_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(grad_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(grad_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(grad_vao) glDrawArrays(GL_LINES, 0, grad_point_count) vf_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -5.5 * surface_size])) glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(vf_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(vf_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glUniform1i(vf_program.uniformLocation("cm_switch"), True) glBindVertexArray(div_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None) glUniform1i(vf_program.uniformLocation("cm_switch"), False) model = translateM4x4(np.array([1.0 * surface_size, 0.0, -6.5 * surface_size])) glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None) traj_program.bindProgram() l_traj_part =[] r_traj_part =[] if offset > 0: traj_part_index = int(traj_points_count - cm_change_counter % cube_steps) r_traj_part = traj_points_list[0:traj_part_index] for traj_coords in r_traj_part: l_traj_part.append( [-x for x in traj_coords] ) else: traj_part_index = int(traj_points_count - cm_change_counter % cube_steps) # traj_part_index = int(cm_change_counter % cube_steps) l_traj_part = traj_points_list[0:traj_part_index] for traj_coords in l_traj_part: r_traj_part.append([-x for x in traj_coords]) l_traj_vec = np.array(l_traj_part, dtype=np.float32) r_traj_vec = np.array(r_traj_part, dtype=np.float32) indices_list = [i for i in range(len(r_traj_part))] indices_vec = np.array(indices_list, dtype=np.uint32) left_traj_vao = glGenVertexArrays(1) right_traj_vao = glGenVertexArrays(1) left_traj_vertices = glGenBuffers(1) left_traj_indices = glGenBuffers(1) right_traj_vertices = glGenBuffers(1) right_traj_indices = glGenBuffers(1) glBindVertexArray(left_traj_vao) glPointSize( 3.0 ) glBindBuffer(GL_ARRAY_BUFFER, left_traj_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(l_traj_vec), l_traj_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, left_traj_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) glBindVertexArray(right_traj_vao) glBindBuffer(GL_ARRAY_BUFFER, right_traj_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(r_traj_vec), r_traj_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, right_traj_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) glBindVertexArray(0) cube_scale_ = scaleM4x4(np.array([1.0, 1.0, 1.0])) left_cube_pos += offset left_translation = translateM4x4(np.array([left_cube_pos, 0.0, -7.5 * surface_size])) glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(left_translation).flatten()) glUniformMatrix4fv(traj_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(traj_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(left_traj_vao) glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None) glBindVertexArray(traj_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None) right_translation = translateM4x4(np.array([-left_cube_pos, 0.0, -8.5 * surface_size])) glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(right_translation).flatten()) glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None) glBindVertexArray(right_traj_vao) glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None) if not cm_change_counter % cube_steps: # left_cube_pos = left_cube_pos + offset * (cube_steps-1) offset *= -1 # r_traj_part, l_traj_part = l_traj_part, r_traj_part traj_program.unbindProgram() glfw.swap_buffers(window) glfw.terminate()
def main(): if not Init(): print 'GLFW initialization failed' sys.exit(-1) OpenWindowHint(OPENGL_VERSION_MAJOR, 3) OpenWindowHint(OPENGL_VERSION_MINOR, 2) OpenWindowHint(OPENGL_PROFILE, OPENGL_CORE_PROFILE) OpenWindowHint(OPENGL_FORWARD_COMPAT, GL_TRUE) if not OpenWindow(1400, 800, 0, 0, 0, 0, 32, 0, WINDOW): print "OpenWindow failed" Terminate() sys.exit(-1) SetKeyCallback(foo) SetWindowTitle("Modern opengl example") Enable(AUTO_POLL_EVENTS) print 'Vendor: %s' % (glGetString(GL_VENDOR)) print 'Opengl version: %s' % (glGetString(GL_VERSION)) print 'GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)) print 'Renderer: %s' % (glGetString(GL_RENDERER)) glEnable(GL_DEPTH_TEST) glViewport(0, 0, 1400, 800) glClearColor(0.8, 1.0, 0.8, 1.0) program = ShaderProgram(fragment=fragment, vertex=vertex) vao_id = glGenVertexArrays(1) vbo_id = glGenBuffers(3) glBindVertexArray(vao_id) glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normal_data), normal_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_normal'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id[2]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(index_data), index_data, GL_STATIC_DRAW) glBindVertexArray(0) running = True while running: t1 = time.clock() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(program.program_id) glBindVertexArray(vao_id) glDrawElements(GL_TRIANGLES, index_data.shape[0] * index_data.shape[1], GL_UNSIGNED_INT, None) glUseProgram(0) glBindVertexArray(0) SwapBuffers() print time.clock() - t1 running = running and GetWindowParam(OPENED)