def show_risk(self):
     # print('%s' % self.infos)
     # print("%s" % hasattr(self, 'reward_strategy'))
     if self.infos[0] != None and self.infos[0]['on_rect'] and hasattr(self, 'reward_strategy'):
         # win = self.env.viewers[0].window
         # win.switch_to()
         # win.dispatch_events()
         rect = self.infos[0]['last_rect']
         rectx = sorted(list(set(map(lambda item: item[0], rect)))) # unique x
         recty = sorted(list(set(map(lambda item: item[1], rect)))) # unique y
         # gl.glViewport(0, 0, 96, 96)
         gl.glPointSize(3.3)
         gl.glBegin(gl.GL_POINTS)
         oc = [0.5, 0.5, 0.5]
         gl.glColor4f(*oc, 1.0)
         x = rectx[0]
         while x < rectx[1]:
             y = recty[0]
             while y < recty[1]:
                 r = self.reward_strategy.risk(x, y)
                 gl.glColor4f(r*oc[0], r*oc[1], r*oc[2], 1.0)
                 print("%s = %s" % ((x, y), r))
                 gl.glVertex2f(x, y, 0)
                 y += 1.0
             x += 1.0
         gl.glEnd()
Beispiel #2
0
 def draw(self):
     """ Render the point """
     # [1]. If OGL transforms enabled , Translate and rotate the OGL state machine to desired rendering frame
     if self.trnsByOGL:
         glTranslated(
             *self.pos3D
         )  # This moves the origin of drawing , so that we can use the above coordinates at each draw location
     # ( Rotation is not applicable to points )
     # [2]. Set color & size
     glColor3ub(*self.colors[0])
     glPointSize(self.size)
     # [3]. Render!
     # print "DEBUG ," , "self.vertX:  " , self.vertX
     # print "DEBUG ," , "self.indices:" , self.indices
     pyglet.graphics.draw_indexed(
         1,  # --------------------- Number of seqential triplet in vertex list
         GL_POINTS,  # ------------- Draw quadrilaterals
         self.
         indices,  # ----------------- Indices where the coordinates are stored
         (
             'v3f', self.vertX
         )  # -- vertex list , OpenGL offers an optimized vertex list object , but this is not it
     )
     # [4]. If OGL transforms enabled , Translate and rotate the OGL state machine to desired rendering frame
     # ( Rotation is not applicable to points )
     if self.trnsByOGL:
         glTranslated(*np.multiply(self.pos3D,
                                   -1))  # Reset the transform coordinates
Beispiel #3
0
 def set_radius(cls, value=10):
     if value < 5:
         value = 5
     if value > 10:
         value = 10
     glPointSize(value * 2)
     cls.radius = value
Beispiel #4
0
    def _draw(self, shader=None, send_uniforms=True, *args, **kwargs):
        super(Mesh, self)._draw(*args, **kwargs)

        if not self.is_updated:
            self.update()
            self.is_updated = True

        if self.visible:

            # Bind the VAO and Texture, and draw.
            with self.texture as texture:

                # Change Material to Mesh's
                if send_uniforms:

                    self.update_model_and_normal_matrix()
                    self.uniforms.send_to(shader)
                    texture.uniforms.send_to(shader)

                    # Send Model and Normal Matrix to shader.
                    try:
                        shader.uniform_matrixf('model_matrix', self.model_matrix_global.T.ravel(), loc=self.modelmat_loc)
                        shader.uniform_matrixf('normal_matrix', self.normal_matrix_global.T.ravel(), loc=self.normalmat_loc)
                    except AttributeError:
                        self.modelmat_loc = shader.get_uniform_location('model_matrix')
                        self.normalmat_loc = shader.get_uniform_location('normal_matrix')
                        pass

                # Set Point Size, if drawing a point cloud
                if self.drawstyle == 'point':
                    gl.glPointSize(int(self.point_size))

                # Send in the vertex and normal data
                self.data.draw(Mesh.drawstyle[self.drawstyle])
Beispiel #5
0
    def _draw(self, shader=None, *args, **kwargs):
        super(Mesh, self)._draw(*args, **kwargs)

        self.update()

        if self.visible:

            # Change Material to Mesh's
            for uniform in self.uniforms:
                uniform.send_to(shader)

            # Send Model and Normal Matrix to shader.
            shader.uniform_matrixf('model_matrix',
                                   self.model_matrix_global.T.ravel())
            shader.uniform_matrixf('normal_matrix',
                                   self.normal_matrix_global.T.ravel())

            # Set Point Size, if drawing a point cloud
            if self.drawstyle == 'point':
                gl.glPointSize(int(self.point_size))

            # Bind the VAO and Texture, and draw.
            with self.texture as texture:
                for uniform in self.texture.uniforms:
                    uniform.send_to(shader)
                self.data.draw(Mesh.drawstyle[self.drawstyle])
Beispiel #6
0
    def render(self):
        # draw scans
        gl.glColor3f(0, 0.2, 0.2)
        for scan in self.scans:
            vertices = [((scan.x + p.x) * 8 + 4, (scan.y + p.y) * 8 + 4)
                        for p in self.scanner_model]
            vertices = tuple(item for sublist in vertices for item in sublist)
            pyglet.graphics.draw(int(len(vertices) / 2), pyglet.gl.GL_LINES,
                                 ('v2f', vertices))

        # draw ships
        for ship in self.ships:
            ship.sprite.position = ship.position * 8 + Vec2d(4, 4)
            ship.sprite.draw()
        gl.glColor3f(1, 1, 0)
        # draw explosions
        for explosion in self.explosions:
            gl.glPointSize(8.0)
            pyglet.graphics.draw(1, pyglet.gl.GL_POINTS,
                                 ('v2i',
                                  (explosion.x * 8 + 4, explosion.y * 8 + 4)))
        # draw laser lines
        for shot in self.shots:
            lasers = continuous_laser(shot.owner.position, shot.position)
            vertices = [(p.x * 8 + 4, p.y * 8 + 4) for p in lasers]
            vertices = tuple(item for sublist in vertices for item in sublist)

            gl.glColor3f(1, 0, 0)
            pyglet.graphics.draw(int(len(vertices) / 2),
                                 pyglet.gl.GL_LINE_LOOP, ('v2i', vertices))
Beispiel #7
0
 def draw_message(self):
     if event.message != self.current_message:
         self.current_message = event.message
         self.message_label.text = event.message
         self.message_label.font_size = event.message_size
     xa = self.message_label.content_width // 2 + 20
     ya = self.message_label.content_height // 2 + 5
     gl.glLineWidth(3.0)
     gl.glPointSize(1.0)
     draw.set_color(0, 0, 0, 0.8)
     draw.rect(
         self.message_label.x - xa, self.message_label.y - ya, self.message_label.x + xa, self.message_label.y + ya
     )
     draw.set_color(0, 0, 0, 1)
     draw.rect_outline(
         self.message_label.x - xa, self.message_label.y - ya, self.message_label.x + xa, self.message_label.y + ya
     )
     draw.points(
         (
             self.message_label.x - xa,
             self.message_label.y - ya,
             self.message_label.x + xa,
             self.message_label.y - ya,
             self.message_label.x + xa,
             self.message_label.y + ya,
             self.message_label.x - xa,
             self.message_label.y + ya,
         )
     )
     self.message_label.draw()
