Пример #1
0
    def _gl_select_(self, x, y):
        '''

        '''
        _gw, gh = self.GetSize()

        self.draw(offscreen=True)
        b = glReadPixels(x, gh - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE)

        _buff = glSelectBuffer(128)
        view = glGetIntegerv(GL_VIEWPORT)
        glRenderMode(GL_SELECT)
        glInitNames()
        glPushName(0)

        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glLoadIdentity()
        gluPickMatrix(x, gh - y, 1.0, 1.0, view)
        self._set_view_volume()

        glMatrixMode(GL_MODELVIEW)
        self.draw(offscreen=True)

        glMatrixMode(GL_PROJECTION)
        glPopMatrix()

        hits = glRenderMode(GL_RENDER)
        glMatrixMode(GL_MODELVIEW)

        self.scene_graph.set_view_cube_face(struct.unpack('BBB', b))  # get the top object

        return min([(h.near, h.names[0]) for h in hits])[1] if hits else None
Пример #2
0
    def initialize(self):
        """
        Set up the viewport.
        """
        x, y = self.viewSize

        # Hide things that are behind other things
        glEnable(GL_DEPTH_TEST)

        # Create the OpenGL viewport, setting the size of the window (in pixels)
        # and defining how the scene is projected onto it.
        glViewport(0, 0, x, y)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # Field of view, aspect ratio, near clipping, far clipping
        gluPerspective(45.0, x / y, 0.5, 1000.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        # This makes material color properties be defined by glColor calls,
        # necessary to get the right colors when lighting is enabled.
        glEnable(GL_COLOR_MATERIAL)
        # This might be desirable at some point, who knows.
        # glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION)

        # Make lighting work, because we like lights.
        glEnable(GL_LIGHTING)

        # Make textures work too.
        glEnable(GL_TEXTURE_2D)
Пример #3
0
 def compile_total_list(self):
     if self.total_list is not None:
         glNewList(self.total_list, GL_COMPILE)
         # reset a few things
         glDisable(GL_DEPTH_TEST)
         glDisable(GL_LIGHTING)
         glMatrixMode(GL_PROJECTION)
         glLoadIdentity()
         glMatrixMode(GL_MODELVIEW)
         glLoadIdentity()
         # change the modelview to camera coordinates
         viewport = glGetIntegerv(GL_VIEWPORT)
         width = viewport[2] - viewport[0]
         height = viewport[3] - viewport[1]
         if width > height:
             w = float(width) / float(height)
             h = 1.0
         else:
             w = 1.0
             h = float(height) / float(width)
         glScalef(2/w, 2/h, 1.0)
         glCallList(self.draw_list)
         glEnable(GL_DEPTH_TEST)
         glEnable(GL_LIGHTING)
         glEndList()
Пример #4
0
    def draw_colour_legend(self):
        menubar_height = self.logo.size[1] + 4
        width = glutGet(GLUT_WINDOW_WIDTH)
        height = glutGet(GLUT_WINDOW_HEIGHT)
        # Colour legend
        left_x = width - 20
        right_x = width - 10
        min_y = menubar_height + 5
        max_y = height - 20
        time_step_size = math.ceil(self.max_hit_time / 20 / 50) * 50
        hit_times = list(range(int(self.min_hit_time), int(self.max_hit_time), int(time_step_size)))
        if len(hit_times) > 1:
            segment_height = int((max_y - min_y) / len(hit_times))
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
            glDisable(GL_LIGHTING)
            glBegin(GL_QUADS)
            for hit_time in hit_times:
                segment_nr = hit_times.index(hit_time)
                glColor3f(*self.spectrum(hit_time))
                glVertex2f(left_x, max_y - segment_height * segment_nr)
                glVertex2f(right_x, max_y - segment_height * segment_nr)
                glColor3f(*self.spectrum(hit_time + time_step_size))
                glVertex2f(left_x, max_y - segment_height * (segment_nr + 1))
                glVertex2f(right_x, max_y - segment_height * (segment_nr + 1))
            glEnd()

            # Colour legend labels
            self.colourist.now_text()
            for hit_time in hit_times:
                segment_nr = hit_times.index(hit_time)
                draw_text_2d("{0:>5}ns".format(hit_time), width - 80, (height - max_y) + segment_height * segment_nr)
    def _setup_lighting(self):
        """
        [private method]
        Set up lighting in the model (according to self._lights).
        [Called from both initializeGL and paintGL.]
        """
        # note: there is some duplicated code in this method
        # in GLPane_lighting_methods (has more comments) and ThumbView,
        # but also significant differences. Should refactor sometime.
        # [bruce 060415/080912 comment]
        
        glEnable(GL_NORMALIZE)
            # bruce comment 050311: I don't know if this relates to lighting or not
            # grantham 20051121: Yes, if NORMALIZE is not enabled (and normals
            # aren't unit length or the modelview matrix isn't just rotation)
            # then the lighting equation can produce unexpected results.  

        #bruce 050413 try to fix bug 507 in direction of lighting:
        ##k might be partly redundant now; not sure whether projection matrix needs to be modified here [bruce 051212]
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        #bruce 051212 moved most code from this method into new function, setup_standard_lights
        setup_standard_lights( self._lights, self.glprefs)

        # record what glprefs data was used by that, for comparison to see when we need to call it again
        # (not needed for _lights since another system tells us when that changes)
        self._last_glprefs_data_used_by_lights = glprefs_data_used_by_setup_standard_lights( self.glprefs)
        return
Пример #6
0
    def draw(self):
        t1 = time.time()
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        glLoadIdentity ()
        horizonY = 1 * 2.2 - .6 + .5
        GLU.gluLookAt(self.eyeX.x, horizonY, 8.0,
                      self.lookX.x, horizonY, 0.0,
                      0.0, 1.0, 0.0)

        glEnable(GL.GL_TEXTURE_2D)

        if 0:
            with pushMatrix():
                glColor3f(1,0,0)
                glTranslatef(*self.ball)
                glScalef(.2, .2, 1)
                imageCard("sample.jpg")

        with pushMatrix():
            with mode(disable=[GL.GL_LIGHTING]):
                for card in self.cards:
                    card.draw(self.eyeX.x, horizonY, self.cardList)

        glFlush()
        pygame.display.flip()
Пример #7
0
    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()
Пример #8
0
    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
Пример #9
0
    def SetupProjection(self, width = 640, 
                              height = 480, 
                              zNear = 5., 
                              zFar = 300.):
        """ Sets up the projection matrix for opengl.
        """
    	# set the projection transformation
	glMatrixMode(GL_PROJECTION)
	glLoadIdentity()

	#TODO: replace the glu call with something else.
	#gluPerspective(45.0, float(width) / height, scale * 50.0, scale * 1000.0)
	#gluPerspective(45.0, float(self.width) / float(self.height), 5.0, 1000.0)
        self.zNear = zNear
	self.zFar = zFar
        self.buffer_calc_a = self.zFar / ( self.zFar - self.zNear )
        self.buffer_calc_b = self.zFar * self.zNear / ( self.zNear - self.zFar )



	gluPerspective(45.0, 
	               float(width) / float(height), 
		       self.zNear,
		       self.zFar)

	self.gl_projection_matrix = glGetFloatv(GL_PROJECTION_MATRIX)

	# set the model transformation
	glMatrixMode(GL_MODELVIEW)
Пример #10
0
    def render(self):
        """ The render pass for the scene """
        self.init_view()

        # Enable lighting and color
        glEnable(GL_LIGHTING)

        glClearColor(0.4, 0.4, 0.4, 0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Load the modelview matrix from the current state of the trackball
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        loc = self.interaction.translation
        glTranslated(-loc[0], -loc[1], -loc[2])
        glMultMatrixf(self.interaction.trackball.matrix)

        # store the inverse of the current modelview.
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))

        # render the scene. This will call the render function for each object in the scene
        self.scene.render()

        # draw the grid
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()

        # flush the buffers so that the scene can be drawn
        glFlush()
