Ejemplo n.º 1
0
Archivo: View.py Proyecto: char-lie/mfm
    def __init__(self, size):
        """Initialize viewport with initial Face rotation and position."""
        self.__size = size

        self.__height, self.__width = self.__size
        self.__output_image = zeros(self.__width * self.__height * 4,
                                    dtype='f')

        self.__light = None
        self.__face = None
        self.__face_vertices = None
        self.__model_matrix = zeros((4, 4), dtype='f')
        self.__light_matrix = zeros((4, 4), dtype='f')

        self.__init_display()
        self.__enable_depth_test()

        glEnableClientState(GL_COLOR_ARRAY)
        glEnableClientState(GL_VERTEX_ARRAY)

        glClearColor(1., 1., 1., 0.)

        self.__sh = ShadersHelper(['face.vert', 'depth.vert'],
                                  ['face.frag', 'depth.frag'], 2, 1)

        glutDisplayFunc(self.__display)
        self.__callback = None
        self.__synchronous = False

        self.__sh.add_attribute(0, array([]), 'face_vertices')
        self.__sh.add_attribute(1, array([]), 'normal_vector')
        self.__sh.bind_buffer()
        self.__sh.use_shaders()
        self.__sh.link_texture('depth_map', 0)
        self.__sh.bind_depth_texture(self.__size)
Ejemplo n.º 2
0
 def on_draw(self):
     glClearColor(*self._clear_color)
     self.clear()
     self._draw_content()
     self._batch.draw()
     self.invalid = False
     self._legacy_invalid = False
Ejemplo n.º 3
0
    def set_background_color(self, color):
        '''
        '''
        if len(color) == 3:
            color += (1,)

        glClearColor(*color)
Ejemplo n.º 4
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()
Ejemplo n.º 5
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()
Ejemplo n.º 6
0
    def drawBackgroundGL(self, painter, rect):
        painter.beginNativePainting()
        
        #This will clear the screen, but also introduce flickering
        glClearColor(0.0, 1.0, 0.0, 1.0);
        glClear(GL_COLOR_BUFFER_BIT);
        
        #update the textures of those patches that were updated
        for t in self._updatableTiles:
            patch = self.imagePatches[t][self._numLayers]
            if patch.texture > -1:
                self._glWidget.deleteTexture(patch.texture)
            patch.texture = self._glWidget.bindTexture(patch.image)
            #see 'backingstore' example by Ariya Hidayat
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
            #this ensures a seamless transition between tiles
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
        self._updatableTiles = []
        
        drawnTiles = 0
        for patches in self.imagePatches:
            patch = patches[self._numLayers]
            if not patch.rectF.intersect(rect): continue
            patch.drawTexture()
            drawnTiles +=1

        #print "ImageView2D.drawBackgroundGL: drew %d of %d tiles" % (drawnTiles, len(self.imagePatches))
        painter.endNativePainting()
Ejemplo n.º 7
0
    def Display(self):
        """ A default display. Which clears the color buffer and depth buffer.
        """

	self._debug("running display", 4)
	glClearColor(1.0, 1.0, 1.0, 0.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
Ejemplo n.º 8
0
    def activateOpenGL( self, qglwidget ):
        self._useGL = True
        self._glWidget = qglwidget

        glDisable(GL_DEPTH_TEST)
        glEnable(GL_TEXTURE_2D)
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glClear(GL_COLOR_BUFFER_BIT)
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    def _draw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glClearColor(0.0, 0.0, 0.0, 1.0)

        view_mat = translation_matrix((0, 0, -self.dist))
        view_mat = view_mat.dot(self.ball.matrix())
        view_mat = view_mat.dot(scale_matrix(self.zoom))
        self.VMatrix = view_mat
        self.draw_hook()
        OpenGL.GLUT.glutSwapBuffers()
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
    def setup(self):
        """Setup OpenGL."""

        self.print_gl_info()

        glClearColor(1.0, 1.0, 1.0, 0.0)

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)

        self.print_gl_settings()
Ejemplo n.º 15
0
 def change_background_color(self):
     background_color =  self.params['background_color']
     try:
         self.glview.setBackgroundColor(background_color)
     except:
         #~ #FIXME this is buggy in pyqtgrap0.9.8
         bgcolor = pg.mkColor(QtGui.QColor(background_color))
         glClearColor(bgcolor.red()/255., bgcolor.green()/255., bgcolor.blue()/255., 1.0)
         glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT )
         self.glview.paintGL()
         self.glview.update()
Ejemplo n.º 16
0
    def draw_all(self):
        glViewport(0, 0, *self.fb_size)

        self.update_vector_uniform('fb_size', self.fb_size)

        glClearColor(*self.clear_color.as_tuple())
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glEnable(GL_DEPTH_TEST)

        for comm in self._draw_commands.values():
            self._draw_one(comm)
Ejemplo n.º 17
0
    def init_opengl(self, width, height, x, y):
        glutInit()
        glutInitWindowPosition(x, y)
        glutInitWindowSize(width, height)
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE)
        glutCreateWindow("Rainbow Alga")
        glutDisplayFunc(self.render)
        glutIdleFunc(self.render)
        glutReshapeFunc(self.resize)

        glutMouseFunc(self.mouse)
        glutMotionFunc(self.drag)
        glutKeyboardFunc(self.keyboard)
        glutSpecialFunc(self.special_keyboard)

        glClearDepth(1.0)
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 3000)
        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)


        # Lighting
        light_ambient = (0.0, 0.0, 0.0, 1.0)
        light_diffuse = (1.0, 1.0, 1.0, 1.0)
        light_specular = (1.0, 1.0, 1.0, 1.0)
        light_position = (-100.0, 100.0, 100.0, 0.0)

        mat_ambient = (0.7, 0.7, 0.7, 1.0)
        mat_diffuse = (0.8, 0.8, 0.8, 1.0)
        mat_specular = (1.0, 1.0, 1.0, 1.0)
        high_shininess = (100)

        glEnable(GL_LIGHT0)
        glEnable(GL_NORMALIZE)
        glEnable(GL_COLOR_MATERIAL)
        glEnable(GL_LIGHTING)

        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient)
        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse)
        glLightfv(GL_LIGHT0, GL_SPECULAR,  light_specular)
        glLightfv(GL_LIGHT0, GL_POSITION, light_position)

        glMaterialfv(GL_FRONT, GL_AMBIENT,   mat_ambient)
        glMaterialfv(GL_FRONT, GL_DIFFUSE,   mat_diffuse)
        glMaterialfv(GL_FRONT, GL_SPECULAR,  mat_specular)
        glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess)

        # Transparency
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Ejemplo n.º 18
0
 def __update(self, widget):
     gldrawable = widget.get_gl_drawable()
     glcontext = widget.get_gl_context()
     # OpenGL begin.
     if not gldrawable.gl_begin(glcontext):
         return
     glClearColor(0.0, 0.0, 0.0, 1.0)
     glClearDepth(1.0)
     glDepthFunc(GL_LESS)    # The type of depth test to do
     glEnable(GL_DEPTH_TEST | GL_LINE_SMOOTH) # Turn on depth testing.
     gldrawable.gl_end()
     # OpenGL end
     return
Ejemplo n.º 19
0
Archivo: fbo.py Proyecto: hansent/pymt
    def clear(self):
        """Clear framebuffer.

        .. warning::
            Must be called inside bind()/release() of FBO !
        """
        assert self._is_bind == True

        glClearColor(*self.clear_color)
        if self.with_depthbuffer:
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        else:
            glClear(GL_COLOR_BUFFER_BIT)
Ejemplo n.º 20
0
def draw_triangle():
    #print "Draw Triangle"
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT)
    #return ###
    glBegin(GL_TRIANGLES)
    glColor3f(1.0, 0.0, 0.0)
    glVertex2i(0, 1)
    glColor3f(0.0, 1.0, 0.0)
    glVertex2i(-1, -1)
    glColor3f(0.0, 0.0, 1.0)
    glVertex2i(1, -1)
    glEnd()
