def render(self): """ The render pass for the scene """ self.init_view() # Enable lighting and color glEnable(GL_LIGHTING) glClearColor(0.4, 0.4, 0.4, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Load the modelview matrix from the current state of the trackball glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() loc = self.interaction.translation glTranslated(-loc[0], -loc[1], -loc[2]) glMultMatrixf(self.interaction.trackball.matrix) # store the inverse of the current modelview. currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) # render the scene. This will call the render function for each object in the scene self.scene.render() # draw the grid glDisable(GL_LIGHTING) glCallList(G_OBJ_PLANE) glPopMatrix() # flush the buffers so that the scene can be drawn glFlush()
def paintGL(self): self.updateCamera() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.drawSky() self.drawGround() self.drawGrid() #self.drawCube() drawn_groundings = set() for g in self._selected_groundings: if not g in drawn_groundings: self.drawGrounding(g, color="yellow") drawn_groundings.add(g) for color, groundings in self._highlighted_groundings.iteritems(): for g in groundings: if not g in drawn_groundings: self.drawGrounding(g, color=color) drawn_groundings.add(g) for g in self._context.groundings: if not g in drawn_groundings and self.groundingFilter(g): self.drawGrounding(g, color="blue") drawn_groundings.add(g) self.drawActivePlace()
def paintGL(self): #This function uses shape objects, such as cube() or meshSector(). Shape objects require the following: #a list named 'vertices' - This list is a list of points, from which edges and faces are drawn. #a list named 'wires' - This list is a list of tuples which refer to vertices, dictating where to draw wires. #a list named 'facets' - This list is a list of tuples which refer to vertices, ditating where to draw facets. #a bool named 'render' - This bool is used to dictate whether or not to draw the shape. #a bool named 'drawWires' - This bool is used to dictate whether wires should be drawn. #a bool named 'drawFaces' - This bool is used to dictate whether facets should be drawn. glLoadIdentity() gluPerspective(45, self.width / self.height, 0.1, 110.0) #set perspective? glTranslatef(0, 0, self.zoomLevel) #I used -10 instead of -2 in the PyGame version. glRotatef(self.rotateDegreeV, 1, 0, 0) #I used 2 instead of 1 in the PyGame version. glRotatef(self.rotateDegreeH, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) if len(self.shapes) != 0: glBegin(GL_LINES) for s in self.shapes: glColor3fv(s.color) if s.render and s.drawWires: for w in s.wires: for v in w: glVertex3fv(s.vertices[v]) glEnd() glBegin(GL_QUADS) for s in self.shapes: glColor3fv(s.color) if s.render and s.drawFaces: for f in s.facets: for v in f: glVertex3fv(s.vertices[v]) glEnd()
def event_loop_window(terrain): """ Catches events """ running = True frames = 0 fps_start_time = time() water_start_time = time() water_mode_func = water_reset while running: for event in pygame.event.get(): running = _quit_control(event) water_mode_func = _water_control(terrain, water_mode_func, event) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) draw_terrain_3d(terrain) draw_water_3d(terrain) time_passed = (time() - water_start_time) water_mode_func(terrain, time_passed) water_start_time = time() time_passed = (time() - fps_start_time) if (time_passed >= 1): fps = frames // time_passed pygame.display.set_caption("{0} - FPS: {1}".format(NAME, str(fps))) fps_start_time = time() frames = 0 pygame.display.flip() frames += 1
def render_all_shapes(self): glClear(GL_COLOR_BUFFER_BIT) #Update our game grid before we draw self.grid_instance.updateGrid() for _, s in self.grid_instance.active_grid_elements.iteritems(): s.draw() glutSwapBuffers()
def display(self): """ Callback function, handler for window re-paint """ # Set background color (clear background) glClearColor( self.background_color[0], self.background_color[1], self.background_color[2], 1.0, ) glClear(GL_COLOR_BUFFER_BIT) # Display background for shape in self.background.shapes: self.draw_geometric2d(shape) # Display objects if len(self.data) > 0: idx = self.time_count % len(self.data) for shape in self.data[idx].shapes: self.draw_geometric2d(shape) self.time_count += 1 glFlush()
def paintGL(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glTranslatef(0., 0., -4. / min(self.aspect, 0.7)) glRotatef(self.yRotDeg, 0., 1., 0.) glRotatef(self.xRotDeg, 1., 0., 0.) if self.shape == 'cuboid': self.paintCuboid(self.sample_width, self.sample_thickness, self.sample_height, rotate=45.) elif self.shape == 'cylinder': self.paintCylinder(self.sample_diameter, self.sample_height) elif self.shape == 'sphere': self.paintSphere(self.sample_diameter) else: self.sample_width = self.sample_thickness = 70 self.sample_height = 100 self.paintCuboid(self.sample_width, self.sample_thickness, self.sample_height) self.paintArrow('x', [0, 0, 1]) self.paintArrow('y', [1, 0, 0]) self.paintArrow('z', [0, 1, 0]) self.paintArrow('n', [0, 0, 0]) self.paintArrow('gamma', [1, 0, 1]) self.paintCells()
def on_draw(self): """Redraw window.""" self.set_3d() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # rotate camera glRotatef(self.camera.v_angle_deg(), 1.0, 0, 0) glRotatef(self.camera.h_angle_deg(), 0.0, 1.0, 0) glTranslatef( -self.camera.x_pos, -self.camera.y_pos, self.camera.z_pos) if self.rendering_type == "fill": self.use_shader("test") elif self.rendering_type == "lines": self.use_shader("lines") self.renderer.render() # draw HUD self.set_2d() self.draw_hud()
def _on_draw(self, evt): self.canvas.renderer.start_draw() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.renderer.draw_sky_box() glClear(GL_DEPTH_BUFFER_BIT) self.canvas.renderer.draw_level() self.canvas.renderer.end_draw()
def render(self): #初始化投影矩阵 self.init_view() #启动光照 glEnable(GL_LIGHTING) #清空颜色缓存与深度缓存 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #设置模型视图矩阵,这节课先用单位矩阵就行了。 glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMultMatrixf(self.interaction.trackball.matrix) # 存储ModelView矩阵与其逆矩阵之后做坐标系转换用 currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) #渲染场景 self.scene.render() #每次渲染后复位光照状态 glDisable(GL_LIGHTING) glCallList(G_OBJ_PLANE) glPopMatrix() #把数据刷新到显存上 glFlush()
def stencilPush(): '''Create a new stack in stencil stack. All the next draw will be done in stencil buffer until stencilUse() will be called.''' global __stencil_stack glPushAttrib(GL_STENCIL_BUFFER_BIT | GL_STENCIL_TEST) # enable stencil test if not yet enabled if not glIsEnabled(GL_STENCIL_TEST): glClearStencil(0) glClear(GL_STENCIL_BUFFER_BIT) glEnable(GL_STENCIL_TEST) # increment the draw buffer glStencilFunc(GL_NEVER, 0x0, 0x0) glStencilOp(GL_INCR, GL_INCR, GL_INCR) glColorMask(0, 0, 0, 0) # save model view m = glGetFloatv(GL_MODELVIEW_MATRIX) __stencil_stack_view.append(m) # start recording GL operation dl = GlDisplayList() dl.start() __stencil_stack_dl.append(dl) __stencil_stack += 1
def main(): pygame.init() display = (800, 600) # pygame.display.set_mode(display, pygame.DOUBLEBUFFER) screen = pygame.display.set_mode(display) gluPerspective(45, display[0] / display[1], 0.001, 1000.0) glTranslatef(0.0, 0.0, -5.0) glRotatef(0, 0, 0, 0) print('before loop') done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10) print('after loop')
def render(self): #init shadow matrix self.init_view() #open light glEnable(GL_LIGHTING) #clear color and depth caches glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #set model view matrix(danwei matrix is ok) #set trackball's rotate matrix as Modelview glMatrixMode(GL_MODELVIEW) glPushMatrix() #replace now-matrix with hengdeng matrix glLoadIdentity() glMultMatrixf(self.interaction.trackball.matrix) #save Modelview matrix, later change system with anti-matrix currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) #rend the scene self.scene.render() #after each shadow , huifu light state glDisable(GL_LIGHTING) glPopMatrix() glFlush()
def render(self): self.clock.record_frame_time() if self.is_recording and not self.timer.is_snoozed: self.frame_index += 1 frame_name = "Frame_{0:05d}.jpg".format(self.frame_index) self.save_screenshot(frame_name) self.timer.snooze() glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if camera.is_rotating: camera.rotate_z(0.2) camera.look() self.draw_detector() glEnable(GL_DEPTH_TEST) glEnable(GL_LINE_SMOOTH) glShadeModel(GL_FLAT) glEnable(GL_LIGHTING) for obj in self.shaded_objects: obj.draw(self.clock.time, self.spectrum) glDisable(GL_LIGHTING) for obj in self.objects: obj.draw(self.clock.time) self.draw_gui() glutSwapBuffers()
def _render(self) -> None: """ Render the whole scene here. Note that, this is a private function and should not be overriden unless you really know what you are dealing with. """ # Disable Depth Test to draw background at the very back of the scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # type: ignore self.background.render() glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) proj, view = self.active_observer.render() self.grid.render(proj, view, self.lights) self._render_lock = True for object in self.objects: self.objects[object].render(proj, view, self.lights) for object in self.huds: self.huds[object].render(proj, view, self.lights) self._render_lock = False for test in self._collision_detectors: test.check() self.__fps_counter += 1 if self.__timer == -1: self.__timer = time.time() diff = time.time() - self.__timer if diff > 1: self.__timer = time.time() self.fps = self.__fps_counter self.__fps_counter = 0
def paintGL(self): if self.crashFlag: #run cleanup operations glUseProgram(0) glDisableVertexAttribArray(self.attrID) glDeleteBuffers(1,[self.vertexBuffer]) glDeleteVertexArrays(1, [self.vertexArrayID]) glLoadIdentity() gluPerspective(45, self.sizeX / self.sizeY, 0.1, 110.0) #set perspective glTranslatef(0, 0, self.zoomLevel) glRotatef(self.rotateDegreeV + self.vOffset, 1, 0, 0) glRotatef(self.rotateDegreeH, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) self.vertexData = [ -1, 1, 0, 0, -1, 0, 1, 1, 0 ] arrayType = GLfloat * len(self.vertexData) target = GL_ARRAY_BUFFER offset = 0 size = len(self.vertexData) * ctypes.sizeof(ctypes.c_float) data = arrayType(*self.vertexData) glBufferSubData(target, offset, size, data) glDrawArrays(GL_TRIANGLES, 0, 3)
def paintGL(self): glLoadIdentity() gluPerspective(45, self.width / self.height, 0.1, 110.0) #set perspective? glTranslatef( 0, 0, self.zoomLevel) #I used -10 instead of -2 in the PyGame version. glRotatef(self.rotateDegreeV, 1, 0, 0) #I used 2 instead of 1 in the PyGame version. glRotatef(self.rotateDegreeH, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if len(self.shapes) != 0: glBegin(GL_LINES) for s in self.shapes: glColor3fv(s.color) if s.render and s.drawWires: for e in s.edges: for v in e: glVertex3fv(s.vertices[v]) glEnd() glBegin(GL_QUADS) for s in self.shapes: glColor3fv(s.color) if s.render and s.drawFaces: for f in s.facets: for v in f: glVertex3fv(s.vertices[v]) glEnd()
def draw(self): """ Render interpreter display buffer to the game screen. :return: None. :rtype: None """ if self.cpu.frame_ready: for index, value in enumerate(reversed(self.display.ravel())): r = index * 3 g = r + 1 b = r + 2 pixel_color = self._pixel_color(value) self.temp_display[r] = pixel_color self.temp_display[g] = pixel_color self.temp_display[b] = pixel_color glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glDrawPixels(*(self.display_width, self.display_height), GL_RGB, GL_UNSIGNED_BYTE, self.temp_display) # Update display. pygame.display.flip() self.cpu.frame_ready = False
def draw(self): t1 = time.time() glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) glLoadIdentity () horizonY = 1 * 2.2 - .6 + .5 GLU.gluLookAt(self.eyeX.x, horizonY, 8.0, self.lookX.x, horizonY, 0.0, 0.0, 1.0, 0.0) glEnable(GL.GL_TEXTURE_2D) if 0: with pushMatrix(): glColor3f(1,0,0) glTranslatef(*self.ball) glScalef(.2, .2, 1) imageCard("sample.jpg") with pushMatrix(): with mode(disable=[GL.GL_LIGHTING]): for card in self.cards: card.draw(self.eyeX.x, horizonY, self.cardList) glFlush() pygame.display.flip()
def prepare_for_rendering(self, projector: Projector, camera: Camera, lights: List[Light]): """Selects the window, clears buffers, and sets up the scene transform and lighting state. :param projector: The projector configuration to use for this rendering pass. :param camera: The camera object to use for this rendering pass. :param lights: The light list to use for this rendering pass. """ glutSetWindow(self._gl_window) # Clear the screen and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Apply our projection so the window is ready to render in perspective projector.apply(self) # Add scene lights light_count = len(lights) for i in range(light_count): lights[i].apply(i) # Set scale from mm to cm glScalef(0.1, 0.1, 0.1) # Orient the camera camera.apply()
def render(self): "Override for custom drawing." # Clear the screen buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for shader in self.shaders: with shader.rendering(): # Set view and perspective glUniformMatrix4fv(shader.uniforms['view'][0], 1, GL_FALSE, np.array(self.view.matrix)) glUniformMatrix4fv(shader.uniforms['projection'][0], 1, GL_FALSE, np.array(self.projection)) glUniform1f(shader.uniforms['light_ambient_weight'][0], self.ambient_light) glUniform3f(shader.uniforms['light_ambient_color'][0], *self.ambient_light_color) glUniform3f(shader.uniforms['light_pos'][0], *(2., 2., 2.)) glUniform3f(shader.uniforms['light_color'][0], *(1, 1, 1)) glUniform1f(shader.uniforms['light_glare'][0], 32.) # Draw models with shader for mdl, vao in shader._models_and_VAOs: # Set the model's transform matrix uniform vbo, mode = mdl.render_data glUniformMatrix4fv(shader.uniforms['model'][0], 1, GL_FALSE, np.array(mdl.model_matrix)) vao.bind() vbo.bind() glDrawArrays(mode, 0, len(vbo)) self.flaggo = False # TODO Apply postprocessing filters # Put it on the screen. pygame.display.flip()
def drawBackgroundGL(self, painter, rect): painter.beginNativePainting() #This will clear the screen, but also introduce flickering glClearColor(0.0, 1.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); #update the textures of those patches that were updated for t in self._updatableTiles: patch = self.imagePatches[t][self._numLayers] if patch.texture > -1: self._glWidget.deleteTexture(patch.texture) patch.texture = self._glWidget.bindTexture(patch.image) #see 'backingstore' example by Ariya Hidayat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) #this ensures a seamless transition between tiles glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) self._updatableTiles = [] drawnTiles = 0 for patches in self.imagePatches: patch = patches[self._numLayers] if not patch.rectF.intersect(rect): continue patch.drawTexture() drawnTiles +=1 #print "ImageView2D.drawBackgroundGL: drew %d of %d tiles" % (drawnTiles, len(self.imagePatches)) painter.endNativePainting()
def InitGL(self, Width, Height): self.view_port_xr = 1 self.view_port_yr = 1 self.original_x = Width self.original_y = Height glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glOrtho(0, Width, 0, Height, -1, 1) glScalef(1, -1, 1) glTranslatef(0, -Height, 0) glMatrixMode(GL_MODELVIEW) glDisable(GL_DEPTH_TEST) # Disables Depth Testing glShadeModel(GL_SMOOTH) # Enables Smooth Color Shading # Anti-aliasing/prettyness stuff glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glHint(GL_POINT_SMOOTH_HINT, GL_NICEST) glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) glEnable(GL_LINE_SMOOTH) glEnable(GL_POINT_SMOOTH) glEnable(GL_POLYGON_SMOOTH) glClearColor(background_color()[0], background_color()[1], background_color()[2], 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
def Display(self): """ A default display. Which clears the color buffer and depth buffer. """ self._debug("running display", 4) glClearColor(1.0, 1.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
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 draw(self): t1 = time.time() glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) glLoadIdentity() horizonY = 1 * 2.2 - .6 + .5 GLU.gluLookAt(self.eyeX.x, horizonY, 8.0, self.lookX.x, horizonY, 0.0, 0.0, 1.0, 0.0) glEnable(GL.GL_TEXTURE_2D) if 0: with pushMatrix(): glColor3f(1, 0, 0) glTranslatef(*self.ball) glScalef(.2, .2, 1) imageCard("sample.jpg") with pushMatrix(): with mode(disable=[GL.GL_LIGHTING]): for card in self.cards: card.draw(self.eyeX.x, horizonY, self.cardList) glFlush() pygame.display.flip()
def _render_loading_message(self, msg): # Render loading screen glClearColor(0.,0.,0.,1.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_ACCUM_BUFFER_BIT|GL_STENCIL_BUFFER_BIT) loading = Text(150) loading.draw(-(600/self._width),-0.05,"Loading {0}...".format(msg),(0,255,0,1)) pygame.display.flip()
def Display(self): """ A default display. Which clears the color buffer and depth buffer. """ self._debug("running display", 4) glClearColor(1.0, 1.0, 1.0, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
def render_figure(self): glClear(GL_COLOR_BUFFER_BIT) for figure in self.list_of_figures_to_draw: figure.draw_me() glFlush()
def render(self): """Render frame. First runs through a picking pass, clears the buffer, and then calls all rendering sub-methods. """ # ensure that canvas is current and initialized if not self._is_shown_on_screen() or not self._set_current(): return # ensure that opengl is initialized if not self.init_opengl(): return canvas_size = self.get_canvas_size() glViewport(0, 0, canvas_size.width, canvas_size.height) # run picking pass self._picking_pass() # reset viewport as _picking_pass tends to mess with it glViewport(0, 0, canvas_size.width, canvas_size.height) # clear buffers and render everything normally self._render_background() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self._render_chamber() self._render_actions_and_cameras() self._render_objects() self._render_viewcube() self._canvas.SwapBuffers()
def activateOpenGL( self, qglwidget ): self._useGL = True self._glWidget = qglwidget glDisable(GL_DEPTH_TEST) glEnable(GL_TEXTURE_2D) glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT)
def paintGL(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glTranslated(0.0, 0.0, -10.0) glRotated(self.xRot / 16.0, 1.0, 0.0, 0.0) glRotated(self.yRot / 16.0, 0.0, 1.0, 0.0) glRotated(self.zRot / 16.0, 0.0, 0.0, 1.0) glCallList(self.object)
def clear_color(color=None): if color: if len(color) == 3: color.append( 1.0) # default alpha. could handle color neater! -> abstract! glClearColor(*color) # TODO: handle color better (validate etc.) glClear(GL_COLOR_BUFFER_BIT)
def default_draw(self): """The default draw logic.""" self.start_draw() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.draw_sky_box() glClear(GL_DEPTH_BUFFER_BIT) self.draw_level() self.end_draw()
def gl_init(self): drawable = self.gl_begin() w, h = self.size debug("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self, w, h, drawable) if not drawable: return None if not self.debug_setup: self.debug_setup = True self.gl_init_debug() if not self.gl_setup: self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) # Could be more optimal to use vertex arrays: # glEnableClientState(GL_VERTEX_ARRAY) # glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear background to transparent black glClearColor(0.0, 0.0, 0.0, 0.0) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO if self.textures is None: self.gl_init_textures() # Define empty FBO texture and set rendering to FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.gl_init_shaders() # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) self.gl_setup = True return drawable
def gl_init(self): drawable = self.gl_begin() w, h = self.size debug("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable) if not drawable: return None if not self.gl_setup: # Ask GL to send us all debug messages if GL_DEBUG_OUTPUT and gl_debug_callback and glInitDebugKHR() == True: glEnable(GL_DEBUG_OUTPUT) glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS) glDebugMessageCallback(gl_debug_callback, None) glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, None, GL_TRUE) # Initialize string_marker GL debugging extension if available if glInitStringMarkerGREMEDY and glInitStringMarkerGREMEDY() == True: log.info("Extension GL_GREMEDY_string_marker available. Will output detailed information about each frame.") else: # General case - running without debugger, extension not available glStringMarkerGREMEDY = None # Initialize frame_terminator GL debugging extension if available if glInitFrameTerminatorGREMEDY and glInitFrameTerminatorGREMEDY() == True: glFrameTerminatorGREMEDY = None self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) #TODO glEnableClientState(GL_VERTEX_ARRAY) #TODO glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear to white glClearColor(1.0, 1.0, 1.0, 1.0) # Default state is good for YUV painting: # - fragment program enabled # - render to offscreen FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(5) debug("textures for wid=%s of size %s : %s", self.wid, self.size, self.textures) if self.offscreen_fbo is None: self.offscreen_fbo = glGenFramebuffers(1) # Define empty FBO texture and set rendering to FBO glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) self.gl_setup = True return drawable
def clear_fbo(): try: glClear(GL_COLOR_BUFFER_BIT) except Exception as e: log("glClear error", exc_info=True) log.warn("Warning: failed to clear FBO") log.warn(" %r", e) if getattr(e, "err", None)==1286: raise Exception("OpenGL error '%r' likely caused by buggy drivers" % e)
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 prepare(self) -> None: """ Clears the screen before rendering the next frame. """ glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glDisable(GL_BLEND) # glEnable(GL_DEPTH_TEST) glDepthFunc(GL_NEVER)
def gl_init(self): drawable = self.gl_begin() w, h = self.size log("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self, w, h, drawable) if not drawable: return None if not self.debug_setup: self.debug_setup = True self.gl_init_debug() if not self.gl_setup: self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) # Could be more optimal to use vertex arrays: # glEnableClientState(GL_VERTEX_ARRAY) # glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear background to transparent black glClearColor(0.0, 0.0, 0.0, 0.0) # we don't use the depth (2D only): glDisable(GL_DEPTH_TEST) # only do alpha blending in present_fbo: glDisable(GL_BLEND) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO if self.textures is None: self.gl_init_textures() # Define empty FBO texture and set rendering to FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.gl_init_shaders() # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) self.gl_setup = True return drawable
def gl_init(self): #must be called within a context! #performs init if needed if not self.debug_setup: self.debug_setup = True self.gl_init_debug() if not self.gl_setup: w, h = self.size self.gl_marker("Initializing GL context for window size %d x %d", w, h) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) # Mesa docs claim: this hint can improve the speed of texturing #when perspective-correct texture coordinate interpolation isn't needed, #such as when using a glOrtho() projection: glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST) # Could be more optimal to use vertex arrays: # glEnableClientState(GL_VERTEX_ARRAY) # glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear background to transparent black glClearColor(0.0, 0.0, 0.0, 0.0) # we don't use the depth (2D only): glDisable(GL_DEPTH_TEST) # only do alpha blending in present_fbo: glDisable(GL_BLEND) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO if self.textures is None: self.gl_init_textures() # Define empty FBO texture and set rendering to FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.gl_init_shaders() # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) self.gl_setup = True
def render(objects): glPushMatrix() for o in objects: glPushMatrix() o.render() glPopMatrix() glPopMatrix() pygame.display.flip() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
def render(self): glClear(GL_COLOR_BUFFER_BIT) glBegin(GL_TRIANGLES) glColor3f(1.0, 0.0, 0.0) glVertex2i(0, 1) glColor3f(0.0, 1.0, 0.0) glVertex2i(-1, -1) glColor3f(0.0, 0.0, 1.0) glVertex2i(1, -1) glEnd()
def iniciar_renderizado(self): """Acciones posteriores al renderizado de objetos.""" self.fbos[0].usar() #glClearColor(*self.capa.escena.color)#0.) para fondo transparente glClear(GL_COLOR_BUFFER_BIT) #| GL_DEPTH_BUFFER_BIT) # Transformación de la cámara glLoadIdentity() glScalef(self.acerc, self.acerc, 0.) glTranslatef(-self.pos.x, -self.pos.y, 0.) glRotatef(-self.angulo, 0., 0., 1.)
def _draw(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glClearColor(0.0, 0.0, 0.0, 1.0) view_mat = translation_matrix((0, 0, -self.dist)) view_mat = view_mat.dot(self.ball.matrix()) view_mat = view_mat.dot(scale_matrix(self.zoom)) self.VMatrix = view_mat self.draw_hook() OpenGL.GLUT.glutSwapBuffers()
def draw_gui(self): logo = self.logo logo_bytes = self.logo_bytes menubar_height = logo.size[1] + 4 width = glutGet(GLUT_WINDOW_WIDTH) height = glutGet(GLUT_WINDOW_HEIGHT) glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glOrtho(0.0, width, height, 0.0, -1.0, 10.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() #glDisable(GL_CULL_FACE) glShadeModel(GL_SMOOTH) glClear(GL_DEPTH_BUFFER_BIT) # Top bar #glBegin(GL_QUADS) #glColor3f(0.14, 0.49, 0.87) #glVertex2f(0, 0) #glVertex2f(width - logo.size[0] - 10, 0) #glVertex2f(width - logo.size[0] - 10, menubar_height) #glVertex2f(0, menubar_height) #glEnd() try: self.draw_colour_legend() except TypeError: pass glPushMatrix() glLoadIdentity() glRasterPos(4, logo.size[1] + 4) glDrawPixels(logo.size[0], logo.size[1], GL_RGB, GL_UNSIGNED_BYTE, logo_bytes) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) self.colourist.now_text() #draw_text_2d("{0}ns".format(int(self.min_hit_time)), width - 80, 20) #draw_text_2d("{0}ns".format(int(self.max_hit_time)), width - 80, height - menubar_height - 10) #draw_text_2d("{0}ns".format(int((self.min_hit_time + self.max_hit_time) / 2)), width - 80, int(height/2)) if self.show_help: self.display_help() if self.show_info: self.display_info()
def __generate_model(self): """Generate rotated model with shadows.""" glEnable(GL_CULL_FACE) self.__sh.change_shader(vertex=0, fragment=0) self.__prepare_shaders(self.__model_matrix, self.__light_matrix, False) self.__sh.bind_buffer() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glDrawElements(GL_TRIANGLES, View.__triangles.size, GL_UNSIGNED_SHORT, View.__triangles) self.__sh.clear()
def draw_all(self): glViewport(0, 0, *self.fb_size) self.update_vector_uniform('fb_size', self.fb_size) glClearColor(*self.clear_color.as_tuple()) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) for comm in self._draw_commands.values(): self._draw_one(comm)
def change_background_color(self): background_color = self.params['background_color'] try: self.glview.setBackgroundColor(background_color) except: #~ #FIXME this is buggy in pyqtgrap0.9.8 bgcolor = pg.mkColor(QtGui.QColor(background_color)) glClearColor(bgcolor.red()/255., bgcolor.green()/255., bgcolor.blue()/255., 1.0) glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ) self.glview.paintGL() self.glview.update()
def main(path=None): glutInit(sys.argv) if sys.platform == 'darwin': if not path: path = dialog() if not path: sys.exit(0) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE) glutInitWindowPosition(0, 0) glutInitWindowSize(730, 650) win = glutCreateWindow(b'MIDI Player') (width, height, img) = read_image('mixer.ppm') glPixelStorei(GL_UNPACK_ALIGNMENT, 1) rbo = c_uint(int(glGenRenderbuffersEXT(1))) glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, rbo) glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGB, width, height) fbo = c_uint(int(glGenFramebuffersEXT(1))) glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, fbo) glFramebufferRenderbufferEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, rbo) glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fbo) glClear(GL_COLOR_BUFFER_BIT) glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, img) glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0) player = Player(win, path, width, height) glutDisplayFunc(player.display_func) glutKeyboardFunc(player.keyboard_func) glutMouseFunc(player.mouse_func) glutMotionFunc(player.motion_func) glutIdleFunc(player.process_events) submenus = [] for instrument in range(128): if instrument % 8 == 0: submenus.append([families[instrument // 8], glutCreateMenu(player.change_instrument)]) glutAddMenuEntry(instruments[instrument].encode('ascii'), instrument) glutCreateMenu(player.change_instrument) for family, submenu in submenus: glutAddSubMenu(family.encode('ascii'), submenu) glutAttachMenu(GLUT_RIGHT_BUTTON) glutMainLoop()
def _drawShadowMap(map): # make the current depth map a rendering target glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, self.texture.glID, 0, map.textureLayer) # clear the depth texture from last time glClear(GL_DEPTH_BUFFER_BIT) map.drawShadowMap()
def DrawGLScene(): modelview_matrix, projection_matrix = update_world_matrices() contexts["world"]["modelview"]["matrix"] = modelview_matrix contexts["world"]["projection"]["matrix"] = projection_matrix glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear The Screen And The Depth Buffer one = time() render_with_context(contexts["world"]) render_with_context(contexts["interface"]) two = time() glutSwapBuffers() three = time()
def paintGL(self): if self.parent.ipcon == None: return glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Move Right And Into The Screen glLoadIdentity() glTranslatef(0.0, 0.0, -5.0) glMultMatrixf(self.m) glCallList(self.display_list)
def init_opengl(self, width, height, x, y): glutInit() glutInitWindowPosition(x, y) glutInitWindowSize(width, height) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE) glutCreateWindow("Rainbow Alga") glutDisplayFunc(self.render) glutIdleFunc(self.render) glutReshapeFunc(self.resize) glutMouseFunc(self.mouse) glutMotionFunc(self.drag) glutKeyboardFunc(self.keyboard) glutSpecialFunc(self.special_keyboard) glClearDepth(1.0) glClearColor(0.0, 0.0, 0.0, 0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 3000) glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) # Lighting light_ambient = (0.0, 0.0, 0.0, 1.0) light_diffuse = (1.0, 1.0, 1.0, 1.0) light_specular = (1.0, 1.0, 1.0, 1.0) light_position = (-100.0, 100.0, 100.0, 0.0) mat_ambient = (0.7, 0.7, 0.7, 1.0) mat_diffuse = (0.8, 0.8, 0.8, 1.0) mat_specular = (1.0, 1.0, 1.0, 1.0) high_shininess = (100) glEnable(GL_LIGHT0) glEnable(GL_NORMALIZE) glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient) glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse) glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular) glLightfv(GL_LIGHT0, GL_POSITION, light_position) glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient) glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse) glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular) glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess) # Transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
def draw_triangle(): #print "Draw Triangle" glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) #return ### glBegin(GL_TRIANGLES) glColor3f(1.0, 0.0, 0.0) glVertex2i(0, 1) glColor3f(0.0, 1.0, 0.0) glVertex2i(-1, -1) glColor3f(0.0, 0.0, 1.0) glVertex2i(1, -1) glEnd()
def clear(self): """Clear framebuffer. .. warning:: Must be called inside bind()/release() of FBO ! """ assert self._is_bind == True glClearColor(*self.clear_color) if self.with_depthbuffer: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) else: glClear(GL_COLOR_BUFFER_BIT)
def main(): window = initWindow() classicProgram, normalMapProgram, skyboxProgram, asteroidProgram = initShaders() glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) # Initialize objects planets, spaceship, skybox, belt = initObjects(classicProgram, normalMapProgram, skyboxProgram, asteroidProgram) projMatrix = mat4.perspective_projection(60, float(WIDTH/HEIGHT), 0.1, 10000.0, dtype='f') eye, viewMatrix = initCamera() dt, oldTime = 0.0, glfw.GetTime() animation_speed = 800 while not glfw.WindowShouldClose(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) currentTime = glfw.GetTime() dt = currentTime - oldTime oldTime = currentTime hAngle, vAngle, eye, direction, right, up, viewMatrix, animation_speed = getNewViewMatrixAndEye(window, animation_speed, dt, eye, WIDTH, HEIGHT) for planet in planets: planet.update(animation_speed) planet.draw(eye, viewMatrix, projMatrix) spaceship.update(eye, direction, right, up, hAngle, vAngle) spaceship.draw(eye, viewMatrix, projMatrix) belt.update(0.1) belt.draw(eye, viewMatrix, projMatrix) skybox.draw(viewMatrix, projMatrix) # Swap front and back buffers glfw.SwapBuffers(window) # Poll for and process events glfw.PollEvents() glfw.Terminate()
def present_fbo(self, drawable): self.gl_marker("Presenting FBO on screen for drawable %s" % drawable) assert drawable # Change state to target screen instead of our FBO glBindFramebuffer(GL_FRAMEBUFFER, 0) if self._has_alpha: # transparent background: glClearColor(0.0, 0.0, 0.0, 0.0) else: # plain white no alpha: glClearColor(1.0, 1.0, 1.0, 1.0) # Draw FBO texture on screen self.set_rgb_paint_state() glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) if self._has_alpha: # support alpha channel if present: glEnable(GL_BLEND) glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD) glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO) w, h = self.size glBegin(GL_QUADS) glTexCoord2i(0, h) glVertex2i(0, 0) glTexCoord2i(0, 0) glVertex2i(0, h) glTexCoord2i(w, 0) glVertex2i(w, h) glTexCoord2i(w, h) glVertex2i(w, 0) glEnd() # Show the backbuffer on screen if drawable.is_double_buffered(): debug("%s.present_fbo() swapping buffers now", self) drawable.swap_buffers() # Clear the new backbuffer to illustrate that its contents are undefined glClear(GL_COLOR_BUFFER_BIT) else: glFlush() if self._has_alpha: glDisable(GL_BLEND) self.gl_frame_terminator() self.unset_rgb_paint_state() glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) debug("%s.present_fbo() done", self)