Python pyglet.graphics() Examples

The following are 28 code examples of pyglet.graphics(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyglet , or try the search function .
Example #1
Source File: shapes.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, blend_src, blend_dest, parent=None):
        """Create a Shape group.

        The group is created internally. Usually you do not
        need to explicitly create it.

        :Parameters:
            `blend_src` : int
                OpenGL blend source mode; for example,
                ``GL_SRC_ALPHA``.
            `blend_dest` : int
                OpenGL blend destination mode; for example,
                ``GL_ONE_MINUS_SRC_ALPHA``.
            `parent` : `~pyglet.graphics.Group`
                Optional parent group.
        """
        super().__init__(_default_program, parent=parent)
        self.blend_src = blend_src
        self.blend_dest = blend_dest 
Example #2
Source File: __init__.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        """Create a graphics batch."""
        # Mapping to find domain.  
        # group -> (attributes, mode, indexed) -> domain
        self.group_map = {}

        # Mapping of group to list of children.
        self.group_children = {}

        # List of top-level groups
        self.top_groups = []

        self._draw_list = []
        self._draw_list_dirty = False

        # Each Batch encompasses one VAO
        self.vao = VertexArray()

        if _debug_graphics_batch:
            print("Batch created. VAO ID: {0}".format(self.vao.id)) 
Example #3
Source File: vertexdomain.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _nearest_pow2(v):
    # From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
    # Credit: Sean Anderson
    v -= 1
    v |= v >> 1
    v |= v >> 2
    v |= v >> 4
    v |= v >> 8
    v |= v >> 16
    return v + 1 
Example #4
Source File: vertexdomain.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_indexed_domain(shader_program_id, *attribute_usage_formats):
    """Create an indexed vertex domain covering the given attribute usage
    formats.  See documentation for :py:class:`create_attribute_usage` and
    :py:func:`pyglet.graphics.vertexattribute.create_attribute` for the grammar
    of these format strings.

    :rtype: :py:class:`VertexDomain`
    """
    attribute_usages = [create_attribute_usage(shader_program_id, f)
                        for f in attribute_usage_formats]
    return IndexedVertexDomain(attribute_usages) 
Example #5
Source File: gltf.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decode(self, file, filename, batch):

        if not batch:
            batch = pyglet.graphics.Batch()

        vertex_lists = parse_gltf_file(file=file, filename=filename, batch=batch)
        textures = {}

        return Model(vertex_lists, textures, batch=batch) 
Example #6
Source File: shapes.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, x, y, width, height, color=(255, 255, 255), batch=None, group=None):
        """Create a rectangle or square.

        The rectangles's anchor point defaults to the (x, y) coordinates,
        which are at the bottom left.

        :Parameters:
            `x` : float
                The X coordinate of the rectangle.
            `y` : float
                The Y coordinate of the rectangle.
            `width` : float
                The width of the rectangle.
            `height` : float
                The height of the rectangle.
            `color` : (int, int, int)
                The RGB color of the rectangle, specified as
                a tuple of three ints in the range of 0-255.
            `batch` : `~pyglet.graphics.Batch`
                Optional batch to add the rectangle to.
            `group` : `~pyglet.graphics.Group`
                Optional parent group of the rectangle.
        """
        self._x = x
        self._y = y
        self._width = width
        self._height = height
        self._rotation = 0
        self._rgb = color

        self._batch = batch or Batch()
        self._group = _ShapeGroup(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, group)
        self._vertex_list = self._batch.add(6, GL_TRIANGLES, self._group, 'position2f', 'colors4Bn')
        self._update_position()
        self._update_color() 
Example #7
Source File: shapes.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, x, y, x2, y2, width=1, color=(255, 255, 255), batch=None, group=None):
        """Create a line.

        The line's anchor point defaults to the center of the line's
        width on the X axis, and the Y axis.

        :Parameters:
            `x` : float
                The first X coordinate of the line.
            `y` : float
                The first Y coordinate of the line.
            `x2` : float
                The second X coordinate of the line.
            `y2` : float
                The second Y coordinate of the line.
            `width` : float
                The desired width of the line.
            `color` : (int, int, int)
                The RGB color of the line, specified as a tuple of
                three ints in the range of 0-255.
            `batch` : `~pyglet.graphics.Batch`
                Optional batch to add the line to.
            `group` : `~pyglet.graphics.Group`
                Optional parent group of the line.
        """
        self._x = x
        self._y = y
        self._x2 = x2
        self._y2 = y2

        self._width = width
        self._rotation = math.degrees(math.atan2(y2 - y, x2 - x))
        self._rgb = color

        self._batch = batch or Batch()
        self._group = _ShapeGroup(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, group)
        self._vertex_list = self._batch.add(6, GL_TRIANGLES, self._group, 'position2f', 'colors4Bn')
        self._update_position()
        self._update_color() 