Ejemplo n.º 21
0
    def present_fbo(self, drawable):
        self.gl_marker("Presenting FBO on screen for drawable %s" % drawable)
        assert drawable
        # Change state to target screen instead of our FBO
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        if self._has_alpha:
            # transparent background:
            glClearColor(0.0, 0.0, 0.0, 0.0)
        else:
            # plain white no alpha:
            glClearColor(1.0, 1.0, 1.0, 1.0)

        # Draw FBO texture on screen
        self.set_rgb_paint_state()

        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
        if self._has_alpha:
            # support alpha channel if present:
            glEnable(GL_BLEND)
            glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD)
            glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO)

        w, h = self.size
        glBegin(GL_QUADS)
        glTexCoord2i(0, h)
        glVertex2i(0, 0)
        glTexCoord2i(0, 0)
        glVertex2i(0, h)
        glTexCoord2i(w, 0)
        glVertex2i(w, h)
        glTexCoord2i(w, h)
        glVertex2i(w, 0)
        glEnd()

        # Show the backbuffer on screen
        if drawable.is_double_buffered():
            debug("%s.present_fbo() swapping buffers now", self)
            drawable.swap_buffers()
            # Clear the new backbuffer to illustrate that its contents are undefined
            glClear(GL_COLOR_BUFFER_BIT)
        else:
            glFlush()
        if self._has_alpha:
            glDisable(GL_BLEND)
        self.gl_frame_terminator()

        self.unset_rgb_paint_state()
        glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
        debug("%s.present_fbo() done", self)
Ejemplo n.º 22
0
    def gl_setup(self, width, height):
        """Private."""
        # cut out invisible faces
        glEnable(GL_CULL_FACE)
        glCullFace(GL_BACK)

        # enable depth buffer
        glEnable(GL_DEPTH_TEST)

        # enable alpha-blending
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        # clear to black
        glClearColor(0.3, 0.3, 0.3, 1)
Ejemplo n.º 23
0
	def render(self):
		'''
		Render the geometry for the scene
		'''
		# Clear the buffer
		glClearColor(0, 0, 0, 1)
		glClear(GL_COLOR_BUFFER_BIT);
		
		# render the stage
		super(MyStage, self).render()
		
		# Swap GLUT buffers
		GLUT.glutSwapBuffers()
		
		# Print FPS every 5 seconds
		now = time()
Ejemplo n.º 24
0
 def _initGL(self, extraArgs):
     """initializes OpenGL and creates the Window"""
     glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
     glutInitWindowSize(self.size, self.size)
     glutInitWindowPosition(self.initx, self.inity)
     glutInit(extraArgs.split(" "))
     glutCreateWindow(VERSIONSTRING.encode("ascii"))
     glutDisplayFunc(self.Draw)
     glutIdleFunc(glutPostRedisplay)
     glutReshapeFunc(self.Reshape)
     glutKeyboardFunc(self.HandleKeys)
     glutSpecialFunc(self.HandleKeys)
     glutMouseFunc(self.HandleMouse)
     glClearColor(*(self.bgcolor + [0.0]))
     glEnable(GL_LINE_SMOOTH)
     glLineWidth(1.3)
    def clear_and_draw_background(self, other_glClear_buffer_bits): #bruce 080910 de-inlined this
        """
        @param other_glClear_buffer_bits: whichever of GL_DEPTH_BUFFER_BIT |
                                          GL_STENCIL_BUFFER_BIT you want to
                                          pass to glClear, in addition to
                                          GL_COLOR_BUFFER_BIT, which we
                                          pass if needed
        """
        c = self.backgroundColor
            # note: self.backgroundGradient and self.backgroundColor
            # are used and maintained entirely in this mixin class, as of 080910
            # (unless other files access them as public attrs -- not reviewed)

        glClearColor(c[0], c[1], c[2], 0.0)
        self.fogColor = (c[0], c[1], c[2], 1.0) # piotr 080515        
        del c

        glClear(GL_COLOR_BUFFER_BIT | other_glClear_buffer_bits )
            # potential optims:
            # - if stencil clear is expensive, we could do it only when needed [bruce ca. 050615]
            # - if color clear is expensive, we needn't do it when self.backgroundGradient 

        self.kluge_reset_texture_mode_to_work_around_renderText_bug()
        
        if self.backgroundGradient:
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()

            _bgGradient = self.background_gradient_corner_colors()

            drawFullWindow(_bgGradient)
            # fogColor is an average of the gradient components
            # piotr 080515
            self.fogColor = \
                (0.25 * (_bgGradient[0][0] + _bgGradient[1][0] + _bgGradient[2][0] + _bgGradient[3][0]), \
                 0.25 * (_bgGradient[0][1] + _bgGradient[1][1] + _bgGradient[2][1] + _bgGradient[3][1]), \
                 0.25 * (_bgGradient[0][2] + _bgGradient[1][2] + _bgGradient[2][2] + _bgGradient[3][2]))
            
            # Note: it would be possible to optimize by not clearing the color buffer
            # when we'll call drawFullWindow, if we first cleared depth buffer (or got
            # drawFullWindow to ignore it and effectively clear it by writing its own
            # depths into it everywhere, if that's possible). [bruce 070913 comment]

        return
Ejemplo n.º 26
0
    def init_opengl(self):
        """ initialize the opengl settings to render the scene """
        self.inverseModelView = numpy.identity(4)
        self.modelView = numpy.identity(4)

        glEnable(GL_CULL_FACE)
        glCullFace(GL_BACK)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)

        glEnable(GL_LIGHT0)
        glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0))
        glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1))

        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        glEnable(GL_COLOR_MATERIAL)
        glClearColor(1.0, 1.0, 1.0, 0.0)
Ejemplo n.º 27
0
    def OnRender(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        self.model = pyrr.Matrix44.from_translation(
            pyrr.Vector3([self.translation1[0], self.translation1[1], 0]))
        self.mvp = self.proj * self.view * self.model
        self.shader.Bind()
        self.shader.SetUniform1i("u_Texture", 0)
        self.shader.SetUniformMat4f("u_MVP", self.mvp)
        self.renderer.Draw(self.va, self.ib, self.shader)

        self.model = pyrr.Matrix44.from_translation(
            pyrr.Vector3([self.translation2[0], self.translation2[1], 0]))
        self.mvp = self.proj * self.view * self.model
        self.shader.SetUniformMat4f("u_MVP", self.mvp)
        self.renderer.Draw(self.va, self.ib, self.shader)
Ejemplo n.º 28
0
    def init_opengl(self) -> bool:
        """Initialize and set OpenGL capabilities.

        Returns:
            True if initialized without error, False otherwise.
        """
        if self._gl_initialized:
            return True

        if self._context is None:
            return False

        glClearColor(*self.background_color)
        glClearDepth(1.0)

        glDepthFunc(GL_LESS)

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        # set antialiasing
        glEnable(GL_LINE_SMOOTH)

        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        glEnable(GL_COLOR_MATERIAL)
        glEnable(GL_MULTISAMPLE)
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        self.create_vaos()

        # compile shader programs
        self._shaders['default'] = shaderlib.compile_shader(*shaderlib.default)
        self._shaders['single_color'] = shaderlib.compile_shader(
            *shaderlib.single_color)
        self._shaders['instanced_model_color'] = shaderlib.compile_shader(
            *shaderlib.instanced_model_color)
        self._shaders['instanced_picking'] = shaderlib.compile_shader(
            *shaderlib.instanced_picking)
        self._shaders['diffuse'] = shaderlib.compile_shader(*shaderlib.diffuse)
        self._shaders['solid'] = shaderlib.compile_shader(*shaderlib.solid)

        self._gl_initialized = True
        return True
Ejemplo n.º 29
0
    def init_opengl(self):
        """ initialize the opengl settings to render the scene """
        self.inverseModelView = numpy.identity(4)
        self.modelView = numpy.identity(4)

        glEnable(GL_CULL_FACE)
        glCullFace(GL_BACK)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)

        glEnable(GL_LIGHT0)
        # put some initial lighting
        glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0))  
        glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1))

        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        glEnable(GL_COLOR_MATERIAL)
        glClearColor(0.4, 0.4, 0.4, 0.0)