Beispiel #8
0
 def render(self):
     # for smooth rendering
     # draw ships
     for ship in self.ships:
         ship.sprite.position = ship.position * 8 + Vec2d(4, 4)
         ship.sprite.draw()
     gl.glColor3f(1, 1, 0)
     # draw explosions TODO: Animate!
     for explosion in self.explosions:
         gl.glPointSize(8.0)
         pyglet.graphics.draw(
             1, pyglet.gl.GL_POINTS,
             ('v2i', (explosion.x * 8 + 4, explosion.y * 8 + 4))
         )
     laser_points = []
     # draw laser lines
     for shot in self.shots:
         startpos = shot.owner.position * 8 + Vec2d(4, 4)
         laser_points.append(startpos.x)
         laser_points.append(startpos.y)
         laser_points.append(shot.position.x * 8 + 4)
         laser_points.append(shot.position.y * 8 + 4)
     gl.glColor3f(1, 0, 0)
     pyglet.graphics.draw(
         len(self.shots) * 2, pyglet.gl.GL_LINES,
         ('v2i', laser_points)
     )
Beispiel #9
0
    def on_draw(self):
        gl.glClearColor(0, 0.0, 0.0, 1.)
        self.clear()
        width, height = self.get_size()
        gl.glViewport(0, 0, width, height)

        K_gl = get_projector_gl_intrinsics()
        TF = get_extrinsics()
        R = np.array([[-1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 0.],
                      [0., 0., 0., 1.]])
        full_mat = np.ascontiguousarray((K_gl.dot(TF.dot(R))).astype('f4'))
        with self.prog.using():
            self.prog.uniforms.Mvp = full_mat.tolist()
            gl.glEnable(gl.GL_DEPTH_TEST)
            gl.glEnable(gl.GL_BLEND)
            gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
            gl.glPointSize(25.)
            distance = (0, 0, 1)
            gl.glPointParameterfv(gl.GL_POINT_DISTANCE_ATTENUATION,
                                  (gl.GLfloat * 3)(*distance))
            gl.glEnable(gl.GL_POINT_SPRITE)
            self.vertex_info.draw(gl.GL_POINTS)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, width, 0, height, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glMatrixMode(gl.GL_TEXTURE)
        gl.glLoadIdentity()
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glDisable(gl.GL_BLEND)

        self.fps_display.draw()
Beispiel #10
0
 def _gl_enable_smooth_lines():
     # make the lines from Path3D objects less ugly
     gl.glEnable(gl.GL_LINE_SMOOTH)
     gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
     # set the width of lines to 4 pixels
     gl.glLineWidth(4)
     # set PointCloud markers to 4 pixels in size
     gl.glPointSize(4)
 def render_additional_points(self, pts):
     if pts == None: return
     gl.glPointSize(5)
     gl.glBegin(gl.GL_POINTS)
     for (x, y) in pts:
         gl.glColor4f(0, 0, 1.0, 1.0)
         gl.glVertex2f(x, y, 0)
     gl.glEnd()
Beispiel #12
0
def gl_enable_smooth_lines():
    gl.glEnable(gl.GL_LINE_SMOOTH)  # make the lines from Path3D objects less ugly
    gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
    gl.glLineWidth(0.5)  # set the width of lines to 2 pixels
    gl.glPointSize(12)  # set PointCloud markers to 8 pixels in size
    gl.glEnable(gl.GL_PROGRAM_POINT_SIZE)  # set
    gl.glEnable(gl.GL_POINT_SMOOTH)
    gl.glEnable(gl.GL_BLEND)
Beispiel #13
0
    def initializeGL(self):
        gl.glClearColor(0, 0, 0, 0)
        gl.glPointSize(10.0)
        gl.glEnable(gl.GL_POINT_SMOOTH)
        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
 def render1(self):
     gl.glPointSize(2.0)
     gl.glEnable(gl.GL_POINT_SMOOTH)
     gl.glBegin(gl.GL_POINTS) # draw point
     for p in self.v:
         #print( '    p: ', p )
         gl.glVertex3f(p[0], p[1], 0)
     gl.glEnd()
     gl.glDisable(gl.GL_POINT_SMOOTH)
Beispiel #15
0
def draw_point(pos, color=(1, 0, 0, 1), size=5):
    gl.glColor4f(*color)
    gl.glPointSize(size)

    gl.glBegin(gl.GL_POINTS)
    gl.glVertex2f(*pos)
    gl.glEnd()
    # -- reset color
    gl.glColor4f(1, 1, 1, 1)
Beispiel #16
0
	def renderCatalog(cat, far):
		gl.glDisable(gl.GL_LIGHTING)
		for s in cat:
			c = s.getRgb()
			gl.glPointSize(s.getSize())
			gl.glBegin(gl.GL_POINTS)
			gl.glColor3f(c[0], c[1], c[2])
			gl.glVertex3f(far * cos(s.ra_rad) * cos(s.dec_rad), far * sin(s.ra_rad) * cos(s.dec_rad), far * sin(s.dec_rad))
			gl.glEnd()
		gl.glEnable(gl.GL_LIGHTING)
Beispiel #17
0
def _generic_draw_line_strip(point_list: PointList,
                             color: Color,
                             line_width: float=1,
                             mode: int=moderngl.LINE_STRIP):
    """
    Draw a line strip. A line strip is a set of continuously connected
    line segments.

    Args:
        :point_list: List of points making up the line. Each point is
         in a list. So it is a list of lists.
        :color: color, specified in a list of 3 or 4 bytes in RGB or
         RGBA format.
        :border_width: Width of the line in pixels.
    Returns:
        None
    Raises:
        None
    """
    program = shader.program(
        vertex_shader=line_vertex_shader,
        fragment_shader=line_fragment_shader,
    )
    buffer_type = np.dtype([('vertex', '2f4'), ('color', '4B')])
    data = np.zeros(len(point_list), dtype=buffer_type)

    data['vertex'] = point_list

    color = get_four_byte_color(color)
    data['color'] = color

    vbo = shader.buffer(data.tobytes())
    vbo_desc = shader.BufferDescription(
        vbo,
        '2f 4B',
        ('in_vert', 'in_color'),
        normalized=['in_color']
    )

    vao_content = [vbo_desc]

    vao = shader.vertex_array(program, vao_content)
    with vao:
        program['Projection'] = get_projection().flatten()

        gl.glLineWidth(line_width)
        gl.glPointSize(line_width)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
        gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST)

        vao.render(mode=mode)
Beispiel #18
0
def draw_point(point):
    """
    Draw a point
    :param point: Coordinates of the point
    """
    from pyglet import gl
    gl.glPointSize(7)
    gl.glBegin(gl.GL_POINTS)
    gl.glColor3f(0, 0, 1)
    gl.glVertex3f(point[0], 0.1, point[2])
    gl.glEnd()
Beispiel #19
0
    def init_gl(self):
        """
        Perform the magic incantations to create an OpenGL scene.
        """
        # the background color
        gl.glClearColor(.97, .97, .97, 1.0)

        max_depth = (np.abs(self.scene.bounds).max(axis=1)**2).sum()**.5
        max_depth = np.clip(max_depth, 500.00, np.inf)
        gl.glDepthRange(0.0, max_depth)

        gl.glClearDepth(1.0)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glDepthFunc(gl.GL_LEQUAL)

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_CULL_FACE)
        gl.glEnable(gl.GL_LIGHTING)
        gl.glEnable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)

        # put the light at one corner of the scenes AABB
        gl.glLightfv(
            gl.GL_LIGHT0, gl.GL_POSITION,
            rendering.vector_to_gl(np.append(self.scene.bounds[1], 0)))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR,
                     rendering.vector_to_gl(.5, .5, 1, 1))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE,
                     rendering.vector_to_gl(1, 1, 1, .75))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT,
                     rendering.vector_to_gl(.1, .1, .1, .2))

        gl.glColorMaterial(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT_AND_DIFFUSE)
        gl.glEnable(gl.GL_COLOR_MATERIAL)
        gl.glShadeModel(gl.GL_SMOOTH)

        gl.glMaterialfv(gl.GL_FRONT, gl.GL_AMBIENT,
                        rendering.vector_to_gl(0.192250, 0.192250, 0.192250))
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_DIFFUSE,
                        rendering.vector_to_gl(0.507540, 0.507540, 0.507540))
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_SPECULAR,
                        rendering.vector_to_gl(.5082730, .5082730, .5082730))

        gl.glMaterialf(gl.GL_FRONT, gl.GL_SHININESS, .4 * 128.0)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)

        gl.glLineWidth(1.5)
        gl.glPointSize(4)
