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 __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 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 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 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 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 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 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 __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 _change_verts(self, verts=None): """Modify the vertices in OpenGL. Requires binding and unbinding.""" if verts is not None: glBufferData(GL_ARRAY_BUFFER, verts.size * 4, verts, self.vertex_usage) else: glBufferData(GL_ARRAY_BUFFER, self.verts.size * 4, self.verts, self.vertex_usage)
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 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 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 __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 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 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 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 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 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 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 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 __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 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 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 _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 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, 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)
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 ); #ff
# 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 __init__(self, data, size): self.m_RendererID = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.m_RendererID) glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW)
def set_data(self, data, usage=None): if usage is None: usage = GL_STATIC_DRAW self.bind() glBufferData(self._kind, data, usage)
def make_buffer(target, buffer_data, size): buf = glGenBuffers(1) glBindBuffer(target, buf) glBufferData(target, size, buffer_data, GL_STATIC_DRAW) return buf
def update_action_vaos(self) -> None: """Update VAOs when action list changes.""" self._vaos['line'].clear() self._vaos['point'].clear() # --- bind data for lines --- for key, value in self._items['line'].items(): # ignore if 1 or fewer points if len(value) <= 1: continue points = glm.array([vec3(mat[1][3]) for mat in value]) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points.ptr, GL_STATIC_DRAW) vao = glGenVertexArrays(1) glBindVertexArray(vao) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) self._vaos['line'][key] = vao glBindVertexArray(0) # --- bind data for points --- point_mats: glm.array = None point_cols: glm.array = None point_ids: glm.array = None scale = glm.scale(mat4(), vec3(3, 3, 3)) for key, value in self._items['point'].items(): new_mats = glm.array([p[1] * scale for p in value]) color = shade_color(vec4(self.colors[key % len(self.colors)]), -0.3) new_cols = glm.array([color] * len(value)) # if point is selected, darken its color for i, v in enumerate(value): # un-offset ids if (v[0] - self._num_devices) in self.core.selected_points: new_cols[i] = shade_color(vec4(new_cols[i]), 0.6) new_ids = glm.array.from_numbers(ctypes.c_int, *(p[0] for p in value)) point_mats = new_mats if point_mats is None else point_mats.concat( new_mats) point_cols = new_cols if point_cols is None else point_cols.concat( new_cols) point_ids = new_ids if point_ids is None else point_ids.concat( new_ids) # we're done if no points to set if not self._items['point']: return self._num_points = sum(len(i) for i in self._items['point'].values()) self._bind_vao_mat_col_id(self._vaos['box'], point_mats, point_cols, point_ids)
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()