Exemplo n.º 1
1
def draw_background(imname):
    ''' Draw background image using a quad. '''

    # load background image (should be .bmp) to OpenGL texture
    bg_image = pygame.image.load(imname).convert()
    bg_data = pygame.image.tostring(bg_image, "RGBA", 1)

    GL.glMatrixMode(GL.GL_MODELVIEW)
    GL.glLoadIdentity()

    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

    # bind the texture
    GL.glEnable(GL.GL_TEXTURE_2D)
    GL.glBindTexture(GL.GL_TEXTURE_2D, GL.glGenTextures(1))
    GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, width, height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, bg_data)
    GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
    GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)

    # create quad to fill the whole window
    GL.glBegin(GL.GL_QUADS)
    GL.glTexCoord2f(0.0, 0.0); GL.glVertex3f(-1.0, -1.0, -1.0)
    GL.glTexCoord2f(1.0, 0.0); GL.glVertex3f(1.0, -1.0, -1.0)
    GL.glTexCoord2f(1.0, 1.0); GL.glVertex3f(1.0, 1.0, -1.0)
    GL.glTexCoord2f(0.0, 1.0); GL.glVertex3f(-1.0, 1.0, -1.0)
    GL.glEnd()

    # clear the texture
    GL.glDeleteTextures(1)
Exemplo n.º 2
0
 def paintGL(self,pick=0):
     GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
     GL.glLoadIdentity()         
     GL.glTranslatef(self.posx,self.posy,self.posz)
     GL.glRotatef(self.rotx,1.0,0.0,0.0)
     GL.glRotatef(self.roty,0.0,1.0,0.0)
     GL.glRotatef(self.rotz,0.0,0.0,1.0)
     GL.glBegin(GL.GL_LINES)
     GL.glColor3f(0.0,0.0,0.0)
     GL.glColor3f(1, 0, 0)
     GL.glVertex3f(0, 0, 0)
     GL.glVertex3f(10000, 0, 0)
     GL.glColor3f(0, 1, 0)
     GL.glVertex3f(0, 0, 0)
     GL.glVertex3f(0, 10000, 0)
     GL.glColor3f(0, 0, 1)
     GL.glVertex3f(0, 0, 0)
     GL.glVertex3f(0, 0, 10000)
     GL.glEnd()
     for obj in self.objects:
         if obj == self.picked:
             GL.glColor3f(1.0,0.0,0.0)
         else:
             GL.glColor3f(1.0,1.0,1.0)
         obj.draw(pick)
Exemplo n.º 3
0
    def display(self):
        """Draw surface to a quad. Call as part of OpenGL rendering code."""
        ogl.glEnable(ogl.GL_BLEND)
        ogl.glBlendFunc(ogl.GL_SRC_ALPHA, ogl.GL_ONE_MINUS_SRC_ALPHA)  
        ogl.glEnable(ogl.GL_TEXTURE_2D)
        ogl.glBindTexture(ogl.GL_TEXTURE_2D, self._txtr)
        ogl.glTexEnvf(ogl.GL_TEXTURE_ENV, ogl.GL_TEXTURE_ENV_MODE, ogl.GL_REPLACE)
        #ogl.glColor4d( 1.0, 1.0, 1.0, alpha )
        #ogl.glTexEnvf(ogl.GL_TEXTURE_ENV, ogl.GL_TEXTURE_ENV_MODE, ogl.GL_MODULATE)
        #glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
        #ogl.glTexEnvfv(ogl.GL_TEXTURE_ENV, ogl.GL_TEXTURE_ENV_COLOR, (0, 0, 0, alpha))

        #ogl.glNormal3f(0.0, 0.0, -1.0)

        ogl.glBegin(ogl.GL_QUADS)
        ogl.glTexCoord2f(0.0, 1-self._usable[1])
        # bottom left corner
        ogl.glVertex3f(*self.dims[0])

        ogl.glTexCoord2f(self._usable[0], 1-self._usable[1])
        # bottom right corner
        ogl.glVertex3f(self.dims[1][0],self.dims[1][1],0.0)

        ogl.glTexCoord2f(self._usable[0], 1.0)
        # top right corner
        ogl.glVertex3f(*self.dims[2])

        ogl.glTexCoord2f(0.0, 1.0)
        # top left corner
        ogl.glVertex3f(*self.dims[3])
        ogl.glEnd()
        ogl.glDisable(ogl.GL_BLEND)
        ogl.glDisable(ogl.GL_TEXTURE_2D)
Exemplo n.º 4
0
 def DrawViolin(self, x_offset):
     
     # Get stats
     stats = self._stats
     
     # Smooth lines
     gl.glEnable(gl.GL_LINE_SMOOTH)
     
     # Translate points
     points = self._points.copy()
     points[:,0] += x_offset
     
     # Draw outer lines
     gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
     gl.glVertexPointerf(points)
     gl.glDrawArrays(gl.GL_LINE_STRIP, 0, points.shape[0])
     gl.glFlush()
     gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
     
     # Draw mean p25, p50 and p75
     w2 = self._width * 0.25
     gl.glBegin(gl.GL_LINES)
     gl.glVertex2f(x_offset-w2, stats.Q2)
     gl.glVertex2f(x_offset+w2, stats.Q2)
     gl.glVertex2f(x_offset, stats.Q1)
     gl.glVertex2f(x_offset, stats.Q3)
     gl.glEnd()