Beispiel #20
0
    def draw(self):
        """Render the particle system."""

        if not self.live_particles:
            return
        if self.dirty_indices:
            indices = [p.slot for p in self.live_particles if not p.dead]
            self.indices = (gl.GLuint * len(indices))(*indices)
            self.dirty_indices = False
        gl.glPointSize(self.particle_class.size)
        gl.glInterleavedArrays(gl.GL_C4F_N3F_V3F, 0, self.data)
        gl.glDrawElements(gl.GL_POINTS, len(self.indices), gl.GL_UNSIGNED_INT,
                          self.indices)
Beispiel #21
0
    def draw(self):
        p = adjust_for_cam(self._body.position)

        gl.glEnable(pyglet.gl.GL_TEXTURE_2D)
        gl.glBindTexture(gl.GL_TEXTURE_2D, BLASTER_IMAGE.id)
        gl.glEnable(gl.GL_POINT_SPRITE)
        gl.glTexEnvi(gl.GL_POINT_SPRITE, gl.GL_COORD_REPLACE, gl.GL_TRUE)
        gl.glPointSize(4 * SPACE.scale)

        gl.glBegin(gl.GL_POINTS)
        # TODO: more optimized to draw as one large batch
        gl.glVertex3f(p.x, p.y, 0)
        gl.glEnd();
Beispiel #22
0
    def update_all(self):
        """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """
        self.update_points()
        self.update_vertex_list()
        self.update_anchor()

        gl.glLoadIdentity()  # reset gl
        gl.glLineWidth(self.line_width)
        gl.glPointSize(self.point_size)
        self.transform.update_gl()

        # handle shapes click envets
        all_shapes.discard(self)
        all_shapes.add(self)
Beispiel #23
0
    def update_all(self):
        """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """
        self.update_points()
        self.update_vertex_list()
        self.update_anchor()

        gl.glLoadIdentity() # reset gl
        gl.glLineWidth(self.line_width)
        gl.glPointSize(self.point_size)
        self.transform.update_gl()

        # handle shapes click envets
        all_shapes.discard(self)
        all_shapes.add(self)     
Beispiel #24
0
 def draw_ai_message(self):
     if event.ai_message != self.current_ai_message:
         self.current_ai_message = event.ai_message
         self.ai_message_label.text = event.ai_message
     w = self.ai_message_label.content_width
     mx = self.ai_message_label.x
     my = self.ai_message_label.y
     gl.glLineWidth(3.0)
     gl.glPointSize(1.0)
     draw.set_color(0, 0, 0, 0.8)
     draw.rect(mx - 80, 10, mx + w + 10, 100)
     self.ai_message_label.draw()
     draw.set_color(1, 1, 1, 1)
     if event.ai_head != None:
         event.ai_head.blit(mx - 80, 17)
Beispiel #25
0
 def draw(self):
     glPushMatrix()
     glPushAttrib(GL_STENCIL_BUFFER_BIT)
     glClear(GL_STENCIL_BUFFER_BIT)
     glTranslatef(self.parent.x, self.parent.y, 0)
     glDisable(GL_TEXTURE_2D)
     loader = self.loader
     if loader.shape == LINE_SHAPE:
         glEnable(GL_LINE_SMOOTH)
         glEnable(GL_POINT_SMOOTH)
         glLineWidth(loader.borderSize)
         glPointSize(loader.borderSize)
         self.vertex.draw(GL_LINES)
         self.vertex.draw(GL_POINTS)
     elif loader.shape == RECTANGLE_SHAPE:
         width = self.parent.width
         height = self.parent.height
         if loader.fillType != NONE_FILL:
             # for counters
             if self.counter_stencil:
                 glEnable(GL_STENCIL_TEST)
                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)
                 glStencilFunc(GL_ALWAYS, 1, 1)
                 glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE)
                 self.counter_stencil.draw(GL_QUADS)
                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
                 glStencilFunc(GL_EQUAL, 1, 1)
                 self.draw_rectangle()
                 glDisable(GL_STENCIL_TEST)
             else:
                 self.draw_rectangle()
         if self.border is not None:
             self.border.draw(GL_QUADS)
     elif loader.shape == ELLIPSE_SHAPE:
         if loader.fillType != NONE_FILL:
             glEnable(GL_STENCIL_TEST)
             glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)
             glStencilFunc(GL_ALWAYS, 1, 1)
             glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE)
             self.stencil.draw(GL_TRIANGLES)
             glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
             glStencilFunc(GL_EQUAL, 1, 1)
             self.draw_rectangle(True)
             glDisable(GL_STENCIL_TEST)
         if self.border:
             self.border.draw(GL_QUADS)
     glPopAttrib()
     glPopMatrix()
Beispiel #26
0
 def draw(self):
     glPushMatrix()
     glPushAttrib(GL_STENCIL_BUFFER_BIT)
     glClear(GL_STENCIL_BUFFER_BIT)
     glTranslatef(self.parent.x, self.parent.y, 0)
     glDisable(GL_TEXTURE_2D)
     loader = self.loader
     if loader.shape == LINE_SHAPE:
         glEnable(GL_LINE_SMOOTH)
         glEnable(GL_POINT_SMOOTH)
         glLineWidth(loader.borderSize)
         glPointSize(loader.borderSize)
         self.vertex.draw(GL_LINES)
         self.vertex.draw(GL_POINTS)
     elif loader.shape == RECTANGLE_SHAPE:
         width = self.parent.width
         height = self.parent.height
         if loader.fillType != NONE_FILL:
             # for counters
             if self.counter_stencil:
                 glEnable(GL_STENCIL_TEST)
                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)
                 glStencilFunc(GL_ALWAYS, 1, 1)
                 glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE)
                 self.counter_stencil.draw(GL_QUADS)
                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
                 glStencilFunc(GL_EQUAL, 1, 1)
                 self.draw_rectangle()
                 glDisable(GL_STENCIL_TEST)
             else:
                 self.draw_rectangle()
         if self.border is not None:
             self.border.draw(GL_QUADS)
     elif loader.shape == ELLIPSE_SHAPE:
         if loader.fillType != NONE_FILL:
             glEnable(GL_STENCIL_TEST)
             glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)
             glStencilFunc(GL_ALWAYS, 1, 1)
             glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE)
             self.stencil.draw(GL_TRIANGLES)
             glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
             glStencilFunc(GL_EQUAL, 1, 1)
             self.draw_rectangle(True)
             glDisable(GL_STENCIL_TEST)
         if self.border:
             self.border.draw(GL_QUADS)
     glPopAttrib()
     glPopMatrix()
Beispiel #27
0
    def draw(self):
        gl.glLoadIdentity()
        gl.glTranslatef(self.x, self.y, self.z)
        # rotation
        gl.glRotatef(self.rx - 40, 1, 0, 0)
        gl.glRotatef(self.ry, 0, 1, 0)
        gl.glRotatef(self.rz - 40, 0, 0, 1)
        # color
        gl.glColor3f(*gray)

        gl.glPointSize(self.pointsize)
        pyglet.graphics.draw(
            len(self.points),
            gl.GL_POINTS,  #v3f/stream c4B/static
            ('v3f', self.points.reshape(-1)),
            ('c3f', self.data_points_color.reshape(-1)))
