def drawbrick(color, center, axis, l, h, w, opacity=1.0): if len(color) == 3: color = (color[0], color[1], color[2], opacity) if opacity != 1.0: glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) apply_material(color) glPushMatrix() glTranslatef(center[0], center[1], center[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2]) * 180.0 / pi if (axis[2] * axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glScale(h, w, l) #bruce 060302 revised the contents of solidCubeList while fixing bug 1595 glCallList(drawing_globals.solidCubeList) if opacity != 1.0: glDisable(GL_BLEND) glDepthMask(GL_TRUE) glPopMatrix() return
def _init_GL(self): ''' ''' glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glEnable(GL_LINE_SMOOTH) glLineWidth(2.0) glEnable(GL_DEPTH_TEST) # glEnable(GL_TEXTURE_2D) # set the lighting self._set_lighting() # set the background color # glClearColor(0.15, 0.15, 0.15, 1) glClearDepth(1.0) # set the camera glMatrixMode(GL_PROJECTION) # glPushMatrix() glLoadIdentity() self._set_view_volume() glMatrixMode(GL_MODELVIEW) return
def draw_vertices(self): # Draw all the vbo defined in set_atoms if self.transparent: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDepthMask(GL_FALSE) if self.wireframe: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glEnableClientState(GL_VERTEX_ARRAY) self._vbo_v.bind_vertexes(3, GL_FLOAT) glEnableClientState(GL_NORMAL_ARRAY) self._vbo_n.bind_normals(GL_FLOAT) glEnableClientState(GL_COLOR_ARRAY) self._vbo_c.bind_colors(4, GL_UNSIGNED_BYTE) glDrawArrays(GL_TRIANGLES, 0, self._n_triangles) self._vbo_v.unbind() self._vbo_n.unbind() self._vbo_c.unbind() if self.transparent: glDisable(GL_BLEND) #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDepthMask(GL_TRUE) if self.wireframe: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def drawbrick(color, center, axis, l, h, w, opacity = 1.0): if len(color) == 3: color = (color[0], color[1], color[2], opacity) if opacity != 1.0: glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) apply_material(color) glPushMatrix() glTranslatef(center[0], center[1], center[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glScale(h, w, l) #bruce 060302 revised the contents of solidCubeList while fixing bug 1595 glCallList(drawing_globals.solidCubeList) if opacity != 1.0: glDisable(GL_BLEND) glDepthMask(GL_TRUE) glPopMatrix() return
def setup(self): ''' Setup the parts of the stage ''' # Ensure that transparency is enabled glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
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 drawGrid(self): grids_per_screen = 10 eye_dist = self.camera_xyz[2] meters_per_grid = round_to_125(eye_dist / grids_per_screen) num_lines = 300 glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_LINE_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_DEPTH_TEST) glPushMatrix() glTranslatef(0, 0, 0) glColor3f(0.2, 0.2, 0.2) glBegin(GL_LINES) for i in range(num_lines): glVertex2f((-num_lines / 2 + i) * meters_per_grid, -num_lines / 2 * meters_per_grid) glVertex2f((-num_lines / 2 + i) * meters_per_grid, num_lines / 2 * meters_per_grid) glVertex2f(-num_lines / 2 * meters_per_grid, (-num_lines / 2 + i) * meters_per_grid) glVertex2f(num_lines / 2 * meters_per_grid, (-num_lines / 2 + i) * meters_per_grid) glEnd() glPopMatrix() glPopAttrib()
def initializeGL(self): ''' Initialize GL ''' self.fieldtemp = [ 1.0, "GL_NEAREST", "GL_NEAREST", "GL_NEAREST_MIPMAP_NEAREST", "On" ] try: js = jsonload(path.join(SAVE_DIR, "gfx_settings.rgs")) self.fieldtemp[0] = loadFloat('gfx.anifilt', js.get('anifilt')) self.fieldtemp[1] = loadString('gfx.minfilter', js.get('minfilter')) self.fieldtemp[2] = loadString('gfx.magfilter', js.get('magfilter')) self.fieldtemp[3] = loadString('gfx.mipminfilter', js.get('mipminfilter')) self.fieldtemp[4] = loadString('gfx.FSAA', js.get('FSAA')) except: #print("no settings detected") pass #mipmap support and NPOT texture support block if not hasGLExtension("GL_ARB_framebuffer_object"): #print("GL_ARB_framebuffer_object not supported, switching to GL_GENERATE_MIPMAP") self.npot = 2 version = glGetString(GL_VERSION) if int(version[0]) == 1 and int( version[2]) < 4: #no opengl 1.4 support #print("GL_GENERATE_MIPMAP not supported, not using mipmapping") self.npot = 1 if not hasGLExtension("GL_ARB_texture_rectangle"): #print("GL_TEXTURE_RECTANGLE_ARB not supported, switching to GL_TEXTURE_2D") self.texext = GL_TEXTURE_2D self.npot = 0 #assorted settings block if hasGLExtension("GL_EXT_texture_filter_anisotropic" ) and self.fieldtemp[0] > 1.0: self.anifilt = self.fieldtemp[0] #print("using " + str(self.fieldtemp[0]) + "x anisotropic texture filtering. max: " + str(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT))) self.minfilter = self.interpretString(self.fieldtemp[1]) self.magfilter = self.interpretString(self.fieldtemp[2]) self.mipminfilter = self.interpretString(self.fieldtemp[3]) if self.mipminfilter == "Off": self.mipminfilter = -1 if self.format().sampleBuffers() and self.fieldtemp[4] == "On": #print("enabling " + str(self.format().samples()) + "x FSAA") glEnable(GL_MULTISAMPLE) else: pass #print("FSAA not supported and/or disabled") glEnable(self.texext) glEnable(GL_BLEND) glDisable(GL_DEPTH_TEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glViewport(0, 0, self.width(), self.height()) glClearColor(0.0, 0.0, 0.0, 0.0)
def wrapper(self, *args, **kvargs): glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) try: return func(self, *args, **kvargs) finally: glDisable(GL_BLEND)
def setup_gl(): """Set various pieces of OpenGL state for better rendering of SVG. """ glEnable(GL_LINE_SMOOTH) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
def basic_gl_setup(): glEnable(GL_POINT_SPRITE) # glEnable(GL_POINT_SMOOTH) glEnable(GL_VERTEX_PROGRAM_POINT_SIZE) # overwrite pointsize glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glClearColor(1.0, 1.0, 1.0, 0.0) glEnable(GL_LINE_SMOOTH)
def bind_frame_buffer(self): glBindFramebuffer(GL_FRAMEBUFFER, self.__frame_buffer) glClearColor(*self.__clear_color) for setting in self.__enable: glEnable(setting) if self.__blend_settings: glEnable(GL_BLEND) glBlendFunc(*self.__blend_settings)
def main(): if not glfw.init(): return -1 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(960, 540, "Window", None, None) if not window: glfw.terminate() return -1 glfw.make_context_current(window) glfw.swap_interval(1) version = glGetString(GL_VERSION).decode('utf-8') print(version) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) renderer = Renderer.Renderer() gui = Gui.Gui(window) testMenu = Test.TestMenu() testMenu.RegisterTest("Clear Color", TestClearColor.TestClearColor) testMenu.RegisterTest("Texture2D", TestTexture2D.TestTexture2D) currentTest = testMenu while not glfw.window_should_close(window): glClearColor(0.0, 0.0, 0.0, 1.0) renderer.Clear() gui.NewFrame() if currentTest: currentTest.OnUpdate() currentTest.OnRender() Gui.begin("Tests") if not currentTest == testMenu and Gui.button("<-"): currentTest = testMenu testMenu.m_CurrentTest = None currentTest.OnImGuiRender() if testMenu.m_CurrentTest and not (currentTest == testMenu.m_CurrentTest): currentTest = testMenu.m_CurrentTest Gui.end() Gui.framerate() gui.EndFrame() glfw.swap_buffers(window) glfw.poll_events() del currentTest del testMenu gui.endGui() glfw.terminate() return 0
def display(self): """Displays the precomputed nav map view. This function will do nothing if no display list has yet been built. """ if '_navmap' in self._display_lists: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glPushMatrix() glCallList(self._display_lists['_navmap']) glPopMatrix()
def paintGL(self): newTime = time.time() deltaTime = newTime - self._prevTime # work around double repaint events collecting in the queue if deltaTime == 0.0: return self._prevTime = newTime width, height = self.calculateAspect(self.width(), self.height()) viewport = (int((self.width() - width) * 0.5), int((self.height() - height) * 0.5), width, height) if self._scene: uniforms = self._animator.evaluate(self._timer.time) textureUniforms = self._animator.additionalTextures(self._timer.time) cameraData = self._cameraData scene = self._scene modifier = os.path.join(ProjectDir(), 'animationprocessor.py') if os.path.exists(modifier): beats = self._timer.time execfile(modifier, globals(), locals()) for name in self._textures: uniforms[name] = self._textures[name]._id self._scene.drawToScreen(self._timer.beatsToSeconds(self._timer.time), self._timer.time, uniforms, viewport, additionalTextureUniforms=textureUniforms) else: # no scene active, time cursor outside any enabled shots? global _noSignalImage if _noSignalImage is None: _noSignalImage = loadImage(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons/nosignal.png')) glDisable(GL_DEPTH_TEST) if _noSignalImage: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) Scene.drawColorBufferToScreen(_noSignalImage, viewport) glDisable(GL_BLEND) if self.__overlays: image = self.__overlays.colorBuffer() if image: color = (self.__overlays.overlayColor().red() / 255.0, self.__overlays.overlayColor().green() / 255.0, self.__overlays.overlayColor().blue() / 255.0, self.__overlays.overlayColor().alpha() / 255.0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) Scene.drawColorBufferToScreen(image, viewport, color) glDisable(GL_BLEND)
def basic_gl_setup(self): glEnable(GL_POINT_SPRITE) glEnable(GL_VERTEX_PROGRAM_POINT_SIZE) # overwrite pointsize glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glClearColor(0.8, 0.8, 0.8, 1.0) glEnable(GL_LINE_SMOOTH) # glEnable(GL_POINT_SMOOTH) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glEnable(GL_LINE_SMOOTH) glEnable(GL_POLYGON_SMOOTH) glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
def schedule(color, func, params): # staticmethod if ColorSorter.sorting: ColorSorter._add_to_sorter(color, func, params) else: ColorSorter._immediate += 1 # for benchmark/debug stats, mostly # 20060216 We know we can do this here because the stack is # only ever one element deep name = ColorSorter._gl_name_stack[-1] if name: glPushName(name) ## Don't check in immediate drawing, e.g. preDraw_glselect_dict. ## else: ## print "bug_1: attempt to push non-glname", name #Apply appropriate opacity for the object if it is specified #in the 'color' param. (Also do necessary things such as #call glBlendFunc it. -- Ninad 20071009 if len(color) == 4: opacity = color[3] else: opacity = 1.0 if opacity >= 0.0 and opacity != 1.0: glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) elif opacity == -1: # piotr 080429: I replaced the " < 0" condition with " == -1" # The opacity flag is now used to signal either "unshaded # colors" (opacity == -1) or "multicolor object" (opacity == -2) glDisable(GL_LIGHTING) # Don't forget to re-enable it! glColor3fv(color[:3]) pass apply_material(color) func(params) # Call the draw worker function. if opacity > 0.0 and opacity != 1.0: glDisable(GL_BLEND) glDepthMask(GL_TRUE) elif opacity == -1: # piotr 080429: See my comment above. glEnable(GL_LIGHTING) if name: glPopName() return
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 render(self, user_data_queue: mp.Queue = None): """Low level OpenGL calls to render the current state in an opengl_viewer. This code will be executed inside the viewer's process. Can be added to a viewer with the following code, telling the viewer to call this whenever it redraws its geometry. .. code-block:: python robot.viewer_3d.add_render_call(my_map_state.render) :param user_data_queue: The queue to read MapState messages from the main process. :type user_data_queue: mulitprocessing.Queue """ try: latest: MapState = user_data_queue.get(False) self._open_nodes = latest._open_nodes # pylint: disable=protected-access self._contact_nodes = latest._contact_nodes # pylint: disable=protected-access self._walls = latest._walls # pylint: disable=protected-access self._cleared_territories = latest._cleared_territories # pylint: disable=protected-access self._collection_active = latest._collection_active # pylint: disable=protected-access except mp.queues.Empty: pass glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glDisable(GL_LIGHTING) if RENDER_METADATA_OBJECTS: self._render_points(self._contact_nodes, NODE_CONTACT_RENDER_SIZE, NODE_CONTACT_RENDER_COLOR) self._render_points(self._open_nodes, NODE_OPEN_RENDER_SIZE, NODE_OPEN_RENDER_COLOR) # render the nav point open sample if self._cleared_territories and self._open_nodes: self._render_circle(self._open_nodes[0], NAV_POINT_RENDER_SIZE, NAV_POINT_RENDER_SECTIONS, NAV_POINT_RENDER_COLOR) for cleared_territory in self._cleared_territories: self._render_circle(cleared_territory.center, cleared_territory.radius, TERRITORY_RENDER_SECTIONS, TERRITORY_RENDER_COLOR) glEnable(GL_LIGHTING) for wall in self._walls: self._render_wall(wall, WALL_RENDER_HEIGHT_MM, WALL_RENDER_COLOR)
def init_window(terrain): """ Initialise the application window """ pygame.init() resolution = (WINDOW_WIDTH, WINDOW_HEIGHT) pygame.display.set_mode(resolution, DOUBLEBUF | OPENGL) pygame.display.set_caption("{0} - FPS: Unknown".format(NAME)) gluPerspective(FOV, (resolution[0] / resolution[1]), 0.1, 1000) glTranslatef(-(terrain.size / 2), -(terrain.height_3d / 2), -10) glRotatef(45, -90, 0, 0) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) color = hex_to_float(BACKGROUND_COLOR) glClearColor(color[0], color[1], color[2], 1)
def draw(self): TextureManager.GetTexture( Platform.asOSPath(self.textureName)).bind() glDisable(GL_CULL_FACE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) glDisable(GL_ALPHA_TEST) glDisable(GL_LIGHTING) glDepthMask( GL_FALSE ) glColor4(1, 1, 1, 0.25) self._drawQuad(self.flowOffset) glColor4(1, 1, 1, 0.25) self._drawQuad(-self.flowOffset) glDepthMask( GL_TRUE ) glEnable(GL_CULL_FACE)
def draw(self): TextureManager.GetTexture(Platform.asOSPath(self.textureName)).bind() glDisable(GL_CULL_FACE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDisable(GL_ALPHA_TEST) glDisable(GL_LIGHTING) glDepthMask(GL_FALSE) glColor4(1, 1, 1, 0.25) self._drawQuad(self.flowOffset) glColor4(1, 1, 1, 0.25) self._drawQuad(-self.flowOffset) glDepthMask(GL_TRUE) glEnable(GL_CULL_FACE)
def gl_setup(self, width, height): """Private.""" # cut out invisible faces glEnable(GL_CULL_FACE) glCullFace(GL_BACK) # enable depth buffer glEnable(GL_DEPTH_TEST) # enable alpha-blending glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # clear to black glClearColor(0.3, 0.3, 0.3, 1)
def set_color(*colors, **kwargs): '''Define current color to be used (as float values between 0 and 1) :: set_color(1, 0, 0, 1) drawLabel('Hello', pos=(100, 0)) set_color(0, 1, 0, 1) drawLabel('World', pos=(200, 0)) .. Note: Blending is activated if alpha value != 1 :Parameters: `*colors` : list Can have 3 or 4 float value (between 0 and 1) `sfactor` : opengl factor, default to GL_SRC_ALPHA Default source factor to be used if blending is activated `dfactor` : opengl factor, default to GL_ONE_MINUS_SRC_ALPHA Default destination factor to be used if blending is activated `blend` : boolean, default to None Set True if you really want to activate blending, even if the alpha color is 1 (mean no blending in theory) ''' kwargs.setdefault('sfactor', GL_SRC_ALPHA) kwargs.setdefault('dfactor', GL_ONE_MINUS_SRC_ALPHA) kwargs.setdefault('blend', None) force_blend = kwargs['blend'] == True if len(colors) == 1: if type(colors[0]) in (unicode, str): colors = get_color_from_hex(colors[0]) else: colors = (colors[0], colors[0], colors[0]) if len(colors) == 4: glColor4f(*colors) if colors[3] == 1 and not force_blend: glDisable(GL_BLEND) else: glEnable(GL_BLEND) glBlendFunc(kwargs.get('sfactor'), kwargs.get('dfactor')) if len(colors) == 3: glColor3f(*colors) if force_blend: glEnable(GL_BLEND) glBlendFunc(kwargs.get('sfactor'), kwargs.get('dfactor')) else: glDisable(GL_BLEND)
def display_lines(resources, view_projection, iteration): glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT) glEnable(GL_BLEND) glBlendEquation(GL_FUNC_ADD) glBlendFunc(GL_ONE, GL_ONE) glBindVertexArray(resources.display_vertex_array) glUseProgram(resources.display_program) update_view_projection(view_projection) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, _select_input_buffer(resources, iteration)) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, _select_output_buffer(resources, iteration)) glDrawArrays(GL_LINES, 0, RAY_COUNT << 1) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0) glUseProgram(0) glBindVertexArray(0) glDisable(GL_BLEND)
def init_opengl(self) -> bool: """Initialize and set OpenGL capabilities. Returns: True if initialized without error, False otherwise. """ if self._gl_initialized: return True if self._context is None: return False glClearColor(*self.background_color) glClearDepth(1.0) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # set antialiasing glEnable(GL_LINE_SMOOTH) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_COLOR_MATERIAL) glEnable(GL_MULTISAMPLE) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) self.create_vaos() # compile shader programs self._shaders['default'] = shaderlib.compile_shader(*shaderlib.default) self._shaders['single_color'] = shaderlib.compile_shader( *shaderlib.single_color) self._shaders['instanced_model_color'] = shaderlib.compile_shader( *shaderlib.instanced_model_color) self._shaders['instanced_picking'] = shaderlib.compile_shader( *shaderlib.instanced_picking) self._shaders['diffuse'] = shaderlib.compile_shader(*shaderlib.diffuse) self._shaders['solid'] = shaderlib.compile_shader(*shaderlib.solid) self._gl_initialized = True return True
def init(): width = mosaic_factory.ratio * size height = size print "loading textures:" for i, img in enumerate(mosaic_factory.images): print " {0}/{1}".format(i + 1, len(mosaic_factory.images)) textures[img] = load_texture(img.get_image()) generate_picture_display_list(img, width, height) print "generating mosaic display lists:" for i, img in enumerate(mosaic_factory.images): print " {0}/{1}".format(i + 1, len(mosaic_factory.images)) generate_mosaic_display_list(img) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 0.0, 0.0, 0.0) glShadeModel(GL_FLAT)
def _loop(self): frame_count = 0 fps_now = time.time() elapsed_now = time.time() while not glfw.window_should_close(self._window): self._key_poller.poll_keys(self._window) self._mouse_poller._poll_mouse(self._window) self._spaces.push() self._spaces.tint = WHITE glClearColor(*self._color) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) now = time.time() self._elapsed_time = (now - elapsed_now) elapsed_now = now # draw call if self._handler is not None: self._handler(self) # render last batch of rects (if any) self._quad.draw_batch_if_started(self._spaces) # Swap front and back buffers glfw.swap_buffers(self._window) # Poll for and process events glfw.poll_events() frame_count += 1 fps_time_delta = (time.time() - fps_now) self.fps = frame_count / fps_time_delta if fps_time_delta >= 1: title = f'{self.title} @ {self.fps:.0f} FPS' glfw.set_window_title(self._window, title) fps_now = time.time() frame_count = 0 glfw.terminate()
def paintGL(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(self.zoom, -self.zoom, -self.zoom, self.zoom, -5000, 5000) arriba = 1 if self.theta == 360: arriba = -1 gluLookAt(self.x, self.y, self.z, self.desviacion_x, self.desviacion_y, self.desviacion_z, 0, arriba, 0) glMatrixMode(GL_MODELVIEW) if self.programa.modo_oscuro: glClearColor(0.3, 0.3, 0.3, 0) else: glClearColor(1, 1, 1, 0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadMatrixf(self.m) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.ordenar_elementos() self.update()
def initializeGL(self): # We call this right after our OpenGL window is created. glClearColor(1.0, 1.0, 1.0, 1.0) glClearDepth(1.0) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glEnable(GL_NORMALIZE) light_position = (0., 0., 1., 0.) white_light = (1., 1., 1., 0.501) d_light = (1., 1., 1., 0.01) spec = (1., 1., 1., 0.08) glLightfv(GL_LIGHT0, GL_POSITION, light_position) glLightfv(GL_LIGHT0, GL_AMBIENT, white_light) #glLightfv(GL_LIGHT0, GL_DIFFUSE, d_light) glLightfv(GL_LIGHT0, GL_SPECULAR, spec) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #glBlendFunc(GL_SRC_ALPHA,GL_ONE) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_COLOR_MATERIAL) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective( 45.0, float(self.size().height()) / float(self.size().width()), 0.1, 1000000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() self.rotation = [0.0, 0.0] self.mesh.prepDraw()
def _on_realize(self, *args): """ Called at the creation of the drawing area. Sets up the OpenGL rendering context. """ print("_on_realize(%s)" % str(args)) gldrawable = self.get_gl_drawable() glcontext = self.get_gl_context() if not gldrawable.gl_begin(glcontext): return self._set_view(WIDTH / float(HEIGHT)) glEnable(GL_TEXTURE_RECTANGLE_ARB) # 2D) glEnable(GL_BLEND) glShadeModel(GL_SMOOTH) glClearColor(0.0, 0.0, 0.0, 1.0) # black background glColor4f(1.0, 1.0, 1.0, 1.0) # default color is white glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) gldrawable.gl_end()
def display(self, pose: util.Pose, head_angle: util.Angle, lift_position: util.Distance): """Displays the precomputed view at a specific pose in 3d space. :param pose: Where to display the robot. """ if not self._display_lists: return robot_matrix = pose.to_matrix() head_angle_degrees = head_angle.degrees # Get the angle of Vector's lift for rendering - we subtract the angle # of the lift in the default pose in the object, and apply the inverse # rotation sin_angle = (lift_position.distance_mm - LIFT_PIVOT_HEIGHT_MM) / LIFT_ARM_LENGTH_MM angle_radians = math.asin(sin_angle) lift_angle = -(angle_radians - LIFT_ANGLE_IN_DEFAULT_POSE) lift_angle_degrees = math.degrees(lift_angle) glPushMatrix() glEnable(GL_LIGHTING) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glMultMatrixf(robot_matrix.in_row_order) robot_scale_amt = 10.0 # cm to mm glScalef(robot_scale_amt, robot_scale_amt, robot_scale_amt) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) self._display_vector_body() self._display_vector_lift(lift_angle_degrees) self._display_vector_head(head_angle_degrees) glDisable(GL_LIGHTING) glPopMatrix()
def initializeGL(self): # We call this right after our OpenGL window is created. glClearColor(1.0, 1.0, 1.0, 1.0) glClearDepth(1.0) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glEnable(GL_NORMALIZE) light_position = (0., 0., 1., 0.) white_light = (1., 1., 1., 0.501) d_light = (1., 1., 1., 0.01) spec = (1., 1., 1., 0.08) glLightfv(GL_LIGHT0, GL_POSITION, light_position) glLightfv(GL_LIGHT0, GL_AMBIENT, white_light) #glLightfv(GL_LIGHT0, GL_DIFFUSE, d_light) glLightfv(GL_LIGHT0, GL_SPECULAR, spec) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) #glBlendFunc(GL_SRC_ALPHA,GL_ONE) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_COLOR_MATERIAL) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, float(self.size().height())/ float(self.size().width()), 0.1, 1000000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() self.rotation = [0.0, 0.0] self.mesh.prepDraw()
def paint(self): """ Draw grid object """ self.setupGLState() if self.antialias: glEnable(GL_LINE_SMOOTH) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glBegin(GL_LINES) _x, _y = self.size() _xs, _ys = self.spacing() _x_vals = np.arange(0, _x + _xs * 0.001, _xs) _y_vals = np.arange(0, _y + _ys * 0.001, _ys) glColor4f(*self.color) for x in _x_vals: glVertex3f(x, _y_vals[0], 0) glVertex3f(x, _y_vals[-1], 0) for y in _y_vals: glVertex3f(_x_vals[0], y, 0) glVertex3f(_x_vals[-1], y, 0) glEnd()
def __init__(self): self.positions = np.array([ -50, -50, 0.0, 0.0, 50, -50, 1.0, 0.0, 50, 50, 1.0, 1.0, -50, 50, 0.0, 1.0 ], np.float32) self.indicies = np.array([0, 1, 2, 2, 3, 0], np.int32) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.vb = VertexBuffer.VertexBuffer( self.positions, 4 * 4 * ctypes.sizeof(ctypes.c_float)) self.ib = IndexBuffer.IndexBuffer(self.indicies, 6) self.va = VertexArray.VertexArray() self.layout = VertexBufferLayout.VertexBufferLayout() self.shader = Shader.Shader("res/shaders/Basic.shader") self.shader.Bind() self.renderer = Renderer.Renderer() self.texture = Texture.Texture("res/textures/image.png") self.texture.Bind() self.layout.push(ctypes.c_float, 2) self.layout.push(ctypes.c_float, 2) self.va.AddBuffer(self.vb, self.layout) self.proj = pyrr.Matrix44.orthogonal_projection( 0, 960, 0, 540, -1.0, 1.0) self.view = pyrr.Matrix44.from_translation(pyrr.Vector3([0, 0, 0])) self.va.Unbind() self.shader.Unbind() self.vb.Unbind() self.ib.Unbind() self.translation1 = 0, 0, 0 self.translation2 = 100, 100, 0 print("Created Instance of Texture2D")
def render(self): """Low level OpenGL calls to render the current state in an opengl_viewer. Can be added to a viewer with the following code, telling the viewer to call this whenever it redraws its geometry. .. code-block:: python my_opengl_viewer.add_render_call(my_map_state.render) """ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glDisable(GL_LIGHTING) if RENDER_METADATA_OBJECTS: self._render_points(self._contact_nodes, NODE_CONTACT_RENDER_SIZE, NODE_CONTACT_RENDER_COLOR) self._render_points(self._open_nodes, NODE_OPEN_RENDER_SIZE, NODE_OPEN_RENDER_COLOR) # render the nav point open sample if self._cleared_territories and self._open_nodes: self._render_circle(self._open_nodes[0], NAV_POINT_RENDER_SIZE, NAV_POINT_RENDER_SECTIONS, NAV_POINT_RENDER_COLOR) for cleared_territory in self._cleared_territories: self._render_circle(cleared_territory.center, cleared_territory.radius, TERRITORY_RENDER_SECTIONS, TERRITORY_RENDER_COLOR) glEnable(GL_LIGHTING) for wall in self._walls: self._render_wall(wall, WALL_RENDER_HEIGHT_MM, WALL_RENDER_COLOR)
def paint(self): super(Grid, self).paint() glEnable(GL_LINE_SMOOTH) glEnable(GL_POLYGON_SMOOTH) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glLineWidth(1.3) glBegin(GL_LINES) # lgtm [py/call/wrong-arguments] xvals = np.linspace(-self.x / 2.0, self.x / 2.0, self.x / self.xs + 1) yvals = np.linspace(-self.y / 2.0, self.y / 2.0, self.y / self.ys + 1) glColor4f(*self.edge_color) for x in xvals: glVertex3f(x, yvals[0], 0) glVertex3f(x, yvals[-1], 0) for y in yvals: glVertex3f(xvals[0], y, 0) glVertex3f(xvals[-1], y, 0) glEnd() # lgtm [py/call/wrong-arguments]
def present_fbo(self, drawable): if not self.paint_screen: return 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._alpha_enabled: # 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() w, h = self.size glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) if self._alpha_enabled: # support alpha channel if present: glEnablei(GL_BLEND, self.textures[TEX_FBO]) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) 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() #if desired, paint window border if self.border and self.border.shown: glDisable(GL_TEXTURE_RECTANGLE_ARB) #double size since half the line will be off-screen glLineWidth(self.border.size*2) glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha) glBegin(GL_LINE_LOOP) for x,y in ((0, 0), (w, 0), (w, h), (0, h)): glVertex2i(x, y) glEnd() #reset color to default glColor4f(1.0, 1.0, 1.0, 1.0) # Show the backbuffer on screen if drawable.is_double_buffered(): log("%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() self.gl_frame_terminator() self.unset_rgb_paint_state() glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) log("%s.present_fbo() done", self)
def draw(self): """ Draws the rulers. """ width = self.glpane.width height = self.glpane.height # These 3 attrs (scale, aspect, and ruler_position) are checked to # determine if they've changed. If any of them have, # getRulerDrawingParameters() must be called to get new drawing parms. if ( (self.scale != self.glpane.scale) or (self.zoomFactor != self.glpane.zoomFactor) or (self.aspect != self.glpane.aspect) or (self.ruler_position != env.prefs[rulerPosition_prefs_key]) ): self.scale = self.glpane.scale self.zoomFactor = self.glpane.zoomFactor self.aspect = self.glpane.aspect self.ruler_position = env.prefs[rulerPosition_prefs_key] self.ruler_drawing_params = getRulerDrawingParameters( width, height, self.aspect, self.scale, self.zoomFactor, self.ruler_position ) ( draw_ticks_and_text, units_text, units_format, units_scale, unit_label_inc, long_tickmark_inc, medium_tickmark_inc, num_vert_ticks, num_horz_ticks, tickmark_spacing_multiplier, ruler_origin, ruler_start_pt, units_text_origin, origin_square_pt1, origin_square_pt2, vr_thickness, vr_tickmark_spacing, vr_long_tick_len, vr_medium_tick_len, vr_short_tick_len, vr_rect_pt1, vr_rect_pt2, vr_line_pt1, vr_line_pt2, vr_units_x_offset, vr_units_y_offset, hr_thickness, hr_tickmark_spacing, hr_long_tick_len, hr_medium_tick_len, hr_short_tick_len, hr_rect_pt1, hr_rect_pt2, hr_line_pt1, hr_line_pt2, hr_units_x_offset, hr_units_y_offset, ) = self.ruler_drawing_params ruler_color = env.prefs[rulerColor_prefs_key] ruler_opacity = env.prefs[rulerOpacity_prefs_key] # These may become user preferences in the future. tickmark_color = darkgray text_color = black # Set up 2D (window) coordinate system. # Bruce - please review this section. glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() # needed! gluOrtho2D(0.0, float(width), 0.0, float(height)) glMatrixMode(GL_MODELVIEW) # About this glMatrixMode(GL_MODELVIEW) call, Bruce wrote in a review: # The only reason this is desirable (it's not really needed) is if, # when someone is editing the large body of drawing code after this, # they inadvertently do something which is only correct if the matrix # mode is GL_MODELVIEW (e.g. if they use glTranslate to shift a ruler # or tickmark position). Most of our drawing code assumes it can do # this, so a typical NE1 OpenGL programmer may naturally assume this, # which is why it's good to leave the matrix mode as GL_MODELVIEW when # entering into a large hunk of ordinary drawing code (especially if # it might call other drawing functions, now or in the future). # Mark 2008-03-03 glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) # Note: disabling GL_DEPTH_TEST is not honored by the 3d version of # glpane.renderText -- ruler text can still be obscured by # previously drawn less-deep model objects. # But the 2d call of renderText in part.py does honor this. # The Qt doc says why, if I guess how to interpret it: # http://doc.trolltech.com/4.3/qglwidget.html#renderText # says, for the 3d version of renderText only (passing three model # coords as opposed to two window coords): # Note that this function only works properly if GL_DEPTH_TEST # is enabled, and you have a properly initialized depth buffer. # Possible fixes: # - revise ruler_origin to be very close to the screen, # and hope that this disable is merely ignored, not a messup; # - or, use the 2d version of the function. # I did the latter fix (2d renderText, below) and it seems to work. # [bruce 081204 comment] # Suppress writing into the depth buffer so anything behind the ruler # can still be highlighted/selected. glDepthMask(GL_FALSE) # == Draw v/h ruler rectangles in the user defined color and opacity. glColor4fv(list(ruler_color) + [ruler_opacity]) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glRectf(origin_square_pt1[0], origin_square_pt1[1], origin_square_pt2[0], origin_square_pt2[1]) # Origin square if env.prefs[displayVertRuler_prefs_key]: glRectf(vr_rect_pt1[0], vr_rect_pt1[1], vr_rect_pt2[0], vr_rect_pt2[1]) # Vertical ruler if env.prefs[displayHorzRuler_prefs_key]: glRectf(hr_rect_pt1[0], hr_rect_pt1[1], hr_rect_pt2[0], hr_rect_pt2[1]) # Horizontal ruler glDisable(GL_BLEND) # Set color of ruler lines, tick marks and text. glColor3fv(tickmark_color) self.glpane.qglColor(RGBf_to_QColor(text_color)) # Draw unit of measurement in corner (A or nm). # piotr 080326: replaced drawText with drawCenteredText self.drawCenteredText(units_text, units_text_origin) # Kludge alert. Finish drawing ruler edge(s) if we will not be # drawing the ruler tick marks and text (only happens when the user # is zoomed out to an "absurd scale factor"). if not draw_ticks_and_text: if env.prefs[displayVertRuler_prefs_key]: self.drawLine(vr_line_pt1, vr_line_pt2) if env.prefs[displayHorzRuler_prefs_key]: self.drawLine(hr_line_pt1, hr_line_pt2) # == Draw vertical ruler line(s) and tick marks if env.prefs[displayVertRuler_prefs_key] and draw_ticks_and_text: # Draw vertical line along right/left edge of ruler. self.drawLine(vr_line_pt1, vr_line_pt2) # Initialize pt1 and pt2, the tick mark endpoints. The first tick # mark will span the entire width of the ruler, which serves as a # divider b/w the unit of measure text (i.e. A or nm) and the rest # of the ruler. pt1 = ruler_start_pt pt2 = ruler_start_pt + V(-vr_thickness, 0.0, 0.0) # Draw vertical ruler tickmarks, including numeric unit labels for tick_num in range(num_horz_ticks + 1): # pt1 and pt2 are modified by each iteration of the loop. self.drawLine(pt1, pt2) # Draw units number beside long tickmarks. if not tick_num % unit_label_inc: units_num_origin = pt1 + V(vr_units_x_offset, vr_units_y_offset, 0.0) units_num = units_format % (tick_num * units_scale) self.drawText(units_num, units_num_origin) # Update tickmark endpoints for next tickmark. pt1 = ruler_start_pt + V(0.0, vr_tickmark_spacing * tickmark_spacing_multiplier * (tick_num + 1), 0.0) if not (tick_num + 1) % long_tickmark_inc: pt2 = pt1 + V(vr_long_tick_len, 0.0, 0.0) elif not (tick_num + 1) % medium_tickmark_inc: pt2 = pt1 + V(vr_medium_tick_len, 0.0, 0.0) else: pt2 = pt1 + V(vr_short_tick_len, 0.0, 0.0) # End vertical ruler # == Draw horizontal ruler line(s) and tick marks if env.prefs[displayHorzRuler_prefs_key] and draw_ticks_and_text: # Draw horizontal line along top/bottom edge of ruler. self.drawLine(hr_line_pt1, hr_line_pt2) # Initialize pt1 and pt2, the tick mark endpoints. The first tick # mark will span the entire width of the ruler, which serves as a # divider b/w the unit of measure text (i.e. A or nm) and the rest # of the ruler. pt1 = ruler_start_pt pt2 = ruler_start_pt + V(0.0, -hr_thickness, 0.0) # Draw horizontal ruler (with vertical) tickmarks, including its # numeric unit labels for tick_num in range(num_vert_ticks + 1): # pt1 and pt2 are modified by each iteration of the loop. self.drawLine(pt1, pt2) # Draw units number beside long tickmarks. if not tick_num % unit_label_inc: units_num_origin = pt1 + V(hr_units_x_offset, hr_units_y_offset, 0.0) units_num = units_format % (tick_num * units_scale) self.drawText(units_num, units_num_origin) # Update tickmark endpoints for next tickmark. pt1 = ruler_start_pt + V(hr_tickmark_spacing * tickmark_spacing_multiplier * (tick_num + 1), 0.0, 0.0) if not (tick_num + 1) % long_tickmark_inc: pt2 = pt1 + V(0.0, hr_long_tick_len, 0.0) elif not (tick_num + 1) % medium_tickmark_inc: pt2 = pt1 + V(0.0, hr_medium_tick_len, 0.0) else: pt2 = pt1 + V(0.0, hr_short_tick_len, 0.0) # End horizontal ruler # Restore OpenGL state. glDepthMask(GL_TRUE) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glDepthMask(GL_TRUE) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() return # from drawRulers
def do_present_fbo(self): bw, bh = self.size ww, wh = self.render_size self.gl_marker("Presenting FBO on screen") # Change state to target screen instead of our FBO glBindFramebuffer(GL_FRAMEBUFFER, 0) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) if self._alpha_enabled: # 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() rect_count = len(self.pending_fbo_paint) if self.glconfig.is_double_buffered() or bw!=ww or bh!=wh: #refresh the whole window: rectangles = ((0, 0, bw, bh), ) else: #paint just the rectangles we have accumulated: rectangles = self.pending_fbo_paint self.pending_fbo_paint = [] log("do_present_fbo: painting %s", rectangles) glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) if self._alpha_enabled: # support alpha channel if present: glEnablei(GL_BLEND, self.textures[TEX_FBO]) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) if SAVE_BUFFERS: glBindFramebuffer(GL_READ_FRAMEBUFFER, self.offscreen_fbo) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glReadBuffer(GL_COLOR_ATTACHMENT0) glViewport(0, 0, bw, bh) from OpenGL.GL import glGetTexImage size = bw*bh*4 import numpy data = numpy.empty(size) img_data = glGetTexImage(GL_TEXTURE_RECTANGLE_ARB, 0, GL_BGRA, GL_UNSIGNED_BYTE, data) from PIL import Image, ImageOps img = Image.frombuffer("RGBA", (bw, bh), img_data, "raw", "BGRA", bw*4) img = ImageOps.flip(img) kwargs = {} if SAVE_BUFFERS=="jpeg": kwargs = { "quality" : 0, "optimize" : False, } t = time.time() tstr = time.strftime("%H-%M-%S", time.localtime(t)) filename = "./W%i-FBO-%s.%03i.%s" % (self.wid, tstr, (t*1000)%1000, SAVE_BUFFERS) log("do_present_fbo: saving %4ix%-4i pixels, %7i bytes to %s", bw, bh, size, filename) img.save(filename, SAVE_BUFFERS, **kwargs) glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) #viewport for painting to window: glViewport(0, 0, ww, wh) if ww!=bw or wh!=bh: glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glBegin(GL_QUADS) for x,y,w,h in rectangles: #note how we invert coordinates.. tx1, ty1, tx2, ty2 = x, bh-y, x+w, bh-y-h vx1, vy1, vx2, vy2 = x, y, x+w, y+h glTexCoord2i(tx1, ty1) glVertex2i(vx1, vy1) #top-left of window viewport glTexCoord2i(tx1, ty2) glVertex2i(vx1, vy2) #bottom-left of window viewport glTexCoord2i(tx2, ty2) glVertex2i(vx2, vy2) #bottom-right of window viewport glTexCoord2i(tx2, ty1) glVertex2i(vx2, vy1) #top-right of window viewport glEnd() glDisable(GL_TEXTURE_RECTANGLE_ARB) if self.paint_spinner: #add spinner: dim = min(bw/3.0, bh/3.0) t = time.time() count = int(t*4.0) bx = bw//2 by = bh//2 for i in range(8): #8 lines glBegin(GL_POLYGON) c = cv.trs[count%8][i] glColor4f(c, c, c, 1) mi1 = math.pi*i/4-math.pi/16 mi2 = math.pi*i/4+math.pi/16 glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10)) glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim)) glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim)) glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10)) glEnd() #if desired, paint window border if self.border and self.border.shown: #double size since half the line will be off-screen glLineWidth(self.border.size*2) glBegin(GL_LINE_LOOP) glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha) for px,py in ((0, 0), (bw, 0), (bw, bh), (0, bh)): glVertex2i(px, py) glEnd() if self.pointer_overlay: x, y, _, _, size, start_time = self.pointer_overlay elapsed = time.time()-start_time if elapsed<6: alpha = max(0, (5.0-elapsed)/5.0) glLineWidth(1) glBegin(GL_LINES) glColor4f(0, 0, 0, alpha) glVertex2i(x-size, y) glVertex2i(x+size, y) glVertex2i(x, y-size) glVertex2i(x, y+size) glEnd() else: self.pointer_overlay = None # Show the backbuffer on screen self.gl_show(rect_count) self.gl_frame_terminator() #restore pbo viewport glViewport(0, 0, bw, bh) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) self.unset_rgb_paint_state() log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) log("%s.do_present_fbo() done", self)
def drawHeightfield(color, w, h, textureReady, opacity, SOLID = False, pickCheckOnly = False, hf = None): """ Draw a heighfield using vertex and normal arrays. Optionally, it could be texture mapped. @pickCheckOnly This is used to draw the geometry only, used for OpenGL pick selection purpose. """ if not hf: # Return if heightfield is not provided return glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) # Don't use opacity, otherwise the heighfield polygons should be sorted # - something to implement later... ## glColor3v(list(color)) if textureReady: # For texturing, use white color (to be modulated by the texture) glColor3f(1,1,1) else: glColor3fv(list(color)) glPushMatrix() glScalef(w, h, 1.0) if SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_CULL_FACE) if not pickCheckOnly: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if textureReady: glEnable(GL_TEXTURE_2D) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) for tstrip_vert, tstrip_norm, tstrip_tex in hf: glVertexPointer(3, GL_FLOAT, 0, tstrip_vert) glNormalPointer(GL_FLOAT, 0, tstrip_norm) glTexCoordPointer(2, GL_FLOAT, 0, tstrip_tex) glDrawArrays(GL_TRIANGLE_STRIP, 0, len(tstrip_vert)) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_COLOR_MATERIAL) if not pickCheckOnly: if textureReady: glDisable(GL_TEXTURE_2D) glDepthMask(GL_TRUE) glEnable(GL_CULL_FACE) if not SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopMatrix() glEnable(GL_LIGHTING) return
def display(self): if self.knowledge_base: # update the world if self.knowledge_base.shelf_xform: # load the shelf once a transform is available if not self.shelf: self.shelf = self.world.loadRigidObject("klampt_models/north_shelf/shelf_with_bins.obj") logger.info("spawned shelf model") self.shelf.setTransform(*self.knowledge_base.shelf_xform) if self.knowledge_base.order_bin_xform: # load the order bin once a transform is available if not self.order_bin: self.order_bin = self.world.loadRigidObject("klampt_models/apc_bin/apc_bin.obj") logger.info("spawned order bin model") self.order_bin.setTransform(*self.knowledge_base.order_bin_xform) # spawn/update objects for (name, xform) in self.knowledge_base.object_xforms.items(): # load the object once a transform is availale if name not in self.objects: body = self.world.loadRigidObject("klampt_models/items/{0}/{0}.obj".format(name)) logger.info("spawned {} model".format(name)) # load the point cloud if name in self.knowledge_base.object_clouds: self.n += 1 display_list = glGenLists(self.n) # compile the display list glNewList(display_list, GL_COMPILE) glDisable(GL_LIGHTING) glBegin(GL_POINTS) points = self.knowledge_base.object_clouds[name] for point in points: if len(point) == 2: xyz = point[0] rgb = point[1] else: xyz = point[:3] if len(point) == 4: rgb = point[3] elif len(point) > 3: rgb = point[3:6] else: rgb = None if rgb is not None: glColor3f(*map(lambda x: x / 255.0, rgb)) else: glColor3f(*colors[i % len(colors)]) glVertex3f(*xyz[:3]) glEnd() glEndList() logging.debug("compiled {} points for {}".format(len(points), name)) else: display_list = None self.objects[name] = {"body": body, "display_list": display_list} # self.objects[name]['body'].setTransform(*xform) # delete objects for (name, props) in self.objects.items(): if name not in self.knowledge_base.object_xforms: # remove the object # XXX: cannot actually delete object... so move it far away... very far away props["body"].setTransform(so3.identity(), [1e3, 1e3, 1e3]) del self.objects[name] # update the robot state if self.robot_state: try: self.robot.setConfig(self.robot_state.sensed_config) except TypeError as e: logger.error("error visualizing config: {}".format(self.robot_state.sensed_config)) logger.error(traceback.format_exc()) sys.exit(-1) self.world.drawGL() # draw commanded configurations glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [0, 1, 0, 0.5]) if self.robot_state: qi = self.robot.getConfig() self.robot.setConfig(self.robot_state.commanded_config) self.robot.drawGL(False) self.robot.setConfig(qi) glDisable(GL_BLEND) # draw the point clouds glPointSize(2) for (name, props) in self.objects.items(): if "display_list" in props: glCallList(props["display_list"]) # draw gripper link transforms for name in ["left_gripper", "right_gripper"]: gldraw.xform_widget(self.robot.getLink(name).getTransform(), 0.1, 0.01) # draw axis-aligned axes for reference gldraw.xform_widget((so3.identity(), [0, 0, 1]), 0.1, 0.01) # draw local origins of objects if self.knowledge_base: for xform in self.knowledge_base.object_xforms.values(): gldraw.xform_widget(xform, 0.1, 0.01)
def on_draw(self): glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glTranslate(self.translatex, self.translatey, self.depth) if self.autoRun: glRotate(self.rotx, 0, 1, 0) else: # Perform arcball rotation. glScale(1,-1,1) glMultMatrixf(self.arcball.transform) glScale(1,-1,1) with displayListify("cubeTranslate") as shouldLeave: if shouldLeave: raise LeaveWith # Scale the co-ordinates so that they are correct glScale(2/128, 2/128, 2/128) glColor(0.25, 0.25, 0.25, 1) glutWireCube(255) glTranslate(-128, -128, -128) with displayListify("allPoints") as shouldLeave: if shouldLeave: raise LeaveWith with SaveMatrix(): # Flip the co-ordinates and translate upwards glScale(1,-1,1) glColor(0.25, 0.25, 0.25, 0.5) glTranslate(0,-255,0) glPointSize(pointSize) for dat in reversed(vLists): glTranslate(0., 0., 1./nChunks*255) dat.draw(GL_POINTS) with displayListify("axisLabels") as shouldLeave: if shouldLeave: raise LeaveWith #if True: with SaveMatrix(): glTranslate(128,0,0) self.makeLabel("End").draw() glTranslate(0,0,255) self.makeLabel("Beginning").draw() with SaveMatrix(): glTranslate(-128,128,0) glRotate(90,0,0,1) self.makeLabel("Byte 1").draw() glTranslate(0,255,0) self.makeLabel("Byte 2").draw() with displayListify("fileName") as shouldLeave: if shouldLeave: raise LeaveWith glLoadIdentity() with SaveMatrix(): glColor(1,0,0) glTranslate(0,-2.2,-4) glScale(1/64, 1/64, 1/64) l = self.makeLabel(basename(currentInputFile)) l.color = (0, 128, 230, 255) l.draw() glTranslate(0,0,-1) if self.autoRun: if self.rotx > 360 - 45: vlist = vertex_list(4, ('v2i', (-1, -1, 1, -1, 1, 1, -1, 1))) glColor(0,0,0,(self.rotx-(360-45))/45) vlist.draw(GL_QUADS) if self.rotx < 45: vlist = vertex_list(4, ('v2i', (-1, -1, 1, -1, 1, 1, -1, 1))) glColor(0,0,0,1-(self.rotx/45)) vlist.draw(GL_QUADS)
screen_w = args.width screen_h = args.height if args.fullscreen: (screen_w, screen_h, *_) = glfwGetVideoMode(glfwGetPrimaryMonitor()) window = glfwCreateWindow(screen_w, screen_h, 'Sila', glfwGetPrimaryMonitor(), None) else: window = glfwCreateWindow(screen_w, screen_h, 'Sila', None, None) if not window: glfwTerminate() raise RuntimeError('glfwCreateWindow failed') glfwMakeContextCurrent(window) glViewport(0, 0, screen_w, screen_h) glEnable(GL_DEPTH_TEST) glEnable(GL_MULTISAMPLE) glEnable(GL_PROGRAM_POINT_SIZE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED) runner = Runner(screen_w, screen_h) for level in (level4, level5, level3, level2, level1, level0): if not glfwWindowShouldClose(window): runner.run_level(level, window) glfwTerminate()
def draw(self): # bind texture for image filename [#e or other image object], # doing whatever is needed of allocating texture name, loading image object, loading texture data; ###e optim: don't call glBindTexture if it's already bound, and/or have a "raw draw" which assumes it's already bound if 'workaround bug in formula for texture_options': texture_options = dict(clamp = self.clamp, pixmap = self.pixmap, use_mipmaps = self.use_mipmaps, decal = self.decal) else: texture_options = self.texture_options # never used, but desired once bug is fixed self.bind_texture( **texture_options) try: # figure out texture coords (from optional args, not yet defined ###e) -- stub for now nreps = float(self.nreps) # float won't be needed once we have type coercion; not analyzed whether int vs float matters in subr ## tex_origin = ORIGIN2 # see also testdraw's drawtest1, still used in testmode to draw whole font texture rect tex_origin = V(self.tex_origin[0], self.tex_origin[1]) ## tex_dx = D2X ; tex_dx *= nreps # this modifies a shared, mutable Numeric array object, namely D2X! Not what I wanted. tex_dx = D2X * nreps tex_dy = D2Y * nreps # where to draw it -- act like a 2D Rect for now, determined by self's lbox, # which presently comes from self.size origin = V(-self.bleft, -self.bbottom, 0) # see also the code in drawfont2 which tweaks the drawing position to improve the pixel alignment # (in a way which won't work right inside a display list if any translation occurred before now in that display list) # in case we want to offer that option here someday [070124 comment] ## dx = DX * self.bright ## dy = DY * self.btop dx = DX * (self.bleft + self.bright) # bugfix 070304: include bleft, bbottom here dy = DY * (self.bbottom + self.btop) blend = self.blend alpha_test = self.alpha_test two_sided = self.two_sided shape = self.shape # for now, None or a symbolic string (choices are hardcoded below) if blend: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if alpha_test: glEnable(GL_ALPHA_TEST) # (red book p.462-463) glAlphaFunc(GL_GREATER, 0.0) # don't draw the fully transparent parts into the depth or stencil buffers ##e maybe let that 0.0 be an option? eg the value of alpha_test itself? Right now, it can be False ~== 0 (not None). if two_sided: glDisable(GL_CULL_FACE) if not shape: draw_textured_rect( origin, dx, dy, tex_origin, tex_dx, tex_dy) else: # support sub-shapes of the image rect, but with unchanged texture coords relative to the whole rect [070404 ###UNTESTED] if type(shape) == type(""): ##e use an external shape name->value mapping? # in fact, should such a mapping be part of the dynamic graphics-instance env (self.env)?? if shape == 'upper-left-half': shape = ((0,0), (1,1), (0,1)) elif shape == 'lower-right-half': shape = ((0,0), (1,0), (1,1)) elif shape == 'upper-right-half': #070628 shape = ((0,1), (1,0), (1,1)) elif shape == 'lower-left-half': #070628; untested shape = ((0,0), (1,0), (0,1)) else: assert 0, "in %r, don't know this shape name: %r" % (self, shape) # otherwise assume it might be the right form to pass directly # (list of 3 2d points in [0,1] x [0,1] relative coords -- might need to be in CCW winding order) draw_textured_rect_subtriangle( origin, dx, dy, tex_origin, tex_dx, tex_dy, shape ) pass if blend: glDisable(GL_BLEND) if alpha_test: glDisable(GL_ALPHA_TEST) if two_sided: glEnable(GL_CULL_FACE) finally: self.kluge_reset_texture_mode_to_work_around_renderText_bug() return # from Image.draw
def do_present_fbo(self): self.gl_marker("Presenting FBO on screen") # Change state to target screen instead of our FBO glBindFramebuffer(GL_FRAMEBUFFER, 0) if self._alpha_enabled: # 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() bw, bh = self.size ww, wh = self.render_size if self.glconfig.is_double_buffered() or bw!=ww or bh!=wh: #refresh the whole window: rectangles = ((0, 0, bw, bh), ) else: #paint just the rectangles we have accumulated: rectangles = self.pending_fbo_paint self.pending_fbo_paint = [] log("do_present_fbo: painting %s", rectangles) glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) if self._alpha_enabled: # support alpha channel if present: glEnablei(GL_BLEND, self.textures[TEX_FBO]) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) #viewport for painting to window: glViewport(0, 0, ww, wh) if ww!=bw or wh!=bh: glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glBegin(GL_QUADS) for x,y,w,h in rectangles: #note how we invert coordinates.. tx1, ty1, tx2, ty2 = x, bh-y, x+w, bh-y-h vx1, vy1, vx2, vy2 = x, y, x+w, y+h glTexCoord2i(tx1, ty1) glVertex2i(vx1, vy1) #top-left of window viewport glTexCoord2i(tx1, ty2) glVertex2i(vx1, vy2) #bottom-left of window viewport glTexCoord2i(tx2, ty2) glVertex2i(vx2, vy2) #bottom-right of window viewport glTexCoord2i(tx2, ty1) glVertex2i(vx2, vy1) #top-right of window viewport glEnd() glDisable(GL_TEXTURE_RECTANGLE_ARB) if self.paint_spinner: #add spinner: dim = min(bw/3.0, bh/3.0) t = time.time() count = int(t*4.0) bx = bw//2 by = bh//2 for i in range(8): #8 lines glBegin(GL_POLYGON) c = cv.trs[count%8][i] glColor4f(c, c, c, 1) mi1 = math.pi*i/4-math.pi/16 mi2 = math.pi*i/4+math.pi/16 glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10)) glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim)) glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim)) glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10)) glEnd() #if desired, paint window border if self.border and self.border.shown: #double size since half the line will be off-screen glLineWidth(self.border.size*2) glBegin(GL_LINE_LOOP) glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha) for px,py in ((0, 0), (bw, 0), (bw, bh), (0, bh)): glVertex2i(px, py) glEnd() # Show the backbuffer on screen self.gl_show() self.gl_frame_terminator() #restore pbo viewport glViewport(0, 0, bw, bh) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) self.unset_rgb_paint_state() log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) log("%s.do_present_fbo() done", self)
def drawHeightfield(color, w, h, textureReady, opacity, SOLID=False, pickCheckOnly=False, hf=None): """ Draw a heighfield using vertex and normal arrays. Optionally, it could be texuture mapped. @pickCheckOnly This is used to draw the geometry only, used for OpenGL pick selection purpose. """ from OpenGL.GL import glTexEnvf from OpenGL.GL import GL_TEXTURE_ENV from OpenGL.GL import GL_TEXTURE_ENV_MODE from OpenGL.GL import GL_MODULATE from OpenGL.GL import glVertexPointer from OpenGL.GL import glNormalPointer from OpenGL.GL import glTexCoordPointer from OpenGL.GL import glDrawArrays from OpenGL.GL import glEnableClientState from OpenGL.GL import GL_VERTEX_ARRAY from OpenGL.GL import GL_NORMAL_ARRAY from OpenGL.GL import GL_TEXTURE_COORD_ARRAY glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) ### glColor4fv(list(color) + [opacity]) ### glColor3fv(list(color)) glColor3f(1.0, 1.0, 1.0) glPushMatrix() glScalef(w, h, 1.0) if SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_CULL_FACE) if not pickCheckOnly: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if textureReady: glEnable(GL_TEXTURE_2D) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) for tstrip_vert, tstrip_norm, tstrip_tex in hf: glVertexPointer(3, GL_FLOAT, 0, tstrip_vert) glNormalPointer(GL_FLOAT, 0, tstrip_norm) glTexCoordPointer(2, GL_FLOAT, 0, tstrip_tex) glDrawArrays(GL_TRIANGLE_STRIP, 0, len(tstrip_vert)) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_COLOR_MATERIAL) if not pickCheckOnly: if textureReady: glDisable(GL_TEXTURE_2D) glDepthMask(GL_TRUE) glEnable(GL_CULL_FACE) if not SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopMatrix() glEnable(GL_LIGHTING) return
def drawPlane(color, w, h, textureReady, opacity, SOLID=False, pickCheckOnly=False, tex_coords=None): """ Draw polygon with size of <w>*<h> and with color <color>. Optionally, it could be texuture mapped, translucent. @pickCheckOnly This is used to draw the geometry only, used for OpenGL pick selection purpose. """ vs = [[-0.5, 0.5, 0.0], [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.5, 0.5, 0.0]] # piotr 080529: use external texture coordinates if provided if tex_coords is None: vt = [[0.0, 1.0], [0.0, 0.0], [1.0, 0.0], [1.0, 1.0]] else: vt = tex_coords if textureReady: opacity = 1.0 glDisable(GL_LIGHTING) glColor4fv(list(color) + [opacity]) glPushMatrix() glScalef(w, h, 1.0) if SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_CULL_FACE) if not pickCheckOnly: # This makes sure a translucent object will not occlude another # translucent object. glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if textureReady: glEnable(GL_TEXTURE_2D) glBegin(GL_QUADS) for ii in range(len(vs)): t = vt[ii]; v = vs[ii] if textureReady: glTexCoord2fv(t) glVertex3fv(v) glEnd() if not pickCheckOnly: if textureReady: glDisable(GL_TEXTURE_2D) glDisable(GL_BLEND) glDepthMask(GL_TRUE) glEnable(GL_CULL_FACE) if not SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopMatrix() glEnable(GL_LIGHTING) return
def present_fbo(self, encoding, is_delta, x, y, w, h): if not self.paint_screen: return self.gl_marker("Presenting FBO on screen") # Change state to target screen instead of our FBO glBindFramebuffer(GL_FRAMEBUFFER, 0) if self._alpha_enabled: # 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() ww, wh = self.size if self.glconfig.is_double_buffered(): #refresh the whole window: x, y = 0, 0 w, h = ww, wh glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) if self._alpha_enabled: # support alpha channel if present: glEnablei(GL_BLEND, self.textures[TEX_FBO]) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) glBegin(GL_QUADS) #note how we invert coordinates.. glTexCoord2i(x, wh-y) glVertex2i(x, y) #top-left of window viewport glTexCoord2i(x, wh-y-h) glVertex2i(x, y+h) #bottom-left of window viewport glTexCoord2i(x+w, wh-y-h) glVertex2i(x+w, y+h) #bottom-right of window viewport glTexCoord2i(x+w, wh-y) glVertex2i(x+w, y) #top-right of window viewport glEnd() glDisable(GL_TEXTURE_RECTANGLE_ARB) #show region being painted: if OPENGL_PAINT_BOX: glLineWidth(1) if is_delta: glLineStipple(1, 0xf0f0) glEnable(GL_LINE_STIPPLE) glBegin(GL_LINE_LOOP) color = BOX_COLORS.get(encoding, _DEFAULT_BOX_COLOR) glColor4f(*color) for px,py in ((x, y), (x+w, y), (x+w, y+h), (x, y+h)): glVertex2i(px, py) glEnd() if is_delta: glDisable(GL_LINE_STIPPLE) if self.paint_spinner: #add spinner: dim = min(ww/3.0, wh/3.0) t = time.time() count = int(t*4.0) bx = ww//2 by = wh//2 for i in range(8): #8 lines glBegin(GL_POLYGON) c = cv.trs[count%8][i] glColor4f(c, c, c, 1) mi1 = math.pi*i/4-math.pi/16 mi2 = math.pi*i/4+math.pi/16 glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10)) glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim)) glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim)) glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10)) glEnd() #if desired, paint window border if self.border and self.border.shown: #double size since half the line will be off-screen glLineWidth(self.border.size*2) glBegin(GL_LINE_LOOP) glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha) for px,py in ((0, 0), (ww, 0), (ww, wh), (0, wh)): glVertex2i(px, py) glEnd() # Show the backbuffer on screen self.gl_show() self.gl_frame_terminator() self.unset_rgb_paint_state() log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) log("%s.present_fbo() done", self)
def __enter__(self): glEnable(GL_BLEND) glBlendFunc(self.sfactor, self.dfactor)