Exemplo n.º 5
0
    def generateList(self,model):
        displayList = GL.glGenLists(1)
        GL.glNewList(displayList,GL.GL_COMPILE)

        for polygon in model.shapes:

            rotation = polygon.rotation
            triangles = polygon.indices
            vertices = polygon.vertices
            
            GL.glPushMatrix()
            GL.glRotatef(rotation[0],1.0,0.0,0.0)
            GL.glRotatef(rotation[1],0.0,1.0,0.0)
            GL.glRotatef(rotation[2],0.0,0.0,1.0)

            GL.glBegin(GL.GL_TRIANGLES)
            for vertex in triangles:
                GL.glVertex3f(*[vertices[vertex][i]/100 for i in range(3)])
            GL.glEnd()

            GL.glPushAttrib(GL.GL_CURRENT_BIT)
            GL.glColor3f(0.0,0.0,0.0)
            for triangle in [triangles[i*3:i*3+3] for i in range(len(triangles)//3)]:
                GL.glBegin(GL.GL_LINES)
                for vertex in triangle:
                    GL.glVertex3f(*[vertices[vertex][i]/100 for i in range(3)])
                GL.glEnd()
            GL.glPopAttrib()

            GL.glPopMatrix()
        
        GL.glEndList()
        return displayList
Exemplo n.º 6
0
 def drawGL(self,**kargs):
     """Draw the triade."""
     # When entering here, the modelview matrix has been set
     # We should make sure it is unchanged on exit
     GL.glMatrixMode(GL.GL_MODELVIEW)
     GL.glPushMatrix()
     GL.glTranslatef (*self.pos) 
     GL.glScalef (self.size,self.size,self.size) 
     # Coord axes of size 1.0
     GL.glBegin(GL.GL_LINES)
     pts = Formex(pattern('1')).coords.reshape(-1,3)
     GL.glColor3f(*black)
     for i in range(3):
         if colored_axes:
             GL.glColor(*self.color[i])
         for x in pts:
             GL.glVertex3f(*x)
         pts = pts.rollAxes(1)
     GL.glEnd()
     if draw_planes:
         # Coord plane triangles of size 0.5
         GL.glBegin(GL.GL_TRIANGLES)
         pts = Formex(mpattern('16')).scale(0.5).coords.reshape(-1,3)
         for i in range(3):
             pts = pts.rollAxes(1)
             GL.glColor(*self.color[i])
             for x in pts:
                 GL.glVertex3f(*x)
         GL.glEnd()
     GL.glMatrixMode(GL.GL_MODELVIEW)
     GL.glPopMatrix()
Exemplo n.º 7
0
 def _draw_me(self):
     """Draw the triade components."""
     GL.glBegin(GL.GL_LINES)
     pts = Formex('1').coords.reshape(-1,3)
     GL.glColor3f(*black)
     for i in range(3):
         #GL.glColor(*self.color[i])
         for x in pts:
             GL.glVertex3f(*x)
         pts = pts.rollAxes(1)
     GL.glEnd()
     # Coord planes
     if self.pat:
         GL.glBegin(GL.GL_TRIANGLES)
         pts = Formex(self.pat)
         #pts += pts.reverse()
         pts = pts.scale(0.5).coords.reshape(-1,3)
         for i in range(3):
             pts = pts.rollAxes(1)
             GL.glColor3f(*self.color[i])
             for x in pts:
                 GL.glVertex3f(*x)
         GL.glEnd()
     # Coord axes denomination
     for i,x in enumerate(self.legend):
         p = unitVector(i)*1.1
         t = TextMark(p,x)
         t.drawGL()
Exemplo n.º 8
0
    def load_object(self, model, color):
        """Loads the object from an stl."""
        self.bottom = None
        self.top = None
        obj_genlist = GL.glGenLists(1)
        GL.glNewList(obj_genlist, GL.GL_COMPILE)

        GL.glBegin(GL.GL_TRIANGLES)

        self.qglColor(color)
        for triangle in model.mesh:
            GL.glNormal3d(*triangle[1])
            for point in triangle[0]:
                #self.log.debug('Adding point %s', point)
                if point[2] < self.bottom or self.bottom is None:
                    self.bottom = point[2]
                if point[2] > self.top or self.bottom is None:
                    self.top = point[2]
                GL.glVertex3d(*point)
        self.log.info("This model has %d facets", model.poly.size_of_facets())
        GL.glEnd()
        GL.glEndList()

        if self.slice_slider is not None:
            self.slice_slider.setMinimum(math.floor(self.bottom))
            self.slice_slider.setMaximum(math.ceil(self.top))


        return obj_genlist
Exemplo n.º 9
0
def drawGrid(x1,y1,x2,y2,nx,ny):
    """Draw a rectangular grid of lines
        
    The rectangle has (x1,y1) and and (x2,y2) as opposite corners.
    There are (nx,ny) subdivisions along the (x,y)-axis. So the grid
    has (nx+1) * (ny+1) lines. nx=ny=1 draws a rectangle.
    nx=0 draws 1 vertical line (at x1). nx=-1 draws no vertical lines.
    ny=0 draws 1 horizontal line (at y1). ny=-1 draws no horizontal lines.
    """
    GL.glBegin(GL.GL_LINES)
    ix = range(nx+1)
    if nx==0:
        jx = [1]
        nx = 1
    else:
        jx = ix[::-1] 
    for i,j in zip(ix,jx):
        x = (i*x2+j*x1)/nx
        GL.glVertex2f(x, y1)
        GL.glVertex2f(x, y2)

    iy = range(ny+1)
    if ny==0:
        jy = [1]
        ny = 1
    else:
        jy = iy[::-1] 
    for i,j in zip(iy,jy):
        y = (i*y2+j*y1)/ny
        GL.glVertex2f(x1, y)
        GL.glVertex2f(x2, y)
    GL.glEnd()
Exemplo n.º 10
0
    def __init__( self, sides, size, color,  position = (0.0, 0.0, 0.0) ):
        self.sides = sides
        self.color = color
        self.size = size
        self.position = np.array(position)
        
        height = LEGO_BIG_HEIGHT if self.size else LEGO_SMALL_HEIGHT
        length = self.bottom - self.top
        combine = lambda _points, _vertices, _weights: _points 
            
        self.__tess = GLU.gluNewTess()
        GLU.gluTessCallback(self.__tess, GLU.GLU_TESS_BEGIN, GL.glBegin)
        GLU.gluTessCallback(self.__tess,GLU.GLU_TESS_VERTEX,GL.glVertex3fv)
        GLU.gluTessCallback(self.__tess,GLU.GLU_TESS_COMBINE,combine)
        GLU.gluTessCallback(self.__tess, GLU.GLU_TESS_END, GL.glEnd)
        GLU.gluTessProperty(self.__tess, GLU.GLU_TESS_WINDING_RULE, GLU.GLU_TESS_WINDING_ODD)

        self.__gllist = GL.glGenLists(1)
        
        GL.glNewList(self.__gllist,GL.GL_COMPILE)
        GL.glColor3fv(self.color)
        GL.glBindTexture(GL.GL_TEXTURE_2D,0)
        
        GLU.gluTessNormal(self.__tess, 0.0, 1.0, 0.0)
        GL.glNormal3f(0.0, 1.0, 0.0)
        GLU.gluTessBeginPolygon(self.__tess,None)
        GLU.gluTessBeginContour(self.__tess)
        for i in range(0,len(self.coords)):
            vertex =  (self.coords[i][0]*LEGO_GRID, height, self.coords[i-1][1]*LEGO_GRID)
            GLU.gluTessVertex(self.__tess, vertex, vertex)
            vertex =  (self.coords[i][0]*LEGO_GRID, height, self.coords[i][1]*LEGO_GRID)
            GLU.gluTessVertex(self.__tess, vertex, vertex)
        GLU.gluTessEndContour(self.__tess)
        GLU.gluTessEndPolygon(self.__tess)
        
        for i in range(0,len(self.coords)):
            GL.glBegin(GL.GL_QUADS)
            sign = float(np.sign(self.sides[2*i-1]))
            GL.glNormal3f( sign, 0.0, 0.0 )
            GL.glVertex3f( self.coords[i][0] * LEGO_GRID, height, self.coords[i-1][1] * LEGO_GRID)
            GL.glVertex3f( self.coords[i][0] * LEGO_GRID, height, self.coords[i]  [1]   * LEGO_GRID)
            GL.glVertex3f( self.coords[i][0] * LEGO_GRID, 0.0,    self.coords[i]  [1]   * LEGO_GRID)
            GL.glVertex3f( self.coords[i][0] * LEGO_GRID, 0.0,    self.coords[i-1][1] * LEGO_GRID)
            sign = float(np.sign(self.sides[2*i-2]))
            GL.glNormal3f( 0.0, 0.0, -sign )
            GL.glVertex3f( self.coords[i-1][0] * LEGO_GRID, height, self.coords[i-1][1] * LEGO_GRID )
            GL.glVertex3f( self.coords[i]  [0] * LEGO_GRID, height, self.coords[i-1][1] * LEGO_GRID )
            GL.glVertex3f( self.coords[i]  [0] * LEGO_GRID, 0.0,    self.coords[i-1][1] * LEGO_GRID )
            GL.glVertex3f( self.coords[i-1][0] * LEGO_GRID, 0.0,    self.coords[i-1][1] * LEGO_GRID )
            GL.glEnd()
            
        GL.glTranslatef( self.left*LEGO_GRID + LEGO_GRID/2.0, (LEGO_BUMP_HEIGHT+height)/2.0 , self.bottom*LEGO_GRID - LEGO_GRID/2.0 )
        for i in range( self.left, self.right ):
            for j in range( self.bottom, self.top ):
                GL.glTranslatef( 0.0, 0.0, LEGO_GRID )
                if self.is_hit( (i+0.5,j+0.5) ):
                    _caped_cylinder( LEGO_BUMP_RADIUS, height+LEGO_BUMP_HEIGHT, 32 )
            GL.glTranslatef( 0.0, 0.0, length*LEGO_GRID )
            GL.glTranslatef( LEGO_GRID, 0.0, 0.0 )
        GL.glEndList()
Exemplo n.º 11
0
    def buildQuad(self):
        if self.drawList > 0:
            GL.glDeleteLists(self.drawList, 1)
        xmin, ymin, zmin = self._limits[0]
        xmax, ymax, zmax = self._limits[1]
        tx0 = 0.0
        tx1 = (1.0 * self.__width)/self.__tWidth
        ty0 = 0.0
        ty1 = (1.0 * self.__height)/self.__tHeight
        self.drawList = GL.glGenLists(1)
        GL.glNewList(self.drawList, GL.GL_COMPILE)
        #The texture gets multiplied by this color!!
        GL.glColor4f(1.0, 1.0, 1.0, self.__alpha)
       	GL.glBindTexture(GL.GL_TEXTURE_2D, self.__textureId)
        GL.glEnable(GL.GL_TEXTURE_2D)
        GL.glBegin(GL.GL_QUADS)
       	GL.glTexCoord2d(tx0, ty0)
       	GL.glVertex3f(xmin, ymin, zmin)
	GL.glTexCoord2d(tx0, ty1)
	GL.glVertex3f(xmin, ymax, zmin)
	GL.glTexCoord2d(tx1, ty1)
	GL.glVertex3f(xmax, ymax, zmin)
	GL.glTexCoord2d(tx1, ty0)
	GL.glVertex3f(xmax, ymin, zmin)
        GL.glEnd()
        GL.glDisable(GL.GL_TEXTURE_2D)
        GL.glEndList()
        self._forceListCalculation = False
Exemplo n.º 12
0
    def _build_plane(self, color):
        """Build the platform plane."""
        plane_genlist = GL.glGenLists(1)
        GL.glNewList(plane_genlist, GL.GL_COMPILE)
        GL.glBegin(GL.GL_TRIANGLES)

        self.qglColor(color)
        GL.glNormal3d(0.0, 0.0, 1.0)
        GL.glVertex3d(-100.0, 100, -0.01)
        GL.glVertex3d(100.0, 100, -0.01)
        GL.glVertex3d(100.0, -100.0, -0.01)

        GL.glNormal3d(0.0, 0.0, 1.0)
        GL.glVertex3d(-100.0, 100, -0.01)
        GL.glVertex3d(100.0, -100, -0.01)
        GL.glVertex3d(-100.0, -100.0, -0.01)

        #GL.glNormal3d(0.0, 0.0, -1.0)
        #GL.glVertex3d(-101.0, 100, 0.0001)
        #GL.glVertex3d(101.0, 100, 0.0001)
        #GL.glVertex3d(101.0, -101.0, 0.0001)

        #GL.glNormal3d(0.0, 0.0, -1.0)
        #GL.glVertex3d(-101.0, 100, 0.0001)
        #GL.glVertex3d(101.0, -100, 0.0001)
        #GL.glVertex3d(-101.0, -101.0, 0.0001)

        GL.glEnd()
        GL.glEndList()
        return plane_genlist
Exemplo n.º 13
0
def drawInterceptor(agent):
    width = agent.width
    length = agent.length
    color = agent.color
    threeFifthsLength = (3.0 * length) / 5.0
    twoFifthsLength = (2.0 * length) / 5.0
    halfWidth = width / 2.0

    GL.glPushMatrix()
    x, y = agent.position
    direction = agent.getDirectionDegrees()
    GL.glTranslate(x, y, 0)
    GL.glRotatef(direction, 0, 0, 1)
    GL.glColor3f(*color)
    GL.glBegin(GL.GL_LINES)

    GL.glVertex2f(0, 0)
    GL.glVertex2f(threeFifthsLength, 0)
    GL.glVertex2f(-twoFifthsLength, halfWidth)
    GL.glVertex2f(twoFifthsLength, halfWidth)
    GL.glVertex2f(-twoFifthsLength, -halfWidth)
    GL.glVertex2f(twoFifthsLength, -halfWidth)
    GL.glVertex2f(0, halfWidth)
    GL.glVertex2f(0, -halfWidth)

    GL.glEnd()
    GL.glPopMatrix()
Exemplo n.º 14
0
    def blit(self, x, y, w, h, z=0, s=(0,1), t=(0,1)):
        ''' Draw texture to active framebuffer. '''

        if self.target == gl.GL_TEXTURE_1D:
            gl.glDisable (gl.GL_TEXTURE_2D)
            gl.glEnable (gl.GL_TEXTURE_1D)
            gl.glBindTexture(self.target, self.id)
            gl.glBegin(gl.GL_QUADS)
            gl.glTexCoord1f(s[0]), gl.glVertex2f(x,   y)
            gl.glTexCoord1f(s[0]), gl.glVertex2f(x,   y+h)
            gl.glTexCoord1f(s[1]), gl.glVertex2f(x+w, y+h)
            gl.glTexCoord1f(s[1]), gl.glVertex2f(x+w, y)
            gl.glEnd()
        else:
            gl.glEnable (gl.GL_TEXTURE_2D)
            gl.glDisable (gl.GL_TEXTURE_1D)
            gl.glBindTexture(self.target, self.id)
            gl.glBegin(gl.GL_QUADS)
            gl.glTexCoord2f(s[0], 1), gl.glVertex2f(x,   y)
            gl.glTexCoord2f(s[0], 0), gl.glVertex2f(x,   y+h)
            gl.glTexCoord2f(s[1], 0), gl.glVertex2f(x+w, y+h)
            gl.glTexCoord2f(s[1], 1), gl.glVertex2f(x+w, y)
            gl.glEnd()
        gl.glDisable (gl.GL_TEXTURE_1D)
        gl.glDisable (gl.GL_TEXTURE_2D)
Exemplo n.º 15
0
def drawMotherShip(agent):
    width = agent.width
    length = agent.length
    color = agent.color
    GL.glPushMatrix()
    x, y = agent.position
    direction = agent.getDirectionDegrees()
    GL.glTranslate(x, y, 0)
    GL.glRotatef(direction, 0, 0, 1)
    GL.glColor3f(*color)
    GL.glBegin(GL.GL_LINE_LOOP)
    halfWidth = width / 2.0
    halfLength = length / 2.0
    sixthWidth = width / 6.0

    # Core of the ship

    GL.glVertex2f(0, halfWidth)
    GL.glVertex2f(-halfLength, sixthWidth)
    GL.glVertex2f(-halfLength, -sixthWidth)
    GL.glVertex2f(0, -halfWidth)
    GL.glVertex2f(halfLength, -sixthWidth)
    GL.glVertex2f(halfLength, sixthWidth)

    GL.glEnd()
    GL.glPopMatrix()
Exemplo n.º 16
0
def drawBomber(agent):
    width = agent.width
    length = agent.length
    color = agent.color
    halfWidth = width / 2.0
    halfLength = length / 2.0
    quarterLength = length / 4.0
    GL.glPushMatrix()
    x, y = agent.position
    direction = agent.getDirectionDegrees()
    GL.glTranslate(x, y, 0)
    GL.glRotatef(direction, 0, 0, 1)
    GL.glColor3f(*color)
    GL.glBegin(GL.GL_LINES)

    GL.glVertex2f(halfLength, halfWidth)
    GL.glVertex2f(-halfLength, halfWidth)
    GL.glVertex2f(halfLength, -halfWidth)
    GL.glVertex2f(-halfLength, -halfWidth)
    GL.glVertex2f(quarterLength, halfWidth)
    GL.glVertex2f(quarterLength, -halfWidth)
    GL.glVertex2f(-quarterLength, halfWidth)
    GL.glVertex2f(-quarterLength, -halfWidth)
    GL.glVertex2f(quarterLength, 0)
    GL.glVertex2f(halfLength, 0)

    GL.glEnd()
    GL.glPopMatrix()
Exemplo n.º 17
0
def drawGridPlanes(x0,x1,nx):
    """Draw a 3D rectangular grid of planes.
        
    A grid of planes parallel to the axes is drawn in the domain bounded
    by the rectangular box [x0,x1]. The grid has nx divisions in the axis
    directions, thus planes will be drawn at nx[i]+1 positions in direction i.
    If nx[i] == 0, planes are only drawn for the initial coordinate x0.
    Thus nx=(0,2,3) results in a grid of 3x4 planes // x and
    one plane // (y,z) at coordinate x=x0[0].
    """
    x0 = asarray(x0)
    x1 = asarray(x1)
    nx = asarray(nx)

    for i in range(3):
        axes = (asarray([1,2]) + i) % 3
        if all(nx[axes] > 0):
            j,k = axes
            base = simple.regularGrid(x0[i],x1[i],nx[i]).ravel()
            x = zeros((base.shape[0],4,3))
            corners = array([x0[axes],[x1[j],x0[k]],x1[axes],[x0[j],x1[k]]])
            for j in range(4):
                x[:,j,i] = base
            x[:,:,axes] = corners
            GL.glBegin(GL.GL_QUADS)
            for p in x.reshape((-1,3)):
                GL.glVertex3fv(p)
            GL.glEnd()
Exemplo n.º 18
0
  def DrawScreen(self):
    OGL.glClear(OGL.GL_COLOR_BUFFER_BIT | OGL.GL_DEPTH_BUFFER_BIT)	# Clear The Screen And The Depth Buffer
    OGL.glLoadIdentity() # Reset The matrix

    # To calculate our collision detection with the camera, it just takes one function
    # call from the client side.  We just pass in the vertices in the world that we
    # want to check, and then the vertex count.  
    objCamera.CheckCameraCollision(g_vWorld, g_NumberOfVerts)

    # Assign Values to Local Variables to Prevent Long Lines Of Code	
    pos.x, pos.y, pos.z = objCamera.mPos.x, objCamera.mPos.y, objCamera.mPos.z
    view.x, view.y, view.z = objCamera.mView.x, objCamera.mView.y, objCamera.mView.z
    up.x, up.y, up.z = objCamera.mUp.x, objCamera.mUp.y, objCamera.mUp.z

    # use this function for opengl target camera
    OGLU.gluLookAt(pos.x, pos.y, pos.z, view.x, view.y, view.z, up.x, up.y, up.z)

    # Since we have the vertices for the world in the correct order, let's create
    # a loop that goes through all of the vertices and passes them in to be rendered.

    OGL.glBegin(OGL.GL_TRIANGLES)
    # Go through all the vertices and draw them
    for i in range(0,g_NumberOfVerts,3):
      OGL.glColor3ub(i, 2*i, 3*i) # All different colors to see the structure while playing
      OGL.glVertex3f(g_vWorld[i].x, g_vWorld[i].y, g_vWorld[i].z)
      OGL.glVertex3f(g_vWorld[i+1].x, g_vWorld[i+1].y, g_vWorld[i+1].z)
      OGL.glVertex3f(g_vWorld[i+2].x, g_vWorld[i+2].y, g_vWorld[i+2].z)
				
    OGL.glEnd()
Exemplo n.º 19
0
    def draw(self):
        ohs = self.owner.healthscale
        ohs = 1
        flippy = 1
        if self.owner.x > self.owner.gmx:
          flippy = -1
        #if self.on:
        GL.glPushMatrix()
        GL.glTranslatef(self.owner.cx, self.owner.cy, 0.0)
        GL.glRotatef(self.owner.aimgle,0,0,1)
        GL.glTranslatef(0.0, 12, 0.0)

        #print flippy
        GL.glTranslatef(self.owner.mx*self.posmult*ohs, self.owner.my*self.posmult*ohs, 0.0)
        GL.glScalef(flippy*self.scale,self.scale,1)
        GL.glScalef(8*ohs,8*ohs,12)

        GL.glBindTexture(GL.GL_TEXTURE_2D, self.image)
        if self.timetofire > 3:
          GL.glBindTexture(GL.GL_TEXTURE_2D, self.loadimage)
        GL.glColor3f(1.0, 1.0, 1.0)
        GL.glBegin(GL.GL_QUADS)
        GL.glTexCoord2f(0.0, 1.0)
        GL.glVertex3f(1.0, 1.0, 0.0)
        GL.glTexCoord2f(1.0, 1.0)
        GL.glVertex3f(-1.0, 1.0, 0.0)
        GL.glTexCoord2f(1.0, 0.0)
        GL.glVertex3f(-1.0, -1.0, 0.0)
        GL.glTexCoord2f(0.0, 0.0)
        GL.glVertex3f(1.0, -1.0, 0.0)
        GL.glEnd()
        GL.glPopMatrix()
Exemplo n.º 20
0
def drawGridLines(x0,x1,nx):
    """Draw a 3D rectangular grid of lines.
        
    A grid of lines parallel to the axes is drawn in the domain bounded
    by the rectangular box [x0,x1]. The grid has nx divisions in the axis
    directions, thus lines will be drawn at nx[i]+1 positions in direction i.
    If nx[i] == 0, lines are only drawn for the initial coordinate x0.
    Thus nx=(0,2,3) results in a grid of 3x4 lines in the plane // (y,z) at
    coordinate x=x0[0].
    """
    x0 = asarray(x0)
    x1 = asarray(x1)
    nx = asarray(nx)

    for i in range(3):
        if nx[i] > 0:
            axes = (asarray([1,2]) + i) % 3
            base = simple.regularGrid(x0[axes],x1[axes],nx[axes]).reshape((-1,2))
            x = zeros((base.shape[0],2,3))
            x[:,0,axes] = base
            x[:,1,axes] = base
            x[:,0,i] = x0[i]
            x[:,1,i] = x1[i]
            GL.glBegin(GL.GL_LINES)
            for p in x.reshape((-1,3)):
                GL.glVertex3fv(p)
            GL.glEnd()
Exemplo n.º 21
0
	def _on_paint(self, event):
		"""
		Respond to paint events.
		Initialize GL if this is the first paint event.
		Resize the view port if the width or height changed.
		Redraw the screen, calling the draw functions.
		"""
		if not self.IsShownOnScreen():	# Cannot realise a GL context on OS X if window is not yet shown
			return
		# create device context (needed on Windows, noop on X)
		dc = None
		if event.GetEventObject():	# Only create DC if paint triggered by WM message (for OS X)
			dc = wx.PaintDC(self)
		self.lock()
		self.SetCurrent(self._gl_ctx)	# Real the explicit GL context

		# check if gl was initialized
		if not self._gl_init_flag:
			GL.glClearColor(*BACKGROUND_COLOR_SPEC)
			for fcn in self._init_fcns: fcn()
			self._gl_init_flag = True

		# check for a change in window size
		if self._resized_flag:
			self.width, self.height = self.GetSize()
			GL.glMatrixMode(GL.GL_PROJECTION)
			GL.glLoadIdentity()
			GL.glOrtho(0, self.width, self.height, 0, 1, 0)
			GL.glMatrixMode(GL.GL_MODELVIEW)
			GL.glLoadIdentity()
			GL.glViewport(0, 0, self.width, self.height)
			for cache in self._gl_caches: cache.changed(True)
			self._resized_flag = False

		# clear buffer if needed
		if self.clear_accum or not self.use_persistence:
			GL.glClear(GL.GL_COLOR_BUFFER_BIT)
			self.clear_accum=False

		# apply fading
		if self.use_persistence:
			GL.glEnable(GL.GL_BLEND)
			GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)

			GL.glBegin(GL.GL_QUADS)
			GL.glColor4f(1,1,1,self.persist_alpha)
			GL.glVertex2f(0, self.height)
			GL.glVertex2f(self.width, self.height)
			GL.glVertex2f(self.width, 0)
			GL.glVertex2f(0, 0)
			GL.glEnd()

			GL.glDisable(GL.GL_BLEND)

		# draw functions
		for fcn in self._draw_fcns: fcn[1]()

		# show result
		self.SwapBuffers()
		self.unlock()
Exemplo n.º 22
0
def DrawGrid():
    global GRID_SIZE, DIST_BALL

    row = col = 0
    rowTotal = 8                   # must be divisible by 2
    colTotal = rowTotal             # must be same as rowTotal
    widthLine = 2.0                 # should be divisible by 2
    sizeCell = GRID_SIZE / rowTotal
    z_offset = -40.0
    xl = xr = 0.0
    yt = yb = 0.0

    gl.glPushMatrix()
    gl.glDisable(gl.GL_CULL_FACE)

    # Another relative Z translation to separate objects.
    gl.glTranslatef(0.0, 0.0, DIST_BALL)

    # Draw vertical lines (as skinny 3D rectangles).
    for col in my_range(0, colTotal):
        # Compute co-ords of line.

        xl = -GRID_SIZE / 2 + col * sizeCell
        xr = xl + widthLine

        yt = GRID_SIZE / 2
        yb = -GRID_SIZE / 2 - widthLine

        gl.glBegin(gl.GL_POLYGON)

        gl.glColor3f(0.60, 0.10, 0.60)        # purple

        gl.glVertex3f(xr, yt, z_offset)       # NE
        gl.glVertex3f(xl, yt, z_offset)       # NW
        gl.glVertex3f(xl, yb, z_offset)       # SW
        gl.glVertex3f(xr, yb, z_offset)       # SE

        gl.glEnd()

    # Draw horizontal lines (as skinny 3D rectangles).
    for row in my_range(0, rowTotal):
        # Compute co-ords of line.
        yt = GRID_SIZE / 2 - row * sizeCell
        yb = yt - widthLine

        xl = -GRID_SIZE / 2
        xr = GRID_SIZE / 2 + widthLine

        gl.glBegin(gl.GL_POLYGON)

        gl.glColor3f(0.60, 0.10, 0.60)        # purple

        gl.glVertex3f(xr, yt, z_offset)       # NE
        gl.glVertex3f(xl, yt, z_offset)       # NW
        gl.glVertex3f(xl, yb, z_offset)       # SW
        gl.glVertex3f(xr, yb, z_offset)       # SE

        gl.glEnd()

    gl.glPopMatrix()
Exemplo n.º 23
0
def draw_bounding_box(minx, miny, minz, maxx, maxy, maxz, color):
    p1 = [minx, miny, minz]
    p2 = [minx, maxy, minz]
    p3 = [maxx, maxy, minz]
    p4 = [maxx, miny, minz]
    p5 = [minx, miny, maxz]
    p6 = [minx, maxy, maxz]
    p7 = [maxx, maxy, maxz]
    p8 = [maxx, miny, maxz]
    # lower rectangle
    GL.glBegin(GL.GL_LINES)
    GL.glColor4f(*color)
    # all combinations of neighbouring corners
    for corner_pair in [
        (p1, p2),
        (p1, p5),
        (p1, p4),
        (p2, p3),
        (p2, p6),
        (p3, p4),
        (p3, p7),
        (p4, p8),
        (p5, p6),
        (p6, p7),
        (p7, p8),
        (p8, p5),
    ]:
        GL.glVertex3f(*(corner_pair[0]))
        GL.glVertex3f(*(corner_pair[1]))
    GL.glEnd()
Exemplo n.º 24
0
def draw_toolpath(moves, color_cut, color_rapid, show_directions=False):
    GL.glMatrixMode(GL.GL_MODELVIEW)
    GL.glLoadIdentity()
    last_position = None
    last_rapid = None
    GL.glBegin(GL.GL_LINE_STRIP)
    for position, rapid in moves:
        if last_rapid != rapid:
            GL.glEnd()
            if rapid:
                GL.glColor4f(*color_rapid)
            else:
                GL.glColor4f(*color_cut)
            GL.glBegin(GL.GL_LINE_STRIP)
            if not last_position is None:
                GL.glVertex3f(last_position.x, last_position.y, last_position.z)
            last_rapid = rapid
        GL.glVertex3f(position.x, position.y, position.z)
        last_position = position
    GL.glEnd()
    if show_directions:
        for index in range(len(moves) - 1):
            p1 = moves[index][0]
            p2 = moves[index + 1][0]
            draw_direction_cone(p1, p2)
Exemplo n.º 25
0
    def draw_line(self, start_x, start_y, end_x, end_y,
                  color=(1.0, 1.0, 1.0, 1.0),
                  width=None):
        """Draw a line on canvas."""
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        gl.glColor4f(*color)

        prev_width = None
        if width is not None:
            prev_width = gl.glGetFloat(gl.GL_LINE_WIDTH)
            gl.glLineWidth(width)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_DONT_CARE)

        gl.glBegin(gl.GL_LINES)
        gl.glVertex2f(start_x, start_y)
        gl.glVertex2f(end_x, end_y)
        gl.glEnd()
        gl.glDisable(gl.GL_BLEND)

        if prev_width is not None:
            gl.glLineWidth(prev_width)