Beispiel #28
0
def bezier_draw_points_curve(cps, n=10, red=False):
    from pyglet import gl
    pts = [bezier_point(cps, i / (n - 1)) for i in range(0, n)]
    gl.glPointSize(5)
    gl.glBegin(gl.GL_POINTS)

    if red:
        gl.glColor3f(0, 0, 1)
    else:
        gl.glColor3f(1, 0, 0)

    for i, p in enumerate(pts):
        gl.glVertex3f(p[0], 0.01, p[2])

    gl.glEnd()
    gl.glColor3f(1, 1, 1)
Beispiel #29
0
    def init_gl(self, on_init=None, **kwargs):
        gl.glClearColor(.97, .97, .97, 1.0)
        max_depth = (np.abs(self.scene.bounds).max(axis=1)**2).sum()**.5
        max_depth = np.clip(max_depth, 500.00, np.inf)
        gl.glDepthRange(0.0, max_depth)

        gl.glClearDepth(1.0)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glDepthFunc(gl.GL_LEQUAL)

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_CULL_FACE)
        gl.glEnable(gl.GL_LIGHTING)
        gl.glEnable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)

        # put the light at one corner of the scenes AABB
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION,
                     _gl_vector(np.append(self.scene.bounds[1], 0)))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR, _gl_vector(.5, .5, 1, 1))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE, _gl_vector(1, 1, 1, .75))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT, _gl_vector(.1, .1, .1, .2))

        gl.glColorMaterial(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT_AND_DIFFUSE)
        gl.glEnable(gl.GL_COLOR_MATERIAL)
        gl.glShadeModel(gl.GL_SMOOTH)

        gl.glMaterialfv(gl.GL_FRONT, gl.GL_AMBIENT,
                        _gl_vector(0.192250, 0.192250, 0.192250))
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_DIFFUSE,
                        _gl_vector(0.507540, 0.507540, 0.507540))
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_SPECULAR,
                        _gl_vector(.5082730, .5082730, .5082730))

        gl.glMaterialf(gl.GL_FRONT, gl.GL_SHININESS, .4 * 128.0)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)

        gl.glLineWidth(1.5)
        gl.glPointSize(4)

        if on_init:
            on_init(gl, **kwargs)
Beispiel #30
0
def draw_points(point_list, color, size):
    """
    Draw a set of points.

    Args:
        :point_list: List of points Each point is
         in a list. So it is a list of lists.
        :color: color, specified in a list of 3 or 4 bytes in RGB or
         RGBA format.
        :size: Size of the point in pixels.
    Returns:
        None
    Raises:
        None

    Example:

    >>> import arcade
    >>> arcade.open_window("Drawing Example", 800, 600)
    >>> arcade.set_background_color(arcade.color.WHITE)
    >>> arcade.start_render()
    >>> point_list = ((165, 495), \
(165, 480), \
(165, 465), \
(195, 495), \
(195, 480), \
(195, 465))
    >>> arcade.draw_points(point_list, arcade.color.ZAFFRE, 10)
    >>> arcade.finish_render()
    >>> arcade.quick_run(0.25)
    """
    GL.glEnable(GL.GL_BLEND)
    GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)

    GL.glLoadIdentity()

    GL.glPointSize(size)
    if len(color) == 4:
        GL.glColor4ub(color[0], color[1], color[2], color[3])
    elif len(color) == 3:
        GL.glColor4ub(color[0], color[1], color[2], 255)
    GL.glBegin(GL.GL_POINTS)
    for point in point_list:
        GL.glVertex3f(point[0], point[1], 0.5)
    GL.glEnd()
Beispiel #31
0
def polygon(vertices: List[Vector], theme=Theme()):
    # batch = pyglet.graphics.Batch()
    n_vertices = len(vertices)
    vertices = vectors2vertices(vertices)
    if theme.fill:
        gl.glPolygonMode(gl.GL_FRONT, gl.GL_FILL)
        pyglet.graphics.draw(n_vertices, gl.GL_POLYGON, ('v2f', vertices),
                             ('c4f', n_vertices * theme.fill.normalized))
    if theme.stroke:
        gl.glLineWidth(float(theme.stroke_weight))
        gl.glPolygonMode(gl.GL_FRONT, gl.GL_LINE)
        pyglet.graphics.draw(n_vertices, gl.GL_POLYGON, ('v2f', vertices),
                             ('c4f', n_vertices * theme.stroke.normalized))

        gl.glPolygonMode(gl.GL_FRONT, gl.GL_POINT)
        gl.glPointSize(float(theme.stroke_weight))
        pyglet.graphics.draw(n_vertices, gl.GL_POLYGON, ('v2f', vertices),
                             ('c4f', n_vertices * theme.stroke.normalized))
Beispiel #32
0
    def init_gl(self):
        gl.glClearColor(.93, .93, 1, 1)

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_CULL_FACE)
        gl.glEnable(gl.GL_LIGHTING)
        gl.glEnable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)

        gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, _gl_vector(.5, .5, 1, 0))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR, _gl_vector(.5, .5, 1, 1))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE, _gl_vector(1, 1, 1, 1))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, _gl_vector(1, 0, .5, 0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_DIFFUSE, _gl_vector(.5, .5, .5, 1))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_SPECULAR, _gl_vector(1, 1, 1, 1))

        gl.glColorMaterial(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT_AND_DIFFUSE)
        gl.glEnable(gl.GL_COLOR_MATERIAL)
        gl.glShadeModel(gl.GL_SMOOTH)

        gl.glMaterialfv(gl.GL_FRONT,
                        gl.GL_AMBIENT,
                        _gl_vector(0.192250, 0.192250, 0.192250))
        gl.glMaterialfv(gl.GL_FRONT,
                        gl.GL_DIFFUSE,
                        _gl_vector(0.507540, 0.507540, 0.507540))
        gl.glMaterialfv(gl.GL_FRONT,
                        gl.GL_SPECULAR,
                        _gl_vector(.5082730, .5082730, .5082730))

        gl.glMaterialf(gl.GL_FRONT,
                       gl.GL_SHININESS,
                       .4 * 128.0)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)

        gl.glLineWidth(1.5)
        gl.glPointSize(4)
Beispiel #33
0
def test_closest_point_in_segment():
    import pyglet
    import draw_util
    from pyglet import gl
    
    w = pyglet.window.Window()

    line = []

    point = vec2(0, 0)

    @w.event
    def on_mouse_press(x, y, button, modifiers):
        if len(line) < 2:
            line.append(vec2(x, y))
        else:
            point.x = x
            point.y = y

    @w.event
    def on_draw():
        w.clear()
        gl.glBegin(gl.GL_POINTS)
        for ep in line:
            gl.glVertex2f(*ep)
        gl.glEnd()
        if len(line) == 2:
            gl.glBegin(gl.GL_LINES)
            gl.glVertex2f(*line[0])
            gl.glVertex2f(*line[1])
            gl.glEnd()
        if not (point.x == point.y == 0):
            closest = closest_point_in_segment(point, *line)
            gl.glBegin(gl.GL_POINTS)
            gl.glVertex2f(*closest)
            gl.glEnd()
            radius = (closest - point).length()
            draw_util.draw_circumference(point.x, point.y, radius)

    gl.glPointSize(4)
    pyglet.app.run()