Пример #11
0
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)
Пример #12
0
    def _setup_lighting(self):
        """
        [private method]
        Set up lighting in the model.
        [Called from both initializeGL and paintGL.]
        """
        # note: there is some duplicated code in this method
        # in GLPane_lighting_methods (has more comments) and ThumbView,
        # but also significant differences. Should refactor sometime.
        # [bruce 060415/080912 comment]
        
        glEnable(GL_NORMALIZE)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        #bruce 060415 moved following from ThumbView.initializeGL to this split-out method...
        #bruce 051212 revised lighting code to share prefs and common code with GLPane
        # (to fix bug 1200 and mitigate bugs 475 and 1158;
        #  fully fixing those would require updating lighting in all ThumbView widgets
        #  whenever lighting prefs change, including making .update calls on them,
        #  and is not planned for near future since it's easy enough to close & reopen them)
        try:
            lights = self.shareWidget._lights #bruce 060415 shareWidget --> self.shareWidget; presumably always failed before that
                ###@@@ will this fix some bugs about common lighting prefs??
        except:
            lights = _default_lights
        
        setup_standard_lights( lights, self.glprefs)
        return
Пример #13
0
 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 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)
Пример #15
0
 def viewport_changed(self):
     """This method is called when the view's size has changed, with
     the view's OpenGL context as the current context, and the OpenGL
     viewport set to (0, 0, width, height). The default implementation
     loads an identity projection matrix and calls init_projection()."""
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     self.init_projection()
Пример #16
0
    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
