def plot(self): # Specify shader to be used glUseProgram(self.gls_pgr.program_id) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls #glBindVertexArray(self.vao_id) glUniform4fv(self.gls_id_xy_color, 1, self.plot_color) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glEnableVertexAttribArray(self.vertIndex) # set buffers glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glVertexAttribPointer(self.vertIndex, 2, GL_FLOAT, GL_FALSE, 0, None) glDrawArrays(GL_LINE_STRIP, 0, self.data_points - 1) # Lets unbind the shader and vertex array state glUseProgram(0) # disable arrays glDisableVertexAttribArray(self.vertIndex) glBindVertexArray(0)
def generate_vbo(chunk_data): """Generate VBO object. Args: chunk_data (Chunk): chunk data Return: VboData: VBO data object """ positions = generate_vbo_blocks(chunk_data) chunk_vertexes = generate_vertexes(positions) gl_vertexes = generate_gl_vertexes(chunk_vertexes) chunk_vbo = graphics.VboData(chunk_data.chunk_id) chunk_vbo.vertexes_count = len(gl_vertexes) glBindBuffer(GL_ARRAY_BUFFER, chunk_vbo.name) glBufferData( GL_ARRAY_BUFFER, len(gl_vertexes) * 4, gl_vertexes, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) return chunk_vbo
def _disable_merged_chunk(self, chunk_coords: Tuple[int, int]): """Zero out the region of memory in the merged chunks related to a given chunk""" if chunk_coords in self._merged_chunk_locations: ( offset, size, translucent_offset, translucent_size, ) = self._merged_chunk_locations.pop(chunk_coords) glBindVertexArray(self._vao) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) glBufferSubData( GL_ARRAY_BUFFER, offset * 4, size * 4, numpy.zeros(size, dtype=numpy.float32), ) glBufferSubData( GL_ARRAY_BUFFER, translucent_offset * 4, translucent_size * 4, numpy.zeros(translucent_size, dtype=numpy.float32), ) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0)
def send_vertices(self, vertices): vertices = np.array(vertices, np.float32) glBindBuffer(GL_ARRAY_BUFFER, self.id) glBufferData(self.kind, len(vertices) * 4, vertices, GL_STATIC_DRAW) # glBindBuffer(GL_ARRAY_BUFFER, self.id) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) return self
def __init__(self, index, args): """ setup two buffers : one for the element index, the other with the actual data """ # assume all index are triangles or quads self.nElement = len(index) # interleave data data = hstack(args).flatten() self.indexBuffer = glGenBuffers(1) self.dataBuffer = glGenBuffers(1) indices_buffer = (c_uint * self.nElement)(*index) data_buffer = (c_float * len(data))(*data) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.indexBuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_buffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, self.dataBuffer) glBufferData(GL_ARRAY_BUFFER, data_buffer, GL_STATIC_DRAW) del indices_buffer del data_buffer
def plot(self): # Specify shader to be used glUseProgram(self.gls_pgr.program_id) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls #glBindVertexArray(self.vao_id) glUniform4fv(self.gls_id_xy_color,1, self.plot_color) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glEnableVertexAttribArray(self.vertIndex) # set buffers glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glVertexAttribPointer(self.vertIndex,2, GL_FLOAT, GL_FALSE, 0, None) glDrawArrays(GL_LINE_STRIP, 0, self.data_points-1) # Lets unbind the shader and vertex array state glUseProgram(0) # disable arrays glDisableVertexAttribArray(self.vertIndex) glBindVertexArray(0)
def __init__(self, data): self.cull_face = data["cull_face"] indicesData, buffer = ObjLoader.load_model( "resources/objects/obj/{}.obj".format(data["name"])) self.__indicesLen = len(indicesData) self.VAO = glGenVertexArrays(1) self.VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.VBO) glBufferData(GL_ARRAY_BUFFER, buffer.nbytes, buffer, GL_STATIC_DRAW) glBindVertexArray(self.VAO) # vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, buffer.itemsize * 8, ctypes.c_void_p(0)) # textures glEnableVertexAttribArray(2) glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, buffer.itemsize * 8, ctypes.c_void_p(12)) # normals glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, buffer.itemsize * 8, ctypes.c_void_p(20)) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) self.texture = LoadTexture('resources/objects/texture/{}'.format( data["texture_name"]))
def bind(self, attrib_index): if self._index == 0: return False glBindBuffer(self._array_type, self._vbo) if self._changed: data = self._arr size = data.itemsize * self._index glBufferData(self._array_type, size, data.ptr, GL_DYNAMIC_DRAW) self._changed = False if self._array_type == GL_ARRAY_BUFFER: glEnableVertexAttribArray(attrib_index) count = self.component_count stride = self.bytes_per_element dtype = self.dtype if dtype == 'float32': gl_type = GL_FLOAT elif dtype == 'float64': gl_type = GL_DOUBLE elif dtype == 'uint8': gl_type = GL_UNSIGNED_BYTE elif dtype == 'uint16': gl_type = GL_UNSIGNED_SHORT elif dtype == 'uint32': gl_type = GL_UNSIGNED_INT else: raise UserWarning(f'Unknown data type: {dtype}') glVertexAttribPointer(attrib_index, count, gl_type, False, stride, None) return True
def make_volume_obj(self, stack, spacing): volume_object = VolumeObject(stack, spacing) glEnableVertexAttribArray(self.b_shader.get_attrib("position")) glVertexAttribPointer(self.b_shader.get_attrib("position"), 3, GL_FLOAT, False, self.volume_stride, volume_object.vtVBO) glEnableVertexAttribArray(self.b_shader.get_attrib("texcoord")) glVertexAttribPointer( self.b_shader.get_attrib("texcoord"), 3, GL_FLOAT, False, self.volume_stride, volume_object.vtVBO+12 ) glBindVertexArray(0) glDisableVertexAttribArray(self.b_shader.get_attrib("position")) glDisableVertexAttribArray(self.b_shader.get_attrib("texcoord")) glBindBuffer(GL_ARRAY_BUFFER, 0) self.volume_objects.append(volume_object)
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 initGL(self): self.vertexData = [-1, -1, 0, 1, -1, 0, 0, 1, 0] self.vertexArrayID = glGenVertexArrays(1) glBindVertexArray(self.vertexArrayID) self.attrID = 0 self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) arrayType = GLfloat * len(self.vertexData) #initialize data for the buffer target = GL_ARRAY_BUFFER size = len(self.vertexData) * ctypes.sizeof(ctypes.c_float) data = arrayType(*self.vertexData) usage = GL_STATIC_DRAW glBufferData(target, size, data, usage) glVertexAttribPointer(self.attrID, 3, GL_FLOAT, False, 0, None) glEnableVertexAttribArray(self.attrID) #access the code for the vertex and fragment shaders with open(self.vertPath, 'r') as vertProg: self.vertCode = vertProg.read() with open(self.fragPath, 'r') as fragProg: self.fragCode = fragProg.read() #compile those shaders self.vertShader = shaders.compileShader(self.vertCode, GL_VERTEX_SHADER) self.fragShader = shaders.compileShader(self.fragCode, GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(self.vertShader, self.fragShader) glUseProgram(self.shader)
def __bind_indices_buffer(self, indices: np.ndarray) -> None: vbo_id = glGenBuffers(1) self.__vbos.append(vbo_id) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id) glBufferData(GL_ELEMENT_ARRAY_BUFFER, size=indices.nbytes, data=indices, usage=GL_STATIC_DRAW)
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 draw(self): """Draw test object.""" glBindBuffer(GL_ARRAY_BUFFER, self.vbo) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glDrawArrays(GL_TRIANGLES, 0, 6) glDisableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0)
def add_attribute(self, vid, data, name): """Add array vertex attribute for shaders.""" if data.ndim > 1: data = data.flatten() glBindBuffer(GL_ARRAY_BUFFER, self.__vbo_id[vid]) glBufferData(GL_ARRAY_BUFFER, data.nbytes, data, GL_STATIC_DRAW) glVertexAttribPointer(glGetAttribLocation(self.__program, name), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(vid) self.__attributes.append(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 bufferize(data: np.ndarray, vbo=None) -> int: """Generating Buffer to store this object's vertex data, necessary for drawing""" if vbo is None: vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, data.nbytes, data, GL_STATIC_DRAW) return vbo
def init_vao_vbo(self,data=None): if data.size: self.vao_data=data # 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 self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glBufferData(GL_ARRAY_BUFFER, 4*len(self.vao_data), self.vao_data,GL_DYNAMIC_DRAW) #self.vbo_id = glGenBuffers(1) #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id) #vertexData = numpy.array(quadV, numpy.float32) #glBufferData(GL_ARRAY_BUFFER, 4*len(self.vao_data), self.vao_data,GL_DYNAMIC_DRAW) # self.vao_id = \ #vao_id=glGenVertexArrays(1,None) #self.vao_id=vao_id #print vao_id #glBindVertexArray(self.vao_id[0]) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data #self.vbo_id = glGenBuffers(1) # Bind a buffer before we can use it #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id[0]) # Now go ahead and fill this bound buffer with some data #glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.data), self.data, GL_DYNAMIC_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 # 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)
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 init_vao_vbo(self, data=None): if data.size: self.vao_data = data # 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 self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glBufferData(GL_ARRAY_BUFFER, 4 * len(self.vao_data), self.vao_data, GL_DYNAMIC_DRAW) #self.vbo_id = glGenBuffers(1) #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id) #vertexData = numpy.array(quadV, numpy.float32) #glBufferData(GL_ARRAY_BUFFER, 4*len(self.vao_data), self.vao_data,GL_DYNAMIC_DRAW) # self.vao_id = \ #vao_id=glGenVertexArrays(1,None) #self.vao_id=vao_id #print vao_id #glBindVertexArray(self.vao_id[0]) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data #self.vbo_id = glGenBuffers(1) # Bind a buffer before we can use it #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id[0]) # Now go ahead and fill this bound buffer with some data #glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.data), self.data, GL_DYNAMIC_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 # 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)
def initialize_buffer(buffer_data_size, buffer_data=None, buffer_usage=GL_STATIC_DRAW): if buffer_data is None: buffer_data_size, buffer_data = buffer_data_size buffer = GLuint(0) glGenBuffers(1, buffer) glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer) glBufferData(GL_SHADER_STORAGE_BUFFER, buffer_data_size, buffer_data, buffer_usage) glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0) return buffer
def SetColors(self, colors): if not iterable(colors): return if len(colors) < self.dataNum: return self.colors = colors workingColors = self.colors # workingData, self.dataNum, workingColors = self.GetWorkingSet(self.data, self.dataNum, self.colors) self.colorsNum = len(workingColors) self.colors_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.colors_vbo) glBufferData(GL_ARRAY_BUFFER, workingColors.nbytes, workingColors, GL_STATIC_DRAW) glColorPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) print "Color is ready"
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" self._vao_gridlines, self._vao_bounding_box = glGenVertexArrays(2) vbo = glGenBuffers(5) vertices, colors = self._get_gridlines() self._count_gridlines = vertices.size // 3 glBindVertexArray(self._vao_gridlines) # gridlines glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, colors.nbytes, colors, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # --- points, indices = self._get_bounding_box() self._count_bounding_box = indices.length glBindVertexArray(self._vao_bounding_box) # bounding box glBindBuffer(GL_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[3]) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ptr, GL_STATIC_DRAW) self._axes.create_vaos() glBindVertexArray(0) glDeleteBuffers(5, vbo)
def render(self): """Render game world.""" for vbo in self.vbos: if vbo.render: glBindBuffer(GL_ARRAY_BUFFER, vbo.name) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glDrawArrays( GL_TRIANGLES, 0, vbo.vertexes_count) glDisableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0)
def SetDisplayingItems(self, data, dataLen, colors): self.data = data self.colors = colors self.xcount = len(unique(data[:, 0])) self.ycount = len(unique(data[:, 1])) workingData = self.data workingColors = self.colors self.dataNum = dataLen self.colorsNum = self.dataNum maxVals = amax(workingData, axis=0) self.xMax = maxVals[0] self.yMax = maxVals[1] self.zMax = maxVals[2] minVals = amin(workingData, axis=0) self.xMin = minVals[0] self.yMin = minVals[1] self.zMin = minVals[2] # print "Max before offset:", self.xMax, self.yMax, self.zMax # print "Min before offset:", self.xMin, self.yMin, self.zMin self.diffX = (self.xMax + self.xMin) / 2 self.diffY = (self.yMax + self.yMin) / 2 self.diffZ = (self.zMax + self.zMin) / 2 # print "Offset:", self.diffX, self.diffY, self.diffZ workingData = subtract(workingData, array([self.diffX, self.diffY, self.diffZ], float32)) # recollect limitations maxVals = amax(workingData, axis=0) self.xMax = maxVals[0] self.yMax = maxVals[1] self.zMax = maxVals[2] minVals = amin(workingData, axis=0) self.xMin = minVals[0] self.yMin = minVals[1] self.zMin = minVals[2] # print "Max:", self.xMax, self.yMax, self.zMax # print "Min:", self.xMin, self.yMin, self.zMin self.eyeDistance = 100 * max(abs(self.xMax), abs(self.xMin), abs(self.yMax), abs(self.yMin), abs(self.zMax), abs(self.zMin)) # print "eye distance:", self.eyeDistance self.vertices_vbo = glGenBuffers(1) glEnableClientState(GL_VERTEX_ARRAY) glBindBuffer(GL_ARRAY_BUFFER, self.vertices_vbo) glBufferData(GL_ARRAY_BUFFER, workingData.nbytes, workingData, GL_STATIC_DRAW) glVertexPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) self.colors_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.colors_vbo) glBufferData(GL_ARRAY_BUFFER, workingColors.nbytes, workingColors, GL_STATIC_DRAW) glColorPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) print "Points and color is ready"
def start(self): self.__VBO = glGenBuffers(1) self.__EBO = glGenBuffers(1) self.__instanceVBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.__VBO) glBufferData(GL_ARRAY_BUFFER, self.__vertices.nbytes, self.__vertices, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__EBO) self.__texture_buffer = Texture.get_default_texture() return self.__all_objects = [ (key, val) for key, val in self.get_all_objects().items() if 'Material' in key.components and 'Mesh' in key.components ] vertices = [] indices = [] shaders = defaultdict(list) verts_len = 0 for obj in self.__all_objects: material = obj[0].components['Material'] mesh = obj[0].components['Mesh'] vertices.extend( list(mesh.get_data_positioned_to_material(material))) object_data = { 'pointer': len(vertices), 'length': mesh.vertices.size, 'matrix': obj[1], 'object': obj[0], 'indices': mesh.indices.flatten() + verts_len } # indices.extend(list(mesh.indices.flatten() + verts_len)) verts_len += len(mesh.vertices) if 'Texture' in obj[0].components: object_data['texture'] = obj[0].components['Texture'] shaders[material].append(object_data) self.__data_for_render = shaders self.__vertices = np.array(vertices, dtype=np.float32) self.__indices = np.array(indices, dtype=np.uint32)
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" vbo = glGenBuffers(1) # initialize camera box # TODO: update to obj file vertices = glm.array( vec3(-1.0, -0.5, -1.0), # bottom vec3(-1.0, -0.5, 1.0), vec3(-1.0, 0.5, 1.0), vec3(-1.0, 0.5, -1.0), vec3(1.0, -0.5, -1.0), # right vec3(-1.0, -0.5, -1.0), vec3(-1.0, 0.5, -1.0), vec3(1.0, 0.5, -1.0), vec3(1.0, -0.5, 1.0), # top vec3(1.0, -0.5, -1.0), vec3(1.0, 0.5, -1.0), vec3(1.0, 0.5, 1.0), vec3(-1.0, -0.5, 1.0), # left vec3(1.0, -0.5, 1.0), vec3(1.0, 0.5, 1.0), vec3(-1.0, 0.5, 1.0), vec3(1.0, 0.5, -1.0), # back vec3(-1.0, 0.5, -1.0), vec3(-1.0, 0.5, 1.0), vec3(1.0, 0.5, 1.0), vec3(-1.0, -0.5, -1.0), # front vec3(1.0, -0.5, -1.0), vec3(1.0, -0.5, 1.0), vec3(-1.0, -0.5, 1.0), ) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices.ptr, GL_STATIC_DRAW) self._vaos['box'] = glGenVertexArrays(1) glBindVertexArray(self._vaos['box']) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) self._vaos['camera'] = glGenVertexArrays(1) glBindVertexArray(self._vaos['camera']) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0)
def _setup(self): """Setup OpenGL attributes if required""" if self._vao is None: # if the opengl state has not been set self._shader = get_shader(self.context_identifier, self.shader_name) glUseProgram(self._shader) self._transform_location = glGetUniformLocation( self._shader, "transformation_matrix" ) self._texture_location = glGetUniformLocation(self._shader, "image") self._vao = glGenVertexArrays(1) # create the array glBindVertexArray(self._vao) self._vbo = glGenBuffers(1) # and the buffer glBindBuffer(GL_ARRAY_BUFFER, self._vbo) self._setup_opengl_attrs() self._change_verts() glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glUseProgram(0)
def build_vbo(self, uid, vertexes, gl_vertexes): chunk_vertexes = vertexes gl_vertexes = gl_vertexes vertexes_count = len(chunk_vertexes) chunk_vbo = graphics.VboData(uid) chunk_vbo.vertexes_count = vertexes_count glBindBuffer(GL_ARRAY_BUFFER, chunk_vbo.name) glBufferData( GL_ARRAY_BUFFER, vertexes_count * 4, gl_vertexes, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) self.active_tasks.remove(uid) self.orig_list.append(chunk_vbo)
def getTriangleVAO1(program): # it is a container for buffers vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) vbo_id = glGenBuffers(2) # bind some GL_ARRAY_BUFFER to generated one id # it's a position buffer glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # fill it with values glBufferData(GL_ARRAY_BUFFER, vertex_data1, GL_STATIC_DRAW) # tell, how to interpret it glVertexAttribPointer(program.attribLocation('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) # open the valve, let it to be used. glEnableVertexAttribArray(0) # repeat it for colors. glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, color_data1, GL_STATIC_DRAW) glVertexAttribPointer(program.attribLocation('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # there we unbind current buffer and vertex array object glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) # will bind VAO's at every draw action. return vao_id
def build(self) -> None: self._vao = glGenVertexArrays(1) vbos = glGenBuffers(2) glBindVertexArray(self._vao) self._material.build_shader() vertices = np.array(self._vertices, dtype=np.float32) indices = np.array(self._indices, dtype=np.int32) glBindBuffer(GL_ARRAY_BUFFER, vbos[0]) glEnableVertexAttribArray(0) # shader layout location glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, ctypes.c_void_p(0)) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW) self._vertex_count = len(indices) glBindVertexArray(0) # glDisableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glDeleteBuffers(2, vbos) if self.static: # we can clear this data to free some more memory self._vertices = [] self._indices = []
def update_objects(self) -> None: """Update proxy objects when object list changes. Called from GLCanvas upon core_o_list_changed signal. """ self._meshes.clear() for index, object3d in enumerate(self.core.objects): vao = glGenVertexArrays(1) glBindVertexArray(vao) vertices: glm.array = None normals: glm.array = None indices: glm.array = None if object3d.__class__ == CylinderObject3D: vertices, normals, indices = get_cylinder_vertices( object3d, 24) elif object3d.__class__ == OBJObject3D: vertices = object3d.vertices normals = object3d.normals indices = object3d.indices elif object3d.__class__ == AABBObject3D: vertices, normals, indices = get_aabb_vertices(object3d) else: continue vbo = glGenBuffers(3) # vertices glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices.ptr, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # normals glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, normals.nbytes, normals.ptr, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ptr, GL_STATIC_DRAW) self._meshes.append( Mesh(color=vec4(0.8, 0.8, 0.8, 0.85), count=indices.length * 3, vao=vao, object_id=index, selected=False)) glBindVertexArray(0)
def on_realize(self, area): # We need to make the context current if we want to # call GL API area.make_current() context = area.get_context() if (area.get_error() != None): return fragment_shader = shaders.compileShader(FRAGMENT_SOURCE, GL_FRAGMENT_SHADER) vertex_shader = shaders.compileShader(VERTEX_SOURCE, GL_VERTEX_SHADER) self.shaderContent.shader_prog = shaders.compileProgram( fragment_shader, vertex_shader) glLinkProgram(self.shaderContent.shader_prog) self.vertex_array_object = glGenVertexArrays(1) glBindVertexArray(self.vertex_array_object) # Generate buffers to hold our vertices self.vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertex_buffer) self.position = glGetAttribLocation(self.shaderContent.shader_prog, 'position') self.time_l = glGetUniformLocation(self.shaderContent.shader_prog, 'time') print(self.time_l) # glBindAttribLocation(self.shaderContent.shader_prog, self.time, 'time') glEnableVertexAttribArray(self.position) glVertexAttribPointer(index=self.position, size=4, type=GL_FLOAT, normalized=False, stride=0, pointer=ctypes.c_void_p(0)) glBufferData(GL_ARRAY_BUFFER, 192, self.vertices, GL_STATIC_DRAW) glBindVertexArray(0) glDisableVertexAttribArray(self.position) glBindBuffer(GL_ARRAY_BUFFER, 0) self.on_render(self.shaderContent) return True
def setup_scene_geometry(self, vertex_data, index_data, faces): self.has_geometry = True from tremor.graphics.vbo import VertexBufferObject from OpenGL.GL import glGenVertexArrays, glBindVertexArray, glBindBuffer, GL_FALSE, GL_FLOAT, glGenBuffers, \ GL_STATIC_DRAW, \ GL_ELEMENT_ARRAY_BUFFER, glBufferData, glVertexAttribPointer, ctypes, glEnableVertexAttribArray self.faces = faces self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) self.faceVBO = VertexBufferObject() self.faceVBO.update_data(vertex_data, True) # vertex information: vec3f pos, vec3f norm, vec2f tex self.faceVBO.bind() self.faceIBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.faceIBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_data, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, (3 + 3 + 2) * 4, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, (3 + 3 + 2) * 4, ctypes.c_void_p(3 * 4)) glEnableVertexAttribArray(1) glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, (3 + 3 + 2) * 4, ctypes.c_void_p(6 * 4)) glEnableVertexAttribArray(3) glBindVertexArray(0)
def store_data_in_attribute_list(self, attribute_number: int, data: np.ndarray, dim: int = 3, datatype: int = GL_FLOAT) -> None: """ Stores the position information of the vertices at attribute 0 of the Vertex Array Object. It handles the necessary VBO Args: (int) attribute_number: The attribute number of the VAO where we want the data to be stored (np.ndarray) data: Data to be stored (int) dim: The dimension number of the individual data point. E.g 3 for (x, y, z) coordinates """ vbo_id = glGenBuffers(1) self.__vbos.append(vbo_id) glBindBuffer(GL_ARRAY_BUFFER, vbo_id) glBufferData(GL_ARRAY_BUFFER, data.nbytes, data, GL_STATIC_DRAW) glVertexAttribPointer(attribute_number, dim, datatype, GL_FALSE, 0, None) # Unbind VBO glBindBuffer(GL_ARRAY_BUFFER, 0)
def __init__(self): self.vbo = GLuint() self.vertexes = ( 0, 0, 0, 1.0, 0, 0, 1.0, 1.0, 0, 0, 0, 0, 1.0, 1.0, 0, 0, 1.0, 0, ) self.vertexes_GL = (GLfloat * len( self.vertexes))(*self.vertexes) glGenBuffers(1, self.vbo) glBindBuffer(GL_ARRAY_BUFFER, self.vbo) glBufferData( GL_ARRAY_BUFFER, len(self.vertexes_GL) * 4, self.vertexes_GL, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0)
def __init__(__, args): # assume all elements have correct size __.nElement = len(args[0]) print('new buffer : %i elements' % __.nElement) # interleave data data = hstack(args).flatten() __.indexBuffer = glGenBuffers(1) __.dataBuffer = glGenBuffers(1) indices_buffer = (c_uint * __.nElement)(*list(range(__.nElement))) data_buffer = (c_float * len(data))(*data) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, __.indexBuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_buffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, __.dataBuffer) glBufferData(GL_ARRAY_BUFFER, data_buffer, GL_STATIC_DRAW) del indices_buffer del data_buffer
def buff_vertices(verts: list, indes: list=None) -> int: """Given a list of vertex-like objects, an optional list of indices, returns a VAO handle. Format (all should be floats): [[pX, pY, pZ, nX, nY, nZ, cR, cR, cB, tU, tV]] * len.""" vao = glGenVertexArrays(1) glBindVertexArray(vao) v = vbo.VBO(array(verts, 'f')) v.bind() glVertexAttribPointer(0, 3, GL_FLOAT, False, 44, v) glVertexAttribPointer(1, 3, GL_FLOAT, False, 44, v+12) glVertexAttribPointer(2, 3, GL_FLOAT, False, 44, v+24) glVertexAttribPointer(3, 2, GL_FLOAT, False, 44, v+36) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glEnableVertexAttribArray(2) glEnableVertexAttribArray(3) # Maybe you want to include the vertices verbatim? Go for it. if indes is not None: ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indes)*8, array(indes, 'i'), GL_STATIC_DRAW) glBindVertexArray(0) return vao
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 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 change_verts(self, verts=None): """Modify the vertices in OpenGL.""" log.debug(f"change_verts {self}") try: glBindVertexArray(self._vao) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) except GLError: # There seems to be errors randomly when binding the VBO log.debug( f"Failed binding the OpenGL state for {self}. Trying to reload it." ) self.unload() self._setup() if verts is None: return glBindVertexArray(self._vao) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) self._change_verts(verts) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0)
def _bind_vao_mat_col_id(self, vao, mat: glm.array, col: glm.array, ids: glm.array) -> None: vbo = glGenBuffers(3) glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, mat.nbytes, mat.ptr, GL_STATIC_DRAW) glBindVertexArray(vao) # modelmats glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(0)) glEnableVertexAttribArray(3) glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(16)) # sizeof(glm::vec4) glVertexAttribDivisor(3, 1) glEnableVertexAttribArray(4) glVertexAttribDivisor(4, 1) glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(32)) # 2 * sizeof(glm::vec4) glEnableVertexAttribArray(5) glVertexAttribDivisor(5, 1) glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(48)) # 3 * sizeof(glm::vec4) glEnableVertexAttribArray(6) glVertexAttribDivisor(6, 1) # colors glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, col.nbytes, col.ptr, GL_STATIC_DRAW) glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(7) glVertexAttribDivisor(7, 1) # ids for picking glBindBuffer(GL_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ARRAY_BUFFER, ids.nbytes, ids.ptr, GL_STATIC_DRAW) # it should be GL_INT here, yet only GL_FLOAT works. huh?? glVertexAttribPointer(8, 1, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(8) glVertexAttribDivisor(8, 1) glEnableVertexAttribArray(0) glBindVertexArray(0)
def bind(self): if self._BoundBufferObjects[self._kind] != self._hnd: glBindBuffer(self._kind, self._hnd) self._BoundBufferObjects[self._kind] = self._hnd
# 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)
def __exit__(self, type, value, tb): if self._is_binded: glBindBuffer(GL_ARRAY_BUFFER, 0) self._is_binded = False
def __init__(self, vertices, indices, normals=None, uvs=None): """Constructor. Creates and initializes corresponding OpenGL objects with given data. :param vertices: Vertex data, specified as a contiguous list of X,Y,Z floating point values. :type vertices: list :param indices: Indices which identify model faces. The only supported geometry primitive is the triangle, thus, the size of indices list must be a multiple of 3. :type indices: list :param normals: Normals data, specified as a contiguos list of Xn,Yn,Zn floating point values. List length must be a multiple of 3. :type normals: list :param uvs: List of texture coordinates, specified as a contigous array of U,V floating pont values.. List length must be a multiple of 2. :type uvs: list """ if len(vertices) < 3 or len(vertices) % 3: raise ValueError( 'Vertex data must be an array of floats, which length is a ' 'positive multiple of 3') if len(indices) < 3 or len(indices) % 3: raise ValueError('Indices count must be a positive multiple of 3') if normals and (len(normals) < 3 or len(normals) % 3): raise ValueError( 'Normals data must be an array of floats, which length is a ' 'positive multiple of 3') if uvs is not None and len(uvs) % 2: raise ValueError('UVs count must be a positive multiple of 2') self.num_elements = len(indices) # generate vertex array object and make it active self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) # generate buffers self.buffers = glGenBuffers(2) vbo, ibo = self.buffers # initialize vertex buffer vertex_data = np.array(vertices, np.float32) # append normals data, if provided normals_offset = 0 if normals: normals_offset = vertex_data.nbytes vertex_data = np.append(vertex_data, np.array(normals, np.float32)) # append UVs data, if provided uvs_offset = 0 if uvs: uvs_offset = vertex_data.nbytes vertex_data = np.append(vertex_data, np.array(uvs, np.float32)) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, vertex_data.nbytes, vertex_data, GL_STATIC_DRAW) # initialize index buffer index_data = np.array(indices, np.uint32) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_data.nbytes, index_data, GL_STATIC_DRAW) # specify first attribute as vertex data glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) # if provided, specify normals as second attribute if normals is not None: glEnableVertexAttribArray(1) glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(normals_offset)) # if provided, specify UVs as third attribute if uvs is not None: glEnableVertexAttribArray(2) glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(uvs_offset)) # unbind the vertex array object glBindVertexArray(0)
if not self.vbo_isinit: self.vbo_init() #--- vertices glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id_data) #--- TODO ck if only y/signal value can be copied step 2 glBufferSubData(GL_ARRAY_BUFFER,0,4*len(self.vbo_data_signal), self.vbo_data_signal) """ index buffer GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices.size(), // count GL_UNSIGNED_INT, // type -> GL_UNSIGNED_SHORT (void*)0 // element array buffer offset );
def make_buffer(target, buffer_data, size): buf = glGenBuffers(1) glBindBuffer(target, buf) glBufferData(target, size, buffer_data, GL_STATIC_DRAW) return buf
def __enter__(self): if not self._is_binded: glBindBuffer(GL_ARRAY_BUFFER, self.id) self._is_binded = True