Exemplo n.º 26
0
    def draw(self):
        gl.glPushMatrix()

        gl.glTranslatef(self.origin_x, self.origin_y, 0)

        gl.glColor4f(1.0, 1.0, 1.0, 1.0)
        render_text(self.text)

#        gl.glPushMatrix()
#        gl.glTranslatef(self.pos - 100, 0, 0)
#        gl.glBegin(GL_LINES)
#        gl.glVertex2i(95, 14)
#        gl.glVertex2i(85, 10)
#        gl.glVertex2i(95, 6)
#        gl.glVertex2i(85, 10)
#
#        gl.glVertex2i(125, 14)
#        gl.glVertex2i(135, 10)
#        gl.glVertex2i(125, 6)
#        gl.glVertex2i(135, 10)
#        gl.glEnd()
#        gl.glPopMatrix()

        gl.glColor4f(0.7, 0.7, 0.7, 0.4)
        gl.glBegin(GL_QUADS)
        gl.glVertex2i(self.pos, 0)
        gl.glVertex2i(self.pos, 20)
        gl.glVertex2i(self.pos + 20, 20)
        gl.glVertex2i(self.pos + 20, 0)
        gl.glEnd()

        gl.glPopMatrix()
Exemplo n.º 27
0
	def DebugDraw(self,scale):
		p0=self.ma.pos*scale
		p1=self.mb.pos*scale
		GL.glBegin(GL.GL_LINES)
		GL.glVertex2d(p0.x(),p0.y())
		GL.glVertex2d(p1.x(),p1.y())
		GL.glEnd()
def flip():
    global frameTexture
    
    if useFBO: 
        FB.glBindFramebufferEXT(FB.GL_FRAMEBUFFER_EXT, 0)
        
        GL.glDisable(GL.GL_BLEND)
        #GL.glBlendEquation(GL.GL_FUNC_ADD)
        #GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
        #GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_DST_ALPHA)
        
        #before flipping need to copy the renderBuffer to the frameBuffer
        GL.glColor4f(1,1,1,1)
        GL.glActiveTexture(GL.GL_TEXTURE0)
        GL.glBindTexture(GL.GL_TEXTURE_2D, frameTexture)
        GL.glBegin( GL.GL_QUADS )
        GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 0.0, 0.0 ) 
        GL.glVertex2f( -1.0,-1.0 )
        GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 0.0, 1.0 ) 
        GL.glVertex2f( -1.0, 1.0 )
        GL.glMultiTexCoord2f(GL.GL_TEXTURE0,1.0, 1.0 ) 
        GL.glVertex2f( 1.0,   1.0 )
        GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 1.0, 0.0 ) 
        GL.glVertex2f( 1.0,   -1.0 )
        GL.glEnd()
    pygame.display.flip()
    
    if useFBO: 
        GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
        GL.glDisable(GL.GL_TEXTURE_2D)
        GL.glEnable(GL.GL_BLEND)
        
        FB.glBindFramebufferEXT(FB.GL_FRAMEBUFFER_EXT, frameBuffer)
Exemplo n.º 29
0
 def drawLine(self, parent, child, color, linewidth):
     GL.glLineWidth(linewidth)
     GL.glColor3f(color[0], color[1], color[2])
     GL.glBegin(GL.GL_LINES)
     GL.glVertex3f(parent[0], parent[1], parent[2])
     GL.glVertex3f(child[0], child[1], child[2])
     GL.glEnd()
Exemplo n.º 30
0
def drawBezier(x,color=None,objtype=GL.GL_LINE_STRIP,granularity=100):
    """Draw a collection of Bezier curves.

    x: (4,3,3) : control points
    color: (4,) or (4,4): colors
    """
    GL.glMap1f(GL.GL_MAP1_VERTEX_3,0.0,1.0,x)
    GL.glEnable(GL.GL_MAP1_VERTEX_3)
    if color is not None and color.shape == (4,4):
        GL.glMap1f(GL.GL_MAP1_COLOR_4,0.0,1.0,color)
        GL.glEnable(GL.GL_MAP1_COLOR_4)

    u = arange(granularity+1) / float(granularity)
    if color is not None and color.shape == (4,):
        GL.glColor4fv(color)
        color = None

    GL.glBegin(objtype)
    for ui in u:
        #  For multicolors, this will generate both a color and a vertex
        GL.glEvalCoord1f(ui)
    GL.glEnd()

    GL.glDisable(GL.GL_MAP1_VERTEX_3)
    if color is not None:
        GL.glDisable(GL.GL_MAP1_COLOR_4)
Exemplo n.º 31
0
    def _OnDrawContent(self, mode, bgcolor, pos, pickerHelper=None):

        # Draw background
        if bgcolor:

            # Set view
            gl.glMatrixMode(gl.GL_PROJECTION)
            gl.glLoadIdentity()
            ortho(0, 1, 0, 1)
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glLoadIdentity()

            # Overwrite all
            gl.glDisable(gl.GL_DEPTH_TEST)

            # Define colors, use gradient?
            bgcolor1 = bgcolor2 = bgcolor3 = bgcolor4 = bgcolor
            if mode != DRAW_SHAPE and self.bgcolors:
                gl.glShadeModel(gl.GL_SMOOTH)
                if len(self.bgcolors) == 2:
                    bgcolor1 = bgcolor2 = self.bgcolors[0]
                    bgcolor3 = bgcolor4 = self.bgcolors[1]
                elif len(self.bgcolors) == 4:
                    bgcolor1, bgcolor2, bgcolor3, bgcolor4 = self.bgcolors

            # Draw
            gl.glBegin(gl.GL_POLYGON)
            gl.glColor3f(bgcolor3[0], bgcolor3[1], bgcolor3[2])
            gl.glVertex2f(0, 0)
            gl.glColor3f(bgcolor1[0], bgcolor1[1], bgcolor1[2])
            gl.glVertex2f(0, 1)
            gl.glColor3f(bgcolor2[0], bgcolor2[1], bgcolor2[2])
            gl.glVertex2f(1, 1)
            gl.glColor3f(bgcolor4[0], bgcolor4[1], bgcolor4[2])
            gl.glVertex2f(1, 0)
            gl.glEnd()

            # Reset
            gl.glEnable(gl.GL_DEPTH_TEST)

        # Draw items in world coordinates
        if True:

            # Setup the camera
            self.camera.SetView()

            # Draw stuff, but wait with lines
            lines2draw = []
            for item in self._wobjects:
                if isinstance(item, (Line, BaseAxis)):
                    lines2draw.append(item)
                else:
                    item._DrawTree(mode, pickerHelper)

            # Lines (and the axis) are a special case. In order to blend
            # them well, we should draw textures, meshes etc, first.
            # Note that this does not work if lines textures are children
            # of each-other. in that case they should be added to the scene
            # in the correct order.
            for item in lines2draw:
                item._DrawTree(mode, pickerHelper)

        # Draw items in screen coordinates
        if mode != DRAW_SHAPE:

            # Set camera to screen coordinates.
            gl.glMatrixMode(gl.GL_PROJECTION)
            gl.glLoadIdentity()
            h = pos.h_fig
            ortho(pos.absLeft, pos.absRight, h - pos.absBottom, h - pos.absTop)
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glLoadIdentity()

            # Allow wobjects to draw in screen coordinates
            # Note that the axis for the 2d camera needs to draw beyond
            # the viewport of the axes, and is therefore drawn later.
            gl.glEnable(gl.GL_DEPTH_TEST)
            is2dcam = isinstance(self.camera, cameras.TwoDCamera)
            for item in self._wobjects:
                if is2dcam and isinstance(item, BaseAxis):
                    continue
                item._DrawTree(DRAW_SCREEN)
Exemplo n.º 32
0
    def makeObject(self):

        genList = GL.glGenLists(1)

        GL.glNewList(genList, GL.GL_COMPILE)

        GL.glBegin(GL.GL_QUADS)

        x1 = +0.06

        y1 = -0.14

        x2 = +0.14

        y2 = -0.06

        x3 = +0.08

        y3 = +0.00

        x4 = +0.30

        y4 = +0.22

        self.quad(x1, y1, x2, y2, y2, x2, y1, x1)

        self.quad(x3, y3, x4, y4, y4, x4, y3, x3)

        self.extrude(x1, y1, x2, y2)

        self.extrude(x2, y2, y2, x2)

        self.extrude(y2, x2, y1, x1)

        self.extrude(y1, x1, x1, y1)

        self.extrude(x3, y3, x4, y4)

        self.extrude(x4, y4, y4, x4)

        self.extrude(y4, x4, y3, x3)

        Pi = 3.14159265358979323846

        NumSectors = 200

        for i in range(NumSectors):

            angle1 = (i * 2 * Pi) / NumSectors

            x5 = 0.30 * math.sin(angle1)

            y5 = 0.30 * math.cos(angle1)

            x6 = 0.20 * math.sin(angle1)

            y6 = 0.20 * math.cos(angle1)

            angle2 = ((i + 1) * 2 * Pi) / NumSectors

            x7 = 0.20 * math.sin(angle2)

            y7 = 0.20 * math.cos(angle2)

            x8 = 0.30 * math.sin(angle2)

            y8 = 0.30 * math.cos(angle2)

            self.quad(x5, y5, x6, y6, x7, y7, x8, y8)

            self.extrude(x6, y6, x7, y7)

            self.extrude(x8, y8, x5, y5)

        GL.glEnd()

        GL.glEndList()

        return genList
Exemplo n.º 33
0
    def paintGL(self, p, opt, widget):
        p.beginNativePainting()
        import OpenGL.GL as gl

        ## set clipping viewport
        view = self.getViewBox()
        if view is not None:
            rect = view.mapRectToItem(self, view.boundingRect())
            #gl.glViewport(int(rect.x()), int(rect.y()), int(rect.width()), int(rect.height()))

            #gl.glTranslate(-rect.x(), -rect.y(), 0)

            gl.glEnable(gl.GL_STENCIL_TEST)
            gl.glColorMask(gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE,
                           gl.GL_FALSE)  # disable drawing to frame buffer
            gl.glDepthMask(gl.GL_FALSE)  # disable drawing to depth buffer
            gl.glStencilFunc(gl.GL_NEVER, 1, 0xFF)
            gl.glStencilOp(gl.GL_REPLACE, gl.GL_KEEP, gl.GL_KEEP)

            ## draw stencil pattern
            gl.glStencilMask(0xFF)
            gl.glClear(gl.GL_STENCIL_BUFFER_BIT)
            gl.glBegin(gl.GL_TRIANGLES)
            gl.glVertex2f(rect.x(), rect.y())
            gl.glVertex2f(rect.x() + rect.width(), rect.y())
            gl.glVertex2f(rect.x(), rect.y() + rect.height())
            gl.glVertex2f(rect.x() + rect.width(), rect.y() + rect.height())
            gl.glVertex2f(rect.x() + rect.width(), rect.y())
            gl.glVertex2f(rect.x(), rect.y() + rect.height())
            gl.glEnd()

            gl.glColorMask(gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE)
            gl.glDepthMask(gl.GL_TRUE)
            gl.glStencilMask(0x00)
            gl.glStencilFunc(gl.GL_EQUAL, 1, 0xFF)

        try:
            x, y = self.getData()
            pos = np.empty((len(x), 2))
            pos[:, 0] = x
            pos[:, 1] = y
            gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
            try:
                gl.glVertexPointerf(pos)
                pen = fn.mkPen(self.opts['pen'])
                color = pen.color()
                gl.glColor4f(color.red() / 255.,
                             color.green() / 255.,
                             color.blue() / 255.,
                             color.alpha() / 255.)
                width = pen.width()
                if pen.isCosmetic() and width < 1:
                    width = 1
                gl.glPointSize(width)
                gl.glLineWidth(width)
                gl.glEnable(gl.GL_LINE_SMOOTH)
                gl.glEnable(gl.GL_BLEND)
                gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
                gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
                gl.glDrawArrays(gl.GL_LINE_STRIP, 0,
                                int(pos.size / pos.shape[-1]))
            finally:
                gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
        finally:
            p.endNativePainting()