Пример #17
0
    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
Пример #18
0
    def render(self):
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        glRotate(self.pitch, 1, 0, 0)
        glRotate(self.yaw,   0, 1, 0)

        x, y, z = self.position
        glTranslate(-x, -y, -z)
Пример #19
0
    def start_render(self):
        '''
        '''
        glDisable(GL_DEPTH_TEST)

        glPushMatrix()
        glLoadIdentity()

        glTranslatef(*self.translate)
Пример #20
0
    def resizeGL(self, width, height):
        if height == 0:
            height = 1

        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)
        glMatrixMode(GL_MODELVIEW)
Пример #21
0
 def translate(self, trans):
     # translate the object
     self.makeCurrent()
     glMatrixMode(GL_MODELVIEW)
     glLoadIdentity()
     glTranslated(trans[0], trans[1], trans[2])
     glMultMatrixd(self._modelview_matrix)
     # update _modelview_matrix
     self._modelview_matrix = glGetDoublev(GL_MODELVIEW_MATRIX)
Пример #22
0
 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')
Пример #23
0
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()
Пример #24
0
    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
Пример #25
0
    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()
Пример #26
0
    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
Пример #27
0
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()
Пример #28
0
 def set_projection(self, near, far, fovy):
     self._near = near
     self._far = far
     self._fovy = fovy
     self.makeCurrent()
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     height = max(self.height(), 1)
     gluPerspective(self._fovy, float(self.width()) / float(height), self._near, self._far)
     self.updateGL()
Пример #29
0
 def set_projection(self, near, far, fovy):
     self._near = near
     self._far = far
     self._fovy = fovy
     self.makeCurrent()
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     height = max(self.height(), 1)
     gluPerspective(self._fovy, float(self.width()) / float(height), self._near, self._far)
     self.updateGL()
Пример #30
0
    def render_me(self):
        glColor3f(1, 1, 1)

        glLoadIdentity()

        glTranslate(self.position[0], self.position[1], self.position[2])

        glutSolidCube(self.side_size)

        glLoadIdentity()
Пример #31
0
 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()