Example #8
Source File: shapes.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, x, y, radius, segments=None, color=(255, 255, 255), batch=None, group=None):
        """Create a circle.

        The circle's anchor point (x, y) defaults to the center of the circle.

        :Parameters:
            `x` : float
                X coordinate of the circle.
            `y` : float
                Y coordinate of the circle.
            `radius` : float
                The desired radius.
            `segments` : int
                You can optionally specifify how many distict triangles
                the circle should be made from. If not specified, it will
                be automatically calculated based on the radius.
            `color` : (int, int, int)
                The RGB color of the circle, specified as a tuple of
                three ints in the range of 0-255.
            `batch` : `~pyglet.graphics.Batch`
                Optional batch to add the circle to.
            `group` : `~pyglet.graphics.Group`
                Optional parent group of the circle.
        """
        self._x = x
        self._y = y
        self._radius = radius
        self._segments = segments or int(radius / 1.25)
        self._rgb = color

        self._batch = batch or Batch()
        self._group = _ShapeGroup(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, group)

        self._vertex_list = self._batch.add(self._segments*3, GL_TRIANGLES, self._group, 'position2f', 'colors4Bn')
        self._update_position()
        self._update_color() 
Example #9
Source File: shapes.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw(self):
        """Draw the shape at its current position.

        Using this method is not recommended. Instead, add the
        shape to a `pyglet.graphics.Batch` for efficient rendering.
        """
        self._vertex_list.draw(GL_LINES) 
Example #10
Source File: __init__.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, texture, order=0, parent=None):
        """Create a texture group.

        :Parameters:
            `texture` : `~pyglet.image.Texture`
                Texture to bind.
            `order` : int
                Change the order to render above or below other Groups.
            `parent` : `~pyglet.graphics.Group`
                Parent group.
        """
        super(TextureGroup, self).__init__(order, parent)
        self.texture = texture 
Example #11
Source File: __init__.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, order=0, parent=None):
        """Create a group.

        :Parameters:
            `order` : int
                Set the order to render above or below other Groups.
            `parent` : `~pyglet.graphics.Group`
                Group to contain this group; its state will be set
                before this Group's state.
        """
        self._order = order
        self.parent = parent 
Example #12
Source File: __init__.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def migrate(self, vertex_list, mode, group, batch):
        """Migrate a vertex list to another batch and/or group.

        `vertex_list` and `mode` together identify the vertex list to migrate.
        `group` and `batch` are new owners of the vertex list after migration.  

        The results are undefined if `mode` is not correct or if `vertex_list`
        does not belong to this batch (they are not checked and will not
        necessarily throw an exception immediately).

        `batch` can remain unchanged if only a group change is desired.
        
        :Parameters:
            `vertex_list` : `~pyglet.graphics.vertexdomain.VertexList`
                A vertex list currently belonging to this batch.
            `mode` : int
                The current GL drawing mode of the vertex list.
            `group` : `~pyglet.graphics.Group`
                The new group to migrate to.
            `batch` : `~pyglet.graphics.Batch`
                The batch to migrate to (or the current batch).

        """
        formats = vertex_list.domain.__formats
        if isinstance(vertex_list, vertexdomain.IndexedVertexList):
            domain = batch._get_domain(True, mode, group, formats)
        else:
            domain = batch._get_domain(False, mode, group, formats)
        vertex_list.migrate(domain) 
Example #13
Source File: __init__.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_indexed(self, count, mode, group, indices, *data):
        """Add an indexed vertex list to the batch.

        :Parameters:
            `count` : int
                The number of vertices in the list.
            `mode` : int
                OpenGL drawing mode enumeration; for example, one of
                ``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc.
                See the module summary for additional information.
            `group` : `~pyglet.graphics.Group`
                Group of the vertex list, or ``None`` if no group is required.
            `indices` : sequence
                Sequence of integers giving indices into the vertex list.
            `data` : data items
                Attribute formats and initial data for the vertex list.  See
                the module summary for details.

        :rtype: `IndexedVertexList`
        """
        formats, initial_arrays = _parse_data(data)
        domain = self._get_domain(True, mode, group, formats)

        # Create vertex list and initialize
        vlist = domain.create(count, len(indices))
        start = vlist.start
        vlist.set_index_data([i + start for i in indices])
        for i, array in initial_arrays:
            vlist.set_attribute_data(i, array)

        return vlist 