Beispiel #34
0
 def render(self):
     # for smooth rendering
     # draw ships
     for ship in self.ships:
         ship.sprite.position = ship.position * 8 + Vec2d(4, 4)
         ship.sprite.draw()
     gl.glColor3f(1, 1, 0)
     # draw explosions TODO: Animate!
     for explosion in self.explosions:
         gl.glPointSize(8.0)
         pyglet.graphics.draw(1, pyglet.gl.GL_POINTS, ("v2i", (explosion.x * 8 + 4, explosion.y * 8 + 4)))
     laser_points = []
     # draw laser lines
     for shot in self.shots:
         startpos = shot.owner.position * 8 + Vec2d(4, 4)
         laser_points.append(startpos.x)
         laser_points.append(startpos.y)
         laser_points.append(shot.position.x * 8 + 4)
         laser_points.append(shot.position.y * 8 + 4)
     gl.glColor3f(1, 0, 0)
     pyglet.graphics.draw(len(self.shots) * 2, pyglet.gl.GL_LINES, ("v2i", laser_points))
Beispiel #35
0
    def set_state(self):
        gl.glPushAttrib( gl.GL_ENABLE_BIT )
        gl.glBindTexture( gl.GL_TEXTURE_2D, self.texture.id )
        gl.glEnable( gl.GL_POINT_SPRITE )
        gl.glDisable( gl.GL_LIGHTING )

        if self.attenuate:
            quadratic = (gl.GLfloat * 3)()
            quadratic[:] = (1.0, 0.0, 0.01)
            gl.glPointParameterfv( gl.GL_POINT_DISTANCE_ATTENUATION, quadratic )

        max_size = gl.GLfloat()
        gl.glGetFloatv( gl.GL_POINT_SIZE_MAX, max_size )

        gl.glPointParameterf( gl.GL_POINT_FADE_THRESHOLD_SIZE, 60.0 )

        gl.glPointParameterf( gl.GL_POINT_SIZE_MIN, 1.0 )
        gl.glPointParameterf( gl.GL_POINT_SIZE_MAX, max_size )

        gl.glTexEnvf( gl.GL_POINT_SPRITE, gl.GL_COORD_REPLACE, gl.GL_TRUE )
        gl.glPointSize( self.point_size )
Beispiel #36
0
    def draw(self):
        if not self.vao:
            self.vao = VAO(indices=self.array_indices)
            self._fill_vao()

        if self.visible:
            if self.dynamic:
                for vbo in self.vbos:
                    vbo._buffer_subdata()

            if self.drawmode == gl.GL_POINTS:
                gl.glPointSize(self.point_size)

            for texture in self.textures:
                texture.bind()

            with self.vao as vao:
                self.uniforms.send()
                vao.draw(mode=self.drawmode)

            for texture in self.textures:
                texture.unbind()
Beispiel #37
0
def draw_point(x, y, color, size):
    """
    Draw a point.

    Args:
        :x: x position of point.
        :y: y position of point.
        :color: color, specified in a list of 3 or 4 bytes in RGB or
         RGBA format.
        :size: Size of the point in pixels.
    Returns:
        None
    Raises:
        None

    Example:

    >>> import arcade
    >>> arcade.open_window("Drawing Example", 800, 600)
    >>> arcade.set_background_color(arcade.color.WHITE)
    >>> arcade.start_render()
    >>> arcade.draw_point(60, 495, arcade.color.RED, 10)
    >>> arcade.finish_render()
    >>> arcade.quick_run(0.25)
    """
    GL.glEnable(GL.GL_BLEND)
    GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)

    GL.glLoadIdentity()

    GL.glPointSize(size)
    if len(color) == 4:
        GL.glColor4ub(color[0], color[1], color[2], color[3])
    elif len(color) == 3:
        GL.glColor4ub(color[0], color[1], color[2], 255)
    GL.glBegin(GL.GL_POINTS)
    GL.glVertex3f(x, y, 0.5)
    GL.glEnd()
Beispiel #38
0
    def render(self):
        # draw scans
        gl.glColor3f(0, 0.2, 0.2)
        for scan in self.scans:
            vertices = [
                ((scan.x + p.x) * 8 + 4, (scan.y + p.y) * 8 + 4) for p in self.scanner_model
            ]
            vertices = tuple(item for sublist in vertices for item in sublist)
            pyglet.graphics.draw(
                int(len(vertices) / 2), pyglet.gl.GL_LINES,
                ('v2f', vertices)
            )

        # draw ships
        for ship in self.ships:
            ship.sprite.position = ship.position * 8 + Vec2d(4, 4)
            ship.sprite.draw()
        gl.glColor3f(1, 1, 0)
        # draw explosions
        for explosion in self.explosions:
            gl.glPointSize(8.0)
            pyglet.graphics.draw(
                1, pyglet.gl.GL_POINTS,
                ('v2i', (explosion.x * 8 + 4, explosion.y * 8 + 4))
            )
        # draw laser lines
        for shot in self.shots:
            lasers = continuous_laser(shot.owner.position, shot.position)
            vertices = [
                (p.x * 8 + 4, p.y * 8 + 4) for p in lasers
            ]
            vertices = tuple(item for sublist in vertices for item in sublist)

            gl.glColor3f(1, 0, 0)
            pyglet.graphics.draw(
                int(len(vertices) / 2), pyglet.gl.GL_LINE_LOOP,
                ('v2i', vertices)
            )
Beispiel #39
0
    def draw(self):
        """ Draw the Mesh if it's visible, from the perspective of the camera and lit by the light. The function sends the uniforms"""
        if not self.vao:
            self.vao = VAO(indices=self.array_indices)
            self._fill_vao()

        if self.visible:
            if self.dynamic:
                for vbo in self.vbos:
                    vbo._buffer_subdata()

            if self.drawmode == gl.GL_POINTS:
                gl.glPointSize(self.point_size)

            for texture in self.textures:
                texture.bind()

            with self.vao as vao:
                self.uniforms.send()
                vao.draw(mode=self.drawmode)

            for texture in self.textures:
                texture.unbind()
Beispiel #40
0
        def drawpoint( pt ):
            'draw a single point with white outline and black interior'
            gl.glPointSize( 6 )
            gl.glBegin( gl.GL_POINTS )
            gl.glColor3f( 1, 1, 1)
            gl.glVertex3d( pt[0], pt[1], pt[2] )
            gl.glEnd()

            gl.glPointSize( 4 )
            gl.glBegin( gl.GL_POINTS )
            gl.glColor3f( 0, 0, 0)
            gl.glVertex3d( pt[0], pt[1], pt[2] )
            gl.glEnd()

            gl.glPointSize( 3 )
Beispiel #41
0
 def _draw(self):
     gl.glLineWidth(self._line_width)
     gl.glPointSize(self._point_size)
     gl.glColor4f(*self._gl_colour)
     self._vertex_list.draw(self._gl_line_type)