Exemplo n.º 34
0
def draw_polygons(x,n,c,t,alpha,objtype):
    """Draw a collection of polygons.

    x : float (nel,nplex,3) : coordinates.
    n : float (nel,3) or (nel,nplex,3) : normals.
    c : float (nel,3) or (nel,nplex,3) : color(s)
    t : float (nplex,2) or (nel,nplex,2) : texture coords
    alpha : float
    objtype : GL Object type (-1 = auto)

    If nplex colors per element are given, and shading mode is flat,
    the last color will be used.
    """
    pf.debug("draw_tex_polygons",pf.DEBUG.DRAW)
    x = x.astype(float32)
    nelems,nplex = x.shape[:2]
    ndn = ndc = ndt = 0
    if n is not None:
        n = n.astype(float32)
        ndn = n.ndim
    if c is not None:
        c = c.astype(float32)
        ndc = c.ndim
    if t is not None:
        t = t.astype(float32)
        ndt = t.ndim
    if objtype < 0:
        objtype = glObjType(nplex)

    pf.debug("nelems=%s, nplex=%s, ndn=%s, ndc=%s, ndt=%s, objtype=%s"%(nelems,nplex,ndn,ndc,ndt,objtype),pf.DEBUG.DRAW)

    simple = nplex <= 4 and objtype == glObjType(nplex)
    if simple:
        GL.glBegin(objtype)
        if ndc == 1:
            glColor(c,alpha)
        for i in range(nelems):
            if ndc == 2:
                glColor(c[i],alpha)
            if ndn == 2:
                GL.glNormal3fv(n[i])
            for j in range(nplex):
                if ndn == 3:
                    GL.glNormal3fv(n[i,j])
                if ndc == 3:
                    glColor(c[i,j],alpha)
                if ndt == 2:
                    GL.glTexCoord2fv(t[j])
                elif ndt == 3:
                    GL.glTexCoord2fv(t[i,j])
                GL.glVertex3fv(x[i,j])
        GL.glEnd()

    else:
        if ndc == 1:
            glColor(c,alpha)
        for i in range(nelems):
            GL.glBegin(objtype)
            if ndc == 2:
                glColor(c[i],alpha)
            if ndn == 2:
                GL.glNormal3fv(n[i])
            for j in range(nplex):
                if ndn == 3:
                    GL.glNormal3fv(n[i,j])
                if ndc == 3:
                    glColor(c[i,j],alpha)
                if ndt == 2:
                    GL.glTexCoord2fv(t[j])
                elif ndt == 3:
                    GL.glTexCoord2fv(t[i,j])
                GL.glVertex3fv(x[i,j])
            GL.glEnd()
    def paintGL(self):
        myBez = Make_bez(xyzs)
        us = [i / 100 for i in range(0, 101, 4)]
        vs = [i / 100 for i in range(0, 101, 4)]

        bezierPoints = myBez.bezierSurface(us, vs)

        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        GL.glLoadIdentity()
        GLU.gluLookAt(1, 1, 3, -2.5, 0, -3, 0, 1.5, 0)
        GL.glColor3f(1, 1, 1)

        # Рисуем оси
        GL.glBegin(GL.GL_LINES)
        GL.glVertex3f(0, 0, 0)
        GL.glVertex3f(0, 0, 40)
        GL.glEnd()
        GL.glBegin(GL.GL_LINES)
        GL.glVertex3f(0, 0, 0)
        GL.glVertex3f(40, 0, 0)
        GL.glEnd()
        GL.glBegin(GL.GL_LINES)
        GL.glVertex3f(0, 0, 0)
        GL.glVertex3f(0, 40, 0)
        GL.glEnd()

        # Рисуем горизонтальные линии многоугольника
        GL.glColor(1, 0, 0)
        GL.glBegin(GL.GL_LINE_STRIP)
        for i in range(len(xyzs)):
            for j in range(len(xyzs)):
                GL.glVertex3f(xyzs[i][j][0], xyzs[i][j][1], xyzs[i][j][2])
        GL.glEnd()
        # Рисуем вертикальные линии многоугольника
        GL.glBegin(GL.GL_LINE_STRIP)
        for i in range(len(xyzs)):
            for j in range(len(xyzs)):
                GL.glVertex3f(xyzs[j][i][0], xyzs[j][i][1], xyzs[j][i][2])
        GL.glEnd()

        # Рисуем горизонтальные линии поверхности Безье
        GL.glColor(0, 1, 0)
        GL.glBegin(GL.GL_LINE_STRIP)
        for i in range(len(bezierPoints)):
            for j in range(len(bezierPoints)):
                if bezierPoints[i][j] == 0:
                    continue
                GL.glVertex3f(bezierPoints[i][j][0], bezierPoints[i][j][1],
                              bezierPoints[i][j][2])
        GL.glEnd()
        # Рисуем вертикальные линии поверхности Безье
        GL.glBegin(GL.GL_LINE_STRIP)
        for i in range(len(bezierPoints)):
            for j in range(len(bezierPoints)):
                GL.glVertex3f(bezierPoints[j][i][0], bezierPoints[j][i][1],
                              bezierPoints[j][i][2])
        GL.glEnd()
Exemplo n.º 36
0
    def render(self):
        super(GatherViewer, self).render()
        ctx = MjRenderContext(self.env.env.sim)
        scn = ctx.scn
        con = ctx.con
        functions.mjv_makeScene(scn, 1000)
        scn.camera[0].frustum_near = 0.05
        scn.camera[1].frustum_near = 0.05

        for obj in self.env.objects:
            x, y, typ = obj
            qpos = np.zeros_like(self.green_ball_sim.data.qpos)
            qpos[0] = x
            qpos[1] = y
            if typ == APPLE:
                self.green_ball_sim.data.qpos[:] = qpos
                self.green_ball_sim.forward()
                self.green_ball_renderer.render()
                self.green_ball_ctx = MjRenderContext(self.green_ball_sim)
                functions.mjv_addGeoms(self.green_ball_sim.model,
                                       self.green_ball_sim.data,
                                       self.green_ball_ctx.vopt,
                                       self.green_ball_ctx.pert, CAT_ALL, scn)
            else:
                self.red_ball_sim.data.qpos[:] = qpos
                self.red_ball_sim.forward()
                self.red_ball_renderer.render()
                self.red_ball_ctx = MjRenderContext(self.red_ball_sim)
                functions.mjv_addGeoms(self.red_ball_sim.model,
                                       self.red_ball_sim.data,
                                       self.red_ball_ctx.vopt,
                                       self.red_ball_ctx.pert, CAT_ALL, scn)

        functions.mjv_addGeoms(self.env.env.sim.model, self.env.env.sim.data,
                               ctx.vopt, ctx.pert, CAT_ALL, scn)
        functions.mjr_render(self.green_ball_renderer.get_rect(), scn, con)

        try:
            import OpenGL.GL as GL
        except ImportError:
            return

        def draw_rect(x, y, width, height):
            # start drawing a rectangle
            GL.glBegin(GL.GL_QUADS)
            # bottom left point
            GL.glVertex2f(x, y)
            # bottom right point
            GL.glVertex2f(x + width, y)
            # top right point
            GL.glVertex2f(x + width, y + height)
            # top left point
            GL.glVertex2f(x, y + height)

        def refresh2d(width, height):
            GL.glViewport(0, 0, width, height)
            GL.glMatrixMode(GL.GL_PROJECTION)
            GL.glLoadIdentity()
            GL.glOrtho(0.0, width, 0.0, height, 0.0, 1.0)
            GL.glMatrixMode(GL.GL_MODELVIEW)
            GL.glLoadIdentity()

        GL.glBegin(GL.GL_QUADS)
        GL.glLoadIdentity()
        width, height = glfw.get_framebuffer_size(self.window)
        refresh2d(width, height)
        GL.glDisable(GL.GL_LIGHTING)
        GL.glEnable(GL.GL_BLEND)

        GL.glColor4f(0.0, 0.0, 0.0, 0.8)
        draw_rect(10, 10, 300, 100)

        apple_readings, bomb_readings = self.env.get_readings()
        for idx, reading in enumerate(apple_readings):
            if reading > 0:
                GL.glColor4f(0.0, 1.0, 0.0, reading)
                draw_rect(20 * (idx + 1), 10, 5, 50)
        for idx, reading in enumerate(bomb_readings):
            if reading > 0:
                GL.glColor4f(1.0, 0.0, 0.0, reading)
                draw_rect(20 * (idx + 1), 60, 5, 50)
Exemplo n.º 37
0
    def redraw_perspective(self):

        w = self.winfo_width()
        h = self.winfo_height()
        GL.glViewport(0, 0, w, h)  # left corner in pixels
        if self.use_gradient_background:
            GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
            ###
            GL.glMatrixMode(GL.GL_PROJECTION)
            GL.glLoadIdentity()  # switch to identity (origin) matrix

            GL.glMatrixMode(GL.GL_MODELVIEW)
            GL.glPushMatrix()
            GL.glPushMatrix()
            GL.glLoadIdentity()

            GL.glDisable(GL.GL_DEPTH_TEST)
            GL.glBegin(GL.GL_QUADS)
            #//bottom color
            color = self.gradient_color1
            GL.glColor3f(color[0], color[1], color[2])
            GL.glVertex2f(-1.0, -1.0)
            GL.glVertex2f(1.0, -1.0)
            #//top color
            color = self.gradient_color2
            GL.glColor3f(color[0], color[1], color[2])
            GL.glVertex2f(1.0, 1.0)
            GL.glVertex2f(-1.0, 1.0)
            GL.glEnd()
            GL.glEnable(GL.GL_DEPTH_TEST)

            GL.glPopMatrix()
            GL.glPopMatrix()

        else:
            # Clear the background and depth buffer.
            GL.glClearColor(*(self.colors['back'] + (0, )))
            GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GLU.gluPerspective(
            self.
            fovy,  # The vertical Field of View, in radians: the amount of "zoom".
            # Think "camera lens". Usually between 90 (extra wide) and 30 (quite zoomed in)
            float(w) / float(
                h
            ),  # Aspect Ratio. Notice that 4/3 == 800/600 screen resolution
            self.
            near,  # near clipping plane. Keep as big as possible, or you'll get precision issues.
            self.far +
            self.distance)  # Far clipping plane. Keep as little as possible.
        GLU.gluLookAt(
            0,
            0,
            self.distance,  # the position of your camera, in world space
            0,
            0,
            0,  # where you want to look at, in world space
            0.,
            1.,
            0.
        )  # probably glm::vec3(0,1,0), but (0,-1,0) would make you looking upside-down
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glPushMatrix()
        try:
            self.redraw()
        finally:
            GL.glFlush()  # Tidy up
            GL.glPopMatrix()  # Restore the matrix
Exemplo n.º 38
0
def draw_line(v1, v2):
    gl.glBegin(gl.GL_LINES)
    gl.glVertex3f(v1.x, v1.y, v1.z)
    gl.glVertex3f(v2.x, v2.y, v2.z)
    gl.glEnd()