Ejemplo n.º 30
0
def init():
    width = mosaic_factory.ratio * size
    height = size
    print "loading textures:"
    for i, img in enumerate(mosaic_factory.images):
        print " {0}/{1}".format(i + 1, len(mosaic_factory.images))
        textures[img] = load_texture(img.get_image())
        generate_picture_display_list(img, width, height)
    print "generating mosaic display lists:"
    for i, img in enumerate(mosaic_factory.images):
        print " {0}/{1}".format(i + 1, len(mosaic_factory.images))
        generate_mosaic_display_list(img)

    glEnable(GL_TEXTURE_2D)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glShadeModel(GL_FLAT)
Ejemplo n.º 31
0
def init():
    width = mosaic_factory.ratio * size
    height = size
    print "loading textures:"
    for i, img in enumerate(mosaic_factory.images):
        print " {0}/{1}".format(i + 1, len(mosaic_factory.images))
        textures[img] = load_texture(img.get_image())
        generate_picture_display_list(img, width, height)
    print "generating mosaic display lists:"
    for i, img in enumerate(mosaic_factory.images):
        print " {0}/{1}".format(i + 1, len(mosaic_factory.images))
        generate_mosaic_display_list(img)

    glEnable(GL_TEXTURE_2D)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glShadeModel(GL_FLAT)
Ejemplo n.º 32
0
def debug_info(setup):
    from OpenGL.GL import (
        glClearColor,
        glClear,
        GL_COLOR_BUFFER_BIT,
        GL_DEPTH_BUFFER_BIT,
        glGetString,
        GL_VENDOR,
        GL_EXTENSIONS,
        glFinish,
    )

    display, ctx, surface = setup
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    log.info("Vendor: %s", glGetString(GL_VENDOR))
    log.info("Extensions: %s", glGetString(GL_EXTENSIONS))
    glFinish()
Ejemplo n.º 33
0
    def _loop(self):
        frame_count = 0
        fps_now = time.time()
        elapsed_now = time.time()
        while not glfw.window_should_close(self._window):
            self._key_poller.poll_keys(self._window)
            self._mouse_poller._poll_mouse(self._window)

            self._spaces.push()
            self._spaces.tint = WHITE

            glClearColor(*self._color)
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

            now = time.time()
            self._elapsed_time = (now - elapsed_now)
            elapsed_now = now

            # draw call
            if self._handler is not None:
                self._handler(self)

            # render last batch of rects (if any)
            self._quad.draw_batch_if_started(self._spaces)

            # Swap front and back buffers
            glfw.swap_buffers(self._window)

            # Poll for and process events
            glfw.poll_events()

            frame_count += 1
            fps_time_delta = (time.time() - fps_now)
            self.fps = frame_count / fps_time_delta

            if fps_time_delta >= 1:
                title = f'{self.title} @ {self.fps:.0f} FPS'
                glfw.set_window_title(self._window, title)
                fps_now = time.time()
                frame_count = 0

        glfw.terminate()
Ejemplo n.º 34
0
    def __init__(self, winname, size=(800, 600), display_func=None, resize_func=None):
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
        glutInitWindowSize(size[0], size[1])
        self._win_id = glutCreateWindow(winname.encode('ascii'))
        self.display_func = display_func
        self.resize_func = resize_func
        self.width = size[0]
        self.height = size[1]

        if display_func is not None:
            display_func = _display_wrapper(display_func)
            glutDisplayFunc(display_func)
            glutIdleFunc(display_func)

        if resize_func is not None:
            resize_func = _resize_wrapper(self, resize_func)
            glutReshapeFunc(resize_func)

        glClearColor(0, 0, 0, 0)
Ejemplo n.º 35
0
    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()
Ejemplo n.º 36
0
    def openglSetup(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glEnable(GL.GL_DEPTH_TEST) 
        glEnable(GL.GL_COLOR_MATERIAL)

        glViewport (0, 0, self.surf.get_width(), self.surf.get_height())
        glMatrixMode (GL.GL_PROJECTION)
        glLoadIdentity ()
        glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)
        glMatrixMode (GL.GL_MODELVIEW)

        self.cardList = glGenLists(1)
        glNewList(self.cardList, GL.GL_COMPILE)
        glColor3f(1,1,1)
        with begin(GL.GL_QUADS):
            glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, -1.0,  0.0)
            glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, -1.0,  0.0)
            glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, 1.0,  0.0)
            glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, 1.0,  0.0)
        glEndList()
Ejemplo n.º 37
0
    def paintGL(self, region=None, viewport=None, useItemNames=False):
        """
        viewport specifies the arguments to glViewport. If None, then we use self.opts['viewport']
        region specifies the sub-region of self.opts['viewport'] that should be rendered.
        Note that we may use viewport != self.opts['viewport'] when exporting.
        """
        if viewport is None:
            glViewport(*self.getViewport())
        else:
            glViewport(*viewport)

        bgcolor = self.props.background_color
        glClearColor(*bgcolor)
        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
        self.drawItemTree(useItemNames=useItemNames)

        self.frame_count += 1
        fps = self.frame_count / (self.frame_time.elapsed() / 1000.0)
        if CONFIG.debug:
            _log.debug("FPS: {}".format(fps))
Ejemplo n.º 38
0
    def Draw(self):
        glClearColor(background_color()[0],
                     background_color()[1],
                     background_color()[2], 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        if not self.graph:
            return

        self.graph.scale(self.window_width, self.window_height)
        selfrefs = []
        for node in self.graph.nodes:
            for edge in node.children:
                if hasattr(self.graph, 'bezier') and self.graph.bezier:
                    (x1, y1, x2, y2) = draw_bezier_edge(node, edge)
                else:
                    far_node = edge.get_far(node)
                    (x1, y1, x2, y2) = (node.x, node.y, far_node.x, far_node.y)
                    draw_regular_line(x1, y1, x2, y2)

                if node != edge.get_far(node):
                    draw_arrowhead(x1, y1, x2, y2, 4, 16, 15, 0.5)
                    draw_arrowhead(x1, y1, x2, y2, 4, 14, 15, 0.7)
                    draw_arrowhead(x1, y1, x2, y2, 4, 12, 13, 1.0)
                else:
                    selfrefs.append(node)

        for node in self.graph.nodes:
            if node in selfrefs:
                draw_selfref_halo(node.x, node.y)

            if len(node.term.redexpositions) == 0:  # Normal form
                draw_nf_node(node.x, node.y)
            elif node.name == "N0" and self.show_start_node:
                draw_start_node(node.x, node.y)
            elif (node is self.graph.newest) and self.show_newest_node:
                draw_newest_node(node.x, node.y)
            else:
                draw_regular_node(node.x, node.y)

        self.output_graph_status(self)
        self.SwapBuffers()
Ejemplo n.º 39
0
    def display(self):
        """
        Callback function, handler for window re-paint
        """
        # Set background color (clear background)
        glClearColor(self.background_color[0], self.background_color[1],
                     self.background_color[2], 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        # Display background
        for shape in self.background.shapes:
            self.draw_geometric2d(shape)

        # Display objects
        if len(self.data) > 0:
            idx = self.time_count % len(self.data)
            for shape in self.data[idx].shapes:
                self.draw_geometric2d(shape)

        self.time_count += 1
        glFlush()
    def paintGL(self):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(self.zoom, -self.zoom, -self.zoom, self.zoom, -5000, 5000)
        arriba = 1
        if self.theta == 360:
            arriba = -1
        gluLookAt(self.x, self.y, self.z, self.desviacion_x, self.desviacion_y,
                  self.desviacion_z, 0, arriba, 0)

        glMatrixMode(GL_MODELVIEW)
        if self.programa.modo_oscuro:
            glClearColor(0.3, 0.3, 0.3, 0)
        else:
            glClearColor(1, 1, 1, 0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadMatrixf(self.m)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        self.ordenar_elementos()
        self.update()
Ejemplo n.º 41
0
    def initializeGL(self):
        # We call this right after our OpenGL window is created.
        glClearColor(1.0, 1.0, 1.0, 1.0)
        glClearDepth(1.0)
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)

        glEnable(GL_NORMALIZE)
        light_position = (0., 0., 1., 0.)
        white_light = (1., 1., 1., 0.501)
        d_light = (1., 1., 1., 0.01)
        spec = (1., 1., 1., 0.08)
        glLightfv(GL_LIGHT0, GL_POSITION, light_position)
        glLightfv(GL_LIGHT0, GL_AMBIENT, white_light)
        #glLightfv(GL_LIGHT0, GL_DIFFUSE,  d_light)
        glLightfv(GL_LIGHT0, GL_SPECULAR, spec)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        #glBlendFunc(GL_SRC_ALPHA,GL_ONE)
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        glEnable(GL_COLOR_MATERIAL)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        gluPerspective(
            45.0,
            float(self.size().height()) / float(self.size().width()), 0.1,
            1000000.0)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        self.rotation = [0.0, 0.0]
        self.mesh.prepDraw()
Ejemplo n.º 42
0
    def _on_realize(self, *args):
        """
        Called at the creation of the drawing area.

        Sets up the OpenGL rendering context.
        """
        print("_on_realize(%s)" % str(args))
        gldrawable = self.get_gl_drawable()
        glcontext = self.get_gl_context()
        if not gldrawable.gl_begin(glcontext):
            return

        self._set_view(WIDTH / float(HEIGHT))

        glEnable(GL_TEXTURE_RECTANGLE_ARB)  # 2D)
        glEnable(GL_BLEND)
        glShadeModel(GL_SMOOTH)
        glClearColor(0.0, 0.0, 0.0, 1.0)  # black background
        glColor4f(1.0, 1.0, 1.0, 1.0)  # default color is white
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        gldrawable.gl_end()
Ejemplo n.º 43
0
    def initialize(self, display_function: callable):
        """Initialze the OpenGL display parts of the Window.

        Warning:
            Must be called on the same thread as OpenGL (usually the main thread),
        """

        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)

        glutInitWindowSize(self.width, self.height)
        glutInitWindowPosition(*self._pos)
        self._gl_window = glutCreateWindow(self._window_name)

        glClearColor(0, 0, 0, 0)
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)

        glutIdleFunc(self._idle)
        glutVisibilityFunc(self._visible)
        glutReshapeFunc(self._reshape)

        glutDisplayFunc(display_function)