Beispiel #42
0
    def training_status(self, mode='human'):
        if self.viewer is None:
            from gym.envs.classic_control import rendering
            self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H)
            self.transform = rendering.Transform()

        if "t" not in self.__dict__: return  # reset() not called yet

        zoom = ZOOM*SCALE #0.1*SCALE*max(1-self.t, 0) + ZOOM*SCALE*min(self.t, 1)   # Animate zoom first second
        zoom_state  = ZOOM*SCALE*STATE_W/WINDOW_W
        zoom_video  = ZOOM*SCALE*VIDEO_W/WINDOW_W
        scroll_x = 0 #self.car.hull.position[0] #0
        scroll_y = 0 #self.car.hull.position[1] #-30
        angle = 0 #-self.car.hull.angle #0
        vel = 0 #self.car.hull.linearVelocity #0
        self.transform.set_scale(zoom, zoom)
        self.transform.set_translation(WINDOW_W/2, WINDOW_H/2)
        # self.transform.set_translation(
        #     WINDOW_W/2 - (scroll_x*zoom*math.cos(angle) - scroll_y*zoom*math.sin(angle)),
        #     WINDOW_H/4 - (scroll_x*zoom*math.sin(angle) + scroll_y*zoom*math.cos(angle)) )
        # self.transform.set_rotation(angle)


        arr = None
        win = self.viewer.window
        if mode != 'state_pixels' and mode != 'rgb_array':
            win.switch_to()
            win.dispatch_events()
        if mode=="rgb_array" or mode=="state_pixels":
            win.clear()
            t = self.transform
            self.transform.set_translation(0, 0)
            self.transform.set_scale(0.0167, 0.0167)
            if mode=='rgb_array':
                VP_W = VIDEO_W
                VP_H = VIDEO_H
            else:
                VP_W = WINDOW_W//2 #STATE_W
                VP_H = WINDOW_H//2 #STATE_H
            gl.glViewport(0, 0, VP_W, VP_H)
            t.enable()
            self.render_road()
            for geom in self.viewer.onetime_geoms:
                geom.render()
            t.disable()
            # self.render_indicators(WINDOW_W, WINDOW_H)  # TODO: find why 2x needed, wtf
            image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()
            arr = np.fromstring(image_data.data, dtype=np.uint8, sep='')
            arr = arr.reshape(VP_H, VP_W, 4)
            arr = arr[::-1, :, 0:3]

        if mode=="rgb_array" and not self.human_render: # agent can call or not call env.render() itself when recording video.
            win.flip()

        if mode=='human':
            self.human_render = True
            win.clear()
            t = self.transform
            gl.glViewport(0, 0, WINDOW_W, WINDOW_H)
            t.enable()
            self.render_road()
            for geom in self.viewer.onetime_geoms:
                geom.render()

            with open("training_positions.csv", 'r') as fin:
                line_number = sum(1 for _ in fin)

            with open("training_positions.csv", 'r') as fin:
                gl.glPointSize(10)
                for i, line in enumerate(fin):
                    epoch, angle, coord_x, coord_y = list(map(float, line.strip().split(",")))
                    new_coord = (angle, coord_x, coord_y)

                    gl.glBegin(gl.GL_POINTS)
                    alpha = (i+1)/line_number
                    gl.glColor4f(alpha, 0, 1-alpha, 0.8)
                    gl.glVertex3f(coord_x, coord_y, 0)
                    gl.glEnd()

            t.disable()
            # self.render_indicators(WINDOW_W, WINDOW_H)
            win.flip()

            # # Drawing a rock:
            # gl.glBegin(gl.GL_QUADS)
            # gl.glColor4f(0,0,0,1)
            # gl.glVertex3f(10, 30, 0)
            # gl.glVertex3f(10, 10, 0)
            # gl.glVertex3f(30, 10, 0)
            # gl.glVertex3f(30, 30, 0)
            # gl.glEnd()

        self.viewer.onetime_geoms = []
        return arr
    def render_road(self):
        gl.glBegin(gl.GL_QUADS)
        gl.glColor4f(0.4, 0.8, 0.4, 1.0)
        gl.glVertex3f(-PLAYFIELD, +PLAYFIELD, 0)
        gl.glVertex3f(+PLAYFIELD, +PLAYFIELD, 0)
        gl.glVertex3f(+PLAYFIELD, -PLAYFIELD, 0)
        gl.glVertex3f(-PLAYFIELD, -PLAYFIELD, 0)
        gl.glColor4f(0.4, 0.9, 0.4, 1.0)
        k = PLAYFIELD / 20.0
        for x in range(-20, 20, 2):
            for y in range(-20, 20, 2):
                gl.glVertex3f(k * x + k, k * y + 0, 0)
                gl.glVertex3f(k * x + 0, k * y + 0, 0)
                gl.glVertex3f(k * x + 0, k * y + k, 0)
                gl.glVertex3f(k * x + k, k * y + k, 0)

        for poly, color in self.road_poly:
            gl.glColor4f(color[0], color[1], color[2], 1)
            for p in poly:
                gl.glVertex3f(p[0], p[1], 0)
        gl.glEnd()

        #####################################

        if DEBUG_DRAWING:
            # Draw control points
            gl.glPointSize(7.0)
            gl.glBegin(gl.GL_POINTS)
            gl.glColor4f(1, 0, 1, 1)
            for i in range(self.next_road_tile,
                           self.next_road_tile + LOOK_AHEAD):
                a, b, x, y = self.track[i % len(self.track)]
                gl.glVertex3f(x, y, 0.9)
            gl.glEnd()

            # Draw angles
            gl.glLineWidth(3.0)
            gl.glColor4f(0, 1, 0, 1)
            for i in range(self.next_road_tile,
                           self.next_road_tile + LOOK_AHEAD):
                a, b, x, y = self.track[i % len(self.track)]
                gl.glBegin(gl.GL_LINES)
                gl.glVertex3f(x, y, 0.9)
                line_len = 1
                rot = math.pi / 2
                gl.glVertex3f(x + line_len * math.cos(b + rot),
                              y + line_len * math.sin(b + rot), 0.9)
                gl.glEnd()

            # Interpolation debug
            gl.glBegin(gl.GL_POINTS)
            gl.glColor4f(1, 1, 1, 1)
            tip = np.array(
                (self.car.wheels[0].position + self.car.wheels[1].position) /
                2)
            gl.glVertex3f(*tip, 0.5)
            gl.glColor4f(1, 0, 0, 1)
            gl.glVertex3f(*self.ctrl_pts[self.next_road_tile - 1], 1)
            gl.glColor4f(1, 0, 0, 1)
            gl.glVertex3f(*self.ctrl_pts[self.next_road_tile - 2], 1)
            gl.glEnd()

            p1 = self.ctrl_pts[self.next_road_tile - 1]
            p2 = self.ctrl_pts[self.next_road_tile - 2]
            u = (p1 - p2) / TRACK_DETAIL_STEP
            v = (tip - p2) / TRACK_DETAIL_STEP
            interp = np.dot(v, u)

            new_ctrl = np.transpose([
                np.interp(self.indices + interp, self.indices,
                          self.ctrl_pts[:, 0]),
                np.interp(self.indices + interp, self.indices,
                          self.ctrl_pts[:, 1]),
            ])

            gl.glBegin(gl.GL_POINTS)
            gl.glColor4f(0, 1, 1, 1)
            for i in range(self.next_road_tile,
                           self.next_road_tile + LOOK_AHEAD):
                gl.glVertex3f(*new_ctrl[i % len(self.ctrl_pts)], 0.9)
            gl.glEnd()
Beispiel #44
0
 def draw(self):
     gl.glPointSize(5.0)
     gl.glCallList(self.list)
     gl.glColor3f(1.0, 1.0, 1.0)
