def _do_render(self, **kwargs): if 'objects' not in kwargs.keys(): return instances: List[Generic[EntityTV, AgentTV]] = kwargs['objects'] model: RawModel = instances[0].model glBindVertexArray(model.vao_id) glEnableVertexAttribArray(0) for instance in instances: model: RawModel = instance.model # transformation_matrix = create_transformation_matrix( # instance.position, instance.rotation, instance.scale) self.shader.load_transformation_matrix(instance.transformation_matrix) if isinstance(self.shader, StaticShader): self.shader.load_vertex_color(instance.color) glDrawElements(GL_TRIANGLES, model.vertex_count, GL_UNSIGNED_INT, None) glDisableVertexAttribArray(0) glBindVertexArray(0)
def paintGL(self): if self.crashFlag: #run cleanup operations glUseProgram(0) glDisableVertexAttribArray(self.attrID) glDeleteBuffers(1,[self.vertexBuffer]) glDeleteVertexArrays(1, [self.vertexArrayID]) glLoadIdentity() gluPerspective(45, self.sizeX / self.sizeY, 0.1, 110.0) #set perspective glTranslatef(0, 0, self.zoomLevel) glRotatef(self.rotateDegreeV + self.vOffset, 1, 0, 0) glRotatef(self.rotateDegreeH, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) self.vertexData = [ -1, 1, 0, 0, -1, 0, 1, 1, 0 ] arrayType = GLfloat * len(self.vertexData) target = GL_ARRAY_BUFFER offset = 0 size = len(self.vertexData) * ctypes.sizeof(ctypes.c_float) data = arrayType(*self.vertexData) glBufferSubData(target, offset, size, data) glDrawArrays(GL_TRIANGLES, 0, 3)
def render(self, model, view_matrix, projection_matrix): glUseProgram(self.program) glEnableVertexAttribArray(self.texcoords) glEnableVertexAttribArray(self.vertices) glUniformMatrix4fv( self.model_view_matrix, 1, GL_TRUE, np.dot(view_matrix, model.matrix) ) glUniformMatrix4fv( self.projection_matrix, 1, GL_TRUE, projection_matrix ) for group in model.groups: glBindTexture(GL_TEXTURE_2D, group.material.texture) glUniform1i(self.texture, 0) glVertexAttribPointer( self.vertices, 3, GL_FLOAT, GL_FALSE, 0, group.vertex_buffer ) glVertexAttribPointer( self.texcoords, 2, GL_FLOAT, GL_FALSE, 0, group.texcoord_buffer ) glDrawArrays(GL_TRIANGLES, 0, len(group.vertex_buffer)) glDisableVertexAttribArray(self.vertices) glDisableVertexAttribArray(self.texcoords)
def cleanup(self): ''' Cleans up after the shader has been used ''' glDisableVertexAttribArray(self.attrib_position) # Unbind the shader shaders.glUseProgram(0)
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 draw_points(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnableClientState(GL_VERTEX_ARRAY) # glVertexPointer(3, GL_FLOAT, 24, points) # glColorPointer(3, GL_INT, 24, points+12) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, points) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, points + 12) glEnableVertexAttribArray(1) glDrawArrays(GL_POINTS, 0, imgnp.shape[0] * imgnp.shape[1]) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glutSwapBuffers()
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 _do_render(self, **kwargs): if 'objects' not in kwargs.keys(): return instances = kwargs['objects'] for instance in instances: glBindVertexArray(instance.vao_id) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glDrawArrays(instance.get_draw_mode(), 0, instance.vertex_count) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) 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 render(self, model, view_matrix, projection_matrix): glUseProgram(self.program) glEnableVertexAttribArray(self.vertices) glUniformMatrix4fv(self.model_view_matrix, 1, GL_TRUE, np.dot(view_matrix, model.matrix)) glUniformMatrix4fv(self.projection_matrix, 1, GL_TRUE, projection_matrix) glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0, model.vertex_buffer) glUniform1f(self.color_uniform, 0) glDrawElements(GL_LINES, model.line_buffer.size, GL_UNSIGNED_BYTE, model.line_buffer) glUniform1f(self.color_uniform, 0.5) glDrawElements(GL_TRIANGLES, model.index_buffer.size, GL_UNSIGNED_BYTE, model.index_buffer) glDisableVertexAttribArray(self.vertices)
def render_thing(thing, position_location, normal_location, color_location, modelview_location, context_matrix): try: translate = np.array(matrix_translate(thing["position"]), 'f') except: print "render_thing can't translate thing: ", thing exit() #print "render_thing type: ", thing["type"], thing["position"] context_matrix = np.dot(context_matrix, translate) rotates = thing["rotates"] if len(rotates) == 2: rotate0 = np.array(matrix_rotate_ortho(rotates[0]["angle"], rotates[0]["axis"]), 'f') tmp_matrix = np.dot(context_matrix, rotate0) rotate1 = np.array(matrix_rotate_ortho(rotates[1]["angle"], rotates[1]["axis"]), 'f') context_matrix = np.dot(tmp_matrix, rotate1) #print "render_thing:\n {}\n{}\n{}".format(translate, rotate0, rotate1) #print "context_matrix:\n", context_matrix glUniformMatrix4fv(modelview_location, 1, True, context_matrix) geometry = thing["geometry"] if geometry != None: if geometry["static"]: key = int(float(geometry["id"])) #print "thing type: {}, key: {}".format(thing["type"], key) if not key in vbos: vertices = geometry["vertices"] #print "adding geometry:\n{}".format(vertices[0]) #vbos[key] = (vbo.VBO(np.array(vertices, 'f')), len(vertices)) vbos[key] = (vbo.VBO(vertices), len(vertices)) buffer_object, buffer_size = vbos[key] else: vertices = geometry["vertices"] buffer_object = vbo.VBO(vertices) buffer_size = len(vertices) #print "rendering type: {}, size: {}".format(buffer_object, buffer_size) #pdb.set_trace() buffer_object.bind() try: glEnableVertexAttribArray( position_location ) glEnableVertexAttribArray( normal_location ) glEnableVertexAttribArray( color_location ) stride = 10*4 glVertexAttribPointer( position_location, 3, GL_FLOAT,False, stride, buffer_object ) glVertexAttribPointer( normal_location, 3, GL_FLOAT,False, stride, buffer_object+12 ) glVertexAttribPointer( color_location, 4, GL_FLOAT,False, stride, buffer_object+24 ) glDrawArrays(GL_TRIANGLES, 0, buffer_size) #print 'buffer size: ', buffer_size finally: buffer_object.unbind() glDisableVertexAttribArray( position_location ) glDisableVertexAttribArray( color_location ) else: for child in thing["children"]: render_thing(child, position_location, normal_location, color_location, modelview_location, context_matrix)
def run(): #Start OpenGL and ask it for an OpenGL context pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode(SCREEN_SIZE, pygame.HWSURFACE|pygame.OPENGL|pygame.DOUBLEBUF) #The first thing we do is print some OpenGL details and check that we have a good enough version print("OpenGL Implementation Details:") if glGetString(GL_VENDOR): print("\tGL_VENDOR: {}".format(glGetString(GL_VENDOR).decode())) if glGetString(GL_RENDERER): print("\tGL_RENDERER: {}".format(glGetString(GL_RENDERER).decode())) if glGetString(GL_VERSION): print("\tGL_VERSION: {}".format(glGetString(GL_VERSION).decode())) if glGetString(GL_SHADING_LANGUAGE_VERSION): print("\tGL_SHADING_LANGUAGE_VERSION: {}".format(glGetString(GL_SHADING_LANGUAGE_VERSION).decode())) major_version = int(glGetString(GL_VERSION).decode().split()[0].split('.')[0]) minor_version = int(glGetString(GL_VERSION).decode().split()[0].split('.')[1]) if major_version < 3 or (major_version < 3 and minor_version < 0): print("OpenGL version must be at least 3.0 (found {0})".format(glGetString(GL_VERSION).decode().split()[0])) #Now onto the OpenGL initialisation #Set up depth culling glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) #We create out shaders which do little more than set a flat colour for each face VERTEX_SHADER = shaders.compileShader(b""" #version 130 in vec4 position; in vec4 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; flat out float theColor; void main() { vec4 temp = modelMatrix * position; temp = viewMatrix * temp; gl_Position = projectionMatrix * temp; theColor = clamp(abs(dot(normalize(normal.xyz), normalize(vec3(0.9,0.1,0.5)))), 0, 1); } """, GL_VERTEX_SHADER) FRAGMENT_SHADER = shaders.compileShader(b""" #version 130 flat in float theColor; out vec4 outputColor; void main() { outputColor = vec4(1.0, 0.5, theColor, 1.0); } """, GL_FRAGMENT_SHADER) shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) #And then grab our attribute locations from it glBindAttribLocation(shader, 0, b"position") glBindAttribLocation(shader, 1, b"normal") #Create the Vertex Array Object to hold our volume mesh vertexArrayObject = GLuint(0) glGenVertexArrays(1, vertexArrayObject) glBindVertexArray(vertexArrayObject) #Create the index buffer object indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER, usage=GL_STATIC_DRAW) #Create the VBO vertexPositions = vbo.VBO(vertices, usage=GL_STATIC_DRAW) #Bind our VBOs and set up our data layout specifications with indexPositions, vertexPositions: glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, False, 6*vertices.dtype.itemsize, vertexPositions+(0*vertices.dtype.itemsize)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, False, 6*vertices.dtype.itemsize, vertexPositions+(3*vertices.dtype.itemsize)) glBindVertexArray(0) glDisableVertexAttribArray(0) #Now grab out transformation martix locations modelMatrixUnif = glGetUniformLocation(shader, b"modelMatrix") viewMatrixUnif = glGetUniformLocation(shader, b"viewMatrix") projectionMatrixUnif = glGetUniformLocation(shader, b"projectionMatrix") modelMatrix = np.array([[1.0,0.0,0.0,-32.0],[0.0,1.0,0.0,-32.0],[0.0,0.0,1.0,-32.0],[0.0,0.0,0.0,1.0]], dtype='f') viewMatrix = np.array([[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,0.0,1.0,-50.0],[0.0,0.0,0.0,1.0]], dtype='f') projectionMatrix = np.array([[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0]], dtype='f') #These next few lines just set up our camera frustum fovDeg = 45.0 frustumScale = 1.0 / tan(radians(fovDeg) / 2.0) zNear = 1.0 zFar = 1000.0 projectionMatrix[0][0] = frustumScale projectionMatrix[1][1] = frustumScale projectionMatrix[2][2] = (zFar + zNear) / (zNear - zFar) projectionMatrix[2][3] = -1.0 projectionMatrix[3][2] = (2 * zFar * zNear) / (zNear - zFar) #viewMatrix and projectionMatrix don't change ever so just set them once here with shader: glUniformMatrix4fv(projectionMatrixUnif, 1, GL_TRUE, projectionMatrix) glUniformMatrix4fv(viewMatrixUnif, 1, GL_TRUE, viewMatrix) #These are used to track the rotation of the volume LastFrameMousePos = (0,0) CurrentMousePos = (0,0) xRotation = 0 yRotation = 0 while True: clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: return if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: CurrentMousePos = event.pos LastFrameMousePos = CurrentMousePos if event.type == pygame.MOUSEMOTION and 1 in event.buttons: CurrentMousePos = event.pos diff = (CurrentMousePos[0] - LastFrameMousePos[0], CurrentMousePos[1] - LastFrameMousePos[1]) xRotation += event.rel[0] yRotation += event.rel[1] LastFrameMousePos = CurrentMousePos glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #Perform the rotation of the mesh moveToOrigin = np.array([[1.0,0.0,0.0,-32.0],[0.0,1.0,0.0,-32.0],[0.0,0.0,1.0,-32.0],[0.0,0.0,0.0,1.0]], dtype='f') rotateAroundX = np.array([[1.0,0.0,0.0,0.0],[0.0,cos(radians(yRotation)),-sin(radians(yRotation)),0.0],[0.0,sin(radians(yRotation)),cos(radians(yRotation)),0.0],[0.0,0.0,0.0,1.0]], dtype='f') rotateAroundY = np.array([[cos(radians(xRotation)),0.0,sin(radians(xRotation)),0.0],[0.0,1.0,0.0,0.0],[-sin(radians(xRotation)),0.0,cos(radians(xRotation)),0.0],[0.0,0.0,0.0,1.0]], dtype='f') modelMatrix = rotateAroundY.dot(rotateAroundX.dot(moveToOrigin)) with shader: glUniformMatrix4fv(modelMatrixUnif, 1, GL_TRUE, modelMatrix) glBindVertexArray(vertexArrayObject) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) # Show the screen pygame.display.flip()
def run(): #Start OpenGL and ask it for an OpenGL context pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode( SCREEN_SIZE, pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF) #The first thing we do is print some OpenGL details and check that we have a good enough version print("OpenGL Implementation Details:") if glGetString(GL_VENDOR): print("\tGL_VENDOR: {}".format(glGetString(GL_VENDOR).decode())) if glGetString(GL_RENDERER): print("\tGL_RENDERER: {}".format(glGetString(GL_RENDERER).decode())) if glGetString(GL_VERSION): print("\tGL_VERSION: {}".format(glGetString(GL_VERSION).decode())) if glGetString(GL_SHADING_LANGUAGE_VERSION): print("\tGL_SHADING_LANGUAGE_VERSION: {}".format( glGetString(GL_SHADING_LANGUAGE_VERSION).decode())) major_version = int( glGetString(GL_VERSION).decode().split()[0].split('.')[0]) minor_version = int( glGetString(GL_VERSION).decode().split()[0].split('.')[1]) if major_version < 3 or (major_version < 3 and minor_version < 0): print("OpenGL version must be at least 3.0 (found {0})".format( glGetString(GL_VERSION).decode().split()[0])) #Now onto the OpenGL initialisation #Set up depth culling glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) #We create out shaders which do little more than set a flat colour for each face VERTEX_SHADER = shaders.compileShader( b""" #version 130 in vec4 position; in vec4 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; flat out float theColor; void main() { vec4 temp = modelMatrix * position; temp = viewMatrix * temp; gl_Position = projectionMatrix * temp; theColor = clamp(abs(dot(normalize(normal.xyz), normalize(vec3(0.9,0.1,0.5)))), 0, 1); } """, GL_VERTEX_SHADER) FRAGMENT_SHADER = shaders.compileShader( b""" #version 130 flat in float theColor; out vec4 outputColor; void main() { outputColor = vec4(1.0, 0.5, theColor, 1.0); } """, GL_FRAGMENT_SHADER) shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) #And then grab our attribute locations from it glBindAttribLocation(shader, 0, b"position") glBindAttribLocation(shader, 1, b"normal") #Create the Vertex Array Object to hold our volume mesh vertexArrayObject = GLuint(0) glGenVertexArrays(1, vertexArrayObject) glBindVertexArray(vertexArrayObject) #Create the index buffer object indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER, usage=GL_STATIC_DRAW) #Create the VBO vertexPositions = vbo.VBO(vertices, usage=GL_STATIC_DRAW) #Bind our VBOs and set up our data layout specifications with indexPositions, vertexPositions: glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, False, 6 * vertices.dtype.itemsize, vertexPositions + (0 * vertices.dtype.itemsize)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, False, 6 * vertices.dtype.itemsize, vertexPositions + (3 * vertices.dtype.itemsize)) glBindVertexArray(0) glDisableVertexAttribArray(0) #Now grab out transformation martix locations modelMatrixUnif = glGetUniformLocation(shader, b"modelMatrix") viewMatrixUnif = glGetUniformLocation(shader, b"viewMatrix") projectionMatrixUnif = glGetUniformLocation(shader, b"projectionMatrix") modelMatrix = np.array([[1.0, 0.0, 0.0, -32.0], [0.0, 1.0, 0.0, -32.0], [0.0, 0.0, 1.0, -32.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') viewMatrix = np.array([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, -50.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') projectionMatrix = np.array([[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], dtype='f') #These next few lines just set up our camera frustum fovDeg = 45.0 frustumScale = 1.0 / tan(radians(fovDeg) / 2.0) zNear = 1.0 zFar = 1000.0 projectionMatrix[0][0] = frustumScale projectionMatrix[1][1] = frustumScale projectionMatrix[2][2] = (zFar + zNear) / (zNear - zFar) projectionMatrix[2][3] = -1.0 projectionMatrix[3][2] = (2 * zFar * zNear) / (zNear - zFar) #viewMatrix and projectionMatrix don't change ever so just set them once here with shader: glUniformMatrix4fv(projectionMatrixUnif, 1, GL_TRUE, projectionMatrix) glUniformMatrix4fv(viewMatrixUnif, 1, GL_TRUE, viewMatrix) #These are used to track the rotation of the volume LastFrameMousePos = (0, 0) CurrentMousePos = (0, 0) xRotation = 0 yRotation = 0 while True: clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: return if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: CurrentMousePos = event.pos LastFrameMousePos = CurrentMousePos if event.type == pygame.MOUSEMOTION and 1 in event.buttons: CurrentMousePos = event.pos diff = (CurrentMousePos[0] - LastFrameMousePos[0], CurrentMousePos[1] - LastFrameMousePos[1]) xRotation += event.rel[0] yRotation += event.rel[1] LastFrameMousePos = CurrentMousePos glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #Perform the rotation of the mesh moveToOrigin = np.array( [[1.0, 0.0, 0.0, -32.0], [0.0, 1.0, 0.0, -32.0], [0.0, 0.0, 1.0, -32.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') rotateAroundX = np.array( [[1.0, 0.0, 0.0, 0.0], [0.0, cos(radians(yRotation)), -sin(radians(yRotation)), 0.0], [0.0, sin(radians(yRotation)), cos(radians(yRotation)), 0.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') rotateAroundY = np.array( [[cos(radians(xRotation)), 0.0, sin(radians(xRotation)), 0.0], [0.0, 1.0, 0.0, 0.0], [-sin(radians(xRotation)), 0.0, cos(radians(xRotation)), 0.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') modelMatrix = rotateAroundY.dot(rotateAroundX.dot(moveToOrigin)) with shader: glUniformMatrix4fv(modelMatrixUnif, 1, GL_TRUE, modelMatrix) glBindVertexArray(vertexArrayObject) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) # Show the screen pygame.display.flip()
def disable(self): " Disable the shader attribute " glDisableVertexAttribArray(self.loc)