Ejemplo n.º 44
0
    def init_opengl(self):
        """A general OpenGL initialization function.  Sets all of the initial parameters.

        We call this right after our OpenGL window is created.
        """

        glClearColor(0.0, 0.0, 0.0,
                     1.0)  # This Will Clear The Background Color To Black
        glClearDepth(1.0)  # Enables Clearing Of The Depth Buffer
        glDepthFunc(GL_LEQUAL)  # The Type Of Depth Test To Do
        glEnable(GL_DEPTH_TEST)  # Enables Depth Testing
        glShadeModel(GL_SMOOTH)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT,
               GL_NICEST)  # Really Nice Perspective Calculations

        glEnable(GL_LIGHT0)
        glEnable(GL_LIGHTING)

        glEnable(GL_COLOR_MATERIAL)
        glEnable(
            GL_NORMALIZE)  # important since we rescale the modelview matrix

        return True
Ejemplo n.º 45
0
    def openglSetup(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glEnable(GL.GL_DEPTH_TEST)
        glEnable(GL.GL_COLOR_MATERIAL)

        glViewport(0, 0, self.surf.get_width(), self.surf.get_height())
        glMatrixMode(GL.GL_PROJECTION)
        glLoadIdentity()
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)
        glMatrixMode(GL.GL_MODELVIEW)

        self.cardList = glGenLists(1)
        glNewList(self.cardList, GL.GL_COMPILE)
        glColor3f(1, 1, 1)
        with begin(GL.GL_QUADS):
            glTexCoord2f(0.0, 1.0)
            glVertex3f(-1.0, -1.0, 0.0)
            glTexCoord2f(1.0, 1.0)
            glVertex3f(1.0, -1.0, 0.0)
            glTexCoord2f(1.0, 0.0)
            glVertex3f(1.0, 1.0, 0.0)
            glTexCoord2f(0.0, 0.0)
            glVertex3f(-1.0, 1.0, 0.0)
        glEndList()
Ejemplo n.º 46
0
    def initializeGL(self):
        glClearColor(0.85, 0.85, 0.85, 1.0)
        glClearDepth(1.0)
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)

        glShadeModel(GL_SMOOTH)
        glEnable(GL_NORMALIZE)
        glEnable(GL_COLOR_MATERIAL)
        glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)
        glLightfv(GL_LIGHT0, GL_POSITION, (0.0, 0.0, 1.0, 0.0))
        glEnable(GL_LIGHT0)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        self.display_list = glGenLists(1)
        glNewList(self.display_list, GL_COMPILE)
        glScalef(0.5, 0.5, 0.5)

        glEnable(GL_LIGHTING)

        # board
        glColor3f(0.0, 0.0, 0.0)
        self.draw_cuboid(4.0, 4.0, 0.16)

        # USB connector
        glPushMatrix()
        glColor3f(0.5, 0.51, 0.58)
        glTranslatef(0.0, -1.6, 0.28)
        self.draw_cuboid(0.75, 0.9, 0.4)
        glPopMatrix()

        # right button
        glPushMatrix()
        glColor3f(0.5, 0.51, 0.58)
        glTranslatef(1.15, -1.85, 0.16)
        self.draw_cuboid(0.4, 0.3, 0.16)
        glColor3f(0.0, 0.0, 0.0)
        glTranslatef(0.0, -0.155, 0.025)
        self.draw_cuboid(0.18, 0.1, 0.08)
        glPopMatrix()

        # left button
        glPushMatrix()
        glColor3f(0.5, 0.51, 0.58)
        glTranslatef(-1.15, -1.85, 0.16)
        self.draw_cuboid(0.4, 0.3, 0.16)
        glColor3f(0.0, 0.0, 0.0)
        glTranslatef(0.0, -0.155, 0.025)
        self.draw_cuboid(0.18, 0.1, 0.08)
        glPopMatrix()

        # left btb top
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glTranslatef(-1.65, 0.0, 0.38)
        self.draw_cuboid(0.5, 1.4, 0.6)
        glPopMatrix()

        # right btb top
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glTranslatef(1.65, 0.0, 0.38)
        self.draw_cuboid(0.5, 1.4, 0.6)
        glPopMatrix()

        # left btb bottom
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glTranslatef(-1.65, 0.0, -0.33)
        self.draw_cuboid(0.5, 1.4, 0.5)
        glPopMatrix()

        # right btb bottom
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glTranslatef(1.65, 0.0, -0.33)
        self.draw_cuboid(0.5, 1.4, 0.5)
        glPopMatrix()

        # left bricklet port
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glTranslatef(-0.85, 1.8, -0.23)
        self.draw_cuboid(1.2, 0.4, 0.3)
        glPopMatrix()

        # right bricklet port
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glTranslatef(0.85, 1.8, -0.23)
        self.draw_cuboid(1.2, 0.4, 0.3)
        glPopMatrix()

        # left direction LED
        glPushMatrix()
        glColor3f(0.0, 0.5, 0.0)
        glTranslatef(-1.05, 1.425, 0.115)
        self.draw_cuboid(0.1, 0.2, 0.07)
        glPopMatrix()

        # top direction LED
        glPushMatrix()
        glColor3f(0.0, 0.5, 0.0)
        glTranslatef(-0.675, 1.8, 0.115)
        self.draw_cuboid(0.2, 0.1, 0.07)
        glPopMatrix()

        # right direction LED
        glPushMatrix()
        glColor3f(0.0, 0.5, 0.0)
        glTranslatef(-0.3, 1.425, 0.115)
        self.draw_cuboid(0.1, 0.2, 0.07)
        glPopMatrix()

        # bottom direction LED
        glPushMatrix()
        glColor3f(0.0, 0.5, 0.0)
        glTranslatef(-0.675, 1.05, 0.115)
        self.draw_cuboid(0.2, 0.1, 0.07)
        glPopMatrix()

        # left y orientation LED
        glPushMatrix()
        glColor3f(0.0, 0.0, 1.0)
        glTranslatef(0.275, 1.7, 0.115)
        self.draw_cuboid(0.1, 0.2, 0.07)
        glPopMatrix()

        # right y orientation LED
        glPushMatrix()
        glColor3f(1.0, 0.0, 0.0)
        glTranslatef(0.425, 1.7, 0.115)
        self.draw_cuboid(0.1, 0.2, 0.07)
        glPopMatrix()

        # top z orientation LED
        glPushMatrix()
        glColor3f(1.0, 0.0, 0.0)
        glTranslatef(0.35, 1.15, 0.115)
        self.draw_cuboid(0.2, 0.1, 0.07)
        glPopMatrix()

        # bottom z orientation LED
        glPushMatrix()
        glColor3f(0.0, 0.0, 1.0)
        glTranslatef(0.35, 1.0, 0.115)
        self.draw_cuboid(0.2, 0.1, 0.07)
        glPopMatrix()

        # top x orientation LED
        glPushMatrix()
        glColor3f(1.0, 0.0, 0.0)
        glTranslatef(1.0, 1.15, 0.115)
        self.draw_cuboid(0.2, 0.1, 0.07)
        glPopMatrix()

        # bottom x orientation LED
        glPushMatrix()
        glColor3f(0.0, 0.0, 1.0)
        glTranslatef(1.0, 1.0, 0.115)
        self.draw_cuboid(0.2, 0.1, 0.07)
        glPopMatrix()

        # top alignment corner
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glBegin(GL_TRIANGLES)
        glNormal3f(0.0, 0.0, 1.0)
        glVertex3f(-2.0, -2.0, 0.081)
        glVertex3f(-1.1, -2.0, 0.081)
        glVertex3f(-2.0, -1.1, 0.081)
        glEnd()
        glPopMatrix()

        # bottom alignment corner
        glPushMatrix()
        glColor3f(1.0, 1.0, 1.0)
        glBegin(GL_TRIANGLES)
        glNormal3f(0.0, 0.0, -1.0)
        glVertex3f(-2.0, -2.0, -0.081)
        glVertex3f(-2.0, -1.1, -0.081)
        glVertex3f(-1.1, -2.0, -0.081)
        glEnd()
        glPopMatrix()

        glDisable(GL_LIGHTING)

        # axis
        glPushMatrix()
        glTranslatef(-2.3, -2.3, -0.38)
        glLineWidth(3.0)
        glBegin(GL_LINES)
        glColor3f(1, 0, 0)  # x axis is red
        glVertex3f(0, 0, 0)
        glVertex3f(3, 0, 0)
        glColor3f(0, 0.5, 0)  # y axis is green
        glVertex3f(0, 0, 0)
        glVertex3f(0, 3, 0)
        glColor3f(0, 0, 1)  # z axis is blue
        glVertex3f(0, 0, 0)
        glVertex3f(0, 0, 3)
        glEnd()
        glLineWidth(1.0)
        glPopMatrix()

        glEndList()