Beispiel #45
0
	def draw(self):
		gl.glLineWidth(1.5)

		phys_comp_list = self.manager.comps[phys.PhysicsEcsComponent.name()]
		grav_comp_list = self.manager.comps[phys.GravityEcsComponent.name()]
		coll_comp_list = self.manager.comps[coll.CollisionEcsComponent.name()]
		planet_comp_list = self.manager.comps[planet.PlanetEcsComponent.name()]
		ship_comp_list = self.manager.comps[ship.ShipEcsComponent.name()]
		base_comp_list = self.manager.comps[base.BaseEcsComponent.name()]
		aster_comp_list = self.manager.comps[asteroid.AsteroidEcsComponent.name()]
		rend_plan_comp_list = self.manager.comps[planet.RenderPlanetEcsComponent.name()]
		rend_ship_comp_list = self.manager.comps[ship.RenderShipEcsComponent.name()]
		rend_base_comp_list = self.manager.comps[base.RenderBaseEcsComponent.name()]
		rend_aster_comp_list = self.manager.comps[asteroid.RenderAsteroidEcsComponent.name()]

		rend_anim_comp_list = self.manager.comps[RenderAnimationEcsComponent.name()]

		entities = self.manager.entities

		player_alive = False
		if self.player_entity_id in entities:
			player_alive = True

			ppc = self.manager.get_entity_comp(self.player_entity_id, phys.PhysicsEcsComponent.name())
			psc = self.manager.get_entity_comp(self.player_entity_id, ship.ShipEcsComponent.name())

			if ppc:
				self.tx = ppc.pos.x - const.WIDTH / 2
				self.ty = ppc.pos.y - const.HEIGHT / 2

		tx = self.tx
		ty = self.ty
		area = (tx, ty, const.WIDTH, const.HEIGHT)

		#img.get(img.IMG_BG).blit(0, 0)

		gl.glPointSize( 1 );
		self.starfield.draw(tx, ty)

		gl.glPushMatrix()
		gl.glLoadIdentity()
		gl.glTranslatef(-tx, -ty, 0.0)		

		# predraw (lines, areas etc)
		for idx, eid in enumerate(entities):
			basec = base_comp_list[idx]
			physc = phys_comp_list[idx]
			if basec:
				rbc = rend_base_comp_list[idx]
				if basec.crew_load > 0:
					draw_circle(physc.pos.x, physc.pos.y, basec.radius, None, gl.GL_LINES, (1, 0, 0, 1))

		for idx, eid in enumerate(entities):
			shipc = ship_comp_list[idx]
			basec = base_comp_list[idx]
			asterc = aster_comp_list[idx]
			planetc = planet_comp_list[idx]
			physc = phys_comp_list[idx]
			collc = coll_comp_list[idx]

			if not physc:
				continue

			#if eid == self.player_entity_id:
			#	print physc.pos.x, physc.pos.y, collc.radius, tx, tx
			#	print circle_rect_intersect(physc.pos.x, physc.pos.y, collc.radius, tx, tx, const.WIDTH, const.HEIGHT)

			#clipping
			if not circle_rect_intersect(physc.pos.x, physc.pos.y, collc.radius, tx, ty, const.WIDTH, const.HEIGHT):
				continue

			if shipc:
				rsc = rend_ship_comp_list[idx]
				rsc.process()

				ship_sprite = rsc.spr
				ship_sprite.x = physc.pos.x
				ship_sprite.y = physc.pos.y
				ship_sprite.rotation = -shipc.rotation
				ship_sprite.draw()				

				if rsc.thrust_cooldown:
					thrust_sprite = rsc.thrust_spr
					thrust_sprite.x = physc.pos.x
					thrust_sprite.y = physc.pos.y
					thrust_sprite.rotation = -shipc.rotation
					thrust_sprite.draw()

				#draw_circle(physc.pos.x, physc.pos.y, collc.radius, None, gl.GL_POLYGON, (1, 1, 0, 1))

				#dir_radians = math.radians(shipc.rotation)
				#dirv = vec2d.vec2d(math.cos(dir_radians), math.sin(dir_radians))
				#dirv.length = collc.radius
				#gl.glColor3f(1, 0, 0, 1)
				#gl.glBegin(gl.GL_LINES)
				#gl.glVertex2f(physc.pos.x, physc.pos.y)
				#gl.glVertex2f(physc.pos.x + dirv.x, physc.pos.y + dirv.y)
				#gl.glEnd()

			elif basec:
				rbc = rend_base_comp_list[idx]	

				base_sprite = rbc.spr
				if base_sprite:
					base_sprite.x = physc.pos.x
					base_sprite.y = physc.pos.y
					base_sprite.draw()
				else:
					draw_circle(physc.pos.x, physc.pos.y, collc.radius, None, gl.GL_POLYGON, (1, 0, 0, 1))

			elif asterc:
				rac = rend_aster_comp_list[idx]

				aster_sprite = rac.spr
				if aster_sprite:
					aster_sprite.x = physc.pos.x
					aster_sprite.y = physc.pos.y
					aster_sprite.draw()
				else:
					draw_circle(physc.pos.x, physc.pos.y, collc.radius, None, gl.GL_POLYGON, (0, 1, 0, 1))

			elif planetc:
				rpc = rend_plan_comp_list[idx]

				planet_sprite = rpc.spr
				if planet_sprite:
					planet_sprite.x = physc.pos.x
					planet_sprite.y = physc.pos.y
					planet_sprite.draw()
				else:
					draw_circle(physc.pos.x, physc.pos.y, collc.radius)

				if planetc.pname:
					label = pyglet.text.Label(planetc.pname,
	                          font_name=font.FONT_MONO.name,
	                          font_size=12,
	                          x=physc.pos.x, y=physc.pos.y, #  + collc.radius + 5
	                          anchor_x='center', anchor_y='center',
	                          color=(0, 0, 255, 255))
					label.draw()

				#gc = grav_comp_list[idx]
				#if gc and gc.gravity_radius:
				#	draw_circle(physc.pos.x, physc.pos.y, gc.gravity_radius, None, gl.GL_LINE_LOOP)

			for anim in rend_anim_comp_list:
				if not anim:
					continue

				#print 'we have an anim to show!'
				a = anim.anim
				a.draw()

			if player_alive and not self.manager.victory:
				for idx, eid in enumerate(entities):
					shipc = ship_comp_list[idx]

					if shipc:
						if shipc.messages:
							pos_mod = 0.0
							for message in shipc.messages:
								label = message[5]
								if not label:
									label = pyglet.text.Label(message[0],
										font_name=font.FONT_MONO.name,
										font_size=12,
										x = message[2], y = message[3] + pos_mod,
										anchor_x='left', anchor_y='bottom',
										color=message[4])
									message[5] = label
								label.draw()
								pos_mod +=  25

		gl.glPopMatrix()

		# interface
		if player_alive and not self.manager.victory:
			if self.manager._navigation:
				gl.glLineWidth(1)
				nav_circle_radius = (const.HEIGHT - 100) // 2
				draw_circle(const.WIDTH // 2, const.HEIGHT // 2, nav_circle_radius, None, gl.GL_LINE_LOOP, (1, 1, 0, 0.4))

				for idx, eid in enumerate(entities):
					basec = base_comp_list[idx]
					physc = phys_comp_list[idx]

					if not physc:
						continue

					distance = ppc.pos.get_distance(physc.pos) / 50

					if distance > 3 and distance < nav_circle_radius:
						gl.glEnable(gl.GL_BLEND)
						gl.glColor4f(1, 1, 0, 0.4)
						if basec and basec.crew_load > 0:
							cpo = get_circle_closest_point(physc.pos, ppc.pos, nav_circle_radius)
							cpi = get_circle_closest_point(physc.pos, ppc.pos, nav_circle_radius - distance)

							gl.glBegin(gl.GL_LINES)
							gl.glVertex2f(cpi.x - self.tx, cpi.y - self.ty)
							gl.glVertex2f(cpo.x - self.tx, cpo.y - self.ty)
							gl.glEnd()

			show_bar(130, const.HEIGHT - 32, psc.fuel, psc.fuel_max,
					width=100., 
					height=15., 
					border_color=(255, 255, 255),
					progress=False)

			show_bar(485, const.HEIGHT - 32, psc.health, psc.health_max,
					width=100., 
					height=15., 
					border_color=(255, 255, 255),
					progress=False)

			show_bar(730, const.HEIGHT - 32, psc.passengers, self.manager.crew_to_rescue,
					width=100., 
					height=15., 
					border_color=(255, 255, 255),
					progress=False)

			seconds_remaining = self.manager.get_system(player.PlayerEscSystem.name()).time_limit / director.director.fps
			self.time_label.text = 'TIME %.2f' % seconds_remaining

			self.speed_label.text = 'SPEED %.2f' % ppc.vel.length

			self.fuel_label.draw()									
			self.health_label.draw()
			self.rescued_label.draw()
			self.time_label.draw()
			self.speed_label.draw()

		self.controls_label.draw()
Beispiel #46
0
    def on_draw():
        window.clear()

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_LINE_SMOOTH)

        width, height = window.get_size()
        gl.glViewport(0, 0, width, height)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluPerspective(60, width / float(height), 0.01, 20)

        gl.glMatrixMode(gl.GL_TEXTURE)
        gl.glLoadIdentity()
        # texcoords are [0..1] and relative to top-left pixel corner, add 0.5 to center
        gl.glTranslatef(0.5 / image_data.width, 0.5 / image_data.height, 0)
        image_texture = image_data.get_texture()
        # texture size may be increased by pyglet to a power of 2
        tw, th = image_texture.owner.width, image_texture.owner.height
        gl.glScalef(image_data.width / float(tw),
                    image_data.height / float(th), 1)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        gl.gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0)

        gl.glTranslatef(0, 0, state.distance)
        gl.glRotated(state.pitch, 1, 0, 0)
        gl.glRotated(state.yaw, 0, 1, 0)

        if any(state.mouse_btns):
            axes(0.1, 4)

        gl.glTranslatef(0, 0, -state.distance)
        gl.glTranslatef(*state.translation)

        gl.glColor3f(0.5, 0.5, 0.5)
        gl.glPushMatrix()
        gl.glTranslatef(0, 0.5, 0.5)
        grid()
        gl.glPopMatrix()

        psz = max(window.get_size()) / float(max(w, h)) if state.scale else 1
        gl.glPointSize(psz)
        distance = (0, 0, 1) if state.attenuation else (1, 0, 0)
        gl.glPointParameterfv(gl.GL_POINT_DISTANCE_ATTENUATION,
                              (gl.GLfloat * 3)(*distance))

        if state.lighting:
            ldir = [0.5, 0.5, 0.5]  # world-space lighting
            ldir = np.dot(state.rotation, (0, 0, 1))  # MeshLab style lighting
            ldir = list(ldir) + [0]  # w=0, directional light
            gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, (gl.GLfloat * 4)(*ldir))
            gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE,
                         (gl.GLfloat * 3)(1.0, 1.0, 1.0))
            gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT,
                         (gl.GLfloat * 3)(0.75, 0.75, 0.75))
            gl.glEnable(gl.GL_LIGHT0)
            gl.glEnable(gl.GL_NORMALIZE)
            gl.glEnable(gl.GL_LIGHTING)

        gl.glColor3f(1, 1, 1)
        texture = image_data.get_texture()
        gl.glEnable(texture.target)
        gl.glBindTexture(texture.target, texture.id)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)

        # comment this to get round points with MSAA on
        gl.glEnable(gl.GL_POINT_SPRITE)

        if not state.scale and not state.attenuation:
            gl.glDisable(gl.GL_MULTISAMPLE)  # for true 1px points with MSAA on
        vertex_list.draw(gl.GL_POINTS)
        gl.glDisable(texture.target)
        if not state.scale and not state.attenuation:
            gl.glEnable(gl.GL_MULTISAMPLE)

        gl.glDisable(gl.GL_LIGHTING)

        gl.glColor3f(0.25, 0.25, 0.25)
        frustum(depth_intrinsics)
        axes()

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, width, 0, height, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glMatrixMode(gl.GL_TEXTURE)
        gl.glLoadIdentity()
        gl.glDisable(gl.GL_DEPTH_TEST)

        fps_display.draw()