Exemplo n.º 39
0
    def glMainLoop(self):
        self.logger.info("Running gl viewer ...")

        flag = False

        pangolin.CreateWindowAndBind('Main', 640, 480)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        panel = pangolin.CreatePanel('menu')
        panel.SetBounds(1.0, 1.0, 0.0, 100 / 640.)

        # Does not work with initialization of window
        # self.Init()

        camera_pose = pangolin.OpenGlMatrix()

        # create scene graph
        #     scene = pangolin.Renderable()
        #     # x : R
        #     # y : G
        #     # z : B
        #     scene.Add(pangolin.Axis())

        #
        rendered_cam = pangolin.OpenGlRenderState(
            pangolin.ProjectionMatrix(640, 480, 420, 420, 320, 240, 0.01,
                                      2000),
            pangolin.ModelViewLookAt(1, 0, 1, 0, 0, 0, 0, 0, 1))
        handler = pangolin.Handler3D(rendered_cam)
        #     handler = pangolin.SceneHandler(scene, rendered_cam)

        # add drawing callback

        #
        viewport = pangolin.CreateDisplay()
        viewport.SetBounds(0.0, 1.0, 0.0, 1.0, -640.0 / 480.0)
        viewport.SetHandler(handler)

        image_viewport = pangolin.Display('image')
        w = 160
        h = 120
        image_viewport.SetBounds(0, h / 480., 0.0, w / 640., 640. / 480.)
        image_viewport.SetLock(pangolin.Lock.LockLeft, pangolin.Lock.LockTop)

        texture = pangolin.GlTexture(w, h, gl.GL_RGB, False, 0, gl.GL_RGB,
                                     gl.GL_UNSIGNED_BYTE)

        # geometries
        self.lines = []
        self.points = {}
        self.colors = {}
        self.poses = []

        self.redundant_points = []
        self.redundant_colors = []

        self.landmarks = {}

        #
        img = np.ones((h, w, 3), 'uint8')

        while not pangolin.ShouldQuit():

            datum = None
            if not self.attributes.empty():
                self.logger.info(
                    "[GL Process] attributes is not empty, fetching datum ...")
                datum = self.attributes.get()
                self.logger.info(
                    "[GL Process] get a datum from the main thread of the parent process"
                )

            if datum is not None:
                # dispatch instructions
                if datum.attrs.get('pose', None) is not None:
                    pose = datum.attrs['pose']
                    # self.camera.pose.m = pose
                    # set Twc
                    camera_pose.m = pose  # np.linalg.inv(pose)
                    # camera_pose.m = pose
                    rendered_cam.Follow(camera_pose, True)
                    self.logger.info(
                        "[GL Process] update camera pose matrix got from datum: \n%s"
                        % pose)
                    pass
                pass

            # self.Clear()
            # self.control.Update(self.camera.pose)

            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            gl.glClearColor(1.0, 1.0, 1.0, 1.0)
            viewport.Activate(rendered_cam)
            #       scene.Render()

            # Just for test
            # pangolin.glDrawColouredCube(0.1)

            # render graph
            if datum is not None:
                # dispatch data

                # update graph
                if datum.attrs.get('lines', None) is not None:
                    lines = datum.attrs['lines']
                    self.lines.extend(lines)
                    self.logger.info("[GL Process] drawing %d lines ..." %
                                     len(lines))

                if datum.attrs.get('pose', None) is not None:
                    pose = datum.attrs['pose']
                    self.poses.append(pose)
                    self.logger.info(
                        "[GL Process] drawing a camera with new pose matrix ..."
                    )
                    pass

                # update image
                if datum.attrs.get('img', None) is not None:
                    img = datum.attrs['img']
                    # see pangolin issue #180
                    # change cv BGR channels to norm one
                    # img = img[::-1, : ,::-1].astype(np.uint8)
                    img = img.astype(np.uint8)
                    img = cv2.resize(img, (w, h))
                    self.logger.info(
                        "[GL Process] drawing image to image viewport ...")

                # show mappoints
                if datum.attrs.get('points', None) is not None:
                    points = datum.attrs['points']
                    if len(points) > 0:
                        # self.points.extend(points)
                        for point in points:
                            self.points[point.seq] = point

                        # colors = np.array([p.color if p.color is not None else np.array([1.0, 0.0, 0.0]) for p in points]).astype(np.float64)
                        colors = [
                            p.color / 255. if p.color is not None else
                            np.array([1.0, 1.0, 0.0]) for p in points
                        ]
                        # print("colors: \n%s" % np.array(colors))

                        # colors = [ [1., 1., 0.] for p in points]

                        # self.colors.extend(colors)
                        for i, color in enumerate(colors):
                            point = points[i]
                            self.colors[point.seq] = color

                        self.logger.info("[GL Process] drawing %d points" %
                                         len(points))
                        # print("new mappoints: \n%s" % np.array([ p.data for p in points]).astype(np.float64))
                        # print("new colors (default): \n%s" % np.array(colors))
                    else:
                        self.logger.info("[GL Process] no points to be drawn.")

                # redundant points
                if datum.attrs.get('points-redundant', None) is not None:
                    points = datum.attrs['points-redundant']
                    colors = datum.attrs['colors-redundant']

                    for i, p in enumerate(points):
                        self.redundant_points.append(p)
                        self.redundant_colors.append(colors[i] / 255.)

                # show landmarks
                if datum.attrs.get('landmarks', None) is not None:
                    landmarks = datum.attrs['landmarks']
                    for landmark in landmarks:
                        self.landmarks[landmark.seq] = landmark
                    self.logger.info("[GL Process] drawing %d landmarks" %
                                     len(landmarks))

                self.attributes.task_done()
                self.logger.info("[GL Process] datum has been processed.")

            ############
            # draw graph
            ############
            line_geometries = np.array([[*line[0], *line[1]]
                                        for line in self.lines])
            if len(line_geometries) > 0:
                gl.glLineWidth(1)
                gl.glColor3f(0.0, 1.0, 0.0)
                pangolin.DrawLines(line_geometries, 3)

            # pose = self.camera.pose
            pose = camera_pose

            # GL 2.0 API
            gl.glPointSize(4)
            gl.glColor3f(1.0, 0.0, 0.0)

            gl.glBegin(gl.GL_POINTS)
            gl.glVertex3d(pose[0, 1], pose[1, 3], pose[2, 3])
            gl.glEnd()

            ############
            # draw poses
            ############
            if len(self.poses) > 0:
                gl.glLineWidth(1)
                gl.glColor3f(0.0, 0.0, 1.0)

                # poses: numpy.ndarray[float64], w: float=1.0, h_ratio: float=0.75, z_ratio: float=0.6
                pangolin.DrawCameras(np.array(self.poses))

                gl.glPointSize(4)
                gl.glColor3f(0.0, 0.0, 1.0)

                gl.glBegin(gl.GL_POINTS)
                for pose in self.poses:
                    gl.glVertex3d(pose[0, 1], pose[1, 3], pose[2, 3])
                gl.glEnd()

            ################
            # draw mappoints
            ################
            if len(self.points) > 0:
                # points_geometries = np.array([p.data for p in self.points]).astype(np.float64)
                points_geometries = []
                colors = []
                for point_key, p in self.points.items():
                    points_geometries.append(p.data)
                    colors.append(self.colors[point_key])

                points_geometries = np.array(points_geometries).astype(
                    np.float64)
                colors = np.array(colors).astype(np.float64)

                gl.glPointSize(6)
                # pangolin.DrawPoints(points_geometries, np.array(self.colors).astype(np.float64) )
                pangolin.DrawPoints(points_geometries, colors)

                # gl.glPointSize(4)
                # gl.glColor3f(1.0, 0.0, 0.0)
                #
                # gl.glBegin(gl.GL_POINTS)
                # for point in points_geometries:
                #   gl.glVertex3d(point[0], point[1], point[2])
                # gl.glEnd()

            ####################
            # redundant points #
            ####################
            if len(self.redundant_points) > 0:
                points_geometries = []
                colors = []
                for i, p in enumerate(self.redundant_points):
                    points_geometries.append(p.data)
                    colors.append(self.redundant_colors[i])

                points_geometries = np.array(points_geometries).astype(
                    np.float64)
                colors = np.array(colors).astype(np.float64)

                gl.glPointSize(3)
                pangolin.DrawPoints(points_geometries, colors)

            ################
            # draw landmarks
            ################
            for key, landmarkDatum in self.landmarks.items():
                # abox = landmark.computeAABB()
                # drawABox(abox.toArray())

                drawABox(landmarkDatum.abox.toArray(),
                         color=landmarkDatum.color)
                pass

            #############
            # draw images
            #############
            # self.camera.RenderImg(img)
            texture.Upload(img, gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
            image_viewport.Activate()
            gl.glColor3f(1.0, 1.0, 1.0)
            texture.RenderToViewport()

            pangolin.FinishFrame()

        print("gl program loop stopped")
        with self._state_locker:
            self._stopped = True
Exemplo n.º 40
0
import glcontext

import OpenGL.GL as gl
import glrenderer
import matplotlib.pyplot as plt

import time

glcontext.create_opengl_context((WIDTH, HEIGHT))
print(gl.glGetString(gl.GL_VERSION))
start = time.time()

for i in range(10000):
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glBegin(gl.GL_TRIANGLES)
    gl.glColor3f(1, 0, 0)
    gl.glVertex2f(0, 1)

    gl.glColor3f(0, 1, 0)
    gl.glVertex2f(-1, -1)

    gl.glColor3f(0, 0, 1)
    gl.glVertex2f(1, -1)
    gl.glEnd()

dt = time.time() - start
print("{} trangles per sec".format(10000 / dt))
# Read result
img_buf = gl.glReadPixels(0, 0, WIDTH, HEIGHT, gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
img = np.frombuffer(img_buf, np.uint8).reshape(HEIGHT, WIDTH, 3)[::-1]
Exemplo n.º 41
0
def Cube():
    GL.glBegin(GL.GL_LINES)
    for edge in edges:
        for vertex in edge:
            GL.glVertex3fv(verticies[vertex])
    GL.glEnd()
Exemplo n.º 42
0
def draw_triangles(vertices: PointList, color: Color4f = (0, 1, 1, 1)) -> None:
    GL.glColor4d(*color)
    GL.glBegin(GL.GL_TRIANGLES)
    for vertex in vertices:
        GL.glVertex3d(*vertex)
    GL.glEnd()
Exemplo n.º 43
0
    def get_2D_signal_traces(self):
        """Get the signal traces from the monitors object and display in 2D."""

        # Exit function if no signals are being monitored
        if not self.monitors.monitors_dictionary:
            return

        y_pos = 20

        # Plot each signal in monitors_dictionary (holds all monitored signals)
        for device_id, output_id in self.monitors.monitors_dictionary:
            signal_list = self.monitors.monitors_dictionary[(device_id,
                                                             output_id)]

            text = self.names.get_name_string(device_id)

            # If device has more than one output ...
            if output_id:
                text += ("." + self.names.get_name_string(output_id))
            self.render_text_2D(text, 5, y_pos + 10)  # Display signal name.

            # Draw grey axis
            if len(signal_list) > 0:
                grey = [0.8, 0.8, 0.8]
                GL.glColor3fv(grey)
                x_next = 0
                y = 0
                y_up = 0
                y_down = 0
                i = 0

                for signal in signal_list:
                    GL.glBegin(GL.GL_LINES)

                    x = (i * 20) + 30
                    x_next = (i * 20) + 50
                    y = y_pos
                    y_up = y + 5
                    y_down = y - 5

                    GL.glVertex2f(x, y_up)
                    GL.glVertex2f(x, y_down)

                    GL.glVertex2f(x, y)
                    GL.glVertex2f(x_next, y)

                    GL.glEnd()

                    self.render_text_2D(str(i), x - 2, y_down - 10, grey)
                    i += 1

                GL.glBegin(GL.GL_LINES)
                GL.glVertex2f(x_next, y_up)
                GL.glVertex2f(x_next, y_down)
                GL.glEnd()

                self.render_text_2D(str(i), x_next - 2, y_down - 10, grey)

            # Draw signal
            GL.glColor3f(0.0, 0.0, 1.0)
            GL.glBegin(GL.GL_LINE_STRIP)
            drawing = True
            i = 0

            for signal in signal_list:
                if signal != self.devices.BLANK:
                    if not drawing:
                        GL.glBegin(GL.GL_LINE_STRIP)
                        drawing = True

                    if signal == self.devices.HIGH:
                        x = (i * 20) + 30
                        x_next = (i * 20) + 50
                        y = y_pos + 20
                        y_next = y
                    elif signal == self.devices.LOW:
                        x = (i * 20) + 30
                        x_next = (i * 20) + 50
                        y = y_pos
                        y_next = y
                    elif signal == self.devices.RISING:
                        x = (i * 20) + 30
                        x_next = x
                        y = y_pos
                        y_next = y_pos + 20
                    elif signal == self.devices.FALLING:
                        x = (i * 20) + 30
                        x_next = x
                        y = y_pos + 20
                        y_next = y_pos

                    GL.glVertex2f(x, y)
                    GL.glVertex2f(x_next, y_next)

                else:
                    if drawing:
                        GL.glEnd()
                        drawing = False

                i += 1

            GL.glEnd()
            y_pos += 60
Exemplo n.º 44
0
    def to_OpenGL(self):
        if not GL_enabled:
            return
        height_field = self.get_height_field()
        def get_box_height_points(x, y):
            """ Get the positions and heights of the the four top corners of a
            height box.

            The result is a tuple of four Points (pycam.Geometry.Point) in the
            following order:
             - left below
             - right below
             - right above
             - left above
            ("above": greater x value; "right": greater y value)
            The height of each corner point is calculated as the average of the
            four neighbouring boxes. Thus a set of 3x3 adjacent boxes is used
            for calculating the heights of the four corners.
            """
            points = []
            # Go through a set of box index combinations (sharing a common
            # corner). The "offsets" tuple is used for indicating the relative
            # position of each corner.
            for offsets, index_list in (
                ((-1, -1), ((x - 1, y - 1), (x, y - 1), (x, y), (x - 1, y))),
                ((+1, -1), ((x, y - 1), (x, y), (x + 1, y), (x + 1, y - 1))),
                ((+1, +1), ((x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1))),
                ((-1, +1), ((x - 1, y), (x, y), (x, y + 1), (x - 1, y + 1)))):
                divisor = 0
                height_sum = 0
                x_positions = []
                y_positions = []
                for ix, iy in index_list:
                    if (0 <= ix < len(height_field)) \
                            and (0 <= iy < len(height_field[ix])):
                        point = height_field[ix][iy]
                        height_sum += point.z
                        x_positions.append(point.x)
                        y_positions.append(point.y)
                        divisor += 1
                # Use the middle between the x positions of two adjacent boxes,
                # _if_ there is a neighbour attached to that corner.
                if (min(x_positions) < height_field[x][y].x) \
                        or (max(x_positions) > height_field[x][y].x):
                    x_value = (min(x_positions) + max(x_positions)) / 2.0
                else:
                    # There is no adjacent box in x direction. Use the step size
                    # to calculate the x value of this edge.
                    x_value = height_field[x][y].x \
                            + offsets[0] * self.x_step_width / 2.0
                # same as above for y instead of x
                if (min(y_positions) < height_field[x][y].y) \
                        or (max(y_positions) > height_field[x][y].y):
                    y_value = (min(y_positions) + max(y_positions)) / 2.0
                else:
                    y_value = height_field[x][y].y \
                            + offsets[1] * self.y_step_width / 2.0
                # Create a Point instance describing the position and the
                # average height.
                points.append(Point(x_value, y_value, height_sum / divisor))
            return points
        # draw the surface
        GL.glBegin(GL.GL_QUADS)
        for x in xrange(self.x_steps):
            for y in xrange(self.y_steps):
                # Get the positions and heights of the four corners surrounding
                # the current box.
                points_around = get_box_height_points(x, y)
                # Calculate the "normal" of polygon. We picked up three random
                # points of this quadrilateral.
                n = self._normal(points_around[1].z, points_around[2].z,
                        points_around[3].z)
                GL.glNormal3f(n[0], n[1], n[2])
                for point in points_around:
                    GL.glVertex3f(point.x, point.y, point.z)
                # go through the conditions for an edge box and use the
                # appropriate corners for the side faces of the material
                for condition, i1, i2 in ((x == 0, 3, 0), (y == 0, 0, 1),
                        (x == self.x_steps - 1, 1, 2),
                        (y == self.y_steps - 1, 2, 3)):
                    # check if this point belongs to an edge of the material
                    if condition:
                        n = self._normal(points_around[1].z, points_around[2].z,
                                points_around[3].z)
                        GL.glNormal3f(n[0], n[1], n[2])
                        GL.glVertex3f(points_around[i1].x, points_around[i1].y,
                                self.z_offset)
                        GL.glVertex3f(points_around[i1].x, points_around[i1].y,
                                points_around[i1].z)
                        GL.glVertex3f(points_around[i2].x, points_around[i2].y,
                                points_around[i2].z)
                        GL.glVertex3f(points_around[i2].x, points_around[i2].y,
                                self.z_offset)
        GL.glEnd()
Exemplo n.º 45
0
    def paintGL(self):
        # The last transformation you specify takes place first.
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        GL.glLoadIdentity()
        GL.glRotatef(self.rotX, 1.0, 0.0, 0.0)
        GL.glRotatef(self.rotY, 0.0, 1.0, 0.0)
        GL.glRotatef(self.rotZ, 0.0, 0.0, 1.0)
        GL.glTranslatef(self.posX, self.posY, self.posZ)
        GL.glScalef(self.scale, self.scale, self.scale)
        for shape in self.shapes.selected_iter():
            if not shape.disabled:
                self.setColor(GLWidget.COLOR_STMOVE)
                GL.glCallList(shape.drawStMove)
                self.setColor(GLWidget.COLOR_SELECT)
                GL.glCallList(shape.drawObject)
            elif self.showDisabledPaths:
                self.setColor(GLWidget.COLOR_SELECT_DISABLED)
                GL.glCallList(shape.drawObject)
        for shape in self.shapes.not_selected_iter():
            if not shape.disabled:
                if shape.parentLayer.isBreakLayer():
                    self.setColor(GLWidget.COLOR_BREAK)
                elif shape.cut_cor == 41:
                    self.setColor(GLWidget.COLOR_LEFT)
                elif shape.cut_cor == 42:
                    self.setColor(GLWidget.COLOR_RIGHT)
                else:
                    self.setColor(GLWidget.COLOR_NORMAL)
                GL.glCallList(shape.drawObject)
                if self.showPathDirections:
                    self.setColor(GLWidget.COLOR_STMOVE)
                    GL.glCallList(shape.drawStMove)
            elif self.showDisabledPaths:
                self.setColor(GLWidget.COLOR_NORMAL_DISABLED)
                GL.glCallList(shape.drawObject)

        # optimization route arrows
        self.setColor(GLWidget.COLOR_ROUTE)
        GL.glBegin(GL.GL_LINES)
        for route in self.routearrows:
            start = route[0]
            end = route[1]
            GL.glVertex3f(start.x, -start.y, start.z)
            GL.glVertex3f(end.x, -end.y, end.z)
        GL.glEnd()

        GL.glScalef(self.scaleCorr / self.scale, self.scaleCorr / self.scale,
                    self.scaleCorr / self.scale)
        scaleArrow = self.scale / self.scaleCorr
        for route in self.routearrows:
            # ignore uninitialized arrows
            if route[2] < 0:
                continue
            end = scaleArrow * route[1]
            GL.glTranslatef(end.x, -end.y, end.z)
            GL.glCallList(route[2])
            GL.glTranslatef(-end.x, end.y, -end.z)

        # direction arrows
        for shape in self.shapes:
            if shape.selected and (not shape.disabled or self.showDisabledPaths) or\
               self.showPathDirections and not shape.disabled:
                start, end = shape.get_start_end_points_physical()
                start = scaleArrow * start.to3D(shape.axis3_start_mill_depth)
                end = scaleArrow * end.to3D(shape.axis3_mill_depth)
                GL.glTranslatef(start.x, -start.y, start.z)
                GL.glCallList(shape.drawArrowsDirection[0])
                GL.glTranslatef(-start.x, start.y, -start.z)
                GL.glTranslatef(end.x, -end.y, end.z)
                GL.glCallList(shape.drawArrowsDirection[1])
                GL.glTranslatef(-end.x, end.y, -end.z)

        if self.wpZero > 0:
            GL.glCallList(self.wpZero)
        GL.glTranslatef(-self.posX / self.scaleCorr,
                        -self.posY / self.scaleCorr,
                        -self.posZ / self.scaleCorr)
        GL.glCallList(self.orientation)
Exemplo n.º 46
0
    def __drawLegend(self):
        """Draws a legend in the bottom left corner of the screen, showing
        anatomical orientation.
        """

        copts = self.opts
        b = self.__displayCtx.bounds
        w, h = self.GetSize()
        xlen, ylen = glroutines.adjust(b.xlen, b.ylen, w, h)

        # A line for each axis
        vertices = np.zeros((6, 3), dtype=np.float32)
        vertices[0, :] = [-1, 0, 0]
        vertices[1, :] = [1, 0, 0]
        vertices[2, :] = [0, -1, 0]
        vertices[3, :] = [0, 1, 0]
        vertices[4, :] = [0, 0, -1]
        vertices[5, :] = [0, 0, 1]

        # Each axis line is scaled to
        # 60 pixels, and the legend is
        # offset from the bottom-left
        # corner by twice this amount.
        scale = [xlen * 30.0 / w] * 3
        offset = [
            -0.5 * xlen + 2.0 * scale[0], -0.5 * ylen + 2.0 * scale[1], 0
        ]

        # Apply the current camera
        # angle and rotation settings
        # to the legend vertices. Offset
        # anatomical labels off each
        # axis line by a small amount.
        rotation = transform.decompose(self.__viewMat)[2]
        xform = transform.compose(scale, offset, rotation)
        labelPoses = transform.transform(vertices * 1.2, xform)
        vertices = transform.transform(vertices, xform)

        # Draw the legend lines
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glColor3f(*copts.cursorColour[:3])
        gl.glLineWidth(2)
        gl.glBegin(gl.GL_LINES)
        gl.glVertex3f(*vertices[0])
        gl.glVertex3f(*vertices[1])
        gl.glVertex3f(*vertices[2])
        gl.glVertex3f(*vertices[3])
        gl.glVertex3f(*vertices[4])
        gl.glVertex3f(*vertices[5])
        gl.glEnd()

        # Figure out the anatomical
        # labels for each axis.
        overlay = self.__displayCtx.getSelectedOverlay()
        dopts = self.__displayCtx.getOpts(overlay)
        labels = dopts.getLabels()[0]

        # getLabels returns (xlo, ylo, zlo, xhi, yhi, zhi) -
        # - rearrange them to (xlo, xhi, ylo, yhi, zlo, zhi)
        labels = [
            labels[0], labels[3], labels[1], labels[4], labels[2], labels[5]
        ]

        canvas = np.array([w, h])
        view = np.array([xlen, ylen])

        # Draw each label
        for i in range(6):

            # Calculate pixel x/y
            # location for this label
            xx, xy = canvas * (labelPoses[i, :2] + 0.5 * view) / view

            # Calculate the size of the label
            # in pixels, so we can centre the
            # label
            tw, th = glroutines.text2D(labels[i], (xx, xy),
                                       10, (w, h),
                                       calcSize=True)

            # Draw the text
            xx -= 0.5 * tw
            xy -= 0.5 * th
            gl.glColor3f(*copts.legendColour[:3])
            glroutines.text2D(labels[i], (xx, xy), 10, (w, h))
Exemplo n.º 47
0
def curve_thicken(points, thickness=1.0, support=0.75):
    """
    """

    alpha = min(thickness, 1.0)
    thickness = max(thickness, 1.0)
    w = math.ceil(2.5 * support + thickness)

    # Points
    P = np.array(points).reshape(len(points), 2)

    # Tangent vectors
    T = np.zeros_like(P)
    T[:-1] = P[1:] - P[:-1]
    T[-1] = T[-2]  # repeating last tangent for last point

    # Normalization and scaling
    L = np.sqrt(T[:, 0]**2 + T[:, 1]**2)
    T *= (w / 2) / L.reshape(len(P), 1)

    # Total length of curve
    L = np.cumsum(L)
    # Last cumulative sum is wrong because of the repeat of the last point
    L[1:] = L[:-1]
    L[0] = 0
    length = L[-1]

    X, Y = P[:, 0], P[:, 1]
    dX, dY = T[:, 0], T[:, 1]
    n = (len(P)) * 2 + 4
    V = np.zeros(n, [('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]),
                     ('texture', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]),
                     ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'),
                                ('a', 'f4')])])

    V['color'] = 0, 0, 0, alpha

    # Main body
    V['vertex']['x'][2:-3:2] = X - dY
    V['vertex']['y'][2:-3:2] = Y + dX
    V['texture']['x'][2:-3:2] = L
    V['texture']['y'][2:-3:2] = -w / 2

    V['vertex']['x'][3:-2:2] = X + dY
    V['vertex']['y'][3:-2:2] = Y - dX
    V['texture']['x'][3:-2:2] = L
    V['texture']['y'][3:-2:2] = +w / 2

    # Cap at start
    V['vertex']['x'][0] = X[0] - dX[0] - dY[0]
    V['vertex']['y'][0] = Y[0] - dY[0] + dX[0]
    V['texture']['x'][0] = -w / 2
    V['texture']['y'][0] = -w / 2

    V['vertex']['x'][1] = X[0] - dX[0] + dY[0]
    V['vertex']['y'][1] = Y[0] - dY[0] - dX[0]
    V['texture']['x'][1] = -w / 2
    V['texture']['y'][1] = +w / 2

    # Cap at end
    V['vertex']['x'][-2] = X[-1] + dX[-1] - dY[-1]
    V['vertex']['y'][-2] = Y[-1] + dY[-1] + dX[-1]
    V['texture']['x'][-2] = length + w / 2
    V['texture']['y'][-2] = -w / 2

    V['vertex']['x'][-1] = X[-1] + dX[-1] + dY[-1]
    V['vertex']['y'][-1] = Y[-1] + dY[-1] - dX[-1]
    V['texture']['x'][-1] = length + w / 2
    V['texture']['y'][-1] = +w / 2

    shader.bind()
    shader.uniformf('support', support)
    shader.uniformf('length', length)
    shader.uniformf('thickness', thickness)
    gl.glColor(0, 0, 0, alpha)

    gl.glBegin(gl.GL_TRIANGLES)
    for i in range(0, len(V) - 3, 2):
        gl.glTexCoord2f(V['texture']['x'][i + 0], V['texture']['y'][i + 0])
        gl.glVertex(V['vertex'][i + 0])
        gl.glTexCoord2f(V['texture']['x'][i + 1], V['texture']['y'][i + 1])
        gl.glVertex(V['vertex'][i + 1])
        gl.glTexCoord2f(V['texture']['x'][i + 2], V['texture']['y'][i + 2])
        gl.glVertex(V['vertex'][i + 2])

        gl.glTexCoord2f(V['texture']['x'][i + 1], V['texture']['y'][i + 1])
        gl.glVertex(V['vertex'][i + 1])
        gl.glTexCoord2f(V['texture']['x'][i + 2], V['texture']['y'][i + 2])
        gl.glVertex(V['vertex'][i + 2])
        gl.glTexCoord2f(V['texture']['x'][i + 3], V['texture']['y'][i + 3])
        gl.glVertex(V['vertex'][i + 3])
    gl.glEnd()
    shader.unbind()