Example #14
Source File: __init__.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def vertex_list(count, *data):
    """Create a :py:class:`~pyglet.graphics.vertexdomain.VertexList` not associated with a batch, group or mode.

    :Parameters:
        `count` : int
            The number of vertices in the list.
        `data` : data items
            Attribute formats and initial data for the vertex list.  See the
            module summary for details.

    :rtype: :py:class:`~pyglet.graphics.vertexdomain.VertexList`
    """
    # Note that mode=0 because the default batch is never drawn: vertex lists
    # returned from this function are drawn directly by their draw() method.
    return get_default_batch().add(count, 0, None, *data) 
Example #15
Source File: vertexdomain.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw(self, mode):
        """Draw this vertex list in the given OpenGL mode.

        :Parameters:
            `mode` : int
                OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.

        """
        with pyglet.graphics.get_default_batch().vao:
            pyglet.graphics.get_default_group().set_state()
            self.domain.draw_subset(mode, self)
            pyglet.graphics.get_default_group().unset_state() 
Example #16
Source File: sprite.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def _create_vertex_list(self):
        if self._batch is None:
            self._vertex_list = graphics.vertex_list(4,
                'v2i/%s' % self._usage,
                'c4B', ('t3f', self._texture.tex_coords))
        else:
            self._vertex_list = self._batch.add(4, GL_QUADS, self._group,
                'v2i/%s' % self._usage,
                'c4B', ('t3f', self._texture.tex_coords))
        self._update_position()
        self._update_color() 
Example #17
Source File: vertexdomain.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_domain(shader_program_id, *attribute_usage_formats):
    """Create a vertex domain covering the given attribute usage formats.
    See documentation for :py:func:`create_attribute_usage` and
    :py:func:`pyglet.graphics.vertexattribute.create_attribute` for the grammar
    of these format strings.

    :rtype: :py:class:`VertexDomain`
    """
    attribute_usages = [create_attribute_usage(shader_program_id, f)
                        for f in attribute_usage_formats]
    return VertexDomain(attribute_usages) 
Example #18
Source File: sprite.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def group(self):
        """Parent graphics group.

        The sprite can change its rendering group, however this can be an
        expensive operation.

        :type: :py:class:`pyglet.graphics.Group`
        """
        return self._group.parent 
Example #19
Source File: sprite.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def batch(self):
        """Graphics batch.

        The sprite can be migrated from one batch to another, or removed from
        its batch (for individual drawing).  Note that this can be an expensive
        operation.

        :type: :py:class:`pyglet.graphics.Batch`
        """
        return self._batch 
Example #20
Source File: sprite.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, texture, blend_src, blend_dest, program=None, order=0, parent=None):
        """Create a sprite group.

        The group is created internally when a :py:class:`~pyglet.sprite.Sprite`
        is created; applications usually do not need to explicitly create it.

        :Parameters:
            `texture` : `~pyglet.image.Texture`
                The (top-level) texture containing the sprite image.
            `blend_src` : int
                OpenGL blend source mode; for example,
                ``GL_SRC_ALPHA``.
            `blend_dest` : int
                OpenGL blend destination mode; for example,
                ``GL_ONE_MINUS_SRC_ALPHA``.
            `program` : `~pyglet.graphics.shader.ShaderProgram`
                A custom ShaderProgram.
            `order` : int
                Change the order to render above or below other Groups.
            `parent` : `~pyglet.graphics.Group`
                Optional parent group.
        """
        super().__init__(order, parent)
        self.texture = texture
        self.blend_src = blend_src
        self.blend_dest = blend_dest
        self.program = program or _default_program 
Example #21
Source File: simulator.py    From VerifAI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_draw(self):
        self.window.clear()
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glPushMatrix()
        gl.glLoadIdentity()
        self.camera()
        gl.glEnable(self.background.target)
        gl.glEnable(gl.GL_BLEND)
        gl.glBindTexture(self.background.target, self.background.id)
        W = 10000.
        graphics.draw(4, gl.GL_QUADS,
                      ('v2f', (-W, -W, W, -W, W, W, -W, W)),
                      ('t2f', (0., 0., W * 5., 0., W * 5., W * 5., 0., W * 5.))
                      )
        gl.glDisable(self.background.target)
        for lane in self.world.lanes:
            self.draw_lane_surface(lane)
            self.draw_lane_lines(lane)
        for obj in self.world.objects:
            self.draw_object(obj)
        for car in self.world.cars:
            self.draw_car(car.trajectory[-1], car.color)
        gl.glPopMatrix()

        self.label.text = self.task_name
        self.label.draw()
        self.iter +=1
        if self.iter%10 == 0:
            print('Iterations: ', self.iter)
        if self.iter == self.max_iters:
            self.event_loop.exit() 