Пример #32
0
 def iniciar_renderizado(self):
     """Acciones posteriores al renderizado de objetos."""
     self.fbos[0].usar()
     #glClearColor(*self.capa.escena.color)#0.) para fondo transparente
     glClear(GL_COLOR_BUFFER_BIT) #| GL_DEPTH_BUFFER_BIT)
     # Transformación de la cámara
     glLoadIdentity()
     glScalef(self.acerc, self.acerc, 0.)
     glTranslatef(-self.pos.x, -self.pos.y, 0.)
     glRotatef(-self.angulo, 0., 0., 1.)
Пример #33
0
def init():
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glShadeModel(GL_FLAT)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    # glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 100.0);
    gluPerspective(60, 1, 0, 100)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslated(0, -5, -20)
Пример #34
0
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()
Пример #35
0
 def ViewportSetup(self):
     xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
     aspect_ratio = float(xSize) / float(ySize)
     self.aspect = aspect_ratio
     # set up the projection matrix
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     glViewport(0, 0, xSize, ySize)
     gluPerspective(self.fovy, self.aspect, self.near, self.far)
     # postcondition: matrix mode is modelview
     glMatrixMode(GL_MODELVIEW)
Пример #36
0
def start():
    global Xdisp
    global Zdisp
    global Ydisp
    global Rotate
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    Zdisp = 0
    Xdisp = 0
    Ydisp = 0
    Rotate = 0
Пример #37
0
    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)
Пример #38
0
    def idle_light_animation_func(self):

        if self.vertical_rotation:
            self.theta_light_angle += 1
        else:
            self.phi_light_angle += 1

        self.draw_light_source()

        glLoadIdentity()
        glutPostRedisplay()
Пример #39
0
 def resize_window(self):
     pygame.display.set_mode(
         (self.W, self.H),
         pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     gluOrtho2D(0, self.W, self.H, 0)
     glViewport(0, 0, self.W, self.H)
     # gluOrtho2D(self.L * (self.W / self.H), self.R * (self.W / self.H), self.B, self.T)
     # gluOrtho2D(self.L, self.R, self.B, self.T)
     pygame.display.flip()
Пример #40
0
 def push(self):
     glMatrixMode(GL_PROJECTION)
     glPushMatrix()
     glLoadIdentity()
     gluPerspective(self.fov, self.aspect, 0.1, 200000.0)
     glTranslatef(*self.distance)
     glRotatef(0, 1, 0, 0)
     glRotatef(self.pitch, 1, 0, 0)
     glRotatef(self.roll, 0, 1, 0)
     glMatrixMode(GL_MODELVIEW)
     glPushMatrix()
Пример #41
0
    def initializeGL(self):
        glClearColor(*self.color_background)
        glClearDepth(1.0)
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glMatrixMode(GL_MODELVIEW)
Пример #42
0
    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()
Пример #43
0
    def initializeGL(self):
        '''
        Initialize GL
        '''

        #set viewing projection
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClearDepth(1.0)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(40.0, 1.0, 1.0, 30.0)
Пример #44
0
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()
Пример #45
0
 def initializeGL(self):             
     # TODO: correct background color
     glClearColor(*self.color_background)    
     glClearDepth(1.0)                   
     glDepthFunc(GL_LESS)                
     glEnable(GL_DEPTH_TEST)             
     glShadeModel(GL_SMOOTH)             
     
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()                    
 
     glMatrixMode(GL_MODELVIEW)
Пример #46
0
 def rotate(self, axis, angle):
     # rotate the object
     self.makeCurrent()
     glMatrixMode(GL_MODELVIEW)
     glLoadIdentity()
     t = [self._modelview_matrix[3][0], self._modelview_matrix[3][1], self._modelview_matrix[3][2]]
     glTranslatef(t[0], t[1], t[2])
     glRotated(angle, axis[0], axis[1], axis[2])
     glTranslatef(-t[0], -t[1], -t[2])
     glMultMatrixd(self._modelview_matrix)
     # update _modelview_matrix
     self._modelview_matrix = glGetDoublev(GL_MODELVIEW_MATRIX)
Пример #47
0
 def rotate(self, axis, angle):
     # rotate the object
     self.makeCurrent()
     glMatrixMode(GL_MODELVIEW)
     glLoadIdentity()
     t = [self._modelview_matrix[3][0], self._modelview_matrix[3][1], self._modelview_matrix[3][2]]
     glTranslatef(t[0], t[1], t[2])
     glRotated(angle, axis[0], axis[1], axis[2])
     glTranslatef(-t[0], -t[1], -t[2])
     glMultMatrixd(self._modelview_matrix)
     # update _modelview_matrix
     self._modelview_matrix = glGetDoublev(GL_MODELVIEW_MATRIX)
Пример #48
0
def init(): 
    glClearColor (0.0, 0.0, 0.0, 0.0)
    glShadeModel (GL_FLAT)
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    # glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 100.0);
    gluPerspective(60,1,0,100)
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity()
    glTranslated(0, Y_OFF, Z_OFF)
    global totDepth
    totDepth += Z_OFF
Пример #49
0
    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)