def on_draw():
    window.clear()

    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glEnable(gl.GL_LINE_SMOOTH)

    width, height = window.get_size()
    gl.glViewport(0, 0, width, height)

    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.gluPerspective(60, width / float(height), 0.01, 20)

    gl.glMatrixMode(gl.GL_TEXTURE)
    gl.glLoadIdentity()
    # texcoords are [0..1] and relative to top-left pixel corner, add 0.5 to center
    gl.glTranslatef(0.5 / image_data.width, 0.5 / image_data.height, 0)
    # texture size may be increased by pyglet to a power of 2
    tw, th = image_data.texture.owner.width, image_data.texture.owner.height
    gl.glScalef(image_data.width / float(tw),
                image_data.height / float(th), 1)

    gl.glMatrixMode(gl.GL_MODELVIEW)
    gl.glLoadIdentity()

    gl.gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0)

    gl.glTranslatef(0, 0, state.distance)
    gl.glRotated(state.pitch, 1, 0, 0)
    gl.glRotated(state.yaw, 0, 1, 0)

    if any(state.mouse_btns):
        axes(0.1, 4)

    gl.glTranslatef(0, 0, -state.distance)
    gl.glTranslatef(*state.translation)

    gl.glColor3f(0.5, 0.5, 0.5)
    gl.glPushMatrix()
    gl.glTranslatef(0, 0.5, 0.5)
    grid()
    gl.glPopMatrix()

    psz = max(window.get_size()) / float(max(w, h)) if state.scale else 1
    gl.glPointSize(psz)
    distance = (0, 0, 1) if state.attenuation else (1, 0, 0)
    gl.glPointParameterfv(gl.GL_POINT_DISTANCE_ATTENUATION,
                          (gl.GLfloat * 3)(*distance))

    if state.lighting:
        ldir = [0.5, 0.5, 0.5]  # world-space lighting
        ldir = np.dot(state.rotation, (0, 0, 1))  # MeshLab style lighting
        ldir = list(ldir) + [0]  # w=0, directional light
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, (gl.GLfloat * 4)(*ldir))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE,
                     (gl.GLfloat * 3)(1.0, 1.0, 1.0))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT,
                     (gl.GLfloat * 3)(0.75, 0.75, 0.75))
        gl.glEnable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_NORMALIZE)
        gl.glEnable(gl.GL_LIGHTING)

    gl.glColor3f(1, 1, 1)
    texture = image_data.get_texture()
    gl.glEnable(texture.target)
    gl.glBindTexture(texture.target, texture.id)
    gl.glTexParameteri(
        gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)

    # comment this to get round points with MSAA on
    gl.glEnable(gl.GL_POINT_SPRITE)

    if not state.scale and not state.attenuation:
        gl.glDisable(gl.GL_MULTISAMPLE)  # for true 1px points with MSAA on
    vertex_list.draw(gl.GL_POINTS)
    gl.glDisable(texture.target)
    if not state.scale and not state.attenuation:
        gl.glEnable(gl.GL_MULTISAMPLE)

    gl.glDisable(gl.GL_LIGHTING)

    gl.glColor3f(0.25, 0.25, 0.25)
    frustum(depth_intrinsics)
    axes()

    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.glOrtho(0, width, 0, height, -1, 1)
    gl.glMatrixMode(gl.GL_MODELVIEW)
    gl.glLoadIdentity()
    gl.glMatrixMode(gl.GL_TEXTURE)
    gl.glLoadIdentity()
    gl.glDisable(gl.GL_DEPTH_TEST)

    fps_display.draw()
Beispiel #48
0
 def extra_initgl(self):
     gl.glEnable( gl.GL_POINT_SMOOTH )
     gl.glPointSize(5)
Beispiel #49
0
 def set_state(self):
     super().set_state()
     gl.glLineWidth(self.width)
     gl.glPointSize(self.width)
 def unset_state(self):
     gl.glPointSize(1.0)
 def set_state(self):
     gl.glPointSize(self.size)
Beispiel #52
0
 def point_size(self, value: float):
     gl.glPointSize(self._point_size)
     self._point_size = value
Beispiel #53
0
 def set_state(self):
     gl.glPointSize(self.event.width + self.event.height)