Exemplo n.º 48
0
    def cylinder(self, center_x, center_y, center_z, x_axis, y_axis, size_z,
                 color, wireframe):
        Pi = 3.14159265358979323846
        if wireframe:
            nbr_sides = 18
        else:
            nbr_sides = 100

        pz = center_z + size_z / 2
        mz = center_z - size_z / 2

        #top
        if wireframe:
            GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE)

        GL.glBegin(GL.GL_POLYGON)
        self.qglColor(color)
        for i in range(nbr_sides):
            angle1 = (i * 2 * Pi) / nbr_sides
            x1 = center_x + x_axis / 2 * math.sin(angle1)
            y1 = center_y + y_axis / 2 * math.cos(angle1)
            GL.glVertex3d(x1, y1, pz)

        GL.glEnd()
        #bottom
        GL.glBegin(GL.GL_POLYGON)
        self.qglColor(color)
        for i in range(nbr_sides):
            angle1 = (i * 2 * Pi) / nbr_sides
            x1 = center_x + x_axis / 2 * math.sin(angle1)
            y1 = center_y + y_axis / 2 * math.cos(angle1)
            GL.glVertex3d(x1, y1, mz)
        GL.glEnd()

        #Sides
        GL.glBegin(GL.GL_QUADS)
        self.qglColor(color.darker(250))
        for i in range(nbr_sides):
            angle1 = (i * 2 * Pi) / nbr_sides
            angle2 = ((i + 1) * 2 * Pi) / nbr_sides
            x1 = center_x + x_axis / 2 * math.sin(angle1)
            y1 = center_y + y_axis / 2 * math.cos(angle1)
            x2 = center_x + x_axis / 2 * math.sin(angle2)
            y2 = center_y + y_axis / 2 * math.cos(angle2)
            GL.glVertex3d(x1, y1, pz)
            GL.glVertex3d(x1, y1, mz)
            GL.glVertex3d(x2, y2, mz)
            GL.glVertex3d(x2, y2, pz)
        GL.glEnd()

        #if wireframe: lines in top and bottom
        if wireframe:
            GL.glBegin(GL.GL_LINES)
            self.qglColor(color)
            for i in range(nbr_sides // 2):
                angle1 = (i * 2 * Pi) / nbr_sides
                angle2 = (i * 2 * Pi) / nbr_sides + Pi
                x1 = center_x + x_axis / 2 * math.sin(angle1)
                y1 = center_y + y_axis / 2 * math.cos(angle1)
                x2 = center_x + x_axis / 2 * math.sin(angle2)
                y2 = center_y + y_axis / 2 * math.cos(angle2)
                GL.glVertex3d(x1, y1, pz)
                GL.glVertex3d(x2, y2, pz)
                GL.glVertex3d(x1, y1, mz)
                GL.glVertex3d(x2, y2, mz)
            GL.glEnd()

        if wireframe:
            GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL)
Exemplo n.º 49
0
    def draw(self):
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        GL.glPushMatrix()
        GLU.gluLookAt(self.EYE[0], self.EYE[1], self.EYE[2], \
        self.LOOK_AT[0], self.LOOK_AT[1], self.LOOK_AT[2],\
        self.EYE_UP[0], self.EYE_UP[1], self.EYE_UP[2])

        # print (self.f_rotate_x,self.f_rotate_y,self.f_rotate_z)
        # ---------------------------------------------------------------
        '''
        Draw the coordinate axis
        '''

        GL.glBegin(GL.GL_LINES)
        # x axis
        GL.glColor4f(1.0, 0.0, 0.0, 1.0)
        GL.glVertex3f(0, 0.0, 0.0)
        GL.glVertex3f(-0.8, 0.0, 0.0)

        # y axis
        GL.glColor4f(0.0, 1.0, 0.0, 1.0)
        GL.glVertex3f(0.0, 0, 0.0)
        GL.glVertex3f(0.0, -0.8, 0.0)

        # z axis
        GL.glColor4f(0.0, 0.0, 1.0, 1.0)
        GL.glVertex3f(0.0, 0.0, 0)
        GL.glVertex3f(0.0, 0.0, 0.8)
        GL.glEnd()
        # ---------------------------------------------------------------

        GL.glPushMatrix()
        GL.glScale(self.SCALE_K[0], self.SCALE_K[1], self.SCALE_K[2])

        GL.glTranslatef(self.f_position_x_gt, self.f_position_y_gt,
                        self.f_position_z_gt)
        GL.glRotatef(self.f_rotate_x_gt, 1, 0, 0)
        GL.glRotatef(self.f_rotate_y_gt, 0, 1, 0)
        GL.glRotatef(self.f_rotate_z_gt, 0, 0, 1)

        GL.glBegin(GL.GL_QUADS)
        self.up_part_gate_gt(0.6, 0.6, 0.2)
        GL.glEnd()
        GL.glPopMatrix()

        GL.glPushMatrix()
        GL.glScale(self.SCALE_K[0], self.SCALE_K[1], self.SCALE_K[2])
        GL.glTranslatef(self.f_position_x, self.f_position_y,
                        self.f_position_z)
        GL.glRotatef(self.f_rotate_x, 1, 0, 0)
        GL.glRotatef(self.f_rotate_y, 0, 1, 0)
        GL.glRotatef(self.f_rotate_z, 0, 0, 1)

        GL.glBegin(GL.GL_QUADS)
        self.up_part_gate_pred(0.6, 0.6, 0.2)
        GL.glEnd()
        GL.glPopMatrix()

        GL.glPopMatrix()

        GLUT.glutSwapBuffers()
Exemplo n.º 50
0
def figure():

    polygon_points = []
    faces_angle = (2 * pi) / vertices

    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
    GL.glLoadIdentity()

    GL.glPushMatrix()

    GL.glTranslatef(0.0, 1.5, -10)
    GL.glRotatef(90, 1.0, 0.0, 0.0)

    # Rotation
    # X axis
    GL.glRotatef(alpha, 0.0, 0.0, 1.0)
    # Y axis
    GL.glRotatef(beta, 0.0, 1.0, 0.0)

    # Figure
    GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0])

    # Bottom
    GL.glBegin(GL.GL_POLYGON)
    for i in range(vertices):
        x = raios * cos(i * faces_angle)
        y = raios * sin(i * faces_angle)
        polygon_points += [(x, y)]
        GL.glTexCoord2f(x, y)
        GL.glVertex3f(x, y, 0.0)
    GL.glEnd()

    # Top
    GL.glBegin(GL.GL_POLYGON)
    for x, y in polygon_points:
        GL.glTexCoord2f(x, y)
        GL.glVertex3f(modificador_piramide * x, modificador_piramide * y,
                      prisma_altura)
    GL.glEnd()

    # Sides
    GL.glBegin(GL.GL_QUADS)
    for i in range(vertices):
        GL.glTexCoord2f(0.0, 0.0)
        GL.glVertex3f(polygon_points[i][0], polygon_points[i][1], 0)
        GL.glTexCoord2f(0.0, 1.0)
        GL.glVertex3f(modificador_piramide * polygon_points[i][0],
                      modificador_piramide * polygon_points[i][1],
                      prisma_altura)

        GL.glTexCoord2f(1.0, 1.0)
        GL.glVertex3f(
            modificador_piramide * polygon_points[(i + 1) % vertices][0],
            modificador_piramide * polygon_points[(i + 1) % vertices][1],
            prisma_altura)
        GL.glTexCoord2f(1.0, 0.0)
        GL.glVertex3f(polygon_points[(i + 1) % vertices][0],
                      polygon_points[(i + 1) % vertices][1], 0)
    GL.glEnd()

    GL.glPopMatrix()

    GLUT.glutSwapBuffers()
Exemplo n.º 51
0
 def glBegin(cls, type):
     try:
         GL.glBegin(type)
         yield
     finally:
         GL.glEnd()
Exemplo n.º 52
0
def render_strip_in_3d_window(vertices, color):
    gl.glColor4f(*color)
    gl.glBegin(gl.GL_LINE_STRIP)
    for vertex in vertices:
        gl.glVertex3f(*vertex)
    gl.glEnd()
Exemplo n.º 53
0
    def paintAxes(self):

        gl.glDisable(gl.GL_CULL_FACE)
        gl.glColor4f(1, 1, 1, 1)
        for start, end in [self.x_axis, self.y_axis, self.z_axis]:
            gl.glBegin(gl.GL_LINES)
            gl.glVertex3f(*start)
            gl.glVertex3f(*end)
            gl.glEnd()

        def paintGrid(planeQuad, sub=7):
            P11, P12, P22, P21 = numpy.asarray(planeQuad)
            Dx = numpy.linspace(0.0, 1.0, num=sub)
            P1vecH = P12 - P11
            P2vecH = P22 - P21
            P1vecV = P21 - P11
            P2vecV = P22 - P12
            gl.glBegin(gl.GL_LINES)
            for i, dx in enumerate(Dx):
                start = P11 + P1vecH * dx
                end = P21 + P2vecH * dx
                gl.glVertex3f(*start)
                gl.glVertex3f(*end)

                start = P11 + P1vecV * dx
                end = P12 + P2vecV * dx
                gl.glVertex3f(*start)
                gl.glVertex3f(*end)
            gl.glEnd()

        def paintQuad(planeQuad):
            P11, P12, P21, P22 = numpy.asarray(planeQuad)
            gl.glBegin(gl.GL_QUADS)
            gl.glVertex3f(*P11)
            gl.glVertex3f(*P12)
            gl.glVertex3f(*P21)
            gl.glVertex3f(*P22)
            gl.glEnd()

        colorPlane = [0.5, 0.5, 0.5, 0.5]
        colorGrid = [0.0, 0.0, 0.0, 1.0]

        def paintPlain(planeQuad):
            gl.glColor4f(*colorPlane)
            paintQuad(planeQuad)
            gl.glColor4f(*colorGrid)
            paintGrid(planeQuad)

        def normalize(Vec):
            return Vec / numpy.sqrt(numpy.sum(Vec**2))

        def normalFromPoints(P1, P2, P3):
            V1 = P2 - P1
            V2 = P3 - P1
            return normalize(numpy.cross(V1, V2))

        cameraVector = normalize(self.center - self.camera)

        def paintPlainIf(planeQuad, ccw=False):
            normal = normalFromPoints(*planeQuad[:3])
            cameraVector = planeQuad[0] - self.camera
            cos = numpy.dot(normal, cameraVector) * (-1 if ccw else 1)
            if cos > 0:
                paintPlain(planeQuad)

        paintPlainIf(self.axisPlaneXY)
        paintPlainIf(self.axisPlaneYZ)
        paintPlainIf(self.axisPlaneXZ)
        paintPlainIf(self.axisPlaneXYBack)
        paintPlainIf(self.axisPlaneYZRight)
        paintPlainIf(self.axisPLaneXZTop)

        gl.glEnable(gl.GL_CULL_FACE)
Exemplo n.º 54
0
	def paintCircle(self, x, y, radius, red = 0, green = 0, blue = 0):
		gl.glColor3f(red, green, blue)
		gl.glBegin(gl.GL_POLYGON)
		for i in range(360):
			gl.glVertex2f(x + (radius * math.sin(math.radians(i))), y + (radius * math.cos(math.radians(i))))
		gl.glEnd()