Ejemplo n.º 47
0
def player_drop(rec_dir, ipc_pub_url, ipc_sub_url, ipc_push_url, user_dir,
                app_version):
    # general imports
    import logging
    # networking
    import zmq
    import zmq_tools
    from time import sleep

    # zmq ipc setup
    zmq_ctx = zmq.Context()
    ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url)

    # log setup
    logging.getLogger("OpenGL").setLevel(logging.ERROR)
    logger = logging.getLogger()
    logger.handlers = []
    logger.setLevel(logging.INFO)
    logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url))
    # create logger for the context of this function
    logger = logging.getLogger(__name__)

    try:

        import glfw
        import gl_utils
        from OpenGL.GL import glClearColor
        from version_utils import VersionFormat
        from file_methods import Persistent_Dict
        from pyglui.pyfontstash import fontstash
        from pyglui.ui import get_roboto_font_path
        from player_methods import is_pupil_rec_dir, update_recording_to_recent

        def on_drop(window, count, paths):
            nonlocal rec_dir
            rec_dir = paths[0].decode('utf-8')

        if rec_dir:
            if not is_pupil_rec_dir(rec_dir):
                rec_dir = None
        # load session persistent settings
        session_settings = Persistent_Dict(
            os.path.join(user_dir, "user_settings_player"))
        if VersionFormat(session_settings.get("version",
                                              '0.0')) != app_version:
            logger.info(
                "Session setting are from a  different version of this app. I will not use those."
            )
            session_settings.clear()
        w, h = session_settings.get('window_size', (1280, 720))
        window_pos = session_settings.get('window_position',
                                          window_position_default)

        glfw.glfwInit()
        glfw.glfwWindowHint(glfw.GLFW_RESIZABLE, 0)
        window = glfw.glfwCreateWindow(w, h, 'Pupil Player')
        glfw.glfwWindowHint(glfw.GLFW_RESIZABLE, 1)

        glfw.glfwMakeContextCurrent(window)
        glfw.glfwSetWindowPos(window, window_pos[0], window_pos[1])
        glfw.glfwSetDropCallback(window, on_drop)

        glfont = fontstash.Context()
        glfont.add_font('roboto', get_roboto_font_path())
        glfont.set_align_string(v_align="center", h_align="middle")
        glfont.set_color_float((0.2, 0.2, 0.2, 0.9))
        gl_utils.basic_gl_setup()
        glClearColor(0.5, .5, 0.5, 0.0)
        text = 'Drop a recording directory onto this window.'
        tip = '(Tip: You can drop a recording directory onto the app icon.)'
        # text = "Please supply a Pupil recording directory as first arg when calling Pupil Player."
        while not glfw.glfwWindowShouldClose(window):

            fb_size = glfw.glfwGetFramebufferSize(window)
            hdpi_factor = float(fb_size[0] / glfw.glfwGetWindowSize(window)[0])
            gl_utils.adjust_gl_view(*fb_size)

            if rec_dir:
                if is_pupil_rec_dir(rec_dir):
                    logger.info(
                        "Starting new session with '{}'".format(rec_dir))
                    text = "Updating recording format."
                    tip = "This may take a while!"
                else:
                    logger.error(
                        "'{}' is not a valid pupil recording".format(rec_dir))
                    tip = "Oops! That was not a valid recording."
                    rec_dir = None

            gl_utils.clear_gl_screen()
            glfont.set_blur(10.5)
            glfont.set_color_float((0.0, 0.0, 0.0, 1.))
            glfont.set_size(w / 25. * hdpi_factor)
            glfont.draw_text(w / 2 * hdpi_factor, .3 * h * hdpi_factor, text)
            glfont.set_size(w / 30. * hdpi_factor)
            glfont.draw_text(w / 2 * hdpi_factor, .4 * h * hdpi_factor, tip)
            glfont.set_blur(0.96)
            glfont.set_color_float((1., 1., 1., 1.))
            glfont.set_size(w / 25. * hdpi_factor)
            glfont.draw_text(w / 2 * hdpi_factor, .3 * h * hdpi_factor, text)
            glfont.set_size(w / 30. * hdpi_factor)
            glfont.draw_text(w / 2 * hdpi_factor, .4 * h * hdpi_factor, tip)

            glfw.glfwSwapBuffers(window)

            if rec_dir:
                update_recording_to_recent(rec_dir)
                glfw.glfwSetWindowShouldClose(window, True)

            glfw.glfwPollEvents()

        session_settings['window_position'] = glfw.glfwGetWindowPos(window)
        session_settings.close()
        glfw.glfwDestroyWindow(window)
        if rec_dir:
            ipc_pub.notify({
                "subject": "player_process.should_start",
                "rec_dir": rec_dir
            })

    except:
        import traceback
        trace = traceback.format_exc()
        logger.error(
            'Process player_drop crashed with trace:\n{}'.format(trace))

    finally:
        sleep(1.0)
