def handle_reshape(self, width, height): glLoadIdentity() aspect = height / width glViewport(0, 0, width, height) bw = self.width / 2 glOrtho(-bw, bw, -bw * aspect, bw * aspect, -bw, bw)
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 do_configure_event(self, event): ClientWindow.do_configure_event(self, event) drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() self.yuv420_shader = None # Re-create textures self.current_mode = GLClientWindow.MODE_UNINITIALIZED if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") w, h = self.get_size() log("Configure widget size: %d x %d" % (w, h)) glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(3) drawable.gl_end()
def display(): glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() if projection_mode == "ortho": width_ratio = DISPLAY_WIDTH / DISPLAY_HEIGHT zoom = -cam_z if zoom > 0: glOrtho(-zoom * width_ratio, zoom * width_ratio, -zoom, zoom, .5, 100) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRotated(rot_deg, 0, 1, 0) glTranslated(cam_x, cam_y, cam_z) else: gluPerspective(55, (DISPLAY_WIDTH / DISPLAY_HEIGHT), 0.1, 100.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRotated(rot_deg, 0, 1, 0) glTranslated(cam_x, cam_y, cam_z) drawTestShape() drawAxisOfRotation() if transform: shape_offset = [30, 0, 40] # problem 1 transform_shape(shape_offset, 40) glFlush()
def display(): glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() if cam.projection_mode == "ortho": width_ratio = DISPLAY_WIDTH / DISPLAY_HEIGHT zoom = -cam.cur_position.z if zoom > 0: glOrtho(-zoom * width_ratio, zoom * width_ratio, -zoom, zoom, .5, 100) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRotated(cam.cur_rotation, 0, 1, 0) glTranslated(cam.cur_position.x, cam.cur_position.y, cam.cur_position.z) else: gluPerspective(60, (DISPLAY_WIDTH / DISPLAY_HEIGHT), 0.1, 100.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRotated(cam.cur_rotation, 0, 1, 0) glTranslated(cam.cur_position.x, cam.cur_position.y, cam.cur_position.z) draw_neighborhood() animate_car() glFlush()
def draw_text_2d(text, x, y, line_height=17, color=None): """Draw a text at a given 2D position. A very basic 2D drawing function for drawing (multi-line) text." """ width = glutGet(GLUT_WINDOW_WIDTH) height = glutGet(GLUT_WINDOW_HEIGHT) glMatrixMode(GL_PROJECTION) glPushMatrix() #matrix = glGetDouble( GL_PROJECTION_MATRIX ) glLoadIdentity() glOrtho(0.0, width, 0.0, height, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() if color: glColor3f(*color) glRasterPos2i(x, y) lines = 0 for character in text: if character == '\n': lines += 1 glRasterPos(x, y - (lines * line_height)) else: glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ord(character)) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() #glLoadMatrixd(matrix) glMatrixMode(GL_MODELVIEW)
def keyboard(key, x, y): global mat, rot, animTrans, animRot if key == chr(27): import sys sys.exit(0) #Your Code Here if key == b'a': mat[2] = mat[2] - math.cos(math.radians(rot[0] + 90)) mat[0] = mat[0] + math.sin(math.radians(rot[0] + 90)) if key == b'd': mat[2] = mat[2] + math.cos(math.radians(rot[0] + 90)) mat[0] = mat[0] - math.sin(math.radians(rot[0] + 90)) if key == b'w': mat[2] = mat[2] + math.cos(math.radians(rot[0])) mat[0] = mat[0] - math.sin(math.radians(rot[0])) if key == b's': mat[2] = mat[2] - math.cos(math.radians(rot[0])) mat[0] = mat[0] + math.sin(math.radians(rot[0])) if key == b'q': rot[0] = rot[0] - 1 if key == b'e': rot[0] = rot[0] + 1 if key == b'r': mat[1] = mat[1] - 1 if key == b'f': mat[1] = mat[1] + 1 if key == b'h': mat = [0, -5, -35] rot = [0, 0, 0] animTrans = [0, 0, 0] animRot = [0, 0, 0] if key == b'o': glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-50, 50, -50, 50, .1, 50) #glOrtho() if key == b'p': glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(50, DISPLAY_HEIGHT / DISPLAY_WIDTH, .1, 200) if key == b'z': import sys sys.exit(0) glutPostRedisplay()
def display(): glClear (GL_COLOR_BUFFER_BIT) glColor3f (1.0, 1.0, 1.0) # viewing transformation global chHor global chVert global home global ortho global chDepth global pers global chRot global totHor global totDepth global totRot #Your Code Here glMatrixMode(GL_MODELVIEW) glRotated(-totRot,0,10,0) glTranslated(-totHor,0,-totDepth) glRotated(chRot, 0, 1, 0) glTranslated(+totHor,0,+totDepth) glTranslated(chHor, chVert, chDepth) glRotated(totRot, 0, 10, 0) rad = math.radians(chRot) if(chRot > 0 or chRot < 0): totHor = totHor * math.cos(rad) + totDepth * math.sin(rad) totHorTemp = totHor totDepth = -totHorTemp * math.sin(rad) + totDepth * math.cos(rad) totHor += chHor totDepth += chDepth totRot += chRot if home == True: init() totRot = 0 totHor = 0 if ortho == True: glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-10.0,10.0,-10.0,10.0,-100.0, 100.0) if pers == True: glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, 1, 0, 100) chHor = 0 chVert = 0 home = False chDepth = 0 ortho = False pers = False chRot = 0 drawHouse() glFlush()
def _set_view(self): log.info("_set_view()") glMatrixMode(GL_PROJECTION) glLoadIdentity() w, h = self.size glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def _set_view_volume(self): ''' ''' glOrtho(-20, 20, -20, 20, 50, -50) size = self.GetSize() glViewport(0, 0, size.width, size.height)
def setupViewport(self, width, height): side = min(width, height) glViewport((width - side) // 2, (height - side) // 2, side, side) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0) glMatrixMode(GL_MODELVIEW)
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 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 resizeGL(self, width, height): side = min(width, height) glViewport(int((width - side) / 2.0), int((height - side) / 2.0), side, side) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0) glMatrixMode(GL_MODELVIEW)
def __enter__(self): glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glOrtho(*self.bounds, -1, 1) # gl coord convention glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity()
def __get_rotation_matrix(coordinates, side_length): """Get rotation matrix from specific point of view and scale.""" assert len(coordinates) == 3 glLoadIdentity() glOrtho(-side_length, side_length, -side_length, side_length, -4 * side_length, 4 * side_length) x, y, z = coordinates gluLookAt(x, y, z, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) return array(glGetFloatv(GL_MODELVIEW_MATRIX), dtype='f')
def draw_line(x1, y1, x2, y2): glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, 730, 0, 650, 0, 1) glMatrixMode(GL_MODELVIEW) glBegin(GL_LINES) glVertex2f(x1, y1) glVertex2f(x2, y2) glEnd()
def __init__(self, wid, w, h, old_backing, mmap_enabled, mmap): Backing.__init__(self, wid, mmap_enabled, mmap) display_mode = (gtk.gdkgl.MODE_RGB | gtk.gdkgl.MODE_SINGLE) # We use single buffer because double doesn't work, figure out why try: self.glconfig = gtk.gdkgl.Config(mode=display_mode) except gtk.gdkgl.NoMatches: raise SystemExit self._backing = gtk.gdkgl.ext( gdk.Pixmap(gdk.get_default_root_window(), w, h)) log.info("Creating GL pixmap size %d %d " % (w, h)) self.gldrawable = self._backing.set_gl_capability(self.glconfig) log.info("drawable ok") # Then create an indirect OpenGL rendering context. self.glcontext = gtk.gdkgl.Context(self.gldrawable, direct=True) log.info("context ok") if not self.glcontext: raise SystemExit, "** Cannot create OpenGL rendering context!" print "OpenGL rendering context is created." self.texture = None self.textures = [0] self.use_openGL_CSC = True self.yuv420_shader = None # OpenGL begin if not self.gldrawable.gl_begin(self.glcontext): return False glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) self.gldrawable.gl_end() cr = self._backing.cairo_create() if old_backing is not None and old_backing._backing is not None: # Really we should respect bit-gravity here but... meh. cr.set_operator(cairo.OPERATOR_SOURCE) cr.set_source_pixmap(old_backing._backing, 0, 0) cr.paint() old_w, old_h = old_backing._backing.get_size() cr.move_to(old_w, 0) cr.line_to(w, 0) cr.line_to(w, h) cr.line_to(0, h) cr.line_to(0, old_h) cr.line_to(old_w, old_h) cr.close_path() else: cr.rectangle(0, 0, w, h) cr.set_source_rgb(1, 1, 1) cr.fill()
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 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 make_coord_system_norm_based(flip=False): glMatrixMode(GL_PROJECTION) glLoadIdentity() if flip: glOrtho(1, 0, 1, 0, -1, 1) # gl coord convention else: glOrtho(0, 1, 0, 1, -1, 1) # gl coord convention glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def adjust_gl_view(self, w, h): """ adjust view onto our scene. """ glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, w, h, 0, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
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(join(dirname(__file__), 'mixer.ppm')) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glMatrixMode(GL_TEXTURE) glLoadIdentity() glScale(1 / width, 1 / height, 1) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, 730, 0, 650, 0, 1) 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 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 handle_reshape(self, width, height): glLoadIdentity() aspect = height / width glViewport(0, 0, width, height) bw = self.width / 2 if self._is_perspective: gluPerspective(45.0, 1 / aspect, 0.1, 2000.0) else: glOrtho(-bw, bw, -bw * aspect, bw * aspect, -bw, bw)
def initializeGL(self): ''' Initialize GL ''' # set viewing projection glClearColor(0.3, 0.3, 0.3, 1.0) glClearDepth(1.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, WIDTH, 0.0, HEIGHT, 0.0, 640.0) glEnable(GL_DEPTH_TEST)
def reshape(w, h): glViewport(0, 0, w, h) ratio = float(w) / h glMatrixMode(GL_PROJECTION) glLoadIdentity() viewport_center = HEIGHT * ratio / 2 photo_center = HEIGHT * mosaic_factory.ratio / 2 left = photo_center - viewport_center right = photo_center + viewport_center glOrtho(left, right, 0.0, HEIGHT, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
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(join(dirname(__file__), 'mixer.ppm')) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glMatrixMode(GL_TEXTURE) glLoadIdentity() glScale(1/width, 1/height, 1) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, 730, 0, 650, 0, 1) 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 draw_rect(x, y, width, height): glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, 730, 0, 650, 0, 1) glMatrixMode(GL_MODELVIEW) glColor4f(0.71, 0.83, 1, 0.3) glBegin(GL_QUADS) glVertex2f(x, y) glVertex2f(x + width, y) glVertex2f(x + width, y + height) glVertex2f(x, y + height) glEnd()
def resizeGL(self, w, h): ''' Resize the GL window ''' WIDTH = w HEIGHT = h glViewport(0, 0, WIDTH, HEIGHT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, WIDTH, 0.0, HEIGHT, 0.0, 640.0) self.update()
def set_2d(self): """Set 2D render mode.""" glDisable(GL_DEPTH_TEST) glViewport(0, 0, self.width, self.height) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, self.width, 0, self.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def setup_2D_projection(width, height): ''' Adapted from http://basic4gl.wikispaces.com/2D+Drawing+in+OpenGL ''' set_matrix_mode(PROJECTION) load_identity_matrix() viewport(0, 0, width, height) glOrtho(0, width, height, 0, 0, 1) glDisable(GL_DEPTH_TEST) set_matrix_mode(MODELVIEW) load_identity_matrix() # Displacement trick for exact pixelization translate(x=0.375, y=0.375)
def make_coord_system_pixel_based(img_shape, flip=False): height, width, channels = img_shape # Set Projection Matrix glMatrixMode(GL_PROJECTION) glLoadIdentity() if flip: glOrtho(width, 0, 0, height, -1, 1) # origin in the top left corner just like the img np-array else: glOrtho(0, width, height, 0, -1, 1) # origin in the top left corner just like the img np-array # Switch back to Model View Matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def draw(self): # this code is modified from GLPane.drawcompass glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode( GL_PROJECTION ) # WARNING: we're now in nonstandard matrixmode (for sake of gluPickMatrix and glOrtho -- needed??##k) glPushMatrix() glLoadIdentity() try: glpane = self.env.glpane ## aspect = 1.0 ###WRONG -- should use glpane.aspect (which exists as of 070919) aspect = glpane.aspect # revised by bruce 070919, UNTESTED corner = self.corner delegate = self.delegate ###e should get glpane to do this for us (ie call a method in it to do this if necessary) # (this code is copied from it) glselect = glpane.current_glselect if glselect: # print "%r (ipath %r) setting up gluPickMatrix" % (self, self.ipath) x, y, w, h = glselect gluPickMatrix( x, y, w, h, glGetIntegerv(GL_VIEWPORT) # k is this arg needed? it might be the default... ) # the first three cases here are still ###WRONG if corner == UPPER_RIGHT: glOrtho(-50 * aspect, 5.5 * aspect, -50, 5.5, -5, 500) # Upper Right elif corner == UPPER_LEFT: glOrtho(-5 * aspect, 50.5 * aspect, -50, 5.5, -5, 500) # Upper Left elif corner == LOWER_LEFT: glOrtho(-5 * aspect, 50.5 * aspect, -5, 50.5, -5, 500) # Lower Left else: ## glOrtho(-50*aspect, 5.5*aspect, -5, 50.5, -5, 500) # Lower Right ## glOrtho(-50*aspect, 0, 0, 50, -5, 500) # Lower Right [used now] -- x from -50*aspect to 0, y (bot to top) from 0 to 50 glOrtho(-glpane.width * PIXELS, 0, 0, glpane.height * PIXELS, -5, 500) # approximately right for the checkbox, but I ought to count pixels to be sure (note, PIXELS is a pretty inexact number) glMatrixMode(GL_MODELVIEW) ###k guess 061210 at possible bugfix (and obviously needed in general) -- # do this last to leave the matrixmode standard # (status of bugs & fixes unclear -- hard to test since even Highlightable(projection=True) w/o any change to # projection matrix (test _9cx) doesn't work!) offset = (-delegate.bright, delegate.bbottom) # only correct for LOWER_RIGHT glTranslatef(offset[0], offset[1], 0) self.drawkid(delegate) ## delegate.draw() finally: glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) # be sure to do this last, to leave the matrixmode standard glPopMatrix() return
def display(): glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) # viewing transformation global chHor global chVert global home global ortho global chDepth global pers global chRot global totHor global totVert global totRot #Your Code Here glMatrixMode(GL_MODELVIEW) glRotated(-totRot, 0, 10, 0) glRotated(chRot, 0, 10, 0) glTranslated(chHor, chVert, chDepth) glRotated(totRot, 0, 10, 0) totHor += chHor totVert += chVert totRot += chRot if home == True: init() totRot = 0 totVert = 0 totHor = 0 if ortho == True: glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-20.0, 20.0, -20.0, 20.0, -100.0, 100.0) if pers == True: glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, 1, 0, 100) chHor = 0 chVert = 0 home = False chDepth = 0 ortho = False pers = False chRot = 0 drawHouse() glFlush()
def draw(self): # this code is modified from GLPane.drawcompass glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) # WARNING: we're now in nonstandard matrixmode (for sake of gluPickMatrix and glOrtho -- needed??##k) glPushMatrix() glLoadIdentity() try: glpane = self.env.glpane ## aspect = 1.0 ###WRONG -- should use glpane.aspect (which exists as of 070919) aspect = glpane.aspect # revised by bruce 070919, UNTESTED corner = self.corner delegate = self.delegate ###e should get glpane to do this for us (ie call a method in it to do this if necessary) # (this code is copied from it) glselect = glpane.current_glselect if glselect: # print "%r (ipath %r) setting up gluPickMatrix" % (self, self.ipath) x,y,w,h = glselect gluPickMatrix( x,y, w,h, glGetIntegerv( GL_VIEWPORT ) #k is this arg needed? it might be the default... ) # the first three cases here are still ###WRONG if corner == UPPER_RIGHT: glOrtho(-50*aspect, 5.5*aspect, -50, 5.5, -5, 500) # Upper Right elif corner == UPPER_LEFT: glOrtho(-5*aspect, 50.5*aspect, -50, 5.5, -5, 500) # Upper Left elif corner == LOWER_LEFT: glOrtho(-5*aspect, 50.5*aspect, -5, 50.5, -5, 500) # Lower Left else: ## glOrtho(-50*aspect, 5.5*aspect, -5, 50.5, -5, 500) # Lower Right ## glOrtho(-50*aspect, 0, 0, 50, -5, 500) # Lower Right [used now] -- x from -50*aspect to 0, y (bot to top) from 0 to 50 glOrtho(-glpane.width * PIXELS, 0, 0, glpane.height * PIXELS, -5, 500) # approximately right for the checkbox, but I ought to count pixels to be sure (note, PIXELS is a pretty inexact number) glMatrixMode(GL_MODELVIEW) ###k guess 061210 at possible bugfix (and obviously needed in general) -- # do this last to leave the matrixmode standard # (status of bugs & fixes unclear -- hard to test since even Highlightable(projection=True) w/o any change to # projection matrix (test _9cx) doesn't work!) offset = (-delegate.bright, delegate.bbottom) # only correct for LOWER_RIGHT glTranslatef(offset[0], offset[1], 0) self.drawkid( delegate) ## delegate.draw() finally: glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) # be sure to do this last, to leave the matrixmode standard glPopMatrix() return
def display(): glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) # viewing transformation global chHor global chVert global home global ortho global chDepth global persz global chRot global totHor global totDepth global totRot global seconds #Your Code Here glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslated(chHor, chVert, chDepth) glRotated(chRot, 0, 1, 0) if home == True: init() chRot = -45 chDepth = 0 chVert = 0 chHor = -20 seconds = 0 if ortho == True: glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-10.0, 10.0, -10.0, 10.0, -100.0, 100.0) seconds = 0 if pers == True: glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, 1, 0, 100) home = False ortho = False pers = False drawCarTurned() drawWheels() drawNeighboorhood() print(seconds) # drawWheels() glFlush() bob = 0
def resizeGL(self, w, h): ''' Resize the GL window ''' glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, w, h, 0, -1, 1) glMatrixMode(GL_MODELVIEW) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) self.w = w self.h = h if self.logoon == "On": if self.logo[0] and len(self.logo) == 5: self.logo[4].setDrawRect([0, 0, w, h])
def display(): global PERSPECTIVE glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) # viewing transformation #Your Code Here glMatrixMode(GL_PROJECTION) glLoadIdentity() if PERSPECTIVE == 'p': gluPerspective(90, 1, 1, 50) else: glOrtho(-10, 10, -10, 10, 1, 100) glMatrixMode(GL_MODELVIEW) drawHouse() glFlush()
def display(): global perspective glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) # viewing transformation glMatrixMode(GL_PROJECTION) glLoadIdentity() if perspective: gluPerspective(100, 1, 1, 100) else: glOrtho(-10, 10, -10, 10, 1, 100) glMatrixMode(GL_MODELVIEW) drawHouse() glFlush()
def gl_init(self): drawable = self.gl_begin() w, h = self.size log("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable) if not drawable: return None if not self.gl_setup: glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(3) self.gl_setup = True return drawable
def _set_view(self, ratio): """ Sets up the orthographic projection. Height is always 1.0 in GL modelview coordinates. Coordinates should give a rendering area height of 1 and a width of 1.33, when in 4:3 ratio. """ print("_set_view(%s)" % str(ratio)) w = ratio h = 1. glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-w, w, -h, h, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def draw_gui(self): 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) glClear(GL_DEPTH_BUFFER_BIT) 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() glPushMatrix() glLoadIdentity() glRasterPos(width - logo.size[0] - 4, logo.size[1] + 2) glDrawPixels(logo.size[0], logo.size[1], GL_RGB, GL_UNSIGNED_BYTE, logo_bytes) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glColor3f(1.0, 1.0, 1.0) draw_text_2d("FPS: {0:.1f}\nTime: {1:.0f} ns" .format(self.clock.fps, self.clock.time), 10, 30) if self.show_help: self.display_help() if self.show_info: self.display_info()
def __init__(self, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT): object.__init__(self) resolution = (width, height) flags = pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF pygame.display.set_mode(resolution, flags, 0) glClearColor(0.0, 0.0, 0.0, 1.0) glDisable(GL_DEPTH_TEST) glDisable(GL_CULL_FACE) glDisable(GL_LIGHTING) glDisable(GL_TEXTURE_2D) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, width, height, 0, 0, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def draw_gui(self): logo = self.logo logo_bytes = self.logo_bytes 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() glShadeModel(GL_SMOOTH) glClear(GL_DEPTH_BUFFER_BIT) 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() if self.show_help: self.display_help() if self.show_info: self.display_info()
def display_screen(self): glDisable(GL_LIGHTING) glColor3f(1, 1, 1) # Projection glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective (self.fov,float(self.width)/float(self.height),self.clippingplanes[0],self.clippingplanes[1]) # Initialize ModelView matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() # View transformation mat = se3.homogeneous(self.camera.matrix()) cols = zip(*mat) pack = sum((list(c) for c in cols),[]) glMultMatrixf(pack) labels = dict([ (k, T[1]) for (k, T) in vantage_point_xforms.items() ]) for (k, v) in labels.items(): try: labels[k] = gluProject(*v) except: labels[k] = None glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0,self.width,self.height,0,-1,1); glMatrixMode(GL_MODELVIEW) glLoadIdentity() for (s, p) in labels.items(): if p: glRasterPos3f(p[0], self.height - p[1], p[2]) gldraw.glutBitmapString(GLUT_BITMAP_HELVETICA_12, s)
def _setup_projection(self, glselect=False): # bruce 050608 split this out; 050615 revised docstring """ Set up standard projection matrix contents using aspect, vdist, and some attributes of self. @warning: leaves matrixmode as GL_PROJECTION. Optional arg glselect should be False (default) or a 4-tuple (to prepare for GL_SELECT picking). """ glMatrixMode(GL_PROJECTION) glLoadIdentity() scale = self.scale # bruce 050608 used this to clarify following code near, far = self.near, self.far # bruce 080219 moved these from one of two callers into here, # to fix bug when insert from partlib is first operation in NE1 self.aspect = (self.width + 0.0) / (self.height + 0.0) self.vdist = 6.0 * scale if glselect: x, y, w, h = glselect gluPickMatrix(x, y, w, h, glGetIntegerv(GL_VIEWPORT)) # k is this arg needed? it might be the default... if self.ortho: glOrtho(-scale * self.aspect, scale * self.aspect, -scale, scale, self.vdist * near, self.vdist * far) else: glFrustum( -scale * near * self.aspect, scale * near * self.aspect, -scale * near, scale * near, self.vdist * near, self.vdist * far, ) return
def _setup_projection(self, glselect = False): ### WARNING: This is not actually private! TODO: rename it. """ Set up standard projection matrix contents using various attributes of self (aspect, vdist, scale, zoomFactor). Also reads the current OpenGL viewport bounds in window coordinates. (Warning: leaves matrixmode as GL_PROJECTION.) @param glselect: False (default) normally, or a 4-tuple (format not documented here) to prepare for GL_SELECT picking by calling gluPickMatrix(). If you are really going to draw in the pick window (for GL_RENDER and glReadPixels picking, rather than GL_SELECT picking), don't forget to set the glViewport *after* calling _setup_projection. Here's why: gluPickMatrix needs to know the current *whole-window* viewport, in order to set up a projection matrix to map a small portion of it to the clipping boundaries for GL_SELECT. From the gluPickMatrix doc page: viewport: Specifies the current viewport (as from a glGetIntegerv call). Description: gluPickMatrix creates a projection matrix that can be used to restrict drawing to a small region of the viewport. In the graphics pipeline, the clipper actually works in homogeneous coordinates, clipping polygons to the {X,Y}==+-W boundaries. This saves the work of doing the homogeneous division: {X,Y}/W==+-1.0, (and avoiding problems when W is zero for points on the eye plane in Z,) but it comes down to the same thing as clipping to X,Y==+-1 in orthographic. So the projection matrix decides what 3D model-space planes map to +-1 in X,Y. (I think it maps [near,far] to [0,1] in Z, because they're not clipped symmetrically.) Then glViewport sets the hardware transform that determines where the +-1 square of clipped output goes in screen pixels within the window. Normally you don't actually draw pixels while picking in GL_SELECT mode because the pipeline outputs hits after the clipping stage, so gluPickMatrix only reads the viewport and sets the projection matrix. """ #bruce 080912 moved this from GLPane into GLPane_minimal glMatrixMode(GL_PROJECTION) glLoadIdentity() scale = self.scale * self.zoomFactor near, far = self.near, self.far aspect = self.aspect vdist = self.vdist if glselect: x, y, w, h = glselect gluPickMatrix( x, y, w, h, glGetIntegerv( GL_VIEWPORT ) #k is this arg needed? it might be the default... ) if self.ortho: glOrtho( - scale * aspect, scale * aspect, - scale, scale, vdist * near, vdist * far ) else: glFrustum( - scale * near * aspect, scale * near * aspect, - scale * near, scale * near, vdist * near, vdist * far) return
def draw(self, width, height, selection_box=None): scene = context.application.scene camera = context.application.camera glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if selection_box is not None: # set up a select buffer glSelectBuffer(self.select_buffer_size) glRenderMode(GL_SELECT) glInitNames() glMatrixMode(GL_PROJECTION) glLoadIdentity() # Apply the pick matrix if selecting if selection_box is not None: gluPickMatrix(0.5 * (selection_box[0] + selection_box[2]), height - 0.5 * (selection_box[1] + selection_box[3]), selection_box[2] - selection_box[0] + 1, selection_box[3] - selection_box[1] + 1, (0, 0, width, height)) # Apply the frustum matrix znear = camera.znear zfar = camera.znear + camera.window_depth if width > height: w = 0.5*float(width) / float(height) h = 0.5 else: w = 0.5 h = 0.5*float(height) / float(width) if znear > 0.0: glFrustum(-w*camera.window_size, w*camera.window_size, -h*camera.window_size, h*camera.window_size, znear, zfar) else: glOrtho(-w*camera.window_size, w*camera.window_size, -h*camera.window_size, h*camera.window_size, znear, zfar) glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Move to eye position (reverse) gl_apply_inverse(camera.eye) glTranslatef(0.0, 0.0, -znear) # Draw the rotation center, only when realy drawing objects: if selection_box is None: glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, [1.0, 1.0, 1.0, 1.0]) glShadeModel(GL_SMOOTH) self.call_list(scene.rotation_center_list) # Now rotate to the model frame and move back to the model center (reverse) gl_apply_inverse(camera.rotation) # Then bring the rotation center at the right place (reverse) gl_apply_inverse(camera.rotation_center) gl_apply_inverse(scene.model_center) scene.draw() if selection_box is not None: # now let the caller analyze the hits by returning the selection # buffer. Note: The selection buffer can be used as an iterator # over 3-tupples (near, far, names) where names is tuple that # contains the gl_names associated with the encountered vertices. return glRenderMode(GL_RENDER) else: # draw the interactive tool (e.g. selection rectangle): glCallList(self.tool.total_list)
def draw(self, aspect, quat, compassPosition, compass_moved_in_from_corner, displayCompassLabels ): """ Draw the "compass" (the perpendicular colored arrows showing orientation of model coordinates) in the specified corner of the GLPane (self.glpane). Doesn't assume a specific glMatrixMode; sets it to GL_MODELVIEW on exit. Doesn't trash either matrix, but does require enough GL_PROJECTION stack depth to do glPushMatrix on it (though the guaranteed depth for that stack is only 2). """ glpane = self.glpane #bruce 050608 improved behavior re GL state requirements and side effects; # 050707 revised docstring accordingly. #mark 0510230 switched Y and Z colors. # Now X = red, Y = green, Z = blue, standard in all CAD programs. glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() # needed! # Set compass position using glOrtho if compassPosition == UPPER_RIGHT: # hack for use in testmode [revised bruce 070110 when GLPane_overrider merged into GLPane]: if compass_moved_in_from_corner: glOrtho(-40 * aspect, 15.5 * aspect, -50, 5.5, -5, 500) else: glOrtho(-50 * aspect, 3.5 * aspect, -50, 4.5, -5, 500) # Upper Right elif compassPosition == UPPER_LEFT: glOrtho(-3.5 * aspect, 50.5 * aspect, -50, 4.5, -5, 500) # Upper Left elif compassPosition == LOWER_LEFT: glOrtho(-3.5 * aspect, 50.5 * aspect, -4.5, 50.5, -5, 500) # Lower Left else: glOrtho(-50 * aspect, 3.5 * aspect, -4.5, 50.5, -5, 500) # Lower Right glRotatef(quat.angle * 180.0/math.pi, quat.x, quat.y, quat.z) glCallList(self._compass_dl) ##Adding "X, Y, Z" text labels for Axis. By test, the following code will get # segmentation fault on Mandrake Linux 10.0 with libqt3-3.2.3-17mdk # or other 3.2.* versions, but works with libqt3-3.3.3-26mdk. Huaicai 1/15/05 if displayCompassLabels: # maybe todo: optimize by caching QString, QColor objects during __init__ glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) ## glPushMatrix() font = self._font glpane.qglColor(QColor(200, 75, 75)) # Dark Red glpane.renderText(_P4, 0.0, 0.0, QString("x"), font) glpane.qglColor(QColor(25, 100, 25)) # Dark Green glpane.renderText(0.0, _P4, 0.0, QString("y"), font) glpane.qglColor(QColor(50, 50, 200)) # Dark Blue glpane.renderText(0.0, 0.0, _P4 + 0.2, QString("z"), font) ## glPopMatrix() glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) # note: this leaves ending matrixmode in standard state, GL_MODELVIEW # (though it doesn't matter for present calling code; see discussion in bug 727) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() return # from draw
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 %s, backing size %s", self.render_size, self.size) # 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) glDisable(GL_SCISSOR_TEST) glDisable(GL_LIGHTING) glDisable(GL_DITHER) # 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() 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) # Define empty tmp FBO glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_TMP_FBO]) set_texture_level() 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.tmp_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_TMP_FBO], 0) clear_fbo() # Define empty FBO texture and set rendering to FBO glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): set_texture_level() 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) clear_fbo() # 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]) glEnable(GL_FRAGMENT_PROGRAM_ARB) self.gl_setup = True
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.gl_setup: #ensure python knows which scope we're talking about: global glInitStringMarkerGREMEDY, glStringMarkerGREMEDY global glInitFrameTerminatorGREMEDY, glFrameTerminatorGREMEDY # 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 #don't bother trying again for another window: glInitStringMarkerGREMEDY = None # Initialize frame_terminator GL debugging extension if available if glInitFrameTerminatorGREMEDY and glInitFrameTerminatorGREMEDY() == True: log.info("Enabling GL frame terminator debugging.") else: glFrameTerminatorGREMEDY = None #don't bother trying again for another window: glInitFrameTerminatorGREMEDY = 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 # - YUV fragment program bound # - render to offscreen FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(5) debug("%s.gl_init() textures of size %s : %s", self, 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]) # 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, GL_RGB, w, h, 0, GL_RGB, 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.shaders = [ 1, 2 ] glGenProgramsARB(2, self.shaders) for progid, progstr in ((0, YUV2RGB_shader), (1, RGBP2RGB_shader)): glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[progid]) glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(progstr), progstr) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[0]) self.gl_setup = True return drawable