Exemplo n.º 55
0
 def drawTarget(self,t,r):
     
     rc = r
     
     p1 = Point3f(rc,rc,rc)
     p2 = Point3f(rc,rc,-rc)
     p3 = Point3f(rc,-rc,-rc)
     p4 = Point3f(rc,-rc,rc)
     p5 = Point3f(-rc,rc,rc)
     p6 = Point3f(-rc,rc,-rc)
     p7 = Point3f(-rc,-rc,-rc)
     p8 = Point3f(-rc,-rc,rc)
     
     gl.glBegin(gl.GL_LINE_LOOP)
     gl.glVertex3f(p1.x,p1.y,p1.z)
     gl.glVertex3f(p2.x,p2.y,p2.z)
     gl.glVertex3f(p3.x,p3.y,p3.z)
     gl.glVertex3f(p4.x,p4.y,p4.z)
     gl.glEnd()
     
     gl.glBegin(gl.GL_LINE_LOOP)
     gl.glVertex3f(p5.x,p5.y,p5.z)
     gl.glVertex3f(p6.x,p6.y,p6.z)
     gl.glVertex3f(p7.x,p7.y,p7.z)
     gl.glVertex3f(p8.x,p8.y,p8.z)
     gl.glEnd()
     
     gl.glBegin(gl.GL_LINES)
     gl.glVertex3f(p1.x,p1.y,p1.z)
     gl.glVertex3f(p5.x,p5.y,p5.z)
     gl.glVertex3f(p2.x,p2.y,p2.z)
     gl.glVertex3f(p6.x,p6.y,p6.z)
     gl.glVertex3f(p3.x,p3.y,p3.z)
     gl.glVertex3f(p7.x,p7.y,p7.z)
     gl.glVertex3f(p4.x,p4.y,p4.z)
     gl.glVertex3f(p8.x,p8.y,p8.z)
     gl.glEnd()
     
     circle = np.linspace(0, ma.pi*2, 50)
     R = r * ma.sqrt(2)
     gl.glBegin(gl.GL_LINE_LOOP)
     for i in range(1,50):
         gl.glVertex3f(R*ma.cos(circle[i]), 0.0, R*ma.sin(circle[i]))
     gl.glEnd()
     gl.glBegin(gl.GL_LINE_LOOP)
     for i in range(1,50):
         gl.glVertex3f(0.0, R*ma.cos(circle[i]), R*ma.sin(circle[i]))
     gl.glEnd()
     gl.glBegin(gl.GL_LINE_LOOP)
     for i in range(1,50):
         gl.glVertex3f(R*ma.cos(circle[i]), R*ma.sin(circle[i]), 0.0)
     gl.glEnd()