Пример #50
0
    def init_view(self):
        """ initialize the projection matrix """
        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
        aspect_ratio = float(xSize) / float(ySize)

        # load the projection matrix. Always the same
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glViewport(0, 0, xSize, ySize)
        gluPerspective(70, aspect_ratio, 0.1, 1000.0)
        glTranslated(0, 0, -15)
Пример #51
0
    def get_ray(self, x, y):
        self.init_view()

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        start = numpy.array(gluUnProject(x, y, 0.001))
        end = numpy.array(gluUnProject(x, y, 0.999))
        direction = end - start
        direction = direction / norm(direction)

        return (start, direction)
Пример #52
0
 def initGL(self):
     """
     initialize GL
     """
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     gluOrtho2D(
         self.clipping_area[0],
         self.clipping_area[1],
         self.clipping_area[2],
         self.clipping_area[3],
     )
Пример #53
0
    def paintGL(self):
        if self.parent.ipcon == None:
            return

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Move Right And Into The Screen
        glLoadIdentity()
        glTranslatef(0.0, 0.0, -5.0)
        glMultMatrixf(self.m)

        glCallList(self.display_list)
Пример #54
0
    def paintGL(self):
        if self.parent.ipcon == None:
            return

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Move Right And Into The Screen
        glLoadIdentity()
        glTranslatef(0.0, 0.0, -5.0)
        glMultMatrixf(self.m)

        glCallList(self.display_list)
Пример #55
0
def resizewin(width, height):
    """
    For resizing window
    """
    if height == 0:
        height = 1
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, 1.0 * width / height, 0.1, 100.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
Пример #56
0
    def display(self):
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        gluLookAt(0.0, 240.0, 1000.0, 0.0, 240.0, 0.0, 0.0, 1.0, 0.0)
        glClear(GL_COLOR_BUFFER_BIT)

        for i in self.fountains:
            i.life -= 1
            i.init()
            i.update()

        glutPostRedisplay()
        glutSwapBuffers()
Пример #57
0
    def opgl_move_to_pose(self, from_fixed_frame: bool = True):
        if from_fixed_frame:
            # Reset init view
            glLoadIdentity()

        # Translate to the right position
        glTranslatef(self.pose.position[0], self.pose.position[1],
                     self.pose.position[2])

        # Rotate to the right orientation
        glRotatef(self.pose.orientation.get_theta(rad=False),
                  self.pose.orientation[1], self.pose.orientation[2],
                  self.pose.orientation[3])
Пример #58
0
    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, GL_RGBA, w, h, 0, GL_RGBA, 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
Пример #59
0
    def set_perspective(self, fovy):
        """
        Set the perspective view
        """
        # Calculate aspect
        aspect = self.width / self.height

        # Make changes to projection matrix
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # Set the perspective accordingly
        gluPerspective(fovy, aspect, 0.1, 10.0)

        self.matrix = glGetFloatv(GL_PROJECTION_MATRIX)
Пример #60
0
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()