Example #22
Source File: simulator.py    From VerifAI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_lane_lines(self, lane):
        gl.glColor3f(1., 1., 1.)
        W = 1000
        graphics.draw(4, gl.GL_LINES, ('v2f',
                                       np.hstack([lane.p - lane.m * W - 0.5 * lane.w * lane.n,
                                                  lane.p + lane.m * W - 0.5 * lane.w * lane.n,
                                                  lane.p - lane.m * W + 0.5 * lane.w * lane.n,
                                                  lane.p + lane.m * W + 0.5 * lane.w * lane.n])
                                       )) 
Example #23
Source File: simulator.py    From VerifAI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_lane_surface(self, lane):
        gl.glColor3f(0.4, 0.4, 0.4)
        W = 1000
        graphics.draw(4, gl.GL_QUAD_STRIP, ('v2f',
                                            np.hstack([lane.p - lane.m * W - 0.5 * lane.w * lane.n,
                                                       lane.p - lane.m * W + 0.5 * lane.w * lane.n,
                                                       lane.q + lane.m * W - 0.5 * lane.w * lane.n,
                                                       lane.q + lane.m * W + 0.5 * lane.w * lane.n])
                                            )) 
Example #24
Source File: sprite.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def _create_vertex_list(self):
        if self._batch is None:
            self._vertex_list = graphics.vertex_list(4,
                'v2i/%s' % self._usage,
                'c4B', ('t3f', self._texture.tex_coords))
        else:
            self._vertex_list = self._batch.add(4, GL_QUADS, self._group,
                'v2i/%s' % self._usage,
                'c4B', ('t3f', self._texture.tex_coords))
        self._update_position()
        self._update_color() 
Example #25
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        '''Create a graphics batch.'''
        # Mapping to find domain.
        # group -> (attributes, mode, indexed) -> domain
        self.group_map = {}

        # Mapping of group to list of children.
        self.group_children = {}

        # List of top-level groups
        self.top_groups = []

        self._draw_list = []
        self._draw_list_dirty = False 
Example #26
Source File: sprite.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def _create_vertex_list(self):
        if self._batch is None:
            self._vertex_list = graphics.vertex_list(4,
                'v2i/%s' % self._usage,
                'c4B', ('t3f', self._texture.tex_coords))
        else:
            self._vertex_list = self._batch.add(4, GL_QUADS, self._group,
                'v2i/%s' % self._usage,
                'c4B', ('t3f', self._texture.tex_coords))
        self._update_position()
        self._update_color() 
Example #27
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        '''Create a graphics batch.'''
        # Mapping to find domain.
        # group -> (attributes, mode, indexed) -> domain
        self.group_map = {}

        # Mapping of group to list of children.
        self.group_children = {}

        # List of top-level groups
        self.top_groups = []

        self._draw_list = []
        self._draw_list_dirty = False 
Example #28
Source File: sprite.py    From pyglet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self,
                 img, x=0, y=0,
                 blend_src=GL_SRC_ALPHA,
                 blend_dest=GL_ONE_MINUS_SRC_ALPHA,
                 batch=None,
                 group=None,
                 usage='dynamic',
                 subpixel=False,
                 program=None):
        """Create a sprite.

        :Parameters:
            `img` : `~pyglet.image.AbstractImage` or `~pyglet.image.Animation`
                Image or animation to display.
            `x` : int
                X coordinate of the sprite.
            `y` : int
                Y coordinate of the sprite.
            `blend_src` : int
                OpenGL blend source mode.  The default is suitable for
                compositing sprites drawn from back-to-front.
            `blend_dest` : int
                OpenGL blend destination mode.  The default is suitable for
                compositing sprites drawn from back-to-front.
            `batch` : `~pyglet.graphics.Batch`
                Optional batch to add the sprite to.
            `group` : `~pyglet.graphics.Group`
                Optional parent group of the sprite.
            `usage` : str
                Vertex buffer object usage hint, one of ``"none"``,
                ``"stream"``, ``"dynamic"`` (default) or ``"static"``.  Applies
                only to vertex data.
            `subpixel` : bool
                Allow floating-point coordinates for the sprite. By default,
                coordinates are restricted to integer values.
            `program` : `~pyglet.graphics.shader.ShaderProgram`
                A custom ShaderProgram.
        """
        self._x = x
        self._y = y

        if isinstance(img, image.Animation):
            self._animation = img
            self._frame_index = 0
            self._texture = img.frames[0].image.get_texture()
            self._next_dt = img.frames[0].duration
            if self._next_dt:
                clock.schedule_once(self._animate, self._next_dt)
        else:
            self._texture = img.get_texture()

        if isinstance(img, image.TextureArrayRegion):
            program = _default_array_program
        else:
            program = _default_program

        self._batch = batch or graphics.get_default_batch()
        self._group = SpriteGroup(self._texture, blend_src, blend_dest, program, 0, group)
        self._usage = usage
        self._subpixel = subpixel
        self._create_vertex_list()