Ejemplo n.º 48
0
    def do_present_fbo(self):
        self.gl_marker("Presenting FBO on screen")
        # Change state to target screen instead of our FBO
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        if self._alpha_enabled:
            # transparent background:
            glClearColor(0.0, 0.0, 0.0, 0.0)
        else:
            # plain white no alpha:
            glClearColor(1.0, 1.0, 1.0, 1.0)

        # Draw FBO texture on screen
        self.set_rgb_paint_state()
        bw, bh = self.size
        ww, wh = self.render_size

        if self.glconfig.is_double_buffered() or bw!=ww or bh!=wh:
            #refresh the whole window:
            rectangles = ((0, 0, bw, bh), )
        else:
            #paint just the rectangles we have accumulated:
            rectangles = self.pending_fbo_paint
        self.pending_fbo_paint = []
        log("do_present_fbo: painting %s", rectangles)

        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
        if self._alpha_enabled:
            # support alpha channel if present:
            glEnablei(GL_BLEND, self.textures[TEX_FBO])
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)

        #viewport for painting to window:
        glViewport(0, 0, ww, wh)
        if ww!=bw or wh!=bh:
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

        glBegin(GL_QUADS)
        for x,y,w,h in rectangles:
            #note how we invert coordinates..
            tx1, ty1, tx2, ty2 = x, bh-y,  x+w, bh-y-h
            vx1, vy1, vx2, vy2 = x, y,     x+w, y+h
            glTexCoord2i(tx1, ty1)
            glVertex2i(vx1, vy1)        #top-left of window viewport
            glTexCoord2i(tx1, ty2)
            glVertex2i(vx1, vy2)        #bottom-left of window viewport
            glTexCoord2i(tx2, ty2)
            glVertex2i(vx2, vy2)        #bottom-right of window viewport
            glTexCoord2i(tx2, ty1)
            glVertex2i(vx2, vy1)        #top-right of window viewport
        glEnd()
        glDisable(GL_TEXTURE_RECTANGLE_ARB)

        if self.paint_spinner:
            #add spinner:
            dim = min(bw/3.0, bh/3.0)
            t = time.time()
            count = int(t*4.0)
            bx = bw//2
            by = bh//2
            for i in range(8):      #8 lines
                glBegin(GL_POLYGON)
                c = cv.trs[count%8][i]
                glColor4f(c, c, c, 1)
                mi1 = math.pi*i/4-math.pi/16
                mi2 = math.pi*i/4+math.pi/16
                glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10))
                glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim))
                glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim))
                glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10))
                glEnd()

        #if desired, paint window border
        if self.border and self.border.shown:
            #double size since half the line will be off-screen
            glLineWidth(self.border.size*2)
            glBegin(GL_LINE_LOOP)
            glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha)
            for px,py in ((0, 0), (bw, 0), (bw, bh), (0, bh)):
                glVertex2i(px, py)
            glEnd()

        # Show the backbuffer on screen
        self.gl_show()
        self.gl_frame_terminator()

        #restore pbo viewport
        glViewport(0, 0, bw, bh)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

        self.unset_rgb_paint_state()
        log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo)
        glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
        log("%s.do_present_fbo() done", self)
Ejemplo n.º 49
0
    def do_present_fbo(self):
        bw, bh = self.size
        ww, wh = self.render_size

        self.gl_marker("Presenting FBO on screen")
        # Change state to target screen instead of our FBO
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)

        left, top, right, bottom = self.offsets

        #viewport for clearing the whole window:
        glViewport(0, 0, left+ww+right, top+wh+bottom)
        if self._alpha_enabled:
            # transparent background:
            glClearColor(0.0, 0.0, 0.0, 0.0)
        else:
            # black, no alpha:
            glClearColor(0.0, 0.0, 0.0, 1.0)
        if left or top or right or bottom:
            try:
                glClear(GL_COLOR_BUFFER_BIT)
            except:
                log("ignoring glClear(GL_COLOR_BUFFER_BIT) error, buggy driver?", exc_info=True)

        #viewport for painting to window:
        glViewport(left, top, ww, wh)

        # Draw FBO texture on screen
        self.set_rgb_paint_state()

        rect_count = len(self.pending_fbo_paint)
        if self.glconfig.is_double_buffered() or bw!=ww or bh!=wh:
            #refresh the whole window:
            rectangles = ((0, 0, bw, bh), )
        else:
            #paint just the rectangles we have accumulated:
            rectangles = self.pending_fbo_paint
        self.pending_fbo_paint = []
        log("do_present_fbo: painting %s", rectangles)

        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
        if self._alpha_enabled:
            # support alpha channel if present:
            glEnablei(GL_BLEND, self.textures[TEX_FBO])
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)

        if SAVE_BUFFERS:
            glBindFramebuffer(GL_READ_FRAMEBUFFER, self.offscreen_fbo)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0)
            glReadBuffer(GL_COLOR_ATTACHMENT0)
            glViewport(0, 0, bw, bh)
            from OpenGL.GL import glGetTexImage
            size = bw*bh*4
            import numpy
            data = numpy.empty(size)
            img_data = glGetTexImage(GL_TEXTURE_RECTANGLE_ARB, 0, GL_BGRA, GL_UNSIGNED_BYTE, data)
            from PIL import Image, ImageOps
            img = Image.frombuffer("RGBA", (bw, bh), img_data, "raw", "BGRA", bw*4)
            img = ImageOps.flip(img)
            kwargs = {}
            if SAVE_BUFFERS=="jpeg":
                kwargs = {
                          "quality"     : 0,
                          "optimize"    : False,
                          }
            t = time.time()
            tstr = time.strftime("%H-%M-%S", time.localtime(t))
            filename = "./W%i-FBO-%s.%03i.%s" % (self.wid, tstr, (t*1000)%1000, SAVE_BUFFERS)
            log("do_present_fbo: saving %4ix%-4i pixels, %7i bytes to %s", bw, bh, size, filename)
            img.save(filename, SAVE_BUFFERS, **kwargs)
            glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)

        if ww!=bw or wh!=bh:
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

        glBegin(GL_QUADS)
        for x,y,w,h in rectangles:
            #note how we invert coordinates..
            tx1, ty1, tx2, ty2 = x, bh-y,  x+w, bh-y-h
            vx1, vy1, vx2, vy2 = x, y,     x+w, y+h
            glTexCoord2i(tx1, ty1)
            glVertex2i(vx1, vy1)        #top-left of window viewport
            glTexCoord2i(tx1, ty2)
            glVertex2i(vx1, vy2)        #bottom-left of window viewport
            glTexCoord2i(tx2, ty2)
            glVertex2i(vx2, vy2)        #bottom-right of window viewport
            glTexCoord2i(tx2, ty1)
            glVertex2i(vx2, vy1)        #top-right of window viewport
        glEnd()
        glDisable(GL_TEXTURE_RECTANGLE_ARB)

        if self.paint_spinner:
            #add spinner:
            dim = min(bw/3.0, bh/3.0)
            t = time.time()
            count = int(t*4.0)
            bx = bw//2
            by = bh//2
            for i in range(8):      #8 lines
                glBegin(GL_POLYGON)
                c = cv.trs[count%8][i]
                glColor4f(c, c, c, 1)
                mi1 = math.pi*i/4-math.pi/16
                mi2 = math.pi*i/4+math.pi/16
                glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10))
                glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim))
                glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim))
                glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10))
                glEnd()

        #if desired, paint window border
        if self.border and self.border.shown:
            #double size since half the line will be off-screen
            glLineWidth(self.border.size*2)
            glBegin(GL_LINE_LOOP)
            glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha)
            for px,py in ((0, 0), (bw, 0), (bw, bh), (0, bh)):
                glVertex2i(px, py)
            glEnd()

        if self.pointer_overlay:
            x, y, _, _, size, start_time = self.pointer_overlay
            elapsed = time.time()-start_time
            if elapsed<6:
                alpha = max(0, (5.0-elapsed)/5.0)
                glLineWidth(1)
                glBegin(GL_LINES)
                glColor4f(0, 0, 0, alpha)
                glVertex2i(x-size, y)
                glVertex2i(x+size, y)
                glVertex2i(x, y-size)
                glVertex2i(x, y+size)
                glEnd()
            else:
                self.pointer_overlay = None

        # Show the backbuffer on screen
        self.gl_show(rect_count)
        self.gl_frame_terminator()

        #restore pbo viewport
        glViewport(0, 0, bw, bh)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

        self.unset_rgb_paint_state()
        log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo)
        glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
        log("%s.do_present_fbo() done", self)
