def v_render(): ''' render to vr and window ''' global hmd, ctx, window # resolve multi-sample offscreen buffer gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, ctx.con.offFBO) gl.glReadBuffer(gl.GL_COLOR_ATTACHMENT0) gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, ctx.con.offFBO_r) gl.glDrawBuffer(gl.GL_COLOR_ATTACHMENT0) gl.glBlitFramebuffer(0, 0, 2 * hmd.width, hmd.height, 0, 0, 2 * hmd.width, hmd.height, gl.GL_COLOR_BUFFER_BIT, gl.GL_NEAREST) # blit to window, left only, window is half-size gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, ctx.con.offFBO_r) gl.glReadBuffer(gl.GL_COLOR_ATTACHMENT0) gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, 0) gl.glDrawBuffer(gl.GL_BACK if ctx.con.windowDoublebuffer else gl.GL_FRONT) gl.glBlitFramebuffer(0, 0, hmd.width, hmd.height, 0, 0, hmd.width // 2, hmd.height // 2, gl.GL_COLOR_BUFFER_BIT, gl.GL_NEAREST) # blit to vr texture gl.glActiveTexture(gl.GL_TEXTURE2) gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, ctx.con.offFBO_r) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT1, gl.GL_TEXTURE_2D, hmd.idtex, 0) gl.glDrawBuffer(gl.GL_COLOR_ATTACHMENT1) gl.glBlitFramebuffer(0, 0, 2 * hmd.width, hmd.height, 0, 0, 2 * hmd.width, hmd.height, gl.GL_COLOR_BUFFER_BIT, gl.GL_NEAREST) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT1, gl.GL_TEXTURE_2D, 0, 0) gl.glDrawBuffer(gl.GL_COLOR_ATTACHMENT0) openvr.VRCompositor().submit(openvr.Eye_Left, hmd.vTex, hmd.boundLeft) openvr.VRCompositor().submit(openvr.Eye_Right, hmd.vTex, hmd.boundRight) # swap if window is double-buffered, flush just in case if ctx.con.windowDoublebuffer: glfw.swap_buffers(window) gl.glFlush()
def main(): global angles, angley, anglez, scale, carcass, sphere if not glfw.init(): return window = glfw.create_window(640, 640, "Lab2", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.set_framebuffer_size_callback(window, resize_callback) glfw.set_window_pos_callback(window, drag_callback) l_cube = Cube(0, 0, 0, 1) # r_cube = Cube(0, 0, 0, 1) sphere.recount(parts) while not glfw.window_should_close(window): glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) set_projection() glLoadIdentity() sphere.draw(scale, angles, [0.3, 0.0, 0.4], carcass) # r_cube.draw(scale, angles, [0.3, 0.2, 0.4], carcass) l_cube.draw(0.5, [0, 0, 0], [-0.5, 0.0, -0.25], False) glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(640, 480, "ラララ", None, None) if not window: glfw.terminate() return #init glfw.make_context_current(window) gluOrtho2D(0.0, 640, 0.0, 480) #where is this in glfw? # loop while not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) randomWidth() drawLine(100.0, 400.0, 200.0, 400.0) drawLine(440.0, 400.0, 540.0, 400.0) drawLine(320.0, 350.0, 320.0, 330.0) drawLine(100.0, 400.0, 200.0, 400.0) drawLine(300.0, 200.0, 340.0, 200.0) glfw.swap_buffers(window) glfw.poll_events() glfw.swap_interval(2) glfw.terminate()
def main(): global R, T if not glfw.init(): return window = glfw.create_window(480, 480, "2015004584", None, None) if not window: glfw.terminate() return glfw.set_key_callback(window, key_callback) glfw.make_context_current(window) glfw.swap_interval(0) while not glfw.window_should_close(window): glfw.poll_events() clear() axis() glMultMatrixf(R.T) glMultMatrixf(T.T) render() glfw.swap_buffers(window) glfw.terminate()
def mainLoop(mainLoopObject, window): VAO = mainLoopObject["VAO"] i = mainLoopObject["Indexs"] VertexCount = mainLoopObject["VertexCount"] pos = mainLoopObject["VertexBuffer"] shaderProgram = mainLoopObject["ShaderProgram"] glEnableVertexAttribArray(0) # Loop until the user closes the window while not glfw.window_should_close(window): glClearColor(0.1, 0.1, 0.5, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) transMatrix = glGetUniformLocation(shaderProgram, "transMatrix") glUseProgram(shaderProgram) glUniformMatrix4fv(transMatrix, 1, GL_TRUE, Matrix.translate(0.5 , 0.0 , 0)) glBindVertexArray(VAO) glBindBuffer(GL_ARRAY_BUFFER, pos) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, i) # draw triangle using index glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, ctypes.c_void_p(0)) # Swap front and back buffers glfw.swap_buffers(window) glfw.poll_events() glBindVertexArray(0) glUseProgram(0)
def main(): global vertices, window_height, window_width, to_redraw if not glfw.init(): return window = glfw.create_window(400, 400, "Lab4", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.set_framebuffer_size_callback(window, resize_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClearColor(0, 0, 0, 0) while not glfw.window_should_close(window): # print(vertices) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) draw() glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate()
def main(): window = init_window() if not window: return shader = get_shader() vao = get_vertex() tex = bind_texture("wall.png") tex2 = bind_texture("wall2.jpg") gl.glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) gl.glEnable(gl.GL_DEPTH_TEST) # Loop until the user closes the window while not glfw.window_should_close(window): # Poll for and process events glfw.poll_events() # Render here, e.g. using pyOpenGL render(shader, vao, tex, tex2) # Swap front and back buffers glfw.swap_buffers(window) time.sleep(0.05) gl.glDeleteVertexArrays(1, vao) glfw.terminate()
def swap_buffers(self): """ Swap buffers, increment frame counter and pull events """ glfw.swap_buffers(self.window) self.frames += 1 glfw.poll_events()
def run(self): # initializer timer glfw.set_time(0.0) t = 0.0 while not glfw.window_should_close(self.win) and not self.exitNow: # update every x seconds currT = glfw.get_time() if currT - t > 0.1: # update time t = currT # clear glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # build projection matrix pMatrix = glutils.perspective(45.0, self.aspect, 0.1, 100.0) mvMatrix = glutils.lookAt([0.0, 0.0, -2.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]) # render self.scene.render(pMatrix, mvMatrix) # step self.scene.step() glfw.swap_buffers(self.win) # Poll for and process events glfw.poll_events() # end glfw.terminate()
def main(): init() window = create_window(500, 500, "Hi", None, None) make_context_current(window) initial_setup() colors = { "front": (1, 0, 0), "back": (0, 1, 0), "left": (1, 1, 0), "right": (1, 0, 1), "up": (0, 0, 1), "down": (0, 1, 1), } glClearColor(1, 1, 1, 1) glEnable(GL_DEPTH_TEST) set_lightning() while not window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glRotate(1, 0, 1, 0) draw_cube(0, 0, 0, 5, colors) swap_buffers(window) poll_events() terminate()
def main(): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context window = glfw.create_window(window_width, window_height, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) glfw.set_window_size_callback(window, on_window_size) initGL(window) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL display() # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def __init__(self): self.dir = Dir.empty self.run = True self.snake = Player() if not glfw.init(): return self.window = glfw.create_window(400, 300, "Hello, World!", None, None) if not self.window: glfw.terminate() return glfw.make_context_current(self.window) glfw.set_key_callback(self.window, self.key_callback) while self.run and not glfw.window_should_close(self.window): # Update player's position self.snake.play(self.dir) sleep(0.075) self.draw() glfw.swap_buffers(self.window) glfw.poll_events() if self.snake.alive is False: sleep(1.075) self.run = False glfw.terminate()
def run(self): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context self.window = glfw.create_window(640, 480, "Hello World", None, None) if not self.window: glfw.terminate() return renderer = RiftGLRendererCompatibility() # Paint a triangle in the center of the screen renderer.append(TriangleDrawerCompatibility()) # Make the window's context current glfw.make_context_current(self.window) # Initialize Oculus Rift renderer.init_gl() renderer.rift.recenter_pose() glfw.set_key_callback(self.window, self.key_callback) # Loop until the user closes the window while not glfw.window_should_close(self.window): # Render here, e.g. using pyOpenGL renderer.display_rift_gl() # Swap front and back buffers glfw.swap_buffers(self.window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): # Initialize the library if not glfw.init(): return glfw.set_error_callback(error_callback) # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 480, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) program = common2d.init_shader_program() # Loop until the user closes the window while not glfw.window_should_close(window): # Render here common2d.display(program) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def renderLoop(self): self.initGL() while not glfw.window_should_close(self.window): w, h = glfw.get_framebuffer_size(self.window) self.renderFrame() glfw.swap_buffers(self.window) glfw.poll_events() self.destroyGL()
def get_image(): glfw.swap_buffers(window) b = glReadPixels(width, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE) glfw.swap_buffers(window) im = Image.fromstring(mode="RGB", size=(width, height), data=b) im = im.transpose(Image.FLIP_TOP_BOTTOM) im = im.convert("L") return im
def draw_a_triangle(): if not glfw.init(): return -1; # Create a windowed mode window and its OpenGL context glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(1024, 768, "Triangle", None, None); if window == None: glfw.terminate() return -1 # Make the window's context current glfw.make_context_current(window) # glfw.Experimental = True glClearColor(0.0, 0.1, 0.2, 1.0) flatten = lambda l: [u for t in l for u in t] vertices = [(-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (0.0, 1.0, 0.0)] indices = range(3) vao_handle = glGenVertexArrays(1) glBindVertexArray(vao_handle) program_handle = tools.load_program("../shader/simple.v.glsl", "../shader/simple.f.glsl") f_vertices = flatten(vertices) c_vertices = (c_float*len(f_vertices))(*f_vertices) v_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, v_buffer) glBufferData(GL_ARRAY_BUFFER, c_vertices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, v_buffer) glVertexAttribPointer(0, #glGetAttribLocation(program_handle, "vertexPosition_modelspace"), 3, GL_FLOAT, False, 0, None) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_handle) glDrawArrays(GL_TRIANGLES, 0, 3) glDisableVertexAttribArray(vao_handle) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate(); pass
def show(molecule, width=500, height=500, show_bonds=True, bonds_method='radii', bonds_param=None, camera=None, title='mogli'): """ Interactively show the given molecule with OpenGL. By default, bonds are drawn, if this is undesired the show_bonds parameter can be set to False. For information on the bond calculation, see Molecule.calculate_bonds. If you pass a tuple of camera position, center of view and an up vector to the camera parameter, the camera will be set accordingly. Otherwise the molecule will be viewed in the direction of the z axis, with the y axis pointing upward. """ global _camera molecule.positions -= np.mean(molecule.positions, axis=0) max_atom_distance = np.max(la.norm(molecule.positions, axis=1)) if show_bonds: molecule.calculate_bonds(bonds_method, bonds_param) # If GR3 was initialized earlier, it would use a different context, so # it will be terminated first. gr3.terminate() # Initialize GLFW and create an OpenGL context glfw.init() glfw.window_hint(glfw.SAMPLES, 16) window = glfw.create_window(width, height, title, None, None) glfw.make_context_current(window) glEnable(GL_MULTISAMPLE) # Set up the camera (it will be changed during mouse rotation) if camera is None: camera_distance = -max_atom_distance*2.5 camera = ((0, 0, camera_distance), (0, 0, 0), (0, 1, 0)) camera = np.array(camera) _camera = camera # Create the GR3 scene gr3.setbackgroundcolor(255, 255, 255, 0) _create_gr3_scene(molecule, show_bonds) # Configure GLFW glfw.set_cursor_pos_callback(window, _mouse_move_callback) glfw.set_mouse_button_callback(window, _mouse_click_callback) glfw.swap_interval(1) # Start the GLFW main loop while not glfw.window_should_close(window): glfw.poll_events() width, height = glfw.get_window_size(window) glViewport(0, 0, width, height) _set_gr3_camera() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gr3.drawimage(0, width, 0, height, width, height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL) glfw.swap_buffers(window) glfw.terminate() gr3.terminate()
def main(): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 480, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL # Swap front and back buffers glfw.swap_buffers(window) gl_begin( GL_TRIANGLES ) glColor3f( 1.0, 0.0, 0.0 ) glVertex3f( 0.0, 1.0, 0.0 ) glColor3f( 0.0, 1.0, 0.0 ) glVertex3f( -1.0, -1.0, 1.0 ) glColor3f( 0.0, 0.0, 1.0 ) glVertex3f( 1.0, -1.0, 1.0) glColor3f( 1.0, 0.0, 0.0 ) glVertex3f( 0.0, 1.0, 0.0) glColor3f( 0.0, 1.0, 0.0 ) glVertex3f( -1.0, -1.0, 1.0) glColor3f( 0.0, 0.0, 1.0 ) glVertex3f( 0.0, -1.0, -1.0) #glColor3f( 1.0f, 0.0f, 0.0f ) #glVertex3f( 0.0f, 1.0f, 0.0f) #glColor3f( 0.0f, 1.0f, 0.0f ) #glVertex3f( 0.0f, -1.0f, -1.0f) #glColor3f( 0.0f, 0.0f, 1.0f ) #glVertex3f( 1.0f, -1.0f, 1.0f) #glColor3f( 1.0f, 0.0f, 0.0f ) #glVertex3f( -1.0f, -1.0f, 1.0f) #glColor3f( 0.0f, 1.0f, 0.0f ) #glVertex3f( 0.0f, -1.0f, -1.0f) #glColor3f( 0.0f, 0.0f, 1.0f ) #glVertex3f( 1.0f, -1.0f, 1.0f) glEnd() # Poll for and process events glfw.poll_events() glfw.terminate()
def run(self): self.setup() while not self.quit: self.clear_screen() self.update() self.render() glfw.swap_buffers(self.window) glfw.poll_events() # time.sleep(.03) self.teardown()
def drawScene(self): # First pass if self.useFramebuffers: glBindFramebuffer(GL_FRAMEBUFFER, self.framebuffers[0].buffer) glDrawBuffers(1, [GL_COLOR_ATTACHMENT0]) if self.antialiasing > 0: glEnable(GL_MULTISAMPLE) else: glBindFramebuffer(GL_FRAMEBUFFER, 0) # Enable writing to depth mask and clear it glDepthMask(GL_TRUE) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.resetShaders() # Draw background, do not use depth mask glDepthMask(GL_FALSE) glDisable(GL_DEPTH_TEST) self.shaderStorage.background.enable() self.screenPlane.draw() # Draw other objects, use depth mask and enable depth test glDepthMask(GL_TRUE) glEnable(GL_DEPTH_TEST) for renderObject in self.objects: renderObject.draw(self.projectionMatrix, self.modelViewMatrix, self.lights, self.wireframe) # Second pass, do not use depth mask, depth test is disabled glDepthMask(GL_FALSE) glDisable(GL_DEPTH_TEST) if self.useFramebuffers: if self.antialiasing > 0: glDisable(GL_MULTISAMPLE) if self.overlay: glBindFramebuffer(GL_FRAMEBUFFER, self.framebuffers[1].buffer) self.shaderStorage.merge.enable(self.framebuffers[0].color) self.screenPlane.draw() glBindFramebuffer(GL_FRAMEBUFFER, self.framebuffers[2].buffer) self.shaderStorage.blur.enable(self.viewport, numpy.array([0.0, 1.0]), self.framebuffers[1].color) self.screenPlane.draw() glBindFramebuffer(GL_FRAMEBUFFER, 0) self.shaderStorage.blurMasked.enable(self.viewport, numpy.array([1.0, 0.0]), self.framebuffers[2].color, self.framebuffers[1].color, self.overlayMask.buffer) self.screenPlane.draw() else: glBindFramebuffer(GL_FRAMEBUFFER, 0) self.shaderStorage.merge.enable(self.framebuffers[0].color) self.screenPlane.draw() glfw.swap_buffers(self.window)
def main(): # Initialize the library if not glfw.init(): return # Set some window hints glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3); glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3); glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE); glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE); glfw.window_hint(glfw.SAMPLES, 16) # This works as expected glfw.window_hint(glfw.RESIZABLE, 0) # These should work, but don't :( # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226 # ended up using xdotool, see run.py glfw.window_hint(glfw.FOCUSED, 0) # I've set 'shader-*' to raise in openbox-rc as workaround # Looking at the code and confirming version 3.1.2 and it should work glfw.window_hint(glfw.FLOATING, 1) # Create a windowed mode window and its OpenGL context window = glfw.create_window(300, 300, "shader-test", None, None) if not window: glfw.terminate() return # Move Window glfw.set_window_pos(window, 1600, 50) # Make the window's context current glfw.make_context_current(window) # vsync glfw.swap_interval(1) # Setup GL shaders, data, etc. initialize() # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL render() # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def run(self): glfw.make_context_current(self._wnd) self._ctx = ModernGL.create_context() self.initialize(self._ctx) while not glfw.window_should_close(self._wnd): width, height = self.size() self._ctx.viewport = (0, 0, width, height) self.render(self._ctx) glfw.swap_buffers(self._wnd) glfw.wait_events()
def main(): global current_vao global vaos if not opengl_init(): return glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_key_callback(window,key_event) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0,0,0.4,0) # Create vertex array object (VAO) 1: Full Triangle vao = glGenVertexArrays(1) glBindVertexArray(vao) init_object(vertex_data) glBindVertexArray(0) # Create vertex array object (VAO) 2: 1/2 Triangle vao2 = glGenVertexArrays(1) glBindVertexArray(vao2) init_object(vertex_data2) glBindVertexArray(0) program_id = common.LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" ) vertex_buffer = glGenBuffers(1) current_vao = 0 vaos = [vao,vao2] glewInit() while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_id) glBindVertexArray(vaos[current_vao]) # Draw the triangle ! glDrawArrays (GL_TRIANGLES, 0, 3)#3 indices starting at 0 -> 1 triangle glBindVertexArray(0) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(640, 480, "Lab2", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) while not glfw.window_should_close(window) and not ex: draw() glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def draw(x): set_param(x) # Render here # Make the window's context current shaject_mat = shadow_proj_mat(vec3(0,1,0), vec3(0,-0.45,0), light_pos) glfw.make_context_current(window) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # draw the scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_CULL_FACE) glViewport(0,0,width,height) glUseProgram(program_handle) glUniform3f(light_pos_loc, light_pos.x, light_pos.y, light_pos.z) model_view_inv = (view_mat * cube.model_mat).inverse() glUniformMatrix4fv(MVint_loc, 1, GL_TRUE, model_view_inv.toList()) glUniformMatrix4fv(M_loc, 1, GL_FALSE, cube.model_mat.toList()) MVP = proj_mat * view_mat * cube.model_mat glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, MVP.toList()) glDrawElements(GL_TRIANGLES, len(cube.obj.indices), GL_UNSIGNED_SHORT, None); glUniformMatrix4fv(MVint_loc, 1, GL_TRUE, floor_MVinv.toList()) glUniformMatrix4fv(M_loc, 1, GL_FALSE, floor_model_mat.toList()) glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, floor_MVP.toList()) glDrawElements(GL_TRIANGLES, len(cube.obj.indices), GL_UNSIGNED_SHORT, None) glDisable(GL_CULL_FACE) glUseProgram(shadow_program_handle) glUniformMatrix4fv(shadow_MsVP_loc, 1, GL_FALSE, (VP_mat*shaject_mat*cube.model_mat).toList()) glDrawElements(GL_TRIANGLES, len(cube.obj.indices), GL_UNSIGNED_SHORT, None) glViewport(width, 0, width, height) glDisable(GL_CULL_FACE) glUseProgram(basic_program_handle) glDrawElements(GL_TRIANGLES, len(cube.obj.indices), GL_UNSIGNED_SHORT, None) glUseProgram(shadow_program_handle) glUniformMatrix4fv(shadow_MsVP_loc, 1, GL_FALSE, (VP_mat_top*shaject_mat*cube.model_mat).toList()) # glUniformMatrix4fv(shadow_M_loc, 1, GL_FALSE, model_mat.toList()) # glUniformMatrix4fv(shadow_VP_loc, 1, GL_FALSE, VP_mat_top.toList()) glDrawElements(GL_TRIANGLES, len(cube.obj.indices), GL_UNSIGNED_SHORT, None) # Swap front and back buffers glfw.swap_buffers(window) glfw.poll_events()
def main(): global delta global angle # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 640, "Lab1", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glClearColor(1.0, 1.0, 1.0, 1.0) glPushMatrix() glRotatef(angle, 0, 0, 1) glBegin(GL_QUADS) glColor3f(0.0,0.0,0.0) glVertex3f( 0.5, 0.5, 0.0) glColor3f(1.0,0.0,0.0) glVertex3f(-0.5, 0.5, 0.0) glColor3f(0.0,0.0,1.0) glVertex3f(-0.5, -0.5, 0.0) glColor3f(1.0,0.0,1.0) glVertex3f( 0.5, -0.5, 0.0) glEnd() glPopMatrix() angle += delta # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.destroy_window(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(640,640,'2015004584', None,None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) while not glfw.window_should_close(window): glfw.poll_events() render(gCamAng) glfw.swap_buffers(window) glfw.terminate()
def main(): # Initialize the library if not glfw.init(): return # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 01", None, None) # glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # GLEW is a framework for testing extension availability. Please see tutorial notes for # more information including why can remove this code. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return glfw.set_input_mode(window,glfw.STICKY_KEYS,True) # Loop until the user closes the window #while not glfw.window_should_close(window): while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): # Draw nothing sucker # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "Hello World", None, None) if not window: glfw.terminate() return glfw.set_key_callback(window, key_callback) glfw.make_context_current(window) while not glfw.window_should_close(window): glfw.poll_events() render() glfw.swap_buffers(window) glfw.terminate()
def world( timebase, eye_procs_alive, ipc_pub_url, ipc_sub_url, ipc_push_url, user_dir, version, preferred_remote_port, hide_ui, debug, ): """Reads world video and runs plugins. Creates a window, gl context. Grabs images from a capture. Maps pupil to gaze data Can run various plug-ins. Reacts to notifications: ``eye_process.started`` ``start_plugin`` ``should_stop`` Emits notifications: ``eye_process.should_start`` ``eye_process.should_stop`` ``world_process.started`` ``world_process.stopped`` ``recording.should_stop``: Emits on camera failure ``launcher_process.should_stop`` Emits data: ``gaze``: Gaze data from current gaze mapping plugin.`` ``*``: any other plugin generated data in the events that it not [dt,pupil,gaze]. """ # We defer the imports because of multiprocessing. # Otherwise the world process each process also loads the other imports. # This is not harmful but unnecessary. # general imports from time import sleep import logging # networking import zmq import zmq_tools # zmq ipc setup zmq_ctx = zmq.Context() ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url) notify_sub = zmq_tools.Msg_Receiver(zmq_ctx, ipc_sub_url, topics=("notify",)) # log setup logging.getLogger("OpenGL").setLevel(logging.ERROR) logger = logging.getLogger() logger.handlers = [] logger.setLevel(logging.NOTSET) logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url)) # create logger for the context of this function logger = logging.getLogger(__name__) def launch_eye_process(eye_id, delay=0): n = { "subject": "eye_process.should_start.{}".format(eye_id), "eye_id": eye_id, "delay": delay, } ipc_pub.notify(n) def stop_eye_process(eye_id): n = { "subject": "eye_process.should_stop.{}".format(eye_id), "eye_id": eye_id, "delay": 0.2, } ipc_pub.notify(n) def start_stop_eye(eye_id, make_alive): if make_alive: launch_eye_process(eye_id) else: stop_eye_process(eye_id) def detection_enabled_getter() -> bool: return g_pool.pupil_detection_enabled def detection_enabled_setter(is_on: bool): g_pool.pupil_detection_enabled = is_on n = {"subject": "set_pupil_detection_enabled", "value": is_on} ipc_pub.notify(n) try: from background_helper import IPC_Logging_Task_Proxy IPC_Logging_Task_Proxy.push_url = ipc_push_url from tasklib.background.patches import IPCLoggingPatch IPCLoggingPatch.ipc_push_url = ipc_push_url from OpenGL.GL import GL_COLOR_BUFFER_BIT # display import glfw from gl_utils import GLFWErrorReporting GLFWErrorReporting.set_default() from version_utils import parse_version from pyglui import ui, cygl, __version__ as pyglui_version assert parse_version(pyglui_version) >= parse_version( "1.27" ), "pyglui out of date, please upgrade to newest version" from pyglui.cygl.utils import Named_Texture import gl_utils # helpers/utils from file_methods import Persistent_Dict from methods import normalize, denormalize, delta_t, get_system_info, timer from uvc import get_time_monotonic logger.info("Application Version: {}".format(version)) logger.info("System Info: {}".format(get_system_info())) logger.debug(f"Debug flag: {debug}") import audio # Plug-ins from plugin import ( Plugin, System_Plugin_Base, Plugin_List, import_runtime_plugins, ) from plugin_manager import Plugin_Manager from calibration_choreography import ( available_calibration_choreography_plugins, CalibrationChoreographyPlugin, patch_loaded_plugins_with_choreography_plugin, ) available_choreography_plugins = available_calibration_choreography_plugins() from gaze_mapping import registered_gazer_classes from gaze_mapping.gazer_base import GazerBase from pupil_detector_plugins.detector_base_plugin import PupilDetectorPlugin from fixation_detector import Fixation_Detector from recorder import Recorder from display_recent_gaze import Display_Recent_Gaze from time_sync import Time_Sync from network_api import NetworkApiPlugin from pupil_groups import Pupil_Groups from surface_tracker import Surface_Tracker_Online from log_display import Log_Display from annotations import Annotation_Capture from log_history import Log_History from blink_detection import Blink_Detection from video_capture import ( source_classes, manager_classes, Base_Manager, Base_Source, ) from pupil_data_relay import Pupil_Data_Relay from remote_recorder import Remote_Recorder from accuracy_visualizer import Accuracy_Visualizer from system_graphs import System_Graphs from camera_intrinsics_estimation import Camera_Intrinsics_Estimation from hololens_relay import Hololens_Relay from head_pose_tracker.online_head_pose_tracker import Online_Head_Pose_Tracker # UI Platform tweaks if platform.system() == "Linux": scroll_factor = 10.0 window_position_default = (30, 30) elif platform.system() == "Windows": scroll_factor = 10.0 window_position_default = (8, 90) else: scroll_factor = 1.0 window_position_default = (0, 0) process_was_interrupted = False def interrupt_handler(sig, frame): import traceback trace = traceback.format_stack(f=frame) logger.debug(f"Caught signal {sig} in:\n" + "".join(trace)) nonlocal process_was_interrupted process_was_interrupted = True signal.signal(signal.SIGINT, interrupt_handler) icon_bar_width = 50 window_size = None camera_render_size = None content_scale = 1.0 # g_pool holds variables for this process they are accessible to all plugins g_pool = SimpleNamespace() g_pool.debug = debug g_pool.app = "capture" g_pool.process = "world" g_pool.user_dir = user_dir g_pool.version = version g_pool.timebase = timebase g_pool.zmq_ctx = zmq_ctx g_pool.ipc_pub = ipc_pub g_pool.ipc_pub_url = ipc_pub_url g_pool.ipc_sub_url = ipc_sub_url g_pool.ipc_push_url = ipc_push_url g_pool.eye_procs_alive = eye_procs_alive g_pool.preferred_remote_port = preferred_remote_port def get_timestamp(): return get_time_monotonic() - g_pool.timebase.value g_pool.get_timestamp = get_timestamp g_pool.get_now = get_time_monotonic # manage plugins runtime_plugins = import_runtime_plugins( os.path.join(g_pool.user_dir, "plugins") ) runtime_plugins = [ p for p in runtime_plugins if not issubclass(p, PupilDetectorPlugin) ] user_plugins = [ Pupil_Groups, NetworkApiPlugin, Time_Sync, Surface_Tracker_Online, Annotation_Capture, Log_History, Fixation_Detector, Blink_Detection, Remote_Recorder, Accuracy_Visualizer, Camera_Intrinsics_Estimation, Hololens_Relay, Online_Head_Pose_Tracker, ] system_plugins = ( [ Log_Display, Display_Recent_Gaze, Recorder, Pupil_Data_Relay, Plugin_Manager, System_Graphs, ] + manager_classes + source_classes ) plugins = ( system_plugins + user_plugins + runtime_plugins + available_choreography_plugins + registered_gazer_classes() ) user_plugins += [ p for p in runtime_plugins if not isinstance( p, ( Base_Manager, Base_Source, System_Plugin_Base, CalibrationChoreographyPlugin, GazerBase, ), ) ] g_pool.plugin_by_name = {p.__name__: p for p in plugins} default_capture_name = "UVC_Source" default_capture_settings = { "preferred_names": [ "Pupil Cam1 ID2", "Logitech Camera", "(046d:081d)", "C510", "B525", "C525", "C615", "C920", "C930e", ], "frame_size": (1280, 720), "frame_rate": 30, } default_plugins = [ (default_capture_name, default_capture_settings), ("Pupil_Data_Relay", {}), ("UVC_Manager", {}), ("NDSI_Manager", {}), ("HMD_Streaming_Manager", {}), ("File_Manager", {}), ("Log_Display", {}), ("Dummy_Gaze_Mapper", {}), ("Display_Recent_Gaze", {}), # Calibration choreography plugin is added below by calling # patch_loaded_plugins_with_choreography_plugin ("Recorder", {}), ("NetworkApiPlugin", {}), ("Fixation_Detector", {}), ("Blink_Detection", {}), ("Accuracy_Visualizer", {}), ("Plugin_Manager", {}), ("System_Graphs", {}), ] def consume_events_and_render_buffer(): gl_utils.glViewport(0, 0, *camera_render_size) for p in g_pool.plugins: p.gl_display() gl_utils.glViewport(0, 0, *window_size) try: clipboard = glfw.get_clipboard_string(main_window).decode() except (AttributeError, glfw.GLFWError): # clipboard is None, might happen on startup clipboard = "" g_pool.gui.update_clipboard(clipboard) user_input = g_pool.gui.update() if user_input.clipboard != clipboard: # only write to clipboard if content changed glfw.set_clipboard_string(main_window, user_input.clipboard) for button, action, mods in user_input.buttons: x, y = glfw.get_cursor_pos(main_window) pos = gl_utils.window_coordinate_to_framebuffer_coordinate( main_window, x, y, cached_scale=None ) pos = normalize(pos, camera_render_size) # Position in img pixels pos = denormalize(pos, g_pool.capture.frame_size) for plugin in g_pool.plugins: if plugin.on_click(pos, button, action): break for key, scancode, action, mods in user_input.keys: for plugin in g_pool.plugins: if plugin.on_key(key, scancode, action, mods): break for char_ in user_input.chars: for plugin in g_pool.plugins: if plugin.on_char(char_): break glfw.swap_buffers(main_window) # Callback functions def on_resize(window, w, h): nonlocal window_size nonlocal camera_render_size nonlocal content_scale if w == 0 or h == 0: return # Always clear buffers on resize to make sure that there are no overlapping # artifacts from previous frames. gl_utils.glClear(GL_COLOR_BUFFER_BIT) gl_utils.glClearColor(0, 0, 0, 1) content_scale = gl_utils.get_content_scale(window) framebuffer_scale = gl_utils.get_framebuffer_scale(window) g_pool.gui.scale = content_scale window_size = w, h camera_render_size = w - int(icon_bar_width * g_pool.gui.scale), h g_pool.gui.update_window(*window_size) g_pool.gui.collect_menus() for p in g_pool.plugins: p.on_window_resize(window, *camera_render_size) # Minimum window size required, otherwise parts of the UI can cause openGL # issues with permanent effects. Depends on the content scale, which can # potentially be dynamically modified, so we re-adjust the size limits every # time here. min_size = int(2 * icon_bar_width * g_pool.gui.scale / framebuffer_scale) glfw.set_window_size_limits( window, min_size, min_size, glfw.DONT_CARE, glfw.DONT_CARE, ) # Needed, to update the window buffer while resizing consume_events_and_render_buffer() def on_window_key(window, key, scancode, action, mods): g_pool.gui.update_key(key, scancode, action, mods) def on_window_char(window, char): g_pool.gui.update_char(char) def on_window_mouse_button(window, button, action, mods): g_pool.gui.update_button(button, action, mods) def on_pos(window, x, y): x, y = gl_utils.window_coordinate_to_framebuffer_coordinate( window, x, y, cached_scale=None ) g_pool.gui.update_mouse(x, y) pos = x, y pos = normalize(pos, camera_render_size) # Position in img pixels pos = denormalize(pos, g_pool.capture.frame_size) for p in g_pool.plugins: p.on_pos(pos) def on_scroll(window, x, y): g_pool.gui.update_scroll(x, y * scroll_factor) def on_drop(window, paths): for plugin in g_pool.plugins: if plugin.on_drop(paths): break tick = delta_t() def get_dt(): return next(tick) # load session persistent settings session_settings = Persistent_Dict( os.path.join(g_pool.user_dir, "user_settings_world") ) if parse_version(session_settings.get("version", "0.0")) != g_pool.version: logger.info( "Session setting are from a different version of this app. I will not use those." ) session_settings.clear() g_pool.min_data_confidence = 0.6 g_pool.min_calibration_confidence = session_settings.get( "min_calibration_confidence", 0.8 ) g_pool.pupil_detection_enabled = session_settings.get( "pupil_detection_enabled", True ) g_pool.active_gaze_mapping_plugin = None g_pool.capture = None audio.set_audio_mode( session_settings.get("audio_mode", audio.get_default_audio_mode()) ) def handle_notifications(noti): subject = noti["subject"] if subject == "set_pupil_detection_enabled": g_pool.pupil_detection_enabled = noti["value"] elif subject == "start_plugin": try: g_pool.plugins.add( g_pool.plugin_by_name[noti["name"]], args=noti.get("args", {}) ) except KeyError as err: logger.error(f"Attempt to load unknown plugin: {err}") elif subject == "stop_plugin": for p in g_pool.plugins: if p.class_name == noti["name"]: p.alive = False g_pool.plugins.clean() elif subject == "eye_process.started": noti = { "subject": "set_pupil_detection_enabled", "value": g_pool.pupil_detection_enabled, } ipc_pub.notify(noti) elif subject == "set_min_calibration_confidence": g_pool.min_calibration_confidence = noti["value"] elif subject.startswith("meta.should_doc"): ipc_pub.notify( {"subject": "meta.doc", "actor": g_pool.app, "doc": world.__doc__} ) for p in g_pool.plugins: if ( p.on_notify.__doc__ and p.__class__.on_notify != Plugin.on_notify ): ipc_pub.notify( { "subject": "meta.doc", "actor": p.class_name, "doc": p.on_notify.__doc__, } ) elif subject == "world_process.adapt_window_size": set_window_size() elif subject == "world_process.should_stop": glfw.set_window_should_close(main_window, True) width, height = session_settings.get( "window_size", (1280 + icon_bar_width, 720) ) # window and gl setup glfw.init() glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE) if hide_ui: glfw.window_hint(glfw.VISIBLE, 0) # hide window main_window = glfw.create_window( width, height, "Pupil Capture - World", None, None ) window_position_manager = gl_utils.WindowPositionManager() window_pos = window_position_manager.new_window_position( window=main_window, default_position=window_position_default, previous_position=session_settings.get("window_position", None), ) glfw.set_window_pos(main_window, window_pos[0], window_pos[1]) glfw.make_context_current(main_window) cygl.utils.init() g_pool.main_window = main_window def reset_restart(): logger.warning("Resetting all settings and restarting Capture.") glfw.set_window_should_close(main_window, True) ipc_pub.notify({"subject": "clear_settings_process.should_start"}) ipc_pub.notify({"subject": "world_process.should_start", "delay": 2.0}) def toggle_general_settings(collapsed): # this is the menu toggle logic. # Only one menu can be open. # If no menu is opened, the menubar should collapse. g_pool.menubar.collapsed = collapsed for m in g_pool.menubar.elements: m.collapsed = True general_settings.collapsed = collapsed # setup GUI g_pool.gui = ui.UI() g_pool.menubar = ui.Scrolling_Menu( "Settings", pos=(-400, 0), size=(-icon_bar_width, 0), header_pos="left" ) g_pool.iconbar = ui.Scrolling_Menu( "Icons", pos=(-icon_bar_width, 0), size=(0, 0), header_pos="hidden" ) g_pool.quickbar = ui.Stretching_Menu("Quick Bar", (0, 100), (120, -100)) g_pool.gui.append(g_pool.menubar) g_pool.gui.append(g_pool.iconbar) g_pool.gui.append(g_pool.quickbar) general_settings = ui.Growing_Menu("General", header_pos="headline") def set_window_size(): # Get current capture frame size f_width, f_height = g_pool.capture.frame_size # Get current display scale factor content_scale = gl_utils.get_content_scale(main_window) framebuffer_scale = gl_utils.get_framebuffer_scale(main_window) display_scale_factor = content_scale / framebuffer_scale # Scale the capture frame size by display scale factor f_width *= display_scale_factor f_height *= display_scale_factor # Increas the width to account for the added scaled icon bar width f_width += icon_bar_width * display_scale_factor # Set the newly calculated size (scaled capture frame size + scaled icon bar width) glfw.set_window_size(main_window, int(f_width), int(f_height)) general_settings.append(ui.Button("Reset window size", set_window_size)) general_settings.append( ui.Selector( "Audio mode", None, getter=audio.get_audio_mode, setter=audio.set_audio_mode, selection=audio.get_audio_mode_list(), ) ) general_settings.append( ui.Switch( "pupil_detection_enabled", label="Pupil detection", getter=detection_enabled_getter, setter=detection_enabled_setter, ) ) general_settings.append( ui.Switch( "eye0_process", label="Detect eye 0", setter=lambda alive: start_stop_eye(0, alive), getter=lambda: eye_procs_alive[0].value, ) ) general_settings.append( ui.Switch( "eye1_process", label="Detect eye 1", setter=lambda alive: start_stop_eye(1, alive), getter=lambda: eye_procs_alive[1].value, ) ) general_settings.append( ui.Info_Text("Capture Version: {}".format(g_pool.version)) ) general_settings.append( ui.Button("Restart with default settings", reset_restart) ) g_pool.menubar.append(general_settings) icon = ui.Icon( "collapsed", general_settings, label=chr(0xE8B8), on_val=False, off_val=True, setter=toggle_general_settings, label_font="pupil_icons", ) icon.tooltip = "General Settings" g_pool.iconbar.append(icon) user_plugin_separator = ui.Separator() user_plugin_separator.order = 0.35 g_pool.iconbar.append(user_plugin_separator) loaded_plugins = session_settings.get("loaded_plugins", default_plugins) # Resolve the active calibration choreography plugin loaded_plugins = patch_loaded_plugins_with_choreography_plugin( loaded_plugins, app=g_pool.app ) session_settings["loaded_plugins"] = loaded_plugins # plugins that are loaded based on user settings from previous session g_pool.plugins = Plugin_List(g_pool, loaded_plugins) if not g_pool.capture: # Make sure we always have a capture running. Important if there was no # capture stored in session settings. g_pool.plugins.add( g_pool.plugin_by_name[default_capture_name], default_capture_settings ) # Register callbacks main_window glfw.set_framebuffer_size_callback(main_window, on_resize) glfw.set_key_callback(main_window, on_window_key) glfw.set_char_callback(main_window, on_window_char) glfw.set_mouse_button_callback(main_window, on_window_mouse_button) glfw.set_cursor_pos_callback(main_window, on_pos) glfw.set_scroll_callback(main_window, on_scroll) glfw.set_drop_callback(main_window, on_drop) # gl_state settings gl_utils.basic_gl_setup() g_pool.image_tex = Named_Texture() toggle_general_settings(True) # now that we have a proper window we can load the last gui configuration g_pool.gui.configuration = session_settings.get("ui_config", {}) # If previously selected plugin was not loaded this time, we will have an # expanded menubar without any menu selected. We need to ensure the menubar is # collapsed in this case. if all(submenu.collapsed for submenu in g_pool.menubar.elements): g_pool.menubar.collapsed = True # create a timer to control window update frequency window_update_timer = timer(1 / 60) def window_should_update(): return next(window_update_timer) # trigger setup of window and gl sizes on_resize(main_window, *glfw.get_framebuffer_size(main_window)) if session_settings.get("eye1_process_alive", True): launch_eye_process(1, delay=0.6) if session_settings.get("eye0_process_alive", True): launch_eye_process(0, delay=0.3) ipc_pub.notify({"subject": "world_process.started"}) logger.warning("Process started.") if platform.system() == "Darwin": # On macOS, calls to glfw.swap_buffers() deliberately take longer in case of # occluded windows, based on the swap interval value. This causes an FPS drop # and leads to problems when recording. To side-step this behaviour, the swap # interval is set to zero. # # Read more about window occlusion on macOS here: # https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/WorkWhenVisible.html glfw.swap_interval(0) # Event loop while not glfw.window_should_close(main_window) and not process_was_interrupted: # fetch newest notifications new_notifications = [] while notify_sub.new_data: t, n = notify_sub.recv() new_notifications.append(n) # notify each plugin if there are new notifications: for n in new_notifications: handle_notifications(n) for p in g_pool.plugins: p.on_notify(n) # a dictionary that allows plugins to post and read events events = {} # report time between now and the last loop interation events["dt"] = get_dt() # allow each Plugin to do its work. for p in g_pool.plugins: p.recent_events(events) # check if a plugin need to be destroyed g_pool.plugins.clean() # "blacklisted" events that were already sent del events["pupil"] del events["gaze"] # delete if exists. More expensive than del, so only use it when key might not exist events.pop("annotation", None) # send new events to ipc: if "frame" in events: del events["frame"] # send explicitly with frame publisher if "depth_frame" in events: del events["depth_frame"] if "audio_packets" in events: del events["audio_packets"] del events["dt"] # no need to send this for data in events.values(): assert isinstance(data, (list, tuple)) for d in data: ipc_pub.send(d) glfw.make_context_current(main_window) # render visual feedback from loaded plugins glfw.poll_events() if window_should_update() and gl_utils.is_window_visible(main_window): gl_utils.glViewport(0, 0, *camera_render_size) for p in g_pool.plugins: p.gl_display() gl_utils.glViewport(0, 0, *window_size) try: clipboard = glfw.get_clipboard_string(main_window).decode() except (AttributeError, glfw.GLFWError): # clipboard is None, might happen on startup clipboard = "" g_pool.gui.update_clipboard(clipboard) user_input = g_pool.gui.update() if user_input.clipboard != clipboard: # only write to clipboard if content changed glfw.set_clipboard_string(main_window, user_input.clipboard) for button, action, mods in user_input.buttons: x, y = glfw.get_cursor_pos(main_window) pos = gl_utils.window_coordinate_to_framebuffer_coordinate( main_window, x, y, cached_scale=None ) pos = normalize(pos, camera_render_size) # Position in img pixels pos = denormalize(pos, g_pool.capture.frame_size) for plugin in g_pool.plugins: if plugin.on_click(pos, button, action): break for key, scancode, action, mods in user_input.keys: for plugin in g_pool.plugins: if plugin.on_key(key, scancode, action, mods): break for char_ in user_input.chars: for plugin in g_pool.plugins: if plugin.on_char(char_): break glfw.swap_buffers(main_window) session_settings["loaded_plugins"] = g_pool.plugins.get_initializers() session_settings["ui_config"] = g_pool.gui.configuration session_settings["version"] = str(g_pool.version) session_settings["eye0_process_alive"] = eye_procs_alive[0].value session_settings["eye1_process_alive"] = eye_procs_alive[1].value session_settings[ "min_calibration_confidence" ] = g_pool.min_calibration_confidence session_settings["pupil_detection_enabled"] = g_pool.pupil_detection_enabled session_settings["audio_mode"] = audio.get_audio_mode() if not hide_ui: glfw.restore_window(main_window) # need to do this for windows os session_settings["window_position"] = glfw.get_window_pos(main_window) session_window_size = glfw.get_window_size(main_window) if 0 not in session_window_size: f_width, f_height = session_window_size if platform.system() in ("Windows", "Linux"): f_width, f_height = ( f_width / content_scale, f_height / content_scale, ) session_settings["window_size"] = int(f_width), int(f_height) session_settings.close() # de-init all running plugins for p in g_pool.plugins: p.alive = False g_pool.plugins.clean() g_pool.gui.terminate() glfw.destroy_window(main_window) glfw.terminate() except Exception: import traceback trace = traceback.format_exc() logger.error("Process Capture crashed with trace:\n{}".format(trace)) finally: # shut down eye processes: stop_eye_process(0) stop_eye_process(1) logger.info("Process shutting down.") ipc_pub.notify({"subject": "world_process.stopped"}) sleep(1.0)
def main(): if not glfw.init(): return -1 #configure glfw (using OpenGL 3.3 Core) 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) # create the window window = glfw.create_window(SCREEN_WIDTH, SCREEN_HEIGHT, "Hello World", None, None) if not window: glfw.terminate() return -1 glfw.make_context_current(window) # set callbacks glfw.set_window_size_callback(window, framebuffer_size_callback) glfw.set_key_callback(window, key_callback) # set the OpenGL viewport to the whole window (width, height) = glfw.get_framebuffer_size(window) glViewport(0, 0, width, height) # SHADERS ######################################################### vertex_shader_source = """ #version 330 core layout (location = 0) in vec3 position; void main() { gl_Position = vec4(position, 1.0f); } """ orange_fragment_shader_source = """ #version 330 core out vec4 color; void main() { color = vec4(1.0f, 0.5f, 0.2f, 1.0f); } """ green_fragment_shader_source = """ #version 330 core out vec4 color; void main() { color = vec4(0.5f, 1.0f, 0.2f, 1.0f); } """ vertex_shader = OpenGL.GL.shaders.compileShader(vertex_shader_source, GL_VERTEX_SHADER) orange_fragment_shader = OpenGL.GL.shaders.compileShader( orange_fragment_shader_source, GL_FRAGMENT_SHADER) green_fragment_shader = OpenGL.GL.shaders.compileShader( green_fragment_shader_source, GL_FRAGMENT_SHADER) orange_shader = OpenGL.GL.shaders.compileProgram(vertex_shader, orange_fragment_shader) green_shader = OpenGL.GL.shaders.compileProgram(vertex_shader, green_fragment_shader) # END SHADERS ######################################################### # vertices data (a triangle) triangle = [-0.5, 0.75, 0.0, -0.9, -0.75, 0.0, -0.1, -0.75, 0.0] triangle = numpy.array(triangle, dtype=numpy.float32) triangleVAO = glGenVertexArrays(1) triangleVBO = glGenBuffers(1) glBindVertexArray(triangleVAO) glBindBuffer(GL_ARRAY_BUFFER, triangleVBO) glBufferData(GL_ARRAY_BUFFER, triangle.itemsize * len(triangle), triangle, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindVertexArray(0) # vertices data (a square) square = [0.1, -0.4, 0.0, 0.1, 0.4, 0.0, 0.9, -0.4, 0.0, 0.9, 0.4, 0.0] square = numpy.array(square, dtype=numpy.float32) squareIndices = [ 0, 1, 2, # first triangle 1, 2, 3 # second triangle ] squareIndices = numpy.array(squareIndices, dtype=numpy.uint32) squareVAO = glGenVertexArrays(1) squareVBO = glGenBuffers(1) squareEBO = glGenBuffers(1) glBindVertexArray(squareVAO) glBindBuffer(GL_ARRAY_BUFFER, squareVBO) glBufferData(GL_ARRAY_BUFFER, square.itemsize * len(square), square, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, squareEBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, squareIndices.itemsize * len(squareIndices), squareIndices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindVertexArray(0) # game loop while not glfw.window_should_close(window): # set the color buffer glClearColor(0.2, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT) glUseProgram(orange_shader) glBindVertexArray(triangleVAO) glDrawArrays(GL_TRIANGLES, 0, 3) glUseProgram(green_shader) glBindVertexArray(squareVAO) glDrawElements(GL_TRIANGLES, len(squareIndices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def draw(self): glClear(GL_COLOR_BUFFER_BIT) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) glfw.swap_buffers(self.window)
def main_rect(): glfw.init() glfw.window_hint(glfw.RESIZABLE, False) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) w = glfw.create_window(800, 600, 'Window Title', None, None) glfw.make_context_current(w) # setup vao vao = glGenVertexArrays(1) glBindVertexArray(vao) # setup vbo for rectangle vertices rect_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, rect_vbo) vertices = [0.5, 0.5, 0.0, 0.5, -0.5, 0.0, -0.5, -0.5, 0.0, -0.5, 0.5, 0.0] glBufferData(GL_ARRAY_BUFFER, len(vertices)*ctypes.sizeof(ctypes.c_float), \ (ctypes.c_float*len(vertices))(*vertices), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) # setup ebo for rectangle indices rect_ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rect_ebo) indices = [0, 1, 3, 1, 2, 3] glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices)*4, \ (ctypes.c_uint*len(indices))(*indices), GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) # unbind stuff glBindVertexArray(0) ##### shader program setup shaderProgram = make_shader_program() glUseProgram(shaderProgram) # Wireframe mode # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) while not glfw.window_should_close(w): glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) glBindVertexArray(vao) if True: # draw both triangles using ebo glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rect_ebo) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) # mode, count, type, indices # count = 6 indices in the array buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) else: # draw only the first triangle glBindBuffer(GL_ARRAY_BUFFER, rect_vbo) glDrawArrays(GL_TRIANGLES, 0, 3) # mode, starting index, count glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) glfw.swap_buffers(w) glfw.poll_events() glDeleteVertexArrays(1, vao) glDeleteBuffers(1, rect_vbo) glDeleteBuffers(1, rect_ebo) glDeleteProgram(shaderProgram) glfw.terminate()
def opengl绘图循环(所有图层, psd尺寸): def 生成纹理(img): w, h = img.shape[:2] d = 2**int(max(math.log2(w), math.log2(h)) + 1) 纹理 = np.zeros([d, d, 4], dtype=img.dtype) 纹理[:w, :h] = img return 纹理, (w / d, h / d) Vtuber尺寸 = 512, 512 glfw.init() 超融合() glfw.window_hint(glfw.RESIZABLE, False) window = glfw.create_window(*Vtuber尺寸, 'Vtuber', None, None) glfw.make_context_current(window) monitor_size = glfw.get_video_mode(glfw.get_primary_monitor()).size glfw.set_window_pos(window, monitor_size.width - Vtuber尺寸[0], monitor_size.height - Vtuber尺寸[1]) glViewport(0, 0, *Vtuber尺寸) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA) for 图层数据 in 所有图层: 纹理编号 = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, 纹理编号) 纹理, 纹理座标 = 生成纹理(图层数据['npdata']) width, height = 纹理.shape[:2] glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_FLOAT, 纹理) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glGenerateMipmap(GL_TEXTURE_2D) 图层数据['纹理编号'] = 纹理编号 图层数据['纹理座标'] = 纹理座标 while not glfw.window_should_close(window): glfw.poll_events() glClearColor(0, 0, 0, 0) glClear(GL_COLOR_BUFFER_BIT) 横旋转量, 竖旋转量 = 特征缓冲() for 图层数据 in 所有图层: a, b, c, d = 图层数据['位置'] z = 图层数据['深度'] if type(z) in [int, float]: z1, z2, z3, z4 = [z, z, z, z] else: [z1, z2], [z3, z4] = z q, w = 图层数据['纹理座标'] p1 = np.array([a, b, z1, 1, 0, 0, 0, z1]) p2 = np.array([a, d, z2, 1, z2 * w, 0, 0, z2]) p3 = np.array([c, d, z3, 1, z3 * w, z3 * q, 0, z3]) p4 = np.array([c, b, z4, 1, 0, z4 * q, 0, z4]) model = matrix.scale(2 / psd尺寸[0], 2 / psd尺寸[1], 1) @ \ matrix.translate(-1, -1, 0) @ \ matrix.rotate_ax(-math.pi / 2, axis=(0, 1)) glBindTexture(GL_TEXTURE_2D, 图层数据['纹理编号']) glColor4f(1, 1, 1, 1) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glBegin(GL_QUADS) for p in [p1, p2, p3, p4]: a = p[:4] b = p[4:8] a = a @ model a[0:2] *= a[2] if not 图层数据['名字'][:2] == '身体': a = a @ matrix.translate(0, 0, -1) \ @ matrix.rotate_ax(横旋转量, axis=(0, 2)) \ @ matrix.rotate_ax(竖旋转量, axis=(2, 1)) \ @ matrix.translate(0, 0, 1) a = a @ matrix.perspective(999) glTexCoord4f(*b) glVertex4f(*a) glEnd() glfw.swap_buffers(window)
def main(): global current_frame, last_frame, delta_time, light_pos # initialize glfw if not glfw.init(): return screen_width = 800 screen_height = 600 window = glfw.create_window(screen_width, screen_height, "LearnOpenGL", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) vertices = [ -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0 ] vertices = np.array(vertices, dtype=np.float32) # camera_target = glm.vec3(0.0, 0.0, 0.0) # up = glm.vec3(0.0, 1.0, 0.0) # camera_direction = glm.normalize(camera_pos - camera_target) # camera_right = glm.normalize(glm.cross(up, camera_direction)) # camera_up = glm.cross(camera_direction, camera_right) projection = glm.perspective(glm.radians(45.0), screen_width / screen_height, 0.1, 100.0) light_vertex_shader = """ #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec3 aNormal; out vec3 FragPos; out vec3 Normal; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { FragPos = vec3(model * vec4(aPos, 1.0)); Normal = mat3(transpose(inverse(model))) * aNormal; gl_Position = projection * view * vec4(FragPos, 1.0); } """ vertex_shader = """ #version 330 core layout (location = 0) in vec3 aPos; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0); } """ light_fragment_shader = """ #version 330 core out vec4 FragColor; in vec3 Normal; in vec3 FragPos; uniform vec3 lightPos; uniform vec3 viewPos; uniform vec3 lightColor; uniform vec3 objectColor; void main() { // ambient float ambientStrength = 0.1; vec3 ambient = ambientStrength * lightColor; // diffuse vec3 norm = normalize(Normal); vec3 lightDir = normalize(lightPos - FragPos); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = diff * lightColor; // specular float specularStrength = .5; vec3 viewDir = normalize(viewPos - FragPos); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32); vec3 specular = specularStrength * spec * lightColor; vec3 result = (ambient + diffuse + specular) * objectColor; FragColor = vec4(result, 1.0); //FragColor = vec4(Normal, 1.0); } """ fragment_shader = """ #version 330 core out vec4 FragColor; void main() { FragColor = vec4(1.0); // set all 4 vector values to 1.0 } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) light_shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(light_vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(light_fragment_shader, GL_FRAGMENT_SHADER)) # cube's VAO and VBO VBO = glGenBuffers( 1) # vertex buffer object, which stores vertices in the GPU's memory. cubeVAO = glGenVertexArrays(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) # now, all calls will configure VBO glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glBindVertexArray(cubeVAO) # position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * np.dtype(np.float32).itemsize, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # normal attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * np.dtype(np.float32).itemsize, ctypes.c_void_p(3 * np.dtype(np.float32).itemsize)) glEnableVertexAttribArray(1) # light's VAO lightVAO = glGenVertexArrays(1) glBindVertexArray(lightVAO) glBindBuffer(GL_ARRAY_BUFFER, VBO) # glBindBuffer(GL_ARRAY_BUFFER, 0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * np.dtype(np.float32).itemsize, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # glBindVertexArray(0) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glEnable(GL_DEPTH_TEST) # render loop while not glfw.window_should_close(window): # per-frame time logic current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # input process_input(window) # render glClearColor(0.1, 0.1, 0.1, 1.0) # state-setting function glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # state-using function glUseProgram(light_shader) objectColorLoc = glGetUniformLocation(light_shader, "objectColor") object_color = glm.vec3(1.0, 0.5, 0.31) glUniform3fv(objectColorLoc, 1, glm.value_ptr(object_color)) lightLoc = glGetUniformLocation(light_shader, "lightColor") light_color = glm.vec3(1.0, 1.0, 1.0) glUniform3fv(lightLoc, 1, glm.value_ptr(light_color)) lightPosLoc = glGetUniformLocation(light_shader, "lightPos") glUniform3fv(lightPosLoc, 1, glm.value_ptr(light_pos)) viewPosLoc = glGetUniformLocation(light_shader, "viewPos") glUniform3fv(viewPosLoc, 1, glm.value_ptr(camera_pos)) # view/projection transformations projectionLoc = glGetUniformLocation(light_shader, "projection") glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm.value_ptr(projection)) view = glm.lookAt(camera_pos, camera_pos + camera_front, camera_up) viewLoc = glGetUniformLocation(light_shader, "view") glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm.value_ptr(view)) # world transformations model = glm.mat4(1.0) modelLoc = glGetUniformLocation(light_shader, "model") glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm.value_ptr(model)) # render the cube glBindVertexArray(cubeVAO) glDrawArrays(GL_TRIANGLES, 0, 36) # also draw the lamp object glUseProgram(shader) projectionLoc = glGetUniformLocation(shader, "projection") glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm.value_ptr(projection)) viewLoc = glGetUniformLocation(shader, "view") glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm.value_ptr(view)) model = glm.mat4(1.0) model = glm.translate(model, light_pos) model = glm.scale(model, glm.vec3(0.2)) modelLoc = glGetUniformLocation(shader, "model") glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm.value_ptr(model)) glBindVertexArray(lightVAO) glDrawArrays(GL_TRIANGLES, 0, 36) # check and call events and swap the buffers glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return window = glfw.create_window(800, 600, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # positions colors cube = [ -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, -0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 6, 7, 3, 3, 2, 6, 5, 6, 2, 2, 1, 5, 7, 4, 0, 0, 3, 7 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in vec3 position; in vec3 color; uniform mat4 transform; out vec3 newColor; void main() { gl_Position = transform * vec4(position, 1.0f); newColor = color; } """ fragment_shader = """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, 192, cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, 144, indices, GL_STATIC_DRAW) position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) color = glGetAttribLocation(shader, "color") glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) pers = glm.perspective(0.5, 1.0, 0.1, 10.0) print(pers) trans = glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, -8.5)) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #rot_x = glm.rotate(glm.mat4(1.0),0.5 * glfw.get_time(),glm.vec3(1.0,0.0,0.0)) #rot_y = glm.rotate(glm.mat4(1.0),0.5 * glfw.get_time(),glm.vec3(0.0,1.0,0.0)) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm.value_ptr(pers * trans)) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_cursor_pos_callback(window, cursor_pos_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) # positions cube = [ -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; uniform mat4 vp; uniform mat4 model; void main() { gl_Position = vp * model * vec4(position, 1.0f); } """ fragment_shader = """ #version 330 out vec4 outColor; uniform vec3 color; void main() { outColor = vec4(color, 1.0); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0])) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) vp_loc = glGetUniformLocation(shader, "vp") model_loc = glGetUniformLocation(shader, "model") color_loc = glGetUniformLocation(shader, "color") cube_positions = [(-2.0, 0.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)] cube_colors = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)] glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 2) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) glUniform3fv(color_loc, 1, cube_colors[i]) if i == 0: if red_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) elif i == 1: if green_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) else: if blue_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def main(): # glfwの初期化 if not glfw.init(): raise RuntimeError('Could not initialize GLFW3') # OpenGLのバージョンを指定(この授業では古いOpenGLを使います) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 2) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_ANY_PROFILE) # 窓を作る window = glfw.create_window(300, 300, 'Program', None, None) # 窓を作る(幅と高さ,タイトルを指定) if not window: # 窓が作れなかった時の処理 glfw.terminate() raise RuntimeError('Could not create an window') glfw.make_context_current(window) # OpenGLの情報を表示 print('Vendor :', gl.glGetString(gl.GL_VENDOR)) print('GPU :', gl.glGetString(gl.GL_RENDERER)) print('OpenGL version :', gl.glGetString(gl.GL_VERSION)) gl.glClearColor(1.0, 1.0, 1.0, 1.0) # 初期化した時のバッファの色(背景色)の設定 gl.glEnable(gl.GL_DEPTH_TEST) # Z-バッファ法による隠面消去を有効にする gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) gl.glPolygonOffset(1.0, 1.0) # 円筒のメッシュを作る npXYZ, npTri = make_unit_cylinder(16, 16) # 長さ方向に16分割,円周方向に16分割 npXYZ[:, 0] = (npXYZ[:, 0] - 0.5) * 3.0 # x方向の長さ3,中心が原点に合わせる npXYZ[:, 1:2] *= 0.3 # 半径を0.3にする # リグウェイトを作る npRig = np.zeros((npXYZ.shape[0], 2), dtype=np.float64) npRig[:, 1] = np.tanh(npXYZ[:, 0] * 2) * 0.5 + 0.5 npRig[:, 0] = 1.0 - npRig[:, 1] time = 0.0 while not glfw.window_should_close(window): # main loop time += 0.01 # ボーンの回転行列を作る theta = math.sin(time) npRot = np.zeros((2, 3, 3), dtype=np.float64) npRot[0, :, :] = np.eye(3) npRot[1, 2, 2] = 1 npRot[1, 0, 0] = +math.cos(theta) npRot[1, 1, 1] = +math.cos(theta) npRot[1, 0, 1] = +math.sin(theta) npRot[1, 1, 0] = -math.sin(theta) # メッシュを変形する npXYZ1 = np.zeros_like(npXYZ) for ib in range(2): npXYZ1[:, :] += npRig[:, ib].reshape(npRig.shape[0], 1) * np.dot(npXYZ, npRot[ib, :, :]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # 描画用のバッファを背景色で塗りつぶす gl.glMatrixMode(gl.GL_PROJECTION) # 今から投影行列を指定 gl.glLoadIdentity() # 単位行列を投影行列に指定 # 並行投影行列を掛ける. gl.glOrtho(-2.0, +2.0, # 画面左端が-2,右端が+2 -2.0, +2.0, # 画面下端が-2,上端が+2 -2.0, +2.0) # 画面の奥行き-2~+2までの範囲を描画 gl.glMatrixMode(gl.GL_MODELVIEW) # 今からモデルビュー行列を指定 gl.glLoadIdentity() # 単位行列をモデルビュー行列に指定 draw_mesh(npXYZ1, npTri, [1, 0, 0]) # メッシュを glfw.swap_buffers(window) # 描画用のバッファと,表示用のバッファを入れ替えて画面を更新 glfw.poll_events() # イベントの受けつけ glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 800, 600 # glfw.window_hint(glfw.RESIZABLE, GL_FALSE) window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) obj = ObjLoader() obj.load_model("res/face.obj") texture_offset = len(obj.vertex_index) * 12 normal_offset = (texture_offset + len(obj.texture_index) * 8) shader = ShaderLoader.compile_shader("shaders/video_18_vert.vs", "shaders/video_18_frag.fs") VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, obj.model.itemsize * len(obj.model), obj.model, GL_STATIC_DRAW) # positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, obj.model.itemsize * 2, ctypes.c_void_p(texture_offset)) glEnableVertexAttribArray(1) # normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, obj.model.itemsize * 3, ctypes.c_void_p(normal_offset)) glEnableVertexAttribArray(2) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # load image image = Image.open("res/african_head_diffuse.tga") flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM) img_data = numpy.array(list(flipped_image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) glEnable(GL_TEXTURE_2D) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) view = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, -3.0])) projection = pyrr.matrix44.create_perspective_projection_matrix( 65.0, w_width / w_height, 0.1, 100.0) model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0])) view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "projection") model_loc = glGetUniformLocation(shader, "model") transform_loc = glGetUniformLocation(shader, "transform") light_loc = glGetUniformLocation(shader, "light") glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) position = None position1 = 0 position2 = 0 coef = -0.05 while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time() ) if (glfw.get_mouse_button(window, 1) == 1): if position is None: if position2 is not None: position = coef * glfw.get_cursor_pos( window)[0] - position2 else: position = coef * glfw.get_cursor_pos(window)[0] position1 = position rot_y = pyrr.Matrix44.from_y_rotation(position1 - position) position1 = coef * glfw.get_cursor_pos(window)[0] position2 = None else: if position2 is None: position2 = position1 - position rot_y = pyrr.Matrix44.from_y_rotation(position2) position = None glUniformMatrix4fv(transform_loc, 1, GL_FALSE, rot_y) glUniformMatrix4fv(light_loc, 1, GL_FALSE, rot_y) glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index)) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw 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.OPENGL_FORWARD_COMPAT, True) w_width, w_height = 800, 600 #glfw.window_hint(glfw.RESIZABLE, GL_FALSE) window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) obj = ObjLoader() obj.load_model("res/cube.obj") texture_offset = len(obj.vertex_index) * 12 VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = ShaderLoader.compile_shader("shaders/video_17_vert.vs", "shaders/video_17_frag.fs") VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, obj.model.itemsize * len(obj.model), obj.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #texture glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, obj.model.itemsize * 2, ctypes.c_void_p(texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # load image image = Image.open("res/cube_texture.jpg") flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM) img_data = numpy.array(list(flipped_image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) view = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, -3.0])) projection = pyrr.matrix44.create_perspective_projection_matrix( 65.0, w_width / w_height, 0.1, 100.0) model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0])) glUseProgram(shader) view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "projection") model_loc = glGetUniformLocation(shader, "model") glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glUseProgram(0) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) glUseProgram(shader) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) glBindVertexArray(VAO) glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index)) glBindVertexArray(0) glUseProgram(0) glfw.swap_buffers(window) glDeleteProgram(shader) glDeleteVertexArrays(1, [VAO]) glDeleteBuffers(1, [VBO]) glfw.terminate()
def main(): if not glfw.init(): return w_width = 800 w_height = 600 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, GL_TRUE) window = glfw.create_window(w_width, w_height, "MY OPENGL", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS,GL_TRUE) # Enable key event callback glfw.set_key_callback(window, key_event) #when window resize # glfw.set_window_size_callback(window, window_resize) #adding colors # x, y, z, r, g, b tx ty cube = [ -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, -0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, -0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, -0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] indices = numpy.array(indices, dtype=numpy.uint32) VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = shaderLoader.compile_shader("./shaders/vertex_shader.vs", "./shaders/fragment_shader.fs") VBO = glGenBuffers(1) # vertex buffer object for GPU glBindBuffer(GL_ARRAY_BUFFER, VBO) #upload data to array buffer # buf type byte point type glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) #get position from vertex_shader variable position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) #get color from vertex_shader program variable color = glGetAttribLocation(shader, "color") glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) texture_cords = glGetAttribLocation(shader, "inTexCords") glVertexAttribPointer(texture_cords, 2, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(24)) glEnableVertexAttribArray(texture_cords) #load texture texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # texture wrapping parametr glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) #texture filtering parametr glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = Image.open("./res/1.jpg") flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM) image_data = numpy.array(list(flipped_image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 564, 555, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data) # glTexImage2D() glUseProgram(shader) glClearColor(.2, .3, .2, 1.0) glEnable(GL_DEPTH_TEST) # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) #perspective part # view matrix view = pyrr.matrix44.create_from_translation(pyrr.Vector3([.0, .0, -3.0])) # global view # projection matrix projection = pyrr.matrix44.create_perspective_projection(45.0, w_width / w_height, 0.1, 100.0) # model position matrix model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0])) view_location = glGetUniformLocation(shader, "view") projection_location = glGetUniformLocation(shader, "projection") model_location = glGetUniformLocation(shader, "model") glUniformMatrix4fv(view_location, 1, GL_FALSE, view) glUniformMatrix4fv(model_location, 1, GL_FALSE, model) glUniformMatrix4fv(projection_location, 1, GL_FALSE, projection) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(.8 * glfw.get_time()) transform_location = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transform_location, 1, GL_FALSE, rot_x * rot_y) glUniformMatrix4fv(model_location, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def opengl循环(所有图层, psd尺寸): Vtuber尺寸 = 512, 512 glfw.init() glfw.window_hint(glfw.RESIZABLE, False) window = glfw.create_window(*Vtuber尺寸, 'Vtuber', None, None) glfw.make_context_current(window) glViewport(0, 0, *Vtuber尺寸) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) for 图层数据 in 所有图层: 纹理编号 = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, 纹理编号) 纹理, 纹理座标 = 生成纹理(图层数据['npdata']) width, height = 纹理.shape[:2] glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_FLOAT, 纹理) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glGenerateMipmap(GL_TEXTURE_2D) 图层数据['纹理编号'] = 纹理编号 图层数据['纹理座标'] = 纹理座标 while not glfw.window_should_close(window): glfw.poll_events() glClearColor(1, 1, 1, 0) glClear(GL_COLOR_BUFFER_BIT) for 图层数据 in 所有图层: a, b, c, d = 图层数据['位置'] z = 图层数据['深度'] if type(z) in [int, float]: z1, z2, z3, z4 = [z, z, z, z] else: [z1, z2], [z3, z4] = z q, w = 图层数据['纹理座标'] p1 = np.array([a, b, z1, 1, 0, 0, 0, 1]) p2 = np.array([a, d, z2, 1, w, 0, 0, 1]) p3 = np.array([c, d, z3, 1, w, q, 0, 1]) p4 = np.array([c, b, z4, 1, 0, q, 0, 1]) model = matrix.scale(2 / psd尺寸[0], 2 / psd尺寸[1], 1) @ \ matrix.translate(-1, -1, 0) @ \ matrix.rotate_ax(-math.pi / 2, axis=(0, 1)) glBindTexture(GL_TEXTURE_2D, 图层数据['纹理编号']) glColor4f(1, 1, 1, 1) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glBegin(GL_QUADS) for p in [p1, p2, p3, p4]: a = p[:4] b = p[4:] a = a @ model z = a[2] a[0:2] *= z b *= z 横旋转量 = 0 if not 图层数据['名字'] == '身体': 横旋转量 = math.sin(time.time() * 5) / 30 a = a @ matrix.translate(0, 0, -1) \ @ matrix.rotate_ax(横旋转量, axis=(0, 2)) \ @ matrix.translate(0, 0, 1) a = a @ matrix.perspective(999) glTexCoord4f(*b) glVertex4f(*a) glEnd() glfw.swap_buffers(window)
def main(): init_glfw() with Triangle() as triangle: with bindTexture(GL_TEXTURE0, GL_TEXTURE_2D, triangle.texture1), \ bindTexture(GL_TEXTURE1, GL_TEXTURE_2D, triangle.texture2): uni_model = triangle.shader_program.get_uniform_location('model') uni_view = triangle.shader_program.get_uniform_location('view') view = glm_mt.lookAt(np.array([2.5, 2.5, 2.5]), np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 1.0])) glUniformMatrix4fv(uni_view, 1, GL_FALSE, np.array(view, dtype=GLfloat)) uni_proj = triangle.shader_program.get_uniform_location('proj') proj = glm_mt.perspective(np.radians(45.0), 4 / 3, 1.0, 10.0) glUniformMatrix4fv(uni_proj, 1, GL_FALSE, np.array(proj, dtype=GLfloat)) uni_color = triangle.shader_program.get_uniform_location( 'overrideColor') while not glfw.window_should_close(triangle.window): glfw.poll_events() model = glm_mt.rotate(glm.mat4(), glfw.get_time() * np.pi, np.array([0., 0., 1.])) glUniformMatrix4fv(uni_model, 1, GL_FALSE, np.array(model, dtype=GLfloat)) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glDrawArrays(GL_TRIANGLES, 0, 36) glEnable(GL_STENCIL_TEST) # Draw floor glStencilFunc(GL_ALWAYS, 1, 0xFF) glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) glStencilMask(0xFF) glDepthMask(GL_FALSE) glClear(GL_STENCIL_BUFFER_BIT) glDrawArrays(GL_TRIANGLES, 36, 6) # Draw cube reflection glStencilFunc(GL_EQUAL, 1, 0xFF) glStencilMask(0x00) glDepthMask(GL_TRUE) model = glm_mt.scale( glm_mt.translate(model, np.array([0., 0., -1.])), np.array([1., 1., -1.])) glUniformMatrix4fv(uni_model, 1, GL_FALSE, np.array(model, dtype=GLfloat)) glUniform3f(uni_color, 0.3, 0.3, 0.3) glDrawArrays(GL_TRIANGLES, 0, 36) glUniform3f(uni_color, 1.0, 1.0, 1.0) glDisable(GL_STENCIL_TEST) glfw.swap_buffers(triangle.window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return # create a window h = 600 w = 800 mywin = glfw.create_window(width=w, height=h, title="My Window", monitor=None, share=None) # check if the window is created if not mywin: glfw.terminate() return # set the window as the current context glfw.make_context_current(mywin) # create the mesh - cube (has 8 vertices) # position # color cube = [ -.5, -.5, -.5, 1., 0., 0., -.5, .5, -.5, 1., 0., 0., .5, .5, -.5, 1., 0., 0., .5, -.5, -.5, 1., 0., 0., -.5, -.5, .5, 0., 0., 1., -.5, .5, .5, 0., 0., 1., .5, .5, .5, 0., 0., 1., .5, -.5, .5, 0., 0., 1. ] # defining all the faces indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 5, 6, 2, 2, 1, 5, 6, 7, 3, 3, 2, 6, 4, 7, 3, 3, 0, 4 ] cube = np.array(cube, dtype=np.float32) indices = np.array(indices, dtype=np.uint32) # create vertex shader vertex_shader = """ #version 330 in vec3 position; in vec3 color; uniform mat4 transform; out vec3 newColor; void main(){ gl_Position = transform * vec4(position, 1.0f); newColor = color; } """ # create fragment shader fragment_shader = """ #version 330 in vec3 newColor; out vec4 outColor; void main(){ outColor = vec4(newColor, 1.0f); } """ # create shader program by compile the two shader objects shader = glShader.compileProgram( glShader.compileShader(vertex_shader, GL_VERTEX_SHADER), glShader.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) # send the data to GPU vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, cube.shape[0] * 4, cube, GL_STATIC_DRAW) ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.shape[0] * 4, indices, GL_STATIC_DRAW) # define the layout by enabling and passing the vertex attributes # position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) # use the shader program glUseProgram(shader) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # draw loop while not glfw.window_should_close(mywin): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # rotation takes place here rot_x = pyrr.Matrix44.from_x_rotation(2.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(1.5 * glfw.get_time()) rot_x = np.array(rot_x, dtype=GLfloat) rot_y = np.array(rot_y, dtype=GLfloat) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(0, 1, GL_FALSE, np.dot(rot_x, rot_y)) """ the location for uniforms and other variables have different index. So in fact, if we use 0 in the code above, we get the same result. And it works because we only have one uniform variable. """ glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glfw.swap_buffers(mywin) glfw.poll_events() glfw.destroy_window(mywin) glfw.terminate()
R.resize_window(W, H) return # ---------------------------------------------------------------------------------------------------------------------- filename_box = './images/ex_GL/box/box_1.obj' # ---------------------------------------------------------------------------------------------------------------------- folder_out = './images/output/gl/' W, H = 720, 720 R = tools_GL3D.render_GL3D(filename_obj=filename_box, W=W, H=H, do_normalize_model_file=False, projection_type='P', scale=(1, 1, 1), tvec=(0, 0, 0)) # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': glfw.set_key_callback(R.window, event_key) glfw.set_mouse_button_callback(R.window, event_button) glfw.set_cursor_pos_callback(R.window, event_position) glfw.set_scroll_callback(R.window, event_scroll) glfw.set_window_size_callback(R.window, event_resize) while not glfw.window_should_close(R.window): R.draw() glfw.poll_events() glfw.swap_buffers(R.window) glfw.terminate()
def flip(): global _window glfw.swap_buffers(_window)
def main(): global delta_time, last_frame if not glfw.init(): raise ValueError("Failed to initialize glfw") 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) window = glfw.create_window(SRC_WIDTH, SRC_HEIGHT, "learnOpenGL", None, None) if not window: glfw.terminate() raise ValueError("Failed to create window") glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) gl.glEnable(gl.GL_DEPTH_TEST) lamp_shader = Shader(CURDIR / "shaders/1.lamp.vs", CURDIR / "shaders/1.lamp.fs") lighting_shader = Shader(CURDIR / "shaders/4.1.lighting_maps.vs", CURDIR / "shaders/4.1.lighting_maps.fs") vertices = [ # positions normals texture coords -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, 1.0, 1.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, 0.0, 1.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0 ] vertices = (c_float * len(vertices))(*vertices) cube_vao = gl.glGenVertexArrays(1) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glBindVertexArray(cube_vao) # -- position attribute gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- normal attribute gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) # -- texture coordinate gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(6 * sizeof(c_float))) gl.glEnableVertexAttribArray(2) # -- second configure light vao (vbo is the same) light_vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(light_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- load texture diffuse_map = load_texture("container2.png") # -- shader configuration lighting_shader.use() lighting_shader.set_int("material.diffuse", 0) while not glfw.window_should_close(window): # -- time logic current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # -- input process_input(window) # -- render gl.glClearColor(0.1, 0.1, 0.1, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) lighting_shader.use() lighting_shader.set_vec3("light.position", light_pos) lighting_shader.set_vec3("viewPos", camera.position) # -- light properties lighting_shader.set_vec3("light.ambient", Vector3([0.2, 0.2, 0.2])) lighting_shader.set_vec3("light.diffuse", Vector3([0.5, 0.5, 0.5])) lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0])) # -- material properties lighting_shader.set_vec3("material.specular", Vector3([0.5, 0.5, 0.5])) lighting_shader.set_float("material.shininess", 32.0) # -- view.projection transformations projection = Matrix44.perspective_projection(camera.zoom, SRC_WIDTH / SRC_HEIGHT, 0.1, 100.0) view = camera.get_view_matrix() lighting_shader.set_mat4("projection", projection) lighting_shader.set_mat4("view", view) # -- world transformation model = Matrix44.identity() lighting_shader.set_mat4("model", model) # -- bind diffuse map gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, diffuse_map) # -- render cube gl.glBindVertexArray(cube_vao) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) # -- draw lamp object lamp_shader.use() lamp_shader.set_mat4("projection", projection) lamp_shader.set_mat4("view", view) model = Matrix44.identity() model *= Matrix44.from_translation(light_pos) model *= Matrix44.from_scale(Vector3([.2, .2, .2])) lamp_shader.set_mat4("model", model) gl.glBindVertexArray(light_vao) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) glfw.swap_buffers(window) glfw.poll_events() gl.glDeleteVertexArrays(1, id(cube_vao)) gl.glDeleteVertexArrays(1, id(light_vao)) gl.glDeleteBuffers(1, id(vbo)) glfw.terminate()
def main(): # 以下初始化glfw和窗口 if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # 新建窗口 window = glfw.create_window(width, height, "Hello Window", None, None) if not window: glfw.terminate() return # 设置context glfw.make_context_current(window) glfw.set_window_size_callback(window, resize_callback) ctx = mg.create_context(require=410) # 顶点数组 vertices = numpy.array([ 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, -0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 1.0 ], dtype='f4') # 建立vbo vbo = ctx.buffer(vertices.tobytes()) # 这是shader vert = ''' #version 410 core layout (location = 0) in vec3 pos; layout (location = 1) in vec3 color; out vec3 ourColor; void main() { gl_Position = vec4(pos, 1.0); ourColor = color; } ''' frag = ''' #version 410 core out vec4 color; in vec3 ourColor; void main() { color = vec4(ourColor, 1.0); } ''' # 编译shader program = ctx.program(vertex_shader=vert, fragment_shader=frag) # 建立vao vao = ctx.simple_vertex_array(program, vbo, 'pos', 'color') while not glfw.window_should_close(window): process_input(window) ctx.viewport = (0, 0, width, height) ctx.clear(0.2, 0.3, 0.3, 1.0) time = glfw.get_time() green = math.sin(time) / 2.0 + 0.5 vao.render() glfw.poll_events() glfw.swap_buffers(window) glfw.terminate()
def main(): # inicia glfw if not glfw.init(): return # crea la ventana, # independientemente del SO que usemos window = glfw.create_window(800, 800, "Mi ventana", None, None) # Configuramos OpenGL glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Validamos que se cree la ventana if not window: glfw.terminate() return # Establecemos el contexto glfw.make_context_current(window) # Activamos la validación de # funciones modernas de OpenGL glewExperimental = True # Inicializar GLEW if glewInit() != GLEW_OK: print("No se pudo inicializar GLEW") return # Obtenemos versiones de OpenGL y Shaders version = glGetString(GL_VERSION) print(version) version_shaders = glGetString(GL_SHADING_LANGUAGE_VERSION) print(version_shaders) glfw.set_key_callback(window, key_callback) while not glfw.window_should_close(window): # Establece regiond e dibujo glViewport(0, 0, 800, 800) # Establece color de borrado glClearColor(0.4, 0.8, 0.1, 1) # Borra el contenido de la ventana glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Dibujar actualizar(window) dibujar() # Preguntar si hubo entradas de perifericos # (Teclado, mouse, game pad, etc.) glfw.poll_events() # Intercambia los buffers glfw.swap_buffers(window) # Se destruye la ventana para liberar memoria glfw.destroy_window(window) # Termina los procesos que inició glfw.init glfw.terminate()
def main(): global shader vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec2 a_texture; uniform mat4 model; // combined translation and rotation uniform mat4 projection; out vec3 v_color; out vec2 v_texture; void main() { gl_Position = projection * model * vec4(a_position, 1.0); v_texture = a_texture; } """ fragment_src = """ # version 330 in vec2 v_texture; out vec4 out_color; uniform sampler2D s_texture; void main() { out_color = texture(s_texture, v_texture); } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") if "Windows" in pltf.platform(): glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) else: glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # creating the window window = glfw.create_window(1280, 720, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 100, 100) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) # make the context current glfw.make_context_current(window) vertices = [ -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0 ] indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] vertices = np.array(vertices, dtype=np.float32) indices = np.array(indices, dtype=np.uint32) VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # Vertex Buffer Object VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) # Element Buffer Object EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, vertices.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, vertices.itemsize * 5, ctypes.c_void_p(12)) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # load image image = Image.open("textures/crate.jpg") image = image.transpose(Image.FLIP_TOP_BOTTOM) img_data = image.convert("RGBA").tobytes() # img_data = np.array(image.getdata(), np.uint8) # second way of getting the raw image data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, 1280 / 720, 0.1, 100) translation = pyrr.matrix44.create_from_translation( pyrr.Vector3([0, 0, -3])) glUseProgram(shader) model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUseProgram(0) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) rotation = pyrr.matrix44.multiply(rot_x, rot_y) model = pyrr.matrix44.multiply(rotation, translation) glUseProgram(shader) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glBindVertexArray(VAO) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) glUseProgram(0) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
import glfw if not glfw.init(): raise Exception("") window = glfw.create_window(600, 400, "first window", None, None) if not window: glfw.terminate() raise Exception("Error") glfw.set_window_pos(window, 300, 300) while not glfw.window_should_close(window): glfw.poll_events() glfw.swap_buffers(window) glfw.terminate()
def Amy_jump(estructura): if __name__ == "__main__": # Initialize glfw if not glfw.init(): sys.exit() width = 700 height = 700 window = glfw.create_window(width, height, "Amy Jump", None, None) if not window: glfw.terminate() sys.exit() glfw.make_context_current(window) # Connecting the callback function 'on_key' to handle keyboard events glfw.set_key_callback(window, on_key) # Defining shader programs pipeline = ls.SimpleGouraudShaderProgram() texture_pipeline = es.SimpleTextureModelViewProjectionShaderProgram() color_pipeline = es.SimpleModelViewProjectionShaderProgram() tex_pipeline = es.SimpleTextureTransformShaderProgram() # Telling OpenGL to use our shader program glUseProgram(pipeline.shaderProgram) # Setting up the clear screen color glClearColor(0.85, 0.85, 0.85, 1.0) # As we work in 3D, we need to check which part is in front, # and which one is at the back glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Creamos los objetos # Amy gpuAmy = es.toGPUShape(shape=readOBJ('amy.obj', (1, 0, 0.5))) # Anillo (trofeo) gpuAnillo = es.toGPUShape(shape=readOBJ('ring.obj', (0.9, 0.9, 0))) # Fondo fondo = Fondo() #Piso piso = bs.createTextureCube('piso.jpg') gpupiso = es.toGPUShape(piso, GL_REPEAT, GL_LINEAR) piso_transform = tr.matmul( [tr.uniformScale(24), tr.translate(0, 0, -0.53)]) # Pantalla de inicio amyi = es.toGPUShape(bs.createTextureQuad("amy2.png", 1, 1), GL_REPEAT, GL_LINEAR) # Pantala de perdida eggman = es.toGPUShape(bs.createTextureQuad("eggman.png", 1, 1), GL_REPEAT, GL_LINEAR) # Pantalla de ganador amyf = es.toGPUShape(bs.createTextureQuad("am.png", 1, 1), GL_REPEAT, GL_LINEAR) # Barras barras = CreateBarras() barras.create(estructura) #Revisamos el tiempo t0 = glfw.get_time() # Posiciones de Amy posX = 0 posY = 0 posZ = 0.5 #Cuenta los fondo que ya se crearon count = 1 # Indica hasta que altura se debe llegar al saltar alt = 0 # Dice si se puede saltar o no salto = True #Indica cuando se "pierde" por saltar mal perder = False #Indica cuando se pierde por una flecha perder2 = False # Dice si se debe mandar una flecha de ataque arrow = True #Se crea la flecha con las posiciones hacia Amy flechas = Flecha(posX, posY, posZ) #Tamaño inicial de la imagen de partida, de perdida y de ganador ag = 2 eg = 0 af = 0 # rotaciones de Amy rotz = np.pi rotx = np.pi / 2 roty = 0 #Indica si ya estuvo en una barra bt = False #Rotaciones y posiciones del aro ra = 0 x = 0 y = 0 #Indica si gana o pierde ganar = False while not glfw.window_should_close(window): # Using GLFW to check for input events glfw.poll_events() # Getting the time difference from the previous iteration t1 = glfw.get_time() dt = t1 - t0 t0 = t1 #Se define la vista "fija" del juego view = tr.lookAt(np.array([12, -5, 8 + (posZ - 0.5)]), np.array([posX * 0.4, posY * 0.4, posZ]), np.array([0, 0, 1])) #Cambia la vista mientras se mantengan apretadas las teclas if (glfw.get_key(window, glfw.KEY_B) == glfw.PRESS): view = tr.lookAt(np.array([0, 1, 17.5 + (posZ)]), np.array([0, 0, 0]), np.array([0, 0, 1])) if (glfw.get_key(window, glfw.KEY_N) == glfw.PRESS): view = tr.lookAt(np.array([-12, -5, 7.5 + posZ]), np.array([posX, posY, posZ]), np.array([0, 0, 1])) if (glfw.get_key(window, glfw.KEY_M) == glfw.PRESS): view = tr.lookAt(np.array([0, 10, -0.5 + posZ]), np.array([posX, posY, posZ]), np.array([0, 0, 1])) # Setting up the projection transform projection = tr.perspective(60, float(width) / float(height), 0.1, 100) # Clearing the screen in both, color and depth glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #Dibujamos el fondo fondo.Draw(texture_pipeline, projection, view) # Revisamos si se debe crear otro fondo if posZ > 13 * count: fondoazul = FondoAzul(count, fondo) count += 1 #Dibujamos el piso glUseProgram(texture_pipeline.shaderProgram) glUniformMatrix4fv( glGetUniformLocation(texture_pipeline.shaderProgram, "model"), 1, GL_TRUE, piso_transform) glUniformMatrix4fv( glGetUniformLocation(texture_pipeline.shaderProgram, "projection"), 1, GL_TRUE, projection) glUniformMatrix4fv( glGetUniformLocation(texture_pipeline.shaderProgram, "view"), 1, GL_TRUE, view) texture_pipeline.drawShape(gpupiso) # Luz glUseProgram(pipeline.shaderProgram) glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "La"), 1.0, 1.0, 1.0) glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ld"), 1.0, 1.0, 1.0) glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ls"), 1.0, 1.0, 1.0) glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ka"), 0.3, 0.3, 0.3) glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Kd"), 0.9, 0.9, 0.9) glUniform3f(glGetUniformLocation(pipeline.shaderProgram, "Ks"), 0.2, 0.2, 0.2) glUniform3f( glGetUniformLocation(pipeline.shaderProgram, "lightPosition"), 0, 0, posZ + 5) glUniform3f( glGetUniformLocation(pipeline.shaderProgram, "viewPosition"), 0, 0, posZ + 5) glUniform1ui( glGetUniformLocation(pipeline.shaderProgram, "shininess"), 1000) glUniform1f( glGetUniformLocation(pipeline.shaderProgram, "constantAttenuation"), 0.01) glUniform1f( glGetUniformLocation(pipeline.shaderProgram, "linearAttenuation"), 0.1) glUniform1f( glGetUniformLocation(pipeline.shaderProgram, "quadraticAttenuation"), 0.01) #Dibujamos a Amy glUniformMatrix4fv( glGetUniformLocation(pipeline.shaderProgram, "projection"), 1, GL_TRUE, projection) glUniformMatrix4fv( glGetUniformLocation(pipeline.shaderProgram, "view"), 1, GL_TRUE, view) glUniformMatrix4fv( glGetUniformLocation(pipeline.shaderProgram, "model"), 1, GL_TRUE, tr.matmul([ tr.translate(posX, posY, posZ), tr.rotationZ(rotz), tr.rotationX(rotx), tr.rotationY(roty), tr.uniformScale(0.4) ])) pipeline.drawShape(gpuAmy) #Dibujamos el anillo a la altura de la ultima barra glUniformMatrix4fv( glGetUniformLocation(pipeline.shaderProgram, "model"), 1, GL_TRUE, tr.matmul([ tr.translate(x, y, barras.altura * 2), tr.rotationZ(ra), tr.uniformScale(0.5) ])) pipeline.drawShape(gpuAnillo) # Dibujamos la pantalla inicial glUseProgram(tex_pipeline.shaderProgram) glUniformMatrix4fv( glGetUniformLocation(tex_pipeline.shaderProgram, "transform"), 1, GL_TRUE, tr.matmul([tr.translate(0, 0, 0), tr.uniformScale(ag)])) tex_pipeline.drawShape(amyi) # Dibujamos la pantalla de perdida glUniformMatrix4fv( glGetUniformLocation(tex_pipeline.shaderProgram, "transform"), 1, GL_TRUE, tr.matmul([tr.translate(0, 0, 0), tr.uniformScale(eg)])) tex_pipeline.drawShape(eggman) # Dibujamos la pantalla de ganador glUniformMatrix4fv( glGetUniformLocation(tex_pipeline.shaderProgram, "transform"), 1, GL_TRUE, tr.matmul([tr.translate(0, 0, 0), tr.uniformScale(af)])) tex_pipeline.drawShape(amyf) # Hace una copia de la lista de barras b = barras.barras #Indica que hay gravedad por lo cual amy va a caer mientras no este en una plataforma grav = True #Cambia el angulo de de rotación del aro ra -= 2 * dt #Revisa que la posición de las barras calza con Amy for i in range(len(b)): if posX <= 2 * b[i].posx + 1 and posX >= 2 * b[ i].posx - 1 and posY <= 2 * b[ i].posy + 1 and posY >= 2 * b[ i].posy - 1 and posZ <= b[ i].posz * 0.3 + 1.4 and posZ >= b[ i].posz * 0.3 + 1.25: if b[i].real == False: #Revisa si la barra es real, de serlo no la dibuja y no apaga la gravedad b[i].dibujo = False else: grav = False #si no, apaga la gravedad bt = True #indica que ya se subio una barra # Implementa la gravedad if posZ > 0.6 and grav == True: posZ -= 3 * dt #Mueve a Amy dependiendo de la tecla que se precione if (glfw.get_key(window, glfw.KEY_A) == glfw.PRESS): if posX > -6: posX -= 5 * dt if (glfw.get_key(window, glfw.KEY_D) == glfw.PRESS): if posX < 6: posX += 5 * dt if (glfw.get_key(window, glfw.KEY_W) == glfw.PRESS): if posY < 6: posY += 5 * dt if (glfw.get_key(window, glfw.KEY_S) == glfw.PRESS): if posY > -6: posY -= 5 * dt #Implementa los saltos if (glfw.get_key(window, glfw.KEY_SPACE) == glfw.PRESS): #si se puede saltar if salto == True: salto = False #se bloquea otro salto alt = 2 + posZ #calcula hasta donde debe llegar #si no pierde y no llega al limite de altura if alt >= posZ and perder == False: posZ += 5 * dt #salta #Si esta en una barra y aún no pierde if grav == False and perder2 == False: salto = True #Puede volver a saltar perder = False #aún no pierde #Inidica que perdio if alt < posZ + 0.01: perder = True # Si es que se puede hacer una flecha if arrow == True: ti = t1 #Revisamos el tiempo actual arrow = False #decimos que no se pueden hacer mas flechas flechas = Flecha(posX, posY, posZ) #se indica las posicones de la flecha # Si ya pasa un tiempo especifico if ti + 3 < t1: arrow = True # se puede hacer otra flecha #Revisamos que una flecha toca a Amy if flechas.posx <= posX + 0.1 and flechas.posx >= posX - 0.1 and flechas.posy <= -posY * 0.2 + 0.1 and flechas.posy >= -posY * 0.2 - 0.1 and flechas.posz <= posZ * 0.2 + 0.1 and flechas.posz >= posZ * 0.2 - 0.1: perder2 = True #Pierde #Mueve las flechas a partir de un tiempo en especifico if t1 > 8: flechas.update(4 * dt) flechas.draw(pipeline, projection, view) #Hace el movimiento de la imagen inicial if t1 < 8: if ag > 0: ag -= dt #Si pierde genera la imagen de game over y Amy empieza a rotar if ((posZ >= 0.5 and posZ <= 0.6 and grav and bt) or perder2 or (salto == False and posZ >= 0.5 and posZ <= 0.6)) and ganar == False: if eg < 2: eg += 0.8 * dt rotx -= 2 * dt rotz -= 2 * dt #Indica cuando gana if barras.altura * 2 - posZ <= 0.5 and barras.altura * 2 - posZ >= 0 and grav == False: ganar = True #Mueve el aro a Amy if x < 1.7 * posX: x += 5 * dt elif x >= 1.7 * posX: x -= 5 * dt if y < 1 * posY: y += 5 * dt elif y >= 1 * posY: y -= 5 * dt #Hace el movimiento de la imagen de ganador if af < 2: af += 0.8 * dt #Dibuja las barras barras.draw(color_pipeline, projection, view) # Once the drawing is rendered, buffers are swap so an uncomplete drawing is never seen. glfw.swap_buffers(window) glfw.terminate()
def run(self): # Initialize the library if not glfw.init(): return # Set some window hints glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.SAMPLES, 16) # This works as expected # glfw.window_hint(glfw.RESIZABLE, 0) # These should work, but don't :( # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226 # ended up using xdotool, see run.py glfw.window_hint(glfw.FOCUSED, 0) # I've set 'shader-*' to raise in openbox-rc as workaround # Looking at the code and confirming version 3.1.2 and it should work glfw.window_hint(glfw.FLOATING, 1) # Create a windowed mode window and its OpenGL context self.w = glfw.create_window(500, 500, "shader-test", None, None) if not self.w: glfw.terminate() return # Move Window glfw.set_window_pos(self.w, 1400, 50) # Callbacks glfw.set_key_callback(self.w, self.on_key) glfw.set_framebuffer_size_callback(self.w, self.on_resize) # Make the window's context current glfw.make_context_current(self.w) # vsync glfw.swap_interval(1) # Setup GL shaders, data, etc. self.initialize() # Loop until the user closes the window while not glfw.window_should_close(self.w): # print difference in time since start # this should always be 16.6-16.7 @ 60fps # print('%0.1fms' % (1000 * (time.time()-self.lastframe))) # start of the frame self.lastframe = time.time() # Render here, e.g. using pyOpenGL self.render() # Swap front and back buffers glfw.swap_buffers(self.w) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): # 以下初始化glfw和窗口 if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # 新建窗口 window = glfw.create_window(width, height, "Hello Window", None, None) if not window: glfw.terminate() return # 设置context glfw.make_context_current(window) glfw.set_window_size_callback(window, resize_callback) ctx = moderngl.create_context(require=410) # 顶点数组 vertices = numpy.array([0, 0, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0], dtype='f4') # 建立vbo vbo = ctx.buffer(vertices.tobytes()) # 顶点index indice = numpy.array([0, 1, 2], dtype='u4') ebo = ctx.buffer(indice.tobytes()) # 读取shader f = open('shaders/transform.vert') vert = f.read() f.close() f = open('shaders/orange.frag') frag = f.read() f.close() # 编译shader program = ctx.program(vertex_shader=vert, fragment_shader=frag) angle = 0 # 建立vao vao = ctx.simple_vertex_array(program, vbo, 'aPos', index_buffer=ebo) # 主循环 while not glfw.window_should_close(window): process_input(window) ctx.viewport = (0, 0, width, height ) # 这个就是glViewport(),设置opengl的窗口大小,不设置其实也无所谓 ctx.clear(0.2, 0.3, 0.3, 1.0) angle += math.pi / 180 trans = mat.rotate(angle, 0, 0, 1) program['transform'].write(trans.tobytes()) vao.render() glfw.poll_events() glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return window = glfw.create_window(800, 600, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # positions colors cube = [ -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, #0.0 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, -0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 6, 7, 3, 3, 2, 6, 5, 6, 2, 2, 1, 5, 7, 4, 0, 0, 3, 7 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in vec3 position; in vec3 color; uniform mat4 transform; out vec3 newColor; void main() { gl_Position = transform * vec4(position, 1.0f); newColor = color; } """ fragment_shader = """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """ #RESIZING def window_resize(window, width, height): glViewport(0, 0, width, height) glfw.set_window_pos(window, 400, 200) #400 # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) #DRAW IN WIREFRAMES #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, 192, cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, 144, indices, GL_STATIC_DRAW) position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) color = glGetAttribLocation(shader, "color") glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) #0.2 glEnable(GL_DEPTH_TEST) while not glfw.window_should_close(window): glfw.poll_events() glClearColor(0, 0, 0, 0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(0.7 * glfw.get_time()) #0.5 rot_y = pyrr.Matrix44.from_y_rotation(1.0 * glfw.get_time()) #0.8 transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def main(): glfw.init() glfw.window_hint(glfw.RESIZABLE, False) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) w = glfw.create_window(800, 600, 'Window Title', None, None) glfw.make_context_current(w) ############### face = freetype.Face("/usr/share/fonts/TTF/IBMPlexSans-Regular.ttf") # Figure out DPI's of different monitors # Perhaps take these into account if you care, as well as window scale. # But what if your window is split across screens? for monitor in glfw.get_monitors(): name = glfw.get_monitor_name(monitor).decode('utf8') pw, ph = glfw.get_monitor_physical_size(monitor) videomode = glfw.get_video_mode(monitor) # in mm vw, vh = videomode.size.width, videomode.size.height # print(name, 25.4*vw/pw, 25.4*vh/ph) # convert to pixels per inch print(name, (1 / 72) * 25.4 * vw / pw, (1 / 72) * 25.4 * vh / ph) # pixels per point # Set char size via physical size calculation # width, height in 1/64 of points # A point is one 1/72 of an inch. My monitors have 1.35 to 1.84 pixels per point. # Device resolution in dots per inch. # pixel_size = point_size * resolution / 72 # face.set_char_size(width=16*64) #,height=0,hres=72,vres=72 # Set size of EM square via pixels directly face.set_pixel_sizes(20, 0) baseline_height = 20 * face.height / face.units_per_EM print(baseline_height) ############### # disable byte-alignment restriction # normally, textures need to occupy a multiple of 4 in memory # but glyphs are single-color so they don't satisfy this glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glyphs = {} for i in range(face.num_glyphs): face.load_glyph(i) #flags=FT_LOAD_RENDER - renders glyph after loading texture = glGenTextures(1) # all of these numbers are pixels*64 by default # so divide by 64 to make these just pixels glyphs[i] = { "texture": texture, "w": face.glyph.metrics.width / 64, "h": face.glyph.metrics.height / 64, "hori": { "advance": face.glyph.metrics.horiAdvance / 64, "bearingX": face.glyph.metrics.horiBearingX / 64, "bearingY": face.glyph.metrics.horiBearingY / 64, }, "vert": { "advance": face.glyph.metrics.vertAdvance / 64, "bearingX": face.glyph.metrics.vertBearingX / 64, "bearingY": face.glyph.metrics.vertBearingY / 64, } } bitmap = face.glyph.bitmap glBindTexture(GL_TEXTURE_2D, texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, bitmap.width, bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, bitmap.buffer) # target, level, internalformat, width, height, border=0, format, type,data glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) # these two seem glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) # to be optional glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) ################## shaderProgram = make_shader_program() glUseProgram(shaderProgram) posParamsUniform = glGetUniformLocation(shaderProgram, "posParams") def set_pos(x, y, dx, dy): s = 1 glUniform4f(posParamsUniform, s * x, s * y, s * dx, s * dy) # location, count, transpose, value vao = glGenVertexArrays(1) glBindVertexArray(vao) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) # two triangles to make a rectangle # coordinates are in screen space # to get texture coordinates to x->x and y->1-y vertices = [0.0, 1.0] + [0.0,0.0] + [1.0,0.0] +\ [0.0, 1.0] + [1.0,0.0] + [1.0,1.0] glBufferData(GL_ARRAY_BUFFER, len(vertices)*ctypes.sizeof(ctypes.c_float), \ (ctypes.c_float*len(vertices))(*vertices), GL_STATIC_DRAW) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glEnable(GL_BLEND) # need this because the shader uses alphas glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) fbsize = {} fbsize["w"], fbsize["h"] = glfw.get_framebuffer_size(w) while not glfw.window_should_close(w): glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) x, y = -1.0, 1.0 y -= baseline_height * 2 / fbsize["h"] for i in range(face.num_glyphs): bx = glyphs[i]["hori"]["bearingX"] * 2 / fbsize["w"] by = glyphs[i]["hori"]["bearingY"] * 2 / fbsize["h"] width = glyphs[i]["w"] * 2 / fbsize["w"] height = glyphs[i]["h"] * 2 / fbsize["h"] set_pos(x + bx, y + by - height, width, height) x += glyphs[i]["hori"]["advance"] * 2 / fbsize["w"] glBindTexture(GL_TEXTURE_2D, glyphs[i]["texture"]) glDrawArrays(GL_TRIANGLES, 0, 6) if i + 1 < face.num_glyphs: x += face.get_kerning(i, i + 1).x if x + glyphs[i + 1]["hori"]["advance"] * 2 / fbsize["w"] >= 1.0: x = -1.0 y -= baseline_height * 2 / fbsize["h"] if y <= -1.0: break glfw.swap_buffers(w) glfw.poll_events() glDeleteBuffers(1, vbo) glDeleteVertexArrays(1, vao) glDeleteProgram(shaderProgram) glfw.terminate()
def update(self): glfw.make_context_current(self.window) self.plotter.setupProjection() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) self.draw() glfw.swap_buffers(self.window)
def Run(self): while not glfw.window_should_close(self.window): self.Step() glfw.swap_buffers(self.window) glfw.poll_events() self.SetView(None)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial9\\StandardShading.vertexshader", ".\\shaders\\Tutorial9\\StandardShading.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = textureutils.load_image(".\\content\\uvmap_suzanne.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load(".\\content\\suzanne.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) normal_data = objloader.generate_2d_ctypes(normal_data) indexed_vertices, indexed_uvs, indexed_normals, indices = vboindexer.indexVBO(vertex_data,uv_data,normal_data) indexed_vertices = c_type_fill(indexed_vertices,GLfloat) indexed_uvs = c_type_fill(indexed_uvs,GLfloat) indexed_normals = c_type_fill(indexed_normals,GLfloat) indices = c_type_fill_1D(indices,GLushort) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_vertices) * 4 * 3, indexed_vertices, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_uvs) * 4 * 2, indexed_uvs, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_normals) * 4 * 3, indexed_normals, GL_STATIC_DRAW) # Generate a buffer for the indices as well elementbuffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices) * 2, indices , GL_STATIC_DRAW); # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id); light_id = glGetUniformLocation(program_id, "LightPosition_worldspace"); last_time = glfw.get_time() frames = 0 while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window,"Tutorial 9. FPS: %d"%(frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data); glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data); lightPos = vec3(4,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0); #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length # glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer) # Draw the triangles ! glDrawElements( GL_TRIANGLES, # mode len(indices), # count GL_UNSIGNED_SHORT, # type null # element array buffer offset ) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()