def render_scene(self): "render scene one time" self.init_gl() glfw.MakeContextCurrent(self.window) self.renderer.render_scene() glfw.SwapBuffers(self.window) glfw.PollEvents()
def process_input(dt): glfw.PollEvents() dposition[:] = 0.0 if key_state[glfw.KEY_W]: dposition[2] -= dt * move_speed if key_state[glfw.KEY_S]: dposition[2] += dt * move_speed if key_state[glfw.KEY_A]: dposition[0] -= dt * move_speed if key_state[glfw.KEY_D]: dposition[0] += dt * move_speed if key_state[glfw.KEY_Q]: dposition[1] += dt * move_speed if key_state[glfw.KEY_Z]: dposition[1] -= dt * move_speed theta = 0.0 if key_state[glfw.KEY_LEFT]: theta -= dt * turn_speed if key_state[glfw.KEY_RIGHT]: theta += dt * turn_speed rotation[0,0] = np.cos(theta) rotation[2,2] = rotation[0,0] rotation[0,2] = np.sin(theta) rotation[2,0] = -rotation[0,2] camera_rotation[...] = rotation.dot(camera_world_matrix[:3,:3]) camera_position[:] += camera_rotation.T.dot(dposition)
def run_loop(self): glfw.MakeContextCurrent(self._win) glfw.SetWindowShouldClose(self._win, False) while not glfw.WindowShouldClose(self._win): if self._next_renderer: if self._renderer: self._renderer.dispose() self._renderer = self._next_renderer self._renderer.prepare() self._next_renderer = None glClearColor(0.5, 0.5, 0.5, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if self._renderer: self._renderer.render() glfw.SwapBuffers(self._win) # Poll for and process events glfw.PollEvents() if self._renderer: self._renderer.dispose() if self._next_renderer is None: self._next_renderer = self._renderer
def test_window_pos_callback(self): called = [False] def callback(window, width, height): called[0] = True glfw.SetWindowPosCallback(self.window, callback) glfw.SetWindowPos(self.window, 10, 50) glfw.PollEvents() glfw.SetWindowPosCallback(self.window, None) self.assertTrue(called[0])
def __call__(self, scene, camera, callbacks): while not glfw.WindowShouldClose(self.window) or self.should_quit: callbacks(self.window) if callbacks.draw: camera.compute_matrices() scene.set_camera(camera) scene.render() glfw.SwapBuffers(self.window) callbacks.draw = False glfw.PollEvents() yield self glfw.Terminate()
def test_window_iconify_callback(self): called = [False, False] def callback(window, iconified): called[int(iconified)] = True glfw.SetWindowIconifyCallback(self.window, callback) glfw.IconifyWindow(self.window) glfw.PollEvents() glfw.RestoreWindow(self.window) glfw.SetWindowIconifyCallback(self.window, None) self.assertTrue(called[0]) self.assertTrue(called[1])
def render(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(self._mapping['program_id']) vp = self._compute_matrices_from_input() lightPos = vec3(2, 2, 6) glUniform3f(self._mapping['light_id'], lightPos.x, lightPos.y, lightPos.z) for object in self._render_objects: object.render(vp, self._mapping) glfw.SwapBuffers(self.window) # Poll for and process events glfw.PollEvents()
def test_vcgl(frame_block=None): # save current working directory cwd = os.getcwd() # initialize glfw - this changes cwd glfw.Init() # restore cwd os.chdir(cwd) # version hints glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 2) glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # make a window win = glfw.CreateWindow(WIDTH, HEIGHT, TITLE) # make context current glfw.MakeContextCurrent(win) glClearColor(0.5, 0.5, 0.5, 1.0) renderer = TextureRenderer() renderer.prepare() fps_checker = FPSChecker() webcam = Webcam() with webcam: while not glfw.WindowShouldClose(win): frame = webcam.frame if frame_block: frame = frame_block(frame) fps_checker.lab(frame) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = frame[::-1, ...] renderer.image = frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) renderer.render() glfw.SwapBuffers(win) # Poll for and process events glfw.PollEvents() glfw.Terminate()
def main(): appName = 'First App' glfw.Init() glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3) # glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) # glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.CreateWindow(800, 800, appName) glfw.SetWindowSizeCallback(window, window_size_callback) glfw.SetKeyCallback(window, key_callback) glfw.MakeContextCurrent(window) glfw.SwapInterval(1) try: initOpenGL() except Exception as e: print(e) exit(1) prevTime = time() frameCount = 0 frameTimeSum = 0 lastUpdateTime = prevTime while not glfw.WindowShouldClose(window): glfw.PollEvents() display(window) glfw.SwapBuffers(window) curTime = time() frameTime = (curTime - prevTime) # if frameTime != 0: print(1 / frameTime) sleep(0.016) if curTime - lastUpdateTime > 1: glfw.SetWindowTitle( window, '%s, FPS: %s' % (appName, str(round(frameCount / frameTimeSum)))) frameCount = 0 frameTimeSum = 0 lastUpdateTime = curTime frameTimeSum += frameTime frameCount += 1 prevTime = curTime glfw.DestroyWindow(window) glfw.Terminate()
def _view(self, meshes=None, window_size=(800,600)): if meshes is None: meshes = [] title = traceback.extract_stack(None, 2)[0][2] window, renderer = setup_glfw(width=window_size[0], height=window_size[1], double_buffered=True, title=title) camera_world_matrix = renderer.camera_matrix camera_position = camera_world_matrix[3,:3] gl.glViewport(0, 0, window_size[0], window_size[1]) gl.glClearColor(*BG_COLOR) gl.glEnable(gl.GL_DEPTH_TEST) for mesh in meshes: mesh.init_gl(force=True) def on_resize(window, width, height): gl.glViewport(0, 0, width, height) renderer.window_size = (width, height) renderer.update_projection_matrix() glfw.SetWindowSizeCallback(window, on_resize) process_keyboard_input = init_keyboard(window) _logger.info('entering render loop...') stdout.flush() nframes = 0 max_frame_time = 0.0 lt = glfw.GetTime() while not glfw.WindowShouldClose(window): t = glfw.GetTime() dt = t - lt lt = t glfw.PollEvents() renderer.process_input() process_keyboard_input(dt, camera_world_matrix) with renderer.render(meshes=meshes): pass max_frame_time = max(max_frame_time, dt) if nframes == 0: st = glfw.GetTime() nframes += 1 glfw.SwapBuffers(window) _logger.info('...exited render loop: average FPS: %f, maximum frame time: %f', (nframes - 1) / (t - st), max_frame_time) renderer.shutdown() _logger.info('...shut down renderer') glfw.DestroyWindow(window) glfw.Terminate()
def main(): cairoSavePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'carpark.pdf') # cairoSavePath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'carpark.pdf') # cairoSavePath = os.path.join(os.path.basename(__file__), 'carpark.pdf') # cairoSavePath = os.path.join(os.getcwd(), 'carpark.pdf') if not glfw.Init(): exit() window = CbWindow(640, 480, 'window') if not window.window: glfw.Terminate() print('GLFW: Failed to create window') exit() print glGetString(GL_VERSION) parkingLot = buildParkingLot() mainRender = ParkingLotRender(parkingLot) window.mainRender = mainRender window.cairoSavePath = cairoSavePath mainRender.renderCairo(window.playerCamera, cairoSavePath) # mainScene = Scene() glfw.MakeContextCurrent(window.window) while not glfw.WindowShouldClose(window.window): # Render here # mainScene.renderModels(window.playerCamera) # mainRender.renderOpenGL(window.playerCamera) mainRender.renderOpenGL(window.currentCamera, window.playerCamera) # Swap front and back buffers glfw.SwapBuffers(window.window) # Poll for and process events glfw.PollEvents() processCameraSelectInput(window, parkingLot) if not window.cameraLocked: window.currentCamera.processPlayerInput(window.window) glfw.DestroyWindow(window.window) glfw.Terminate()
def OnInit(self): #start main loop self.colorInc = 0.000 self.radInc = 0.0001 t = 0 radStep = 0 colorStep = 0 while not glfw.WindowShouldClose(self.win) and not self.exitNow: currT = glfw.GetTime() if currT - t > 1 / 60.0: colorStep += self.colorInc radStep += self.radInc t = currT self.logic() self.draw(colorStep, radStep) glfw.PollEvents()
def test_window_framebuffer_resize_callback(self): w_called = [False] def w_callback(window, width, height): w_called[0] = True f_called = [False] def f_callback(window, width, height): f_called[0] = True glfw.SetWindowSizeCallback(self.window, w_callback) glfw.SetFramebufferSizeCallback(self.window, f_callback) glfw.SetWindowSize(self.window, 800, 600) glfw.PollEvents() glfw.SetWindowSizeCallback(self.window, None) glfw.SetFramebufferSizeCallback(self.window, None) self.assertTrue(w_called[0]) self.assertTrue(f_called[0])
def main(): # save current working directory cwd = os.getcwd() # initialize glfw - this changes cwd glfw.Init() # restore cwd os.chdir(cwd) # version hints glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 2) glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # make a window win = glfw.CreateWindow(512, 512, b'simpleglfw') # make context current glfw.MakeContextCurrent(win) glClearColor(0.5, 0.5, 0.5, 1.0) # renderer = TriangleRenderer() # renderer = RectangleRenderer() with Image.open('./image/psh.jpg') as img: data = np.asarray(img, dtype='uint8') data = data[::-1, ...] renderer = TextureRenderer(image=data) renderer.prepare() while not glfw.WindowShouldClose(win): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) renderer.render() glfw.SwapBuffers(win) # Poll for and process events glfw.PollEvents() glfw.Terminate()
def __init__(self, width=1024, height=1024, title="vol_render"): curdir = os.getcwd() glfw.Init() # glfw sometimes changes the current working directory, see # https://github.com/adamlwgriffiths/cyglfw3/issues/21 os.chdir(curdir) glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) self.window = glfw.CreateWindow(width, height, title) if not self.window: glfw.Terminate() exit() glfw.MakeContextCurrent(self.window) GL.glClearColor(0.0, 0.0, 0.0, 0.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) glfw.SwapBuffers(self.window) glfw.PollEvents()
def process_input(dt): nonlocal _capture_wait, _num_captures glfw.PollEvents() if _capture_wait > 0: _capture_wait -= dt elif key_state[glfw.KEY_C]: _logger.info('''capturing screen... camera position: %s''', camera_position) save_screen(window, '.'.join([screen_capture_prefix, '%03d' % _num_captures, 'png'])) _num_captures += 1 _capture_wait = 0.25 dposition[:] = 0.0 if key_state[glfw.KEY_W]: dposition[2] -= dt * move_speed if key_state[glfw.KEY_S]: dposition[2] += dt * move_speed if key_state[glfw.KEY_A]: dposition[0] -= dt * move_speed if key_state[glfw.KEY_D]: dposition[0] += dt * move_speed if key_state[glfw.KEY_Q]: dposition[1] += dt * move_speed if key_state[glfw.KEY_Z]: dposition[1] -= dt * move_speed theta = 0.0 if key_state[glfw.KEY_LEFT]: theta -= dt * turn_speed if key_state[glfw.KEY_RIGHT]: theta += dt * turn_speed if theta: rotation[0,0] = np.cos(theta) rotation[2,2] = rotation[0,0] rotation[0,2] = np.sin(theta) rotation[2,0] = -rotation[0,2] camera_rotation[...] = rotation.dot(camera_world_matrix[:3,:3]) if dposition.any(): camera_position[:] += camera_rotation.T.dot(dposition)
Unfortunately PyOpenGL doesn't always handle error cases well. """) version = 3,2 glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, version[0]) glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, version[1]) glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, 0) glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.CreateWindow(640, 480, 'Hello World') if not window: glfw.Terminate() print('Failed to create window') exit() glfw.MakeContextCurrent(window) print('GL:',GL.glGetString(GL.GL_VERSION)) print('GLFW3:',glfw.GetVersionString()) for iteration in range(100): if glfw.WindowShouldClose(window): break GL.glClearColor(0.2, 0.2, 0.2, 1.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) glfw.SwapBuffers(window) glfw.PollEvents() glfw.DestroyWindow(window) glfw.Terminate()
def show(game, title='poolvr.py *** GLViewer', window_size=(800, 600), gl_clear_color=(0.24, 0.18, 0.08, 0.0), before_frame_cb=None, after_frame_cb=None, double_buffered=True, playback_rate=1.0, screenshots_dir='', use_billboards=False): if not glfw.Init(): raise Exception('failed to initialize glfw') if not double_buffered: glfw.WindowHint(glfw.DOUBLEBUFFER, False) glfw.SwapInterval(0) window = glfw.CreateWindow(window_size[0], window_size[1], title) if not window: raise Exception('failed to create glfw window') glfw.MakeContextCurrent(window) _logger.info('GL_VERSION: %s', gl.glGetString(gl.GL_VERSION)) renderer = OpenGLRenderer(window_size=window_size, znear=0.1, zfar=1000) def on_resize(window, width, height): gl.glViewport(0, 0, width, height) renderer.window_size = (width, height) renderer.update_projection_matrix() glfw.SetWindowSizeCallback(window, on_resize) table = game.table physics = game.physics ball_meshes = table.setup_balls(game.ball_radius, game.ball_colors[:9], game.ball_positions, striped_balls=set(range(9, game.num_balls)), use_bb_particles=use_billboards) ball_shadow_meshes = [mesh.shadow_mesh for mesh in ball_meshes] camera_world_matrix = renderer.camera_matrix camera_position = camera_world_matrix[3, :3] camera_position[1] = table.height + 0.19 camera_position[2] = 0.183 * table.length cue = PoolCue() cue.position[1] = table.height + 0.1 process_keyboard_input = init_keyboard(window) meshes = [table.mesh, floor_mesh, skybox_mesh] + ball_meshes #+ [cue] for mesh in meshes: mesh.init_gl(force=True) ball_positions = game.ball_positions ball_quaternions = game.ball_quaternions ball_mesh_positions = [mesh.world_matrix[3, :3] for mesh in ball_meshes] ball_mesh_rotations = [mesh.world_matrix[:3, :3].T for mesh in ball_meshes] ball_shadow_mesh_positions = [ mesh.world_matrix[3, :3] for mesh in ball_shadow_meshes ] gl.glViewport(0, 0, window_size[0], window_size[1]) gl.glClearColor(*gl_clear_color) gl.glEnable(gl.GL_DEPTH_TEST) _logger.info('entering render loop...') stdout.flush() nframes = 0 max_frame_time = 0.0 lt = glfw.GetTime() t0 = physics.events[0].t t1 = physics.events[-1].t + min(2.0, physics.events[-1].T) pt = t0 while not glfw.WindowShouldClose(window) and pt <= t1: t = glfw.GetTime() dt = t - lt lt = t glfw.PollEvents() process_keyboard_input(dt, camera_world_matrix, cue=cue) renderer.process_input() with renderer.render(meshes=meshes) as frame_data: camera_position = frame_data.get('camera_position', renderer.camera_position) physics.eval_positions(pt, out=ball_positions) physics.eval_quaternions(pt, out=ball_quaternions) ball_positions[ ~physics. on_table] = camera_position # hacky way to only show balls that are on table for i, pos in enumerate(ball_positions): ball_mesh_positions[i][:] = pos ball_shadow_mesh_positions[i][0::2] = pos[0::2] for i, quat in enumerate(ball_quaternions): set_matrix_from_quaternion(quat, ball_mesh_rotations[i]) physics.step(dt) max_frame_time = max(max_frame_time, dt) if nframes == 0: st = glfw.GetTime() nframes += 1 pt += dt * playback_rate glfw.SwapBuffers(window) _logger.info( '...exited render loop: average FPS: %f, maximum frame time: %f', (nframes - 1) / (t - st), max_frame_time) mWidth, mHeight = glfw.GetWindowSize(window) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1) pixels = gl.glReadPixels(0, 0, mWidth, mHeight, gl.GL_RGB, gl.GL_UNSIGNED_BYTE) pil_image = PIL.Image.frombytes('RGB', (mWidth, mHeight), pixels) pil_image = pil_image.transpose(PIL.Image.FLIP_TOP_BOTTOM) filename = title.replace(' ', '_') + '-screenshot.png' filepath = os.path.join(screenshots_dir, filename) pil_image.save(filepath) _logger.info('..saved screen capture to "%s"', filepath) try: renderer.shutdown() _logger.info('...shut down renderer') except Exception as err: _logger.error(err) glfw.DestroyWindow(window) glfw.Terminate()
def process_input(dt): glfw.PollEvents() process_keyboard_input(dt, camera_world_matrix) process_mouse_input(dt, cue)
def poll_events(self): glfw.PollEvents()