Ejemplo n.º 50
0
 def clear_color(cls, color: GlColor, alpha=1.0):
     glClearColor(*color.to_float(), alpha)
Ejemplo n.º 51
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 %s, backing size %s", self.render_size, self.size)
            # Initialize viewport and matrices for 2D rendering
            x, _, _, y = self.offsets
            glViewport(x, y, 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
Ejemplo n.º 52
0
 def clear_gl_screen(self):
     glClearColor(0.9, 0.9, 0.9, 1.0)
     glClear(GL_COLOR_BUFFER_BIT)
Ejemplo n.º 53
0
def main():
    pg.init()
    display = (1680, 1050)
    pg.display.set_mode(display, DOUBLEBUF|OPENGL)

    # If everything went well the following calls
    # will display the version of opengl being used
    print('Vendor: %s' % (glGetString(GL_VENDOR)))
    print('Opengl version: %s' % (glGetString(GL_VERSION)))
    print('GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)))
    print('Renderer: %s' % (glGetString(GL_RENDERER)))

    glClearColor(0.95, 1.0, 0.95, 0)

    # Lets compile our shaders since the use of shaders is now
    # mandatory. We need at least a vertex and fragment shader
    # begore we can draw anything
    program = ShaderProgram(fragment=fragment, vertex=vertex)

    # Lets create a VAO and bind it
    # Think of VAO's as object that encapsulate buffer state
    # Using a VAO enables you to cut down on calls in your draw
    # loop which generally makes things run faster
    vao_id = glGenVertexArrays(1)
    glBindVertexArray(vao_id)

    # Lets create our Vertex Buffer objects - these are the buffers
    # that will contain our per vertex data
    vbo_id = glGenBuffers(2)

    # Bind a buffer before we can use it
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0])

    # Now go ahead and fill this bound buffer with some data
    glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW)

    # Now specify how the shader program will be receiving this data
    # In this case the data from this buffer will be available in the shader as the vin_position vertex attribute
    glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None)

    # Turn on this vertex attribute in the shader
    glEnableVertexAttribArray(0)

    # Now do the same for the other vertex buffer
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1])
    glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW)
    glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(1)

    # Lets unbind our vbo and vao state
    # We will bind these again in the draw loop
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindVertexArray(0)


    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                quit()

        glClear(GL_COLOR_BUFFER_BIT)

        # Specify shader to be used
        glUseProgram(program.program_id)

        # Bind VAO - this will automatically
        # bind all the vbo's saving us a bunch
        # of calls
        glBindVertexArray(vao_id)

        # Modern GL makes the draw call really simple
        # All the complexity has been pushed elsewhere
        glDrawArrays(GL_TRIANGLES, 0, 3)

        # Lets unbind the shader and vertex array state
        glUseProgram(0)
        glBindVertexArray(0)

        # Now lets show our master piece on the screen
        pg.display.flip()
        pg.time.wait(10)
Ejemplo n.º 54
0
 def on_realize(self, widget):
     with GLContext(widget):
         glClearColor(0.0, 0.0, 0.0, 0.0)
Ejemplo n.º 55
0
def init():
    glClearColor(0, 0, 0, 0.0)
    glMatrixMode(GL_PROJECTION)
    gluOrtho2D(0.0, 300, 0.0, 300)
Ejemplo n.º 56
0
    def present_fbo(self, drawable):
        if not self.paint_screen:
            return
        self.gl_marker("Presenting FBO on screen for drawable %s" % drawable)
        assert drawable
        # Change state to target screen instead of our FBO
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        if self._alpha_enabled:
            # transparent background:
            glClearColor(0.0, 0.0, 0.0, 0.0)
        else:
            # plain white no alpha:
            glClearColor(1.0, 1.0, 1.0, 1.0)

        # Draw FBO texture on screen
        self.set_rgb_paint_state()
        w, h = self.size

        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
        if self._alpha_enabled:
            # support alpha channel if present:
            glEnablei(GL_BLEND, self.textures[TEX_FBO])
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glBegin(GL_QUADS)
        glTexCoord2i(0, h)
        glVertex2i(0, 0)
        glTexCoord2i(0, 0)
        glVertex2i(0, h)
        glTexCoord2i(w, 0)
        glVertex2i(w, h)
        glTexCoord2i(w, h)
        glVertex2i(w, 0)
        glEnd()

        #if desired, paint window border
        if self.border and self.border.shown:
            glDisable(GL_TEXTURE_RECTANGLE_ARB)
            #double size since half the line will be off-screen
            glLineWidth(self.border.size * 2)
            glColor4f(self.border.red, self.border.green, self.border.blue,
                      self.border.alpha)
            glBegin(GL_LINE_LOOP)
            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
                glVertex2i(x, y)
            glEnd()
            #reset color to default
            glColor4f(1.0, 1.0, 1.0, 1.0)

        # Show the backbuffer on screen
        if drawable.is_double_buffered():
            log("%s.present_fbo() swapping buffers now", self)
            drawable.swap_buffers()
            # Clear the new backbuffer to illustrate that its contents are undefined
            glClear(GL_COLOR_BUFFER_BIT)
        else:
            glFlush()
        self.gl_frame_terminator()

        self.unset_rgb_paint_state()
        glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
        log("%s.present_fbo() done", self)