Exemplo n.º 56
0
	def paintEvent(self, event):
		gl.glClear(gl.GL_COLOR_BUFFER_BIT)
		gl.glLoadIdentity();
		
		# Initialize the painter
		painter = QtGui.QPainter()
		painter.begin(self)
		
		'''
		***********************************************************
		Changed the if statement
		Bind the texture to nothing
		***********************************************************
		'''
		gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
		if self.showing == self.GRAPH_ONE:
			# Get the bounding rectangles
			tripEndBR = self.printer.getTextBox(painter, "Trip End", self.printer.fontNormal)
			
			# Draw OpenGL stuff
			self.paintGrid()
			self.paintDSM()
			
			self.paintRect(self.highRiskX, self.highRiskY, 0.851, 0.3255, 0.3099)
			self.paintRect(self.mediumRiskX, self.mediumRiskY, 0.9412, 0.6784, 0.3059)
			self.paintRect(self.lowRiskX, self.lowRiskY, 0.7, 0.7, 0.7)
			
			self.btnGraph1.drawBackground()
			self.btnGraph3.drawBackground()
			
			# Draw painter stuff
			self.printer.printCentered(painter, "Trip Summary", self.printer.fontXLarge, 0, 0, self.width, self.titleHeight, 50, 50, 50)
			self.printer.printCentered(painter, "Glance Patterns to the Display", self.printer.fontLarge, self.graphX, self.graphY - 60, self.graphWidth, self.heightFivePercent, 50, 50, 50)
			self.printer.printText(painter, "Trip Start", self.printer.fontNormal, self.graphX, self.graphY + self.graphHeight, self.width, self.height, 50, 50, 50)
			self.printer.printText(painter, "Trip End", self.printer.fontNormal, self.graphX + self.graphWidth - tripEndBR.right(), self.graphY + self.graphHeight, self.width, self.height, 50, 50, 50)
			self.printer.printCentered(painter, "Driving Safety Metrics", self.printer.fontLarge, self.dsmX, self.dsmY, self.dsmWidth, self.heightFivePercent, 50, 50, 50)
			
			# self.printer.printTextWrap(painter, u"\u2022", self.printer.fontSmall, self.dsmX + 10, self.dsmY + 70, self.dsmWidth - 60, self.dsmHeight, 50, 50, 50)
			self.printer.printTextWrap(painter, " %i"%(8-self.ube), self.printer.fontNormal, self.dsmX + 50, self.dsmY + 70, self.dsmWidth - 30, self.dsmHeight, 40, 193, 34)
			self.printer.printTextWrap(painter, "      out of 8 safe responses to lead    vehicle braking", self.printer.fontNormal, self.dsmX + 50, self.dsmY + 70, self.dsmWidth - 30, self.dsmHeight, 50, 50, 50)
			
			# self.printer.printTextWrap(painter, u"\u2022", self.printer.fontSmall, self.dsmX + 10, self.dsmY + 200, self.dsmWidth - 30, self.dsmHeight, 50, 50, 50)
			self.printer.printTextWrap(painter, " %i"%self.ube, self.printer.fontNormal, self.dsmX + 50, self.dsmY + 200, self.dsmWidth - 30, self.dsmHeight, 255, 0, 0)
			self.printer.printTextWrap(painter, "      out of 8 unsafe responses to    lead vehicle braking", self.printer.fontNormal, self.dsmX + 50, self.dsmY + 200, self.dsmWidth - 30, self.dsmHeight, 50, 50, 50)
			
			# self.printer.printTextWrap(painter, u"\u2022", self.printer.fontSmall, self.dsmX + 10, self.dsmY + 330, self.dsmWidth - 30, self.dsmHeight, 50, 50, 50)
			self.printer.printTextWrap(painter, " %i"%self.ld, self.printer.fontNormal, self.dsmX + 50, self.dsmY + 330, self.dsmWidth - 30, self.dsmHeight, 255, 0, 0)#255, 153, 255)
			self.printer.printTextWrap(painter, "      lane departures", self.printer.fontNormal, self.dsmX + 50, self.dsmY + 330, self.dsmWidth - 30, self.dsmHeight, 50, 50, 50)

			self.printer.printText(painter, str(int(self.low)), self.printer.fontNormal, self.lowRiskX + self.rectSize + 16, self.lowRiskY, self.width, self.height)
			self.printer.printText(painter, str(int(self.medium)), self.printer.fontNormal, self.mediumRiskX + self.rectSize + 16, self.mediumRiskY, self.width, self.height)
			self.printer.printText(painter, str(int(self.high)), self.printer.fontNormal, self.highRiskX + self.rectSize + 16, self.highRiskY, self.width, self.height)
			self.printer.printText(painter, "Low Risk Glances", self.printer.fontNormal, self.lowRiskX + self.rectSize + 150, self.lowRiskY, self.width, self.height)
			self.printer.printText(painter, "Medium Risk Glances", self.printer.fontNormal, self.mediumRiskX + self.rectSize + 150, self.mediumRiskY, self.width, self.height)
			self.printer.printText(painter, "High Risk Glances", self.printer.fontNormal, self.highRiskX + self.rectSize + 150, self.highRiskY, self.width, self.height)
			
			self.btnGraph1.drawText(painter, self.printer, self.printer.fontLarge)
			self.btnGraph3.drawText(painter, self.printer, self.printer.fontLarge)

		elif self.showing == self.GRAPH_TWO:
			self.paintCircle(self.lowIconX, self.lowIconY, self.glanceNumRadius, 0.851, 0.325, 0.31)
			self.paintCircle(self.mediumIconX, self.mediumIconY, self.glanceNumRadius, 0.941, 0.678, 0.305)
			self.paintCircle(self.highIconX, self.highIconY, self.glanceNumRadius, 0.5, 0.5, 0.5)
			
			self.btnGraph4.drawBackground()
			
			'''
			***********************************************************
			Removed the gl.GL_LINES block
			Added the paintLineHorizontal functions
			***********************************************************
			'''
			self.paintLineHorizontal(self.glancesGridX, self.glancesGridY + self.glancesGridBarPaddingTop, self.glancesGridX + self.glancesGridWidth, self.glancesGridY + self.glancesGridBarPaddingTop, 2, 0.3, 0.3, 0.3)
			self.paintLineHorizontal(self.glancesGridX, self.glancesGridY + self.glancesGridBarPaddingTop + (self.glancesGridBarHeight/2.0), self.glancesGridX + self.glancesGridWidth, self.glancesGridY + self.glancesGridBarPaddingTop + (self.glancesGridBarHeight/2.0), 2, 0.3, 0.3, 0.3)
			self.paintLineHorizontal(self.glancesGridX, self.glancesGridY + self.glancesGridHeight, self.glancesGridX + self.glancesGridWidth, self.glancesGridY + self.glancesGridHeight, 2, 0.3, 0.3, 0.3)
			
			gl.glBegin(gl.GL_QUADS)
			gl.glColor3f(0.5, 0.5, 0.5)
			gl.glVertex2f(self.glancesGridX, self.glancesGridTitleY)
			gl.glVertex2f(self.glancesGridX + self.glancesGridWidth, self.glancesGridTitleY)
			gl.glVertex2f(self.glancesGridX + self.glancesGridWidth, self.glancesGridTitleY + self.glancesGridTitleHeight)
			gl.glVertex2f(self.glancesGridX, self.glancesGridTitleY + self.glancesGridTitleHeight)
			gl.glVertex2f(self.tripsTitleX, self.tripsTitleY)
			gl.glVertex2f(self.tripsTitleX + self.tripsTitleWidth, self.tripsTitleY)
			gl.glVertex2f(self.tripsTitleX + self.tripsTitleWidth, self.tripsTitleY + self.tripsTitleHeight)
			gl.glVertex2f(self.tripsTitleX, self.tripsTitleY + self.tripsTitleHeight)

			# Safety metric text block
			gl.glVertex2f(self.safetyMetricsTitleX, self.safetyMetricsTitleY-60)
			gl.glVertex2f(self.safetyMetricsTitleX + self.safetyMetricsTitleWidth, self.safetyMetricsTitleY-60)
			gl.glVertex2f(self.safetyMetricsTitleX + self.safetyMetricsTitleWidth, self.safetyMetricsTitleY + self.safetyMetricsTitleHeight-60)
			gl.glVertex2f(self.safetyMetricsTitleX, self.safetyMetricsTitleY + self.safetyMetricsTitleHeight-60)
			
			# Comparison Bars -- COLOR
			# gl.glColor3f(0.67, 0.78, 0.82)
			gl.glColor3f(0.576, 0.72, 0.85)
			barOffset = self.glancesGridBarHeight - ((float(self.pastNumbersSum) / float(self.glancesGridMaxNum)) * self.glancesGridBarHeight)
			gl.glVertex2f(self.glancesGridX + self.glancesGridPadding, self.glancesGridY + barOffset + self.glancesGridBarPaddingTop)
			gl.glVertex2f(self.glancesGridX + self.glancesGridPadding + self.glancesGridBarWidth, self.glancesGridY + barOffset + self.glancesGridBarPaddingTop)
			gl.glVertex2f(self.glancesGridX + self.glancesGridPadding + self.glancesGridBarWidth, self.glancesGridY + self.glancesGridHeight)
			gl.glVertex2f(self.glancesGridX + self.glancesGridPadding, self.glancesGridY + self.glancesGridHeight)
			# gl.glColor3f(0.576, 0.65, 0.9)
			barOffset = self.glancesGridBarHeight - ((float(self.currentNumbersSum) / float(self.glancesGridMaxNum)) * self.glancesGridBarHeight)
			gl.glVertex2f(self.glancesGridX + (self.glancesGridPadding*2) + self.glancesGridBarWidth, self.glancesGridY + barOffset + self.glancesGridBarPaddingTop)
			gl.glVertex2f(self.glancesGridX + (self.glancesGridPadding*2) + (self.glancesGridBarWidth*2), self.glancesGridY + barOffset + self.glancesGridBarPaddingTop)
			gl.glVertex2f(self.glancesGridX + (self.glancesGridPadding*2) + (self.glancesGridBarWidth*2), self.glancesGridY + self.glancesGridHeight)
			gl.glVertex2f(self.glancesGridX + (self.glancesGridPadding*2) + self.glancesGridBarWidth, self.glancesGridY + self.glancesGridHeight)
			
			gl.glColor3f(0.7, 0.7, 0.7)
			gl.glVertex2f(self.glanceNumTitleX, self.glanceNumTitleY)
			gl.glVertex2f(self.glanceNumTitleX + self.glanceNumTitleWidth, self.glanceNumTitleY)
			gl.glVertex2f(self.glanceNumTitleX + self.glanceNumTitleWidth, self.glanceNumTitleY + self.glanceNumTitleHeight)
			gl.glVertex2f(self.glanceNumTitleX, self.glanceNumTitleY + self.glanceNumTitleHeight)
			
			gl.glVertex2f(self.safetyMetricsTitleX, self.safetyMetricsTitleY+20)
			gl.glVertex2f(self.safetyMetricsTitleX + self.safetyMetricsTitleWidth, self.safetyMetricsTitleY+20)
			gl.glVertex2f(self.safetyMetricsTitleX + self.safetyMetricsTitleWidth, self.safetyMetricsTitleY + self.safetyMetricsTitleHeight+20)
			gl.glVertex2f(self.safetyMetricsTitleX, self.safetyMetricsTitleY + self.safetyMetricsTitleHeight+20)
			gl.glEnd()
			
			bottomBar = self.glancesGridY + self.glancesGridHeight
			self.paintCircle(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[2]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 18, 0.5, 0.5, 0.5)
			self.paintCircle(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[1]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 18, 0.941, 0.678, 0.305)
			self.paintCircle(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[0]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 18, 0.851, 0.325, 0.31)
			self.paintCircle(self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[2]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 18, 0.5, 0.5, 0.5)
			self.paintCircle(self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[1]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 18, 0.941, 0.678, 0.305)
			self.paintCircle(self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[0]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 18, 0.851, 0.325, 0.31)
			
			self.paintLineHorizontal(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[2]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[2]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 10, 0.5, 0.5, 0.5)
			self.paintLineHorizontal(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[1]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[1]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 10, 0.941, 0.678, 0.305)
			self.paintLineHorizontal(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[0]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[0]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 10, 0.851, 0.325, 0.31)
			
			self.paintCircle(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[2]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 8, 1.0, 1.0, 1.0)
			self.paintCircle(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[1]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 8, 1.0, 1.0, 1.0)
			self.paintCircle(self.glancesGridX + self.glancesGridPadding + (self.glancesGridBarWidth/2.0), bottomBar - ((self.pastNumbers[0]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 8, 1.0, 1.0, 1.0)
			self.paintCircle(self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[2]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 8, 1.0, 1.0, 1.0)
			self.paintCircle(self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[1]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 8, 1.0, 1.0, 1.0)
			self.paintCircle(self.glancesGridX + self.glancesGridBarWidth + (self.glancesGridPadding*2) + (self.glancesGridBarWidth/2.0), bottomBar - ((self.currentNumbers[0]/float(self.glancesGridMaxNum))*self.glancesGridBarHeight), 8, 1.0, 1.0, 1.0)
			
			self.printer.printCentered(painter, "Compare Recent Trips", self.printer.fontXLarge, 0, 0, self.width, self.titleHeight, 50, 50, 50)
			self.printer.printCentered(painter, "Glances to Display", self.printer.fontLarge, self.glancesGridTitleX, self.glancesGridTitleY, self.glancesGridTitleWidth, self.glancesGridTitleHeight, 240, 240, 240)
			self.printer.printCentered(painter, "Number of Glances", self.printer.fontLarge, self.tripsTitleX, self.tripsTitleY, self.tripsTitleWidth, self.tripsTitleHeight, 240, 240, 240)
			self.printer.printCentered(painter, "Trips:\t\t\t\tPrevious\t\t\t\tCurrent", self.printer.fontLarge, self.glanceNumTitleX, self.glanceNumTitleY, self.glanceNumTitleWidth, self.glanceNumTitleHeight, 240, 240, 240)
			self.printer.printCentered(painter, "Safety Metrics", self.printer.fontLarge, self.safetyMetricsTitleX, self.safetyMetricsTitleY-60, self.glanceNumTitleWidth, self.glanceNumTitleHeight, 240, 240, 240)
			self.printer.printCentered(painter, "Trips:\t\t\t\tPrevious\t\t\t\tCurrent", self.printer.fontLarge, self.safetyMetricsTitleX, self.safetyMetricsTitleY+20, self.glanceNumTitleWidth, self.glanceNumTitleHeight, 240, 240, 240)
			self.printer.printCenteredHor(painter, str(self.glancesGridMaxNum), self.printer.fontNormal, 0, self.glancesGridY + 3, self.glancesGridX, 100, 40, 40, 40)
			self.printer.printCenteredHor(painter, str(int(self.glancesGridMaxNum/2.0)), self.printer.fontNormal, 0, self.glancesGridY + 3 + (self.glancesGridBarHeight/2.0), self.glancesGridX, 100, 40, 40, 40)
			self.printer.printCenteredHor(painter, "0", self.printer.fontNormal, 0, self.glancesGridY + self.glancesGridHeight - 20, self.glancesGridX, 100, 40, 40, 40)
			self.printer.printCenteredHor(painter, "Previous", self.printer.fontNormal, self.glancesGridX + self.glancesGridPadding, self.glancesGridY + self.glancesGridHeight, self.glancesGridBarWidth, 100, 40, 40, 40)
			self.printer.printCenteredHor(painter, "Current", self.printer.fontNormal, self.glancesGridX + (self.glancesGridPadding*2) + self.glancesGridBarWidth, self.glancesGridY + self.glancesGridHeight, self.glancesGridBarWidth, 100, 40, 40, 40)
			self.printer.printText(painter, str(self.pastNumbers[2]), self.printer.fontNormal, self.highPastTitleX+40, self.highPastTitleY, self.width, self.height)
			self.printer.printText(painter, str(self.currentNumbers[2]), self.printer.fontNormal, self.highCurrentTitleX+45, self.highCurrentTitleY, self.width, self.height)
			self.printer.printText(painter, str(self.pastNumbers[1]), self.printer.fontNormal, self.mediumPastTitleX+40, self.mediumPastTitleY, self.width, self.height)
			self.printer.printText(painter, str(self.currentNumbers[1]), self.printer.fontNormal, self.mediumCurrentTitleX+45, self.mediumCurrentTitleY, self.width, self.height)
			self.printer.printText(painter, str(self.pastNumbers[0]), self.printer.fontNormal, self.lowPastTitleX+40, self.lowPastTitleY, self.width, self.height)
			self.printer.printText(painter, str(self.currentNumbers[0]), self.printer.fontNormal, self.lowCurrentTitleX+45, self.lowCurrentTitleY, self.width, self.height)
			self.printer.printText(painter, "Total", self.printer.fontNormal, self.totalTitleX, self.totalTitleY+20, self.width, self.height)
			self.printer.printText(painter, str(self.pastNumbersSum), self.printer.fontNormal, self.totalPastTitleX+40, self.totalPastTitleY+20, self.width, self.height)
			self.printer.printText(painter, str(self.currentNumbersSum), self.printer.fontNormal, self.totalCurrentTitleX+45, self.totalCurrentTitleY+20, self.width, self.height)
			self.printer.printText(painter, "Safe Braking", self.printer.fontNormal, self.safeEventTitleX, self.safeEventTitleY+40, self.width, self.height, 40, 193, 34)
			self.printer.printText(painter, "%s"%str(self.compSafe[0]), self.printer.fontNormal, self.safeEventPastNumTitleX+40, self.safeEventPastNumTitleY+40, self.width, self.height)
			self.printer.printText(painter, "%s"%str(self.compSafe[1]), self.printer.fontNormal, self.safeEventCurrentNumTitleX+45, self.safeEventCurrentNumTitleY+40, self.width, self.height)
			self.printer.printText(painter, "Unsafe Braking", self.printer.fontNormal, self.unsafeEventTitleX, self.unsafeEventTitleY+55, self.width, self.height, 217, 83, 79)
			self.printer.printText(painter, "%s"%str(self.compUnsafe[0]), self.printer.fontNormal, self.unsafeEventPastNumTitleX+40, self.unsafeEventPastNumTitleY+55, self.width, self.height)
			self.printer.printText(painter, "%s"%str(self.compUnsafe[1]), self.printer.fontNormal, self.unsafeEventCurrentNumTitleX+45, self.unsafeEventCurrentNumTitleY+55, self.width, self.height)
			self.printer.printText(painter, "Lane Departures", self.printer.fontNormal, self.deviationsEventTitleX, self.deviationsEventTitleY+70, self.width, self.height, 217, 83, 79)
			self.printer.printText(painter, "%s"%str(self.compLane[0]), self.printer.fontNormal, self.deviationsEventPastNumTitleX+40, self.deviationsEventPastNumTitleY+70, self.width, self.height)
			self.printer.printText(painter, "%s"%str(self.compLane[1]), self.printer.fontNormal, self.deviationsEventCurrentNumTitleX+45, self.deviationsEventCurrentNumTitleY+70, self.width, self.height)
			
			self.btnGraph4.drawText(painter, self.printer, self.printer.fontLarge)
			
		elif self.showing == self.BADGE_SCREEN:
			self.btnGraph2.drawBackground()
			
			self.badgeScreen.draw(painter)
			
			self.btnGraph2.drawText(painter, self.printer, self.printer.fontLarge)
			
		# End the painter
		painter.end()
Exemplo n.º 57
0
        renderer.cam.update(pygame.key.get_pressed())

        renderer.clear()

        weapon.animator()

        renderer.ortho()
        hud.render()
        weapon.render()

        renderer.perspective()

        # draw terrain
        tileset.bind()
        gl.glBegin(gl.GL_QUADS)
        for v, t, c in vb.data:
            for i in range(4):
                gl.glColor3fv(c[i])
                gl.glTexCoord2fv(t[i])
                gl.glVertex3fv(v[i])
        gl.glEnd()

        sprite1.rotate = renderer.cam.angle
        sprite2.rotate = renderer.cam.angle
        sprite3.rotate = renderer.cam.angle

        sprite1.animator()
        sprite3.animator()

        sprite1.render()
Exemplo n.º 58
0
    def paintGL(self, p, opt, widget):
        p.beginNativePainting()
        import OpenGL.GL as gl

        if sys.platform == 'win32':
            # If Qt is built to dynamically load OpenGL, then the projection and
            # modelview matrices are not setup.
            # https://doc.qt.io/qt-6/windows-graphics.html
            # https://code.woboq.org/qt6/qtbase/src/opengl/qopenglpaintengine.cpp.html
            # Technically, we could enable it for all platforms, but for now, just
            # enable it where it is required, i.e. Windows
            gl.glMatrixMode(gl.GL_PROJECTION)
            gl.glLoadIdentity()
            gl.glOrtho(0, widget.width(), widget.height(), 0, -999999, 999999)
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glLoadMatrixf(QtGui.QMatrix4x4(self.sceneTransform()).data())

        ## set clipping viewport
        view = self.getViewBox()
        if view is not None:
            rect = view.mapRectToItem(self, view.boundingRect())
            #gl.glViewport(int(rect.x()), int(rect.y()), int(rect.width()), int(rect.height()))

            #gl.glTranslate(-rect.x(), -rect.y(), 0)

            gl.glEnable(gl.GL_STENCIL_TEST)
            gl.glColorMask(gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE,
                           gl.GL_FALSE)  # disable drawing to frame buffer
            gl.glDepthMask(gl.GL_FALSE)  # disable drawing to depth buffer
            gl.glStencilFunc(gl.GL_NEVER, 1, 0xFF)
            gl.glStencilOp(gl.GL_REPLACE, gl.GL_KEEP, gl.GL_KEEP)

            ## draw stencil pattern
            gl.glStencilMask(0xFF)
            gl.glClear(gl.GL_STENCIL_BUFFER_BIT)
            gl.glBegin(gl.GL_TRIANGLES)
            gl.glVertex2f(rect.x(), rect.y())
            gl.glVertex2f(rect.x() + rect.width(), rect.y())
            gl.glVertex2f(rect.x(), rect.y() + rect.height())
            gl.glVertex2f(rect.x() + rect.width(), rect.y() + rect.height())
            gl.glVertex2f(rect.x() + rect.width(), rect.y())
            gl.glVertex2f(rect.x(), rect.y() + rect.height())
            gl.glEnd()

            gl.glColorMask(gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE)
            gl.glDepthMask(gl.GL_TRUE)
            gl.glStencilMask(0x00)
            gl.glStencilFunc(gl.GL_EQUAL, 1, 0xFF)

        try:
            x, y = self.getData()
            pos = np.empty((len(x), 2))
            pos[:, 0] = x
            pos[:, 1] = y
            gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
            try:
                gl.glVertexPointerf(pos)
                pen = fn.mkPen(self.opts['pen'])
                gl.glColor4f(*pen.color().getRgbF())
                width = pen.width()
                if pen.isCosmetic() and width < 1:
                    width = 1
                gl.glPointSize(width)
                gl.glLineWidth(width)

                # enable antialiasing if requested
                if self._exportOpts is not False:
                    aa = self._exportOpts.get('antialias', True)
                else:
                    aa = self.opts['antialias']
                if aa:
                    gl.glEnable(gl.GL_LINE_SMOOTH)
                    gl.glEnable(gl.GL_BLEND)
                    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
                    gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
                else:
                    gl.glDisable(gl.GL_LINE_SMOOTH)

                gl.glDrawArrays(gl.GL_LINE_STRIP, 0,
                                int(pos.size / pos.shape[-1]))
            finally:
                gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
        finally:
            p.endNativePainting()
Exemplo n.º 59
0
    def paint(self):
        self.setupGLState()
        if self.antialias:
            ogl.glEnable(ogl.GL_LINE_SMOOTH)
            ogl.glHint(ogl.GL_LINE_SMOOTH_HINT, ogl.GL_NICEST)
        ogl.glBegin(ogl.GL_LINES)

        x, y, z = self.size()

        # vertices
        v = [(-x, -y, 0), (x, -y, 0), (x, y, 0), (-x, y, 0), (-x, -y, z),
             (x, -y, z), (x, y, z), (-x, y, z), (-x, -y, -z), (x, -y, -z),
             (x, y, -z), (-x, y, -z)]

        # HORIZONTAL AXIS AT Z = 0
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[0][0], v[0][1], v[0][2])
        ogl.glVertex3f(v[1][0], v[1][1], v[1][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[1][0], v[1][1], v[1][2])
        ogl.glVertex3f(v[2][0], v[2][1], v[2][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[2][0], v[2][1], v[2][2])
        ogl.glVertex3f(v[3][0], v[3][1], v[3][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[3][0], v[3][1], v[3][2])
        ogl.glVertex3f(v[0][0], v[0][1], v[0][2])

        # HORIZONTAL AXIS AT Z = z
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[4][0], v[4][1], v[4][2])
        ogl.glVertex3f(v[5][0], v[5][1], v[5][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[5][0], v[5][1], v[5][2])
        ogl.glVertex3f(v[6][0], v[6][1], v[6][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[6][0], v[6][1], v[6][2])
        ogl.glVertex3f(v[7][0], v[7][1], v[7][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[7][0], v[7][1], v[7][2])
        ogl.glVertex3f(v[4][0], v[4][1], v[4][2])

        # HORIZONTAL AXIS AT Z = -z
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[8][0], v[8][1], v[8][2])
        ogl.glVertex3f(v[9][0], v[9][1], v[9][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[9][0], v[9][1], v[9][2])
        ogl.glVertex3f(v[10][0], v[10][1], v[10][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[10][0], v[10][1], v[10][2])
        ogl.glVertex3f(v[11][0], v[11][1], v[11][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[11][0], v[11][1], v[11][2])
        ogl.glVertex3f(v[8][0], v[8][1], v[8][2])

        # UPPER Z-AXES
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[0][0], v[0][1], v[0][2])
        ogl.glVertex3f(v[4][0], v[4][1], v[4][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[1][0], v[1][1], v[1][2])
        ogl.glVertex3f(v[5][0], v[5][1], v[5][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[2][0], v[2][1], v[2][2])
        ogl.glVertex3f(v[6][0], v[6][1], v[6][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[3][0], v[3][1], v[3][2])
        ogl.glVertex3f(v[7][0], v[7][1], v[7][2])

        # LOWER Z-AXES
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[0][0], v[0][1], v[0][2])
        ogl.glVertex3f(v[8][0], v[8][1], v[8][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[1][0], v[1][1], v[1][2])
        ogl.glVertex3f(v[9][0], v[9][1], v[9][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[2][0], v[2][1], v[2][2])
        ogl.glVertex3f(v[10][0], v[10][1], v[10][2])
        ogl.glColor4f(self.c[0], self.c[1], self.c[2], self.c[3])
        ogl.glVertex3f(v[3][0], v[3][1], v[3][2])
        ogl.glVertex3f(v[11][0], v[11][1], v[11][2])

        ogl.glEnd()
Exemplo n.º 60
0
    def drawCone(self,c,v,r,n):
        
        c0 = np.array([c.x,c.y,c.z])
        v0 = np.array([v.x,v.y,v.z])
        
        # calculate the distance for the height
        
        h = ma.sqrt(np.sum((c0-v0) * (c0-v0)))
        alpha = ma.acos(np.dot(np.array([0.0,0.0,1.0]),v0-c0) / (h+0.00001))
        
        if v0[0]-c0[0] == 0 and v0[1]-c0[1] == 0:
            dx = 0
            dy = 0
        elif v0[0]-c0[0] == 0:
            dx = -(v0[1]-c0[1])
            dy = 0
        elif v0[1]-c0[1] == 0:
            dx = 0
            dy = v0[0]-c0[0]
        else:
            k = (v0[1]-c0[1]) / (v0[0]-c0[0])
            l = -1.0/k
            
            if l > 0.0:
                dx = v0[0] - c0[0]
            else:
                dx = -(v0[0] - c0[0])
            
            dy = dx * l
        
        zdir = np.array([dx+c0[0], dy+c0[1], c0[2]])
        t = np.linspace(0, ma.pi*2, n)
        tx = t.copy()
        ty = t.copy()
        
        for i in range(0,n):
            tx[i] = r * ma.cos(t[i]) + c0[0]
            ty[i] = r * ma.sin(t[i]) + c0[1]
        #print(tx)
        
        vert = np.array([tx-c0[0],ty-c0[1],c0[2]*np.linspace(1.0,1.0,n)-c0[2]]).T

        if zdir[0] != c0[0] and zdir[1] != c0[1]:
            vert = self.rot3d(vert, np.array([0.0,0.0,0.0]), zdir-c0, alpha)
        vert = vert + c0
        #print(vert)
        
        # reference points
        
        gl.glBegin(gl.GL_LINES)
        #gl.glVertex3f(c0[0],c0[1],c0[2])
        #gl.glVertex3f(v0[0],v0[1],v0[2])
        #gl.glVertex3f(c0[0],c0[1],c0[2])
        #gl.glVertex3f(zdir[0],zdir[1],zdir[2])
        #gl.glVertex3f(v0[0],v0[1],v0[2])
        #gl.glVertex3f(self.Trx[1],self.Try[1],self.Trz[1])

        for i in range(0,n):
            gl.glVertex3f(v0[0],v0[1],v0[2])
            gl.glVertex3f(vert[i][0], vert[i][1], vert[i][2])
        gl.glEnd()
        
        gl.glBegin(gl.GL_LINE_LOOP)
        for i in range(0,n):
            gl.glVertex3f(vert[i][0], vert[i][1], vert[i][2])
        gl.glEnd()