Ejemplo n.º 57
0
def player_drop(rec_dir, ipc_pub_url, ipc_sub_url, ipc_push_url, user_dir,
                app_version, debug):
    # general imports
    import logging

    # networking
    import zmq
    import zmq_tools
    from time import sleep

    # zmq ipc setup
    zmq_ctx = zmq.Context()
    ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url)

    # log setup
    logging.getLogger("OpenGL").setLevel(logging.ERROR)
    logger = logging.getLogger()
    logger.handlers = []
    logger.setLevel(logging.INFO)
    logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url))
    # create logger for the context of this function
    logger = logging.getLogger(__name__)

    try:
        import glfw
        import gl_utils
        from OpenGL.GL import glClearColor
        from version_utils import VersionFormat
        from file_methods import Persistent_Dict
        from pyglui.pyfontstash import fontstash
        from pyglui.ui import get_roboto_font_path
        import player_methods as pm
        from pupil_recording import (
            assert_valid_recording_type,
            InvalidRecordingException,
        )
        from pupil_recording.update import update_recording

        process_was_interrupted = False

        def interrupt_handler(sig, frame):
            import traceback

            trace = traceback.format_stack(f=frame)
            logger.debug(f"Caught signal {sig} in:\n" + "".join(trace))
            nonlocal process_was_interrupted
            process_was_interrupted = True

        signal.signal(signal.SIGINT, interrupt_handler)

        def on_drop(window, count, paths):
            nonlocal rec_dir
            rec_dir = paths[0].decode("utf-8")

        if rec_dir:
            try:
                assert_valid_recording_type(rec_dir)
            except InvalidRecordingException as err:
                logger.error(str(err))
                rec_dir = None
        # load session persistent settings
        session_settings = Persistent_Dict(
            os.path.join(user_dir, "user_settings_player"))
        if VersionFormat(session_settings.get("version",
                                              "0.0")) != app_version:
            logger.info(
                "Session setting are from a  different version of this app. I will not use those."
            )
            session_settings.clear()
        w, h = session_settings.get("window_size", (1280, 720))
        window_pos = session_settings.get("window_position",
                                          window_position_default)

        glfw.glfwInit()
        glfw.glfwWindowHint(glfw.GLFW_RESIZABLE, 0)
        window = glfw.glfwCreateWindow(w, h, "Pupil Player")
        glfw.glfwWindowHint(glfw.GLFW_RESIZABLE, 1)

        glfw.glfwMakeContextCurrent(window)
        glfw.glfwSetWindowPos(window, window_pos[0], window_pos[1])
        glfw.glfwSetDropCallback(window, on_drop)

        glfont = fontstash.Context()
        glfont.add_font("roboto", get_roboto_font_path())
        glfont.set_align_string(v_align="center", h_align="middle")
        glfont.set_color_float((0.2, 0.2, 0.2, 0.9))
        gl_utils.basic_gl_setup()
        glClearColor(0.5, 0.5, 0.5, 0.0)
        text = "Drop a recording directory onto this window."
        tip = "(Tip: You can drop a recording directory onto the app icon.)"

        # text = "Please supply a Pupil recording directory as first arg when calling Pupil Player."

        def display_string(string, font_size, center_y):
            x = w / 2 * hdpi_factor
            y = center_y * hdpi_factor

            glfont.set_size(font_size * hdpi_factor)

            glfont.set_blur(10.5)
            glfont.set_color_float((0.0, 0.0, 0.0, 1.0))
            glfont.draw_text(x, y, string)

            glfont.set_blur(0.96)
            glfont.set_color_float((1.0, 1.0, 1.0, 1.0))
            glfont.draw_text(x, y, string)

        while not glfw.glfwWindowShouldClose(
                window) and not process_was_interrupted:

            fb_size = glfw.glfwGetFramebufferSize(window)
            hdpi_factor = glfw.getHDPIFactor(window)
            gl_utils.adjust_gl_view(*fb_size)

            if rec_dir:
                try:
                    assert_valid_recording_type(rec_dir)
                    logger.info(
                        "Starting new session with '{}'".format(rec_dir))
                    text = "Updating recording format."
                    tip = "This may take a while!"
                except InvalidRecordingException as err:
                    logger.error(str(err))
                    if err.recovery:
                        text = err.reason
                        tip = err.recovery
                    else:
                        text = "Invalid recording"
                        tip = err.reason
                    rec_dir = None

            gl_utils.clear_gl_screen()

            display_string(text, font_size=51, center_y=216)
            for idx, line in enumerate(tip.split("\n")):
                tip_font_size = 42
                center_y = 288 + tip_font_size * idx * 1.2
                display_string(line,
                               font_size=tip_font_size,
                               center_y=center_y)

            glfw.glfwSwapBuffers(window)

            if rec_dir:
                try:
                    update_recording(rec_dir)
                except AssertionError as err:
                    logger.error(str(err))
                    tip = "Oops! There was an error updating the recording."
                    rec_dir = None
                except InvalidRecordingException as err:
                    logger.error(str(err))
                    if err.recovery:
                        text = err.reason
                        tip = err.recovery
                    else:
                        text = "Invalid recording"
                        tip = err.reason
                    rec_dir = None
                else:
                    glfw.glfwSetWindowShouldClose(window, True)

            glfw.glfwPollEvents()

        session_settings["window_position"] = glfw.glfwGetWindowPos(window)
        session_settings.close()
        glfw.glfwDestroyWindow(window)
        if rec_dir:
            ipc_pub.notify({
                "subject": "player_process.should_start",
                "rec_dir": rec_dir
            })

    except Exception:
        import traceback

        trace = traceback.format_exc()
        logger.error(
            "Process player_drop crashed with trace:\n{}".format(trace))

    finally:
        sleep(1.0)
Ejemplo n.º 58
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
Ejemplo n.º 59
0
    def paintGL(self):
        """
        Called by QtGL when redrawing is needed. For every redraw, color &
        depth butter are cleared, view projection are reset, view location &
        orientation are also reset.
        """
        if not self.initialised:
            return

        self._call_whatever_waits_for_gl_context_current()  #bruce 071103

        glDepthFunc(GL_LEQUAL)

        self.setDepthRange_setup_from_debug_pref()
        self.setDepthRange_Normal()

        from utilities.debug_prefs import debug_pref, Choice_boolean_False
        if debug_pref("always setup_lighting?", Choice_boolean_False):
            #bruce 060415 added debug_pref("always setup_lighting?"), in GLPane and ThumbView [KEEP DFLTS THE SAME!!];
            # see comments in GLPane_lighting_methods
            self._setup_lighting()  #bruce 060415 added this call

        self.backgroundColor = env.prefs[backgroundColor_prefs_key]
        c = self.backgroundColor
        glClearColor(c[0], c[1], c[2], 0.0)
        del c
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        self.backgroundGradient = env.prefs[backgroundGradient_prefs_key]
        if self.backgroundGradient:

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

            # Setting to blue sky (default), but might change to something else
            _bgGradient = bluesky
            if self.backgroundGradient == bgEVENING_SKY:
                _bgGradient = eveningsky
            if self.backgroundGradient == bgSEAGREEN:
                _bgGradient = bg_seagreen

            drawFullWindow(_bgGradient)  # gradient color

        self._setup_projection()

        self._setup_modelview()
        ##        glMatrixMode(GL_MODELVIEW)
        ##        glLoadIdentity()
        ##        glTranslatef(0.0, 0.0, - self.vdist)
        ##        q = self.quat
        ##        glRotatef(q.angle * 180.0 / math.pi, q.x, q.y, q.z)
        ##        glTranslatef(self.pov[0], self.pov[1], self.pov[2])

        if self.model_is_valid():
            #bruce 080117 [testing this at start of paintGL to skip most of it]:
            # precaution (perhaps a bugfix); see similar code in GLPane.
            #
            # update, bruce 080220: this may have caused a bug by making this
            # not draw a blank-background graphics area when it has no model.
            # E.g. the partlib has no model when first entered.
            # Fixing this by only not drawing the model itself in that case [UNTESTED].
            # (The GLPane always has a model, so has no similar issue.)
            #
            # I'm not moving the coordinate transforms into this if statement,
            # since I don't know if they might be depended on by non-paintGL
            # drawing (e.g. for highlighting, which btw is called "selection"
            # in some method names and comments in this file). [bruce 080220]
            self._drawModel_using_DrawingSets()
Ejemplo n.º 60
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('model', metavar='MODEL.MS3D', type=str)
    parser.add_argument('--show-skeleton', action='store_true')

    args = parser.parse_args()

    pygame.init()
    pygame.display.set_mode((800, 600), pygame.DOUBLEBUF | pygame.OPENGL)

    glViewport(0, 0, 800, 600)

    glEnable(GL_DEPTH_TEST)
    glClearColor(0, 0, 0, 0)

    model = MS3DModel(args.model)
    bone_model = BoneModel()
    start = time.time()

    projection_matrix = matrix.perspective(math.radians(45), 800 / 600, 0.1,
                                           1000)

    # Fit the model into the viewport
    min_vert, max_vert = map(Vector._make, model.bbox)
    model_h = max_vert.y - min_vert.y
    model_w = max_vert.x - min_vert.x

    model_center = lerp(min_vert, max_vert, 1 / 2)

    distance = max(model_h, model_w) / (2 * math.tan(math.radians(45 / 2)))
    distance = distance + max_vert.z

    view_matrix = matrix.look_at(eye=np.subtract(model_center,
                                                 [0, 0, distance]),
                                 center=model_center,
                                 up=UP)

    rot = matrix.rotate_y(math.radians(1))

    running = True
    while running:
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Update models current animation frame
        model.timestamp = time.time() - start
        # Draw the model
        model.render(view_matrix, projection_matrix)

        if args.show_skeleton:
            glClear(GL_DEPTH_BUFFER_BIT)
            for M in model_skeleton_matrices(model):
                bone_model.matrix = M
                bone_model.render(view_matrix, projection_matrix)

        # Rotate the view by 1 degree
        view_matrix = np.dot(view_matrix, rot)

        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False