
    \
j
J                       d Z ddlZddlZddlT ddlmZmZ ddlmZ ddl	Z	ddl
T ddl
mZ ddlmZ dd	lmZmZ dd
lmZmZmZ ddlmZmZmZ ddlmZmZ ddlmZ  G d de          ZdDdZdDdZdEdZ  e            d             Z! e            d             Z" e            d             Z# e            d             Z$ G d d          Z% G d de%          Z& G d de%          Z' G d d          Z( G d d           Z) G d! d"e)          Z* G d# d$e*          Z+ G d% d&e(          Z, G d' d(e,          Z- G d) d*e(          Z. G d+ d,e(          Z/ G d- d.e/          Z0e0e/_1         G d/ d0e/e+          Z2 G d1 d2e/          Z3 G d3 d4e/          Z4 G d5 d6          Z5d7 Z6 G d8 d9e(          Z7 G d: d;e7          Z8 G d< d=e7          Z9 G d> d?e7          Z: G d@ dAe(e)          Z; G dB dCe0e+          Z< e             dS )Fa  Image load, capture and high-level texture functions.

Only basic functionality is described here; for full reference see the
accompanying documentation.

To load an image::

    from pyglet import image
    pic = image.load('picture.png')

The supported image file types include PNG, BMP, GIF, JPG, and many more,
somewhat depending on the operating system.  To load an image from a file-like
object instead of a filename::

    pic = image.load('hint.jpg', file=fileobj)

The hint helps the module locate an appropriate decoder to use based on the
file extension.  It is optional.

Once loaded, images can be used directly by most other modules of pyglet.  All
images have a width and height you can access::

    width, height = pic.width, pic.height

You can extract a region of an image (this keeps the original image intact;
the memory is shared efficiently)::

    subimage = pic.get_region(x, y, width, height)

Remember that y-coordinates are always increasing upwards.

Drawing images
--------------

To draw an image at some point on the screen::

    pic.blit(x, y, z)

This assumes an appropriate view transform and projection have been applied.

Some images have an intrinsic "anchor point": this is the point which will be
aligned to the ``x`` and ``y`` coordinates when the image is drawn.  By
default the anchor point is the lower-left corner of the image.  You can use
the anchor point to center an image at a given point, for example::

    pic.anchor_x = pic.width // 2
    pic.anchor_y = pic.height // 2
    pic.blit(x, y, z)

Texture access
--------------

If you are using OpenGL directly, you can access the image as a texture::

    texture = pic.get_texture()

(This is the most efficient way to obtain a texture; some images are
immediately loaded as textures, whereas others go through an intermediate
form).  To use a texture with pyglet.gl::

    from pyglet.gl import *
    glEnable(texture.target)        # typically target is GL_TEXTURE_2D
    glBindTexture(texture.target, texture.id)
    # ... draw with the texture

Pixel access
------------

To access raw pixel data of an image::

    rawimage = pic.get_image_data()

(If the image has just been loaded this will be a very quick operation;
however if the image is a texture a relatively expensive readback operation
will occur).  The pixels can be accessed as a string::

    format = 'RGBA'
    pitch = rawimage.width * len(format)
    pixels = rawimage.get_data(format, pitch)

"format" strings consist of characters that give the byte order of each color
component.  For example, if rawimage.format is 'RGBA', there are four color
components: red, green, blue and alpha, in that order.  Other common format
strings are 'RGB', 'LA' (luminance, alpha) and 'I' (intensity).

The "pitch" of an image is the number of bytes in a row (this may validly be
more than the number required to make up the width of the image, it is common
to see this for word alignment).  If "pitch" is negative the rows of the image
are ordered from top to bottom, otherwise they are ordered from bottom to top.

Retrieving data with the format and pitch given in `ImageData.format` and
`ImageData.pitch` avoids the need for data conversion (assuming you can make
use of the data in this arbitrary format).

    N)*)openBytesIO)	lru_cache)gl_info)asbytes   )ImageEncodeExceptionImageDecodeException)add_default_image_codecsadd_decodersadd_encoders)get_animation_decodersget_decodersget_encoders)	AnimationAnimationFrame)atlasc                       e Zd ZdS )ImageExceptionN)__name__
__module____qualname__     O/DATA/AppData/hermes/venv/lib/python3.11/site-packages/pyglet/image/__init__.pyr   r      s        Dr   r   c                 Z   |st          | d          }|}nd}t          |d          s!t          |                                          }	 |r-|                    ||           |r|                                 S S d}t          |           D ]s}	 |                    ||           }|c |r|                                 S S # t          $ r3}|r|j        |j        k     r|}|	                    d           Y d}~ld}~ww xY w|st          d          |# |r|                                 w w xY w)a  Load an image from a file.

    :note: You can make no assumptions about the return type; usually it will
        be ImageData or CompressedImageData, but decoders are free to return
        any subclass of AbstractImage.

    :Parameters:
        `filename` : str
            Used to guess the image format, and to load the file if `file` is
            unspecified.
        `file` : file-like object or None
            Source of image data in any supported format.        
        `decoder` : ImageDecoder or None
            If unspecified, all decoders that are registered for the filename
            extension are tried.  If none succeed, the exception from the
            first decoder is raised.

    :rtype: AbstractImage
    rbNseekr   No image decoders are available)
r   hasattrr   readdecodecloser   r   exception_priorityr   )filenamefiledecoderopened_filefirst_exceptionimagees          r   loadr-      s   *  Hd##4   $tyy{{##  	">>$11"  	 	  #O'11 ! !!#NN4::E LL  	 	  , ! ! !+ ,+>AUUU*+IIaLLLLLLLL	! # N*+LMMM!! 	 	 s<   
D 9D B>$D >
C;)C61D 6C;;D D*c                    |st          | d          }t          |d          s!t          |                                          }|r|                    ||           S d}t          |           D ]L}	 |                    ||           }|c S # t          $ r#}|p|}|                    d           Y d}~Ed}~ww xY w|st          d          |)aK  Load an animation from a file.

    Currently, the only supported format is GIF.

    :Parameters:
        `filename` : str
            Used to guess the animation format, and to load the file if `file`
            is unspecified.
        `file` : file-like object or None
            File object containing the animation stream.
        `decoder` : ImageDecoder or None
            If unspecified, all decoders that are registered for the filename
            extension are tried.  If none succeed, the exception from the
            first decoder is raised.

    :rtype: Animation
    r   r   Nr   r    )r   r!   r   r"   decode_animationr   r   r   )r&   r'   r(   r*   r+   r,   s         r   load_animationr0      s   $  $Hd##4   $tyy{{## ''h777-h77 	 	G00x@@'   "1"6Q		!  	J&'HIIIs   0B


B7B22B7c                 N    |st                      }|                    | |          S )a=  Create an image optionally filled with the given pattern.

    :note: You can make no assumptions about the return type; usually it will
        be ImageData or CompressedImageData, but patterns are free to return
        any subclass of AbstractImage.

    :Parameters:
        `width` : int
            Width of image to create
        `height` : int
            Height of image to create
        `pattern` : ImagePattern or None
            Pattern to fill image with.  If unspecified, the image will
            initially be transparent.

    :rtype: AbstractImage
    )SolidColorImagePatterncreate_image)widthheightpatterns      r   creater7      s-    $  +(**v...r   c                  V    t                      } t          t          |            | j        S )z(Query the maximum texture size available)c_intglGetIntegervGL_MAX_TEXTURE_SIZEvalue)sizes    r   get_max_texture_sizer>     s&     77D%t,,,:r   c                 d    t          |           dk    rt          d          t          |           S )N   z&color is expected to have 4 components)len	TypeErrorbytes)colors    r   _color_as_bytesrE     s,    
5zzQ@AAA<<r   c                 f    | dz  } | | dz	  z  } | | dz	  z  } | | dz	  z  } | | dz	  z  } | | dz	  z  } | dz   S )Nr	      r@         r   vs    r   _nearest_pow2rL     sW     FAaKAaKAaKAaKAbLAq5Lr   c                     | | dz
  z  dk    S )Nr	   r   r   rJ   s    r   _is_pow2rN   +  s     QKAr   c                       e Zd ZdZd ZdS )ImagePatternzAbstract image creation class.c                      t          d          )zCreate an image of the given size.

        :Parameters:
            `width` : int
                Width of image to create
            `height` : int
                Height of image to create
        
        :rtype: AbstractImage
        abstractNotImplementedErrorselfr4   r5   s      r   r3   zImagePattern.create_image4  s     "*---r   N)r   r   r   __doc__r3   r   r   r   rP   rP   1  s)        ((. . . . .r   rP   c                        e Zd ZdZddZd ZdS )r2   z+Creates an image filled with a solid color.r   r   r   r   c                 .    t          |          | _        dS )zCreate a solid image pattern with the given color.

        :Parameters:
            `color` : (int, int, int, int)
                4-tuple of ints in range [0,255] giving RGBA components of
                color to fill with.

        N)rE   rD   )rV   rD   s     r   __init__zSolidColorImagePattern.__init__E  s     %U++


r   c                 @    | j         |z  |z  }t          ||d|          S )NRGBA)rD   	ImageData)rV   r4   r5   datas       r   r3   z#SolidColorImagePattern.create_imageP  s'    zE!F*555r   N)rY   r   r   r   rW   r[   r3   r   r   r   r2   r2   B  s=        55	, 	, 	, 	,6 6 6 6 6r   r2   c                        e Zd ZdZddZd ZdS )CheckerImagePatternz3Create an image with a tileable checker image.
       rd   rd         rg   rg   re   c                 V    t          |          | _        t          |          | _        dS )a-  Initialise with the given colors.

        :Parameters:
            `color1` : (int, int, int, int)
                4-tuple of ints in range [0,255] giving RGBA components of
                color to fill with.  This color appears in the top-left and
                bottom-right corners of the image.
            `color2` : (int, int, int, int)
                4-tuple of ints in range [0,255] giving RGBA components of
                color to fill with.  This color appears in the top-right and
                bottom-left corners of the image.

        N)rE   color1color2)rV   ri   rj   s      r   r[   zCheckerImagePattern.__init__Y  s&     &f--%f--r   c                     |dz  }|dz  }| j         |z  | j        |z  z   }| j        |z  | j         |z  z   }||z  ||z  z   }t          ||d|          S )NrG   r]   )ri   rj   r^   )rV   r4   r5   hwhhrow1row2r_   s           r   r3   z CheckerImagePattern.create_imagej  sj    aZq[{R$+"22{R$+"22by4"9$555r   N)rc   rf   r`   r   r   r   rb   rb   U  sA         . . . ."6 6 6 6 6r   rb   c                   b    e Zd ZdZdZdZdZd Zd Zd Z	ddZ
d Zd	 ZddZddZd ZddZd
S )AbstractImagead  Abstract class representing an image.

    :Parameters:
        `width` : int
            Width of image
        `height` : int
            Height of image
        `anchor_x` : int
            X coordinate of anchor, relative to left edge of image data
        `anchor_y` : int
            Y coordinate of anchor, relative to bottom edge of image data
    r   Fc                 "    || _         || _        d S N)r4   r5   rU   s      r   r[   zAbstractImage.__init__  s    
r   c                 :    d| j         j        | j        | j        fz  S )Nz
<%s %dx%d>)	__class__r   r4   r5   rV   s    r   __repr__zAbstractImage.__repr__  s    t~6
DKPPPr   c                 &    t          d| z            )zGet an ImageData view of this image.  
        
        Changes to the returned instance may or may not be reflected in this
        image.

        :rtype: :py:class:`~pyglet.image.ImageData`

        .. versionadded:: 1.1
        z!Cannot retrieve image data for %rr   rv   s    r   get_image_datazAbstractImage.get_image_data  s     @4GHHHr   c                 &    t          d| z            )a  A :py:class:`~pyglet.image.Texture` view of this image.  

        By default, textures are created with dimensions that are powers of
        two.  Smaller images will return a :py:class:`~pyglet.image.TextureRegion` that covers just
        the image portion of the larger texture.  This restriction is required
        on older video cards, and for compressed textures, or where texture
        repeat modes will be used, or where mipmapping is desired.

        If the `rectangle` parameter is ``True``, this restriction is ignored
        and a texture the size of the image may be created if the driver
        supports the ``GL_ARB_texture_rectangle`` or
        ``GL_NV_texture_rectangle`` extensions.  If the extensions are not
        present, the image already is a texture, or the image has power 2
        dimensions, the `rectangle` parameter is ignored.

        Examine `Texture.target` to determine if the returned texture is a
        rectangle (``GL_TEXTURE_RECTANGLE_ARB`` or
        ``GL_TEXTURE_RECTANGLE_NV``) or not (``GL_TEXTURE_2D``).

        If the `force_rectangle` parameter is ``True``, one of these
        extensions must be present, and the returned texture always
        has target ``GL_TEXTURE_RECTANGLE_ARB`` or ``GL_TEXTURE_RECTANGLE_NV``.
        
        Changes to the returned instance may or may not be reflected in this
        image.

        :Parameters:
            `rectangle` : bool
                True if the texture can be created as a rectangle.
            `force_rectangle` : bool
                True if the texture must be created as a rectangle.

                .. versionadded:: 1.1.4.
        :rtype: :py:class:`~pyglet.image.Texture`

        .. versionadded:: 1.1
        zCannot retrieve texture for %rry   rV   	rectangleforce_rectangles      r   get_texturezAbstractImage.get_texture  s    L =DEEEr   c                 &    t          d| z            )zRetrieve a :py:class:`~pyglet.image.Texture` instance with all mipmap levels filled in.

        Requires that image dimensions be powers of 2. 

        :rtype: :py:class:`~pyglet.image.Texture`

        .. versionadded:: 1.1
        z(Cannot retrieve mipmapped texture for %rry   rv   s    r   get_mipmapped_texturez#AbstractImage.get_mipmapped_texture  s     G$NOOOr   c                 &    t          d| z            )aZ  Retrieve a rectangular region of this image.

        :Parameters:
            `x` : int
                Left edge of region.
            `y` : int
                Bottom edge of region.
            `width` : int
                Width of region.
            `height` : int
                Height of region.

        :rtype: AbstractImage
        zCannot get region for %rry   rV   xyr4   r5   s        r   
get_regionzAbstractImage.get_region  s     7$>???r   Nc                 >   |st          |d          }|r|                    | ||           dS d}t          |          D ]L}	 |                    | ||            dS # t          $ r#}|p|}|                    d           Y d}~Ed}~ww xY w|st          d          |)a  Save this image to a file.

        :Parameters:
            `filename` : str
                Used to set the image file format, and to open the output file
                if `file` is unspecified.
            `file` : file-like object or None
                File to write image data to.
            `encoder` : ImageEncoder or None
                If unspecified, all encoders matching the filename extension
                are tried.  If all fail, the exception from the first one
                attempted is raised.

        wbNr   zNo image encoders are available)r   encoder   r
   r   )rV   r&   r'   encoderr*   r,   s         r   savezAbstractImage.save  s      	($''D 	"NN4x00000"O'11 ! !!NN4x888FF+ ! ! !&5&:OIIaLLLLLLLL! # 7*57 7 7!!s   A
B	&BB	c                 &    t          d| z            )zDraw this image to the active framebuffers.
        
        The image will be drawn with the lower-left corner at 
        (``x -`` `anchor_x`, ``y -`` `anchor_y`, ``z``).
        zCannot blit %r.ry   )rV   r   r   zs       r   blitzAbstractImage.blit  s     .5666r   c                 &    t          d| z            )a  Draw `source` on this image.

        `source` will be copied into this image such that its anchor point
        is aligned with the `x` and `y` parameters.  If this image is a 3D
        texture, the `z` coordinate gives the image slice to copy into.
        
        Note that if `source` is larger than this image (or the positioning
        would cause the copy to go out of bounds) then you must pass a
        region of `source` to this method, typically using get_region().
        zCannot blit images onto %r.ry   rV   sourcer   r   r   s        r   	blit_intozAbstractImage.blit_into  s     :TABBBr   c                 &    t          d| z            )am  Draw this image on the currently bound texture at `target`.
        
        This image is copied into the texture such that this image's anchor
        point is aligned with the given `x` and `y` coordinates of the
        destination texture.  If the currently bound texture is a 3D texture,
        the `z` coordinate gives the image slice to blit into.
        zCannot blit %r to a texture.ry   rV   targetlevelr   r   r   s         r   blit_to_texturezAbstractImage.blit_to_texture  s     ;dBCCCr   FFNNNr   )r   r   r   rW   anchor_xanchor_y_is_rectangler[   rw   rz   r   r   r   r   r   r   r   r   r   r   rq   rq   s  s          HHM  Q Q Q
I 
I 
I&F &F &F &FP	P 	P 	P@ @ @"!" !" !" !"F7 7 7 7C C CD D D D D Dr   rq   c                   8    e Zd ZdZd Zd
dZd Zd Zd Zd Z	d	S )AbstractImageSequencea  Abstract sequence of images.

    The sequence is useful for storing image animations or slices of a volume.
    For efficient access, use the `texture_sequence` member.  The class
    also implements the sequence interface (`__len__`, `__getitem__`,
    `__setitem__`).
    c                      t          d          )zaGet a TextureSequence.

        :rtype: `TextureSequence`

        .. versionadded:: 1.1
        rR   rS   rv   s    r   get_texture_sequencez*AbstractImageSequence.get_texture_sequence(       "*---r   Tc                 .    t          j        | ||          S )aw  Create an animation over this image sequence for the given constant
        framerate.

        :Parameters
            `period` : float
                Number of seconds to display each frame.
            `loop` : bool
                If True, the animation will loop continuously.

        :rtype: :py:class:`~pyglet.image.Animation`

        .. versionadded:: 1.1
        )r   from_image_sequence)rV   periodloops      r   get_animationz#AbstractImageSequence.get_animation1  s     ,T64@@@r   c                      t          d          )zKRetrieve a (list of) image.
        
        :rtype: AbstractImage
        rR   rS   )rV   slices     r   __getitem__z!AbstractImageSequence.__getitem__A  s    
 "*---r   c                      t          d          )a  Replace one or more images in the sequence.
        
        :Parameters:
            `image` : `~pyglet.image.AbstractImage`
                The replacement image.  The actual instance may not be used,
                depending on this implementation.

        rR   rS   )rV   r   r+   s      r   __setitem__z!AbstractImageSequence.__setitem__H  s     "*---r   c                      t          d          NrR   rS   rv   s    r   __len__zAbstractImageSequence.__len__S      !*---r   c                      t          d          )zfIterate over the images in sequence.

        :rtype: Iterator

        .. versionadded:: 1.1
        rR   rS   rv   s    r   __iter__zAbstractImageSequence.__iter__V  r   r   N)T)
r   r   r   rW   r   r   r   r   r   r   r   r   r   r   r     s         . . .A A A A . . .	. 	. 	.. . .. . . . .r   r   c                       e Zd ZdZd ZdS )TextureSequencezInterface for a sequence of textures.

    Typical implementations store multiple :py:class:`~pyglet.image.TextureRegion` s within one
    :py:class:`~pyglet.image.Texture` so as to minimise state changes.
    c                     | S rs   r   rv   s    r   r   z$TextureSequence.get_texture_sequenceg      r   N)r   r   r   rW   r   r   r   r   r   r   `  s-             r   r   c                   J    e Zd ZdZd Zd Zed             Zed             ZdS )UniformTextureSequencezInterface for a sequence of textures, each with the same dimensions.

    :Parameters:
        `item_width` : int
            Width of each texture in the sequence.
        `item_height` : int
            Height of each texture in the sequence.
    
    c                      t          d          r   rS   rv   s    r   _get_item_widthz&UniformTextureSequence._get_item_widthv  r   r   c                      t          d          r   rS   rv   s    r   _get_item_heightz'UniformTextureSequence._get_item_heighty  r   r   c                 *    |                                  S rs   )r   rv   s    r   
item_widthz!UniformTextureSequence.item_width|  s    ##%%%r   c                 *    |                                  S rs   )r   rv   s    r   item_heightz"UniformTextureSequence.item_height  s    $$&&&r   N)	r   r   r   rW   r   r   propertyr   r   r   r   r   r   r   k  sr         . . .. . . & & X& ' ' X' ' 'r   r   c                       e Zd ZdZ ej         ed          ej                  Z ej         ed          ej                  Z	 ej         ed          ej                  Z
 ej         ed          ej                  ZdZdZd fd	Zd Zd	 Zed
             Zej        d             ZddZd Zd ZddZddZd Zd ZddZddZd Zd Zd Zd Z d Z! xZ"S ) r^   a}  An image represented as a string of unsigned bytes.

    :Parameters:
        `data` : str
            Pixel data, encoded according to `format` and `pitch`.
        `format` : str
            The format string to use when reading or writing `data`.
        `pitch` : int
            Number of bytes per row.  Negative values indicate a top-to-bottom
            arrangement.

    z(.)z(.)(.)z	(.)(.)(.)z(.)(.)(.)(.)Nc                     t          t          |                               ||           |                                x| _        | _        || _        |s|t          |          z  }|x| _        | _	        g | _
        dS )aZ  Initialise image data.

        :Parameters:
            `width` : int
                Width of image data
            `height` : int
                Height of image data
            `format` : str
                A valid format string, such as 'RGB', 'RGBA', 'ARGB', etc.
            `data` : sequence
                String or array/list of bytes giving the decoded data.
            `pitch` : int or None
                If specified, the number of bytes per row.  Negative values
                indicate a top-to-bottom arrangement.  Defaults to 
                ``width * len(format)``.

        N)superr^   r[   upper_current_format_desired_format_current_datarA   _current_pitchpitchmipmap_images)rV   r4   r5   formatr_   r   ru   s         r   r[   zImageData.__init__  sz    $ 	i''v6666<llnnDt3! 	(CKK'E+00djr   c           	          | j         | j        |                     | j        | j                  | j        | j        | j        | j        | j        dS )N)r4   r5   r   r   r   r   r   r   )r4   r5   get_datar   r   r   r   r   rv   s    r   __getstate__zImageData.__getstate__  sO    Zk!]]4+?ATUU#3#3"1Z!/	
 	
 		
r   c                     | S rs   r   rv   s    r   rz   zImageData.get_image_data  r   r   c                     | j         S )zLFormat string of the data.  Read-write.
        
        :type: str
        )r   rv   s    r   r   zImageData.format  s     ##r   c                 F    |                                 | _        d | _        d S rs   )r   r   _current_texture)rV   fmts     r   r   zImageData.format  s     "yy{{ $r   c                     |p| j         }|p| j        }|| j        k    r|| j        k    r| j        S |                     ||          S )a\  Get the byte data of the image.

        :Parameters:
            `fmt` : str
                Format string of the return data.
            `pitch` : int
                Number of bytes per row.  Negative values indicate a
                top-to-bottom arrangement.

        .. versionadded:: 1.1

        :rtype: sequence of bytes, or str
        )r   r   r   r   _convert)rV   r   r   s      r   r   zImageData.get_data  sV     )T),,$&&&5D4G+G+G%%}}S%(((r   c                 L    || _         || _        || _        d| _        d| _        dS )a{  Set the byte data of the image.

        :Parameters:
            `fmt` : str
                Format string of the return data.
            `pitch` : int
                Number of bytes per row.  Negative values indicate a
                top-to-bottom arrangement.
            `data` : str or sequence of bytes
                Image data.

        .. versionadded:: 1.1
        N)r   r   r   r   _current_mipmap_texture)rV   r   r   r_   s       r   set_datazImageData.set_data  s2      ##! $'+$$$r   c                    |dk    rt          d          t          | j                  rt          | j                  st          d          | j        | j        }}t	          |          D ]}|dz  }|dz  }||j        k    s||j        k    rt          d|z            | xj        dg|t          | j                  z
  z  z  c_        || j        |dz
  <   dS )a  Set a mipmap image for a particular level.

        The mipmap image will be applied to textures obtained via
        `get_mipmapped_texture`.

        :Parameters:
            `level` : int
                Mipmap level to set image at, must be >= 1.
            `image` : AbstractImage
                Image to set.  Must have correct dimensions for that mipmap
                level (i.e., width >> level, height >> level)
        r   z5Cannot set mipmap image at level 0 (it is this image)4Image dimensions must be powers of 2 to use mipmaps.r	   z.Mipmap image has wrong dimensions for level %dN)r   rN   r4   r5   ranger   rA   )rV   r   r+   r4   r5   is         r   set_mipmap_imagezImageData.set_mipmap_image  s    A:: GI I I 
## 	H8DK+@+@ 	H FH H H 
DKvu 	 	AaKEqLFFEK6U\#9#9 @5HJ J J 	tfD4F0G0G(GHH(-519%%%r   Fc                 (   |                      | j                  }|                    | j        | j        |||          }| j        s| j        r| j        |_        | j        |_        |                     |j        |j	        | j        | j        dd           |S )a  Create a texture containing this image.

        If the image's dimensions are not powers of 2, a TextureRegion of
        a larger Texture will be returned that matches the dimensions of this
        image.

        :Parameters:
            `cls` : class (subclass of Texture)
                Class to construct.
            `rectangle` : bool
                ``True`` if a rectangle can be created; see
                `AbstractImage.get_texture`.

                .. versionadded:: 1.1
            `force_rectangle` : bool
                ``True`` if a rectangle must be created; see
                `AbstractImage.get_texture`.

                .. versionadded:: 1.1.4

        :rtype: cls or cls.region_class
        r   N)
_get_internalformatr   r7   r4   r5   r   r   r   r   r   )rV   clsr}   r~   internalformattextures         r   create_texturezImageData.create_texture  s    . 11$+>>**TZn&9 9= 	-DM 	-#}G#}GW^W]!]DM1d	D 	D 	D r   c                 |    | j         r| j         j        s#|r!|                     t          ||          | _         | j         S rs   )r   r   r   Texturer|   s      r   r   zImageData.get_texture@  sI    % 	]*8	]=L	]$($7$7O$\$\D!$$r   c           	      h   | j         r| j         S t          | j                  rt          | j                  st	          d          t
                              t          | j        | j                  }| j        s| j	        r| j        |_        | j	        |_	        | 
                    | j                  }t          |j        |j                   t          |j        t           t"                     | j        rk|                     |j        |j        | j        | j	        d|           d}| j        D ]2}|dz  }|r)|                    |j        || j        | j	        d|           3nNt          |j        t*          t,                     |                     |j        |j        | j        | j	        d|           || _         |S )a  Return a Texture with mipmaps.  
        
        If :py:class:`~pyglet.image.set_mipmap_Image` has been called with at least one image, the set
        of images defined will be used.  Otherwise, mipmaps will be
        automatically generated.

        The texture dimensions must be powers of 2 to use mipmaps.

        :rtype: :py:class:`~pyglet.image.Texture`

        .. versionadded:: 1.1
        r   r   r	   )r   rN   r4   r5   r   r   create_for_sizeGL_TEXTURE_2Dr   r   r   r   glBindTexturer   idglTexParameteriGL_TEXTURE_MIN_FILTERGL_LINEAR_MIPMAP_LINEARr   r   r   GL_GENERATE_MIPMAPGL_TRUE)rV   r   r   r   r+   s        r   r   zImageData.get_mipmapped_textureF  s    ' 	0//
## 	H8DK+@+@ 	H FH H H ))-T[QQ= 	-DM 	-#}G#}G11$+>>gngj111(=?VWWW 	R  !%q.R R RE+ [ [
 [))'.%*.->[ [ [[ GN,>HHH  !%q.R R R (/$r   c                 (    t          |||||           S )aa  Retrieve a rectangular region of this image data.

        :Parameters:
            `x` : int
                Left edge of region.
            `y` : int
                Bottom edge of region.
            `width` : int
                Width of region.
            `height` : int
                Height of region.

        :rtype: ImageDataRegion
        )ImageDataRegionr   s        r   r   zImageData.get_regionv  s     q!UFD999r   r   c                 \    |                                                      |||||           d S rs   )r   r   )rV   r   r   r   r4   r5   s         r   r   zImageData.blit  s0    1a77777r   c                    || j         z  }|| j        z  }| j        }t          | j                  }d}	|                     |          \  }
}|
%t          |          dv rt          j        d          rd }|dz   } ||d                    ||d                   z    ||d                   z    ||d	                   z   }	t          t          d                    t          |                    }
t          }t          t                     t                       t!          t#          d
z  |	            n?ddddd                    t          |                    }|                     |          \  }
}t$          j        j        j        r| j        t          |          z  }|                     ||          }|dz  rd}n
|dz  rd}nd}|t          |          z  }t1          t2                     t5          t6          |           t5          t8          |           |                                  |t<          k    r(|rJ t?          |||||| j        | j         d|
||           nE|r"tC          |||| j        | j         d|
||	  	         n!tE          ||||| j        | j         |
||	  	         tG                       |	r"tI                       t          tJ                     tM                       dS )a  Draw this image to to the currently bound texture at `target`.

        This image's anchor point will be aligned to the given `x` and `y`
        coordinates.  If the currently bound texture is a 3D texture, the `z`
        parameter gives the image slice to blit into.

        If `internalformat` is specified, glTexImage is used to initialise
        the texture; otherwise, glTexSubImage is used to update a region.
        N)   r@   GL_ARB_imagingc                 ~    	 d                     |           }dg|z  dgz   dgd|z
  z  z   S # t          $ r g dcY S w xY w)Nr]   r   r	   r   rY   )index
ValueError)	componentposs     r   component_columnz3ImageData.blit_to_texture.<locals>.component_column  sd    ,$ll955 !sSyA3!C@@% , , ,+||+++,s   (+ <<XXXr   r	   rG   r   rI   LLARGBr]   )r	   rG   r   r@   r@   )'r   r   r   absr   _get_gl_format_and_typerA   r   have_extensionGL_RGBGL_RGBAgetGL_UNSIGNED_BYTEglMatrixModeGL_COLORglPushMatrixglLoadMatrixfGLfloatpygletglcurrent_context_workaround_unpack_row_lengthr4   r   glPushClientAttribGL_CLIENT_PIXEL_STORE_BITglPixelStoreiGL_UNPACK_ALIGNMENTGL_UNPACK_ROW_LENGTH_apply_region_unpackGL_TEXTURE_3DglTexSubImage3Dr5   glTexImage2DglTexSubImage2DglPopClientAttribglPopMatrixGL_MODELVIEWglFlush)rV   r   r   r   r   r   r   data_format
data_pitchmatrixr   typer   lookup_formatr_   	alignment
row_lengths                    r   r   zImageData.blit_to_texture  sW    	
T]	T]k,--
 33K@@>K  F***+;<< +, , , !,e 3**=+;<<**=+;<<=**=+;<<= +*=+;<<=
     #C$4$4 5 5  (X&&&w|f56666 	   #s3{#3#344	 
  $;;KHH 9$B 	7c+&6&66J
 }}[*55 	II# 	III3{#3#33
4555)9555*J777!!###]""%%%%FEq! JQ"D 	" " " "
  	"'T[    FEq J"D 	" " "
 	 	'MMM&&& 						r   c                     d S rs   r   rv   s    r   r  zImageData._apply_region_unpack  s    r   c                    	
 || j         k    rA|| j        k    r6t          | j                  t          u rt          | j                  S | j        S |                                  | j        	| j        }| j         }|t          |          z  }|| j         k    rt          d          |D ]C}	 |                    |          dz   }n# t          $ r d}Y nw xY wt          d|z            z  Dt          |          dk    r| j        n`t          |          dk    r| j        nEt          |          dk    r| j        n*t          |          dk    r| j        nt          d          | j        t          |          z  t          | j                  k    rrt          | j                  	fdt#          d	t          	                    D             }fd
|D             }t          d                              |          	n                    	          	|t          |          | j        z  z  }||k    r.t          |          t          |          z
  

d	k    r<t          |          	
fdt#          d	t          	                    D             }nT
d	k     rNt          |          t          d          
 z  	fdt#          d	t          	                    D             }||z  d	k     rNt          |          	fdt#          d	t          	                    D             }|                                 t          d                              |          	t          	          S )zkReturn data in the desired format; does not alter this instance's
        current format or pitch.
         r	   z\%drG   r   r@   z+Current image format is wider than 32 bits.c                 *    g | ]}||z            S r   r   .0r   r_   	new_pitchs     r   
<listcomp>z&ImageData._convert.<locals>.<listcomp>  &    TTTQq{]+TTTr   r   c                 L    g | ] }                     |d                    !S rs   )sub)r+  rpacked_pitchreplswap_patterns     r   r-  z&ImageData._convert.<locals>.<listcomp>  s2    OOOQ((q,/?@@OOOr   c                 0    g | ]}||z   z
           S r   r   )r+  r   r_   diffr,  s     r   r-  z&ImageData._convert.<locals>.<listcomp>,  s,    YYYQQq{4//0YYYr   c                 0    g | ]}||z            z   S r   r   )r+  r   r_   r,  paddings     r   r-  z&ImageData._convert.<locals>.<listcomp>1  s+    ^^^!Qq{]+g5^^^r   c                 *    g | ]}||z            S r   r   r*  s     r   r-  z&ImageData._convert.<locals>.<listcomp>6  r.  r   )r   r   r"  r   strr   _ensure_string_datar  r   r   rA   _swap1_pattern_swap2_pattern_swap3_pattern_swap4_patternr   r4   r   joinr0  reverse)rV   r   r   current_pitchcurrent_format
sign_pitchcidxrowsr_   r6  r,  r2  r8  r3  r4  s            @@@@@@@r   r   zImageData._convert  s    T)))et7J.J.JD&''3..t1222%%  """!+-"c-&8&88
T))) 2;;D . .(..q11A5CC!   CCC--->""a''#2^$$))#2^$$))#2^$$))#2$AC C C  :N(;(;;L4&''<77 344	TTTTTU1c$ii5S5STTTOOOOOO$OOOr{{''-- $''d33 '#f++
*BCMM!!}%%E

2DaxxJJ	YYYYYY%3t99i:X:XYYY..	!!**u,^^^^^^uQD		S\?]?]^^^u$q((JJ	TTTTTU1c$ii5S5STTT2;;##D))Dt}}s   /CCCc                     t          | j                  t          urWt          t	          | j                            }t          || j        t	          | j                             |j        | _        d S d S rs   )r"  r   rC   create_string_bufferrA   memmoveraw)rV   bufs     r   r;  zImageData._ensure_string_data=  sh    "##500&s4+='>'>??CC+S1C-D-DEEE!$D 10r   c                    |dk    rt           t          fS |dk    rt           t          fS |dk    rt          t          fS |dk    rt          t          fS |dk    rt          t          fS |dk    rt
          t          fS |dk    rt          t          fS |dk    rt          t          fS |d	k    rt          t          fS |d
k    r6t          j
        d          r"t          j
        d          rt          t          fS |dk    r"t          j
        d          rt          t          fS |dk    r"t          j
        d          rt          t          fS |dk    r"t          j
        d          rt          t          fS dS )NIr   r   RGBAr   r]   ARGBGL_EXT_bgraGL_APPLE_packed_pixelsABGRGL_EXT_abgrBGRBGRANN)GL_LUMINANCEr  GL_LUMINANCE_ALPHAGL_REDGL_GREENGL_BLUEGL_ALPHAr  r  r   r  GL_BGRAGL_UNSIGNED_INT_8_8_8_8_REVGL_ABGR_EXTGL_BGRrV   r   s     r   r  z!ImageData._get_gl_format_and_typeC  s   S==!111s]]!111t^^%'777s]]+++s]]---s]],,,s]]---u__+++v,,,(77 ()ABB  777(77  000oo(77 +++(77 ,,,zr   c                     t          |          dk    rt          S t          |          dk    rt          S t          |          dk    rt          S |dk    rt          S |dk    rt
          S |dk    rt          S t          S )Nr@   r   rG   rR  r   rN  )rA   r  r  r\  r`  r[  GL_INTENSITYre  s     r   r   zImageData._get_internalformatf  sv    v;;!N[[AM[[A%%s]]Os]]s]]r   rs   rZ  r   r   NN)#r   r   r   rW   recompiler   DOTALLr<  r=  r>  r?  r   r   r[   r   rz   r   r   setterr   r   r   r   r   r   r   r   r   r  r   r;  r  r   __classcell__ru   s   @r   r^   r^     s          RZ	::NRZ 1 129==NRZ 4 4bi@@NRZ 7 7CCN"           6

 

 

   $ $ X$ ]% % ]%) ) ) )*, , ,(!. !. !.F! ! ! !F% % % %. . .`: : :"8 8 8 8e e e eN  G G GR) ) )! ! !F      r   r^   c                   J     e Zd Z fdZd Zd fd	Z fdZd Z fdZ xZ	S )	r   c                     t          t          |                               |||j        |j        |j                   || _        || _        d S rs   )r   r   r[   r   r   r   r   r   )rV   r   r   r4   r5   
image_dataru   s         r   r[   zImageDataRegion.__init__w  sQ    ot$$--eV.8.H*Jb.8.G	I 	I 	I r   c                     | j         | j        |                     | j        | j                  | j        | j        | j        | j        | j        | j        | j	        d
S )N)
r4   r5   r   r   r   r   r   r   r   r   )
r4   r5   r   r   r   r   r   r   r   r   rv   s    r   r   zImageDataRegion.__getstate__~  sY    Zkd2D4GHH#3#3"1Z!/
 
 	
r   Nc                    t          | j                  | j        z  t          | j                  | j        | j        z   z  |                                  |                     | j        t          | j                            t          | j                  fdt          dt                              D             }fd|| j	        | j	        | j
        z            D             }d                    |          | _        | j        t          | j                  z  | _        d | _        d| _        d| _	        |p| j        }|p| j        }t          t           |                               ||          S )Nc                 *    g | ]}||z            S r   r   r*  s     r   r-  z,ImageDataRegion.get_data.<locals>.<listcomp>  s&    LLLQq{]#LLLr   r   c                 $    g | ]}|         S r   r   )r+  rowx1x2s     r   r-  z,ImageDataRegion.get_data.<locals>.<listcomp>  s!    HHHsBrE
HHHr   r   )rA   r   r   r4   r;  r   r  r   r   r   r5   r@  r   r   r   r   r   r   )	rV   r   r   rG  r_   r,  rw  rx  ru   s	       @@@@r   r   zImageDataRegion.get_data  sZ   %&&/%&&$&4:*=>  """}}T13t7J3K3KLL+,,	LLLLLU1c$ii-K-KLLLHHHHHd46$&4;2F+F&GHHH XXd^^"j3t/C+D+DD $)T),,_d++44S%@@@r   c                 x    d| _         d| _        t          t          |                               |||           d S Nr   )r   r   r   r   r   )rV   r   r   r_   ru   s       r   r   zImageDataRegion.set_data  s9    ot$$--c5$?????r   c                 n    t          t          | j                   t          t          | j                   d S rs   )r  GL_UNPACK_SKIP_PIXELSr   GL_UNPACK_SKIP_ROWSr   rv   s    r   r  z$ImageDataRegion._apply_region_unpack  s.    +TV444)4622222r   c                     || j         z  }|| j        z  }t          t          |                               ||||          S rs   )r   r   r   r   r   )rV   r   r   r4   r5   ru   s        r   r   zImageDataRegion.get_region  s=    	TV	TV_d++66q!UFKKKr   rZ  )
r   r   r   r[   r   r   r   r  r   rm  rn  s   @r   r   r   v  s            
 
 
A A A A A A&@ @ @ @ @
3 3 3L L L L L L L L Lr   r   c                   R     e Zd ZdZdZdZd fd	Zd Zd Zd Z	ddZ
d	 Zd
 Z xZS )CompressedImageDatazYImage representing some compressed data suitable for direct uploading
    to driver.
    Nc                     t          t          |                               ||           || _        || _        || _        || _        g | _        dS )aO  Construct a CompressedImageData with the given compressed data.

        :Parameters:
            `width` : int
                Width of image
            `height` : int
                Height of image
            `gl_format` : int
                GL constant giving format of compressed data; for example,
                ``GL_COMPRESSED_RGBA_S3TC_DXT5_EXT``.
            `data` : sequence
                String or array/list of bytes giving compressed image data.
            `extension` : str or None
                If specified, gives the name of a GL extension to check for
                before creating a texture.
            `decoder` : function(data, width, height) -> AbstractImage
                A function to decode the compressed data, to be used if the
                required extension is not present.
                
        N)r   r  r[   r_   	gl_format	extensionr(   mipmap_data)rV   r4   r5   r  r_   r  r(   ru   s          r   r[   zCompressedImageData.__init__  sP    * 	!4((11%@@@	""r   c                 r    | xj         dg|t          | j                   z
  z  z  c_         || j         |dz
  <   dS )a  Set data for a mipmap level.

        Supplied data gives a compressed image for the given mipmap level.
        The image must be of the correct dimensions for the level 
        (i.e., width >> level, height >> level); but this is not checked.  If
        any mipmap levels are specified, they are used; otherwise, mipmaps for
        `mipmapped_texture` are generated automatically.

        :Parameters:
            `level` : int
                Level of mipmap image to set.
            `data` : sequence
                String or array/list of bytes giving compressed image data.
                Data must be in same format as specified in constructor.

        Nr	   )r  rA   )rV   r   r_   s      r   set_mipmap_dataz#CompressedImageData.set_mipmap_data  sF    $ 	TFec$2B.C.C&CDD&*###r   c                 F    | j         d u pt          j        | j                   S rs   )r  r   r  rv   s    r   _have_extensionz#CompressedImageData._have_extension  s!    ~%O)?)O)OOr   c                 `    |                                  st          | j        d|           dS )z~Assert that the extension required for this image data is
        supported.

        Raises `ImageException` if not.
        z is required to decode N)r  r   r  rv   s    r   _verify_driver_supportedz,CompressedImageData._verify_driver_supported  sB     ##%% 	Y $...RVRV!WXXX	Y 	Yr   Fc                    |rt          d          | j        r| j        S t                      }t          dt	          |                     t          | j        | j        t          |j	                  }t          t          |           t          t          t          t
          j                   t          t          t          t
          j                   | j        s| j        r| j        |_        | j        |_        |                                 rGt'          |j        |j        | j        | j        | j        dt/          | j                  | j                   n^|                     | j        | j        | j                  }|                                }|j        | j        k    sJ |j        | j        k    sJ t7                       || _        |S )Nz+Compressed texture rectangles not supportedr	   r   )r   r   GLuintglGenTexturesbyrefr   r4   r5   r   r<   r   r   r   default_min_filterGL_TEXTURE_MAG_FILTERdefault_mag_filterr   r   r  glCompressedTexImage2Dr   r   r  rA   r_   r(   r   r  )rV   r}   r~   tex_idr   r+   s         r   r   zCompressedImageData.get_texture  s    	P !NOOO  	)((av'''$*dk=&,OOmV,,,'<g>XYYY'<g>XYYY= 	-DM 	-#}G#}G!! 		1"7>7=#'>#':t{A#&ty>>49> > > >
 LLDJDDE''))G=DJ....>T[0000			 'r   c                 8   | j         r| j         S |                                 s|                                 S t                              t
          | j        | j                  }| j        s| j	        r| j        |_        | j	        |_	        t          |j        |j                   t          |j        t          t                     | j        s t          |j        t"          t$                     t'          |j        |j        | j        | j        | j        dt-          | j                  | j                   | j        | j        }}d}| j        D ]>}|dz  }|dz  }|dz  }t'          |j        || j        ||dt-          |          |           ?t1                       || _         |S )Nr   r	   )r   r  r   r   r   r   r4   r5   r   r   r   r   r   r   r   r   r  r   r   glCompressedTexImage2DARBr   r  rA   r_   r  )rV   r   r4   r5   r   r_   s         r   r   z)CompressedImageData.get_mipmapped_texture  s   ' 	0//##%% 	& ##%%%))-T[QQ= 	-DM 	-#}G#}Ggngj111(=?VWWW 	IGN,>HHH!'.'-"&."&*dk1"%di..$)	= 	= 	=
 
DKv$ 	7 	7DaKEqLFQJE%gne&*n&+VQ&)$ii7 7 7 7
 				'.$r   c                    |                                   |t          k    rQt          |||| j        z
  || j        z
  || j        | j        d| j        t          | j	                  | j	                   d S t          |||| j        z
  || j        z
  | j        | j        | j        t          | j	                  | j	        	  	         d S Nr	   )r  r  glCompressedTexSubImage3DARBr   r   r4   r5   r  rA   r_   glCompressedTexSubImage2DARBr   s         r   r   z#CompressedImageData.blit_to_texture@  s    %%''']""()*T]):A<Mq)-T[!)-),TY	D D D D D ))*T]):A<M)-T[)-),TY	D D D D Dr   rZ  r   )r   r   r   rW   r   r   r[   r  r  r  r   r   r   rm  rn  s   @r   r  r    s          "     8+ + +*P P PY Y Y   B( ( (TD D D D D D Dr   r  c                        e Zd ZdZdZdZdZdZdZdxZ	xZ
ZeZeZ fdZd Zeed	d	ddfd
            Ze	 dd            ZddZddZddZd Zd ZddZd Z xZS )r   a  An image loaded into video memory that can be efficiently drawn
    to the framebuffer.

    Typically you will get an instance of Texture by accessing the `texture`
    member of any other AbstractImage.

    :Parameters:
        `region_class` : class (subclass of TextureRegion)
            Class to use when constructing regions of this texture.
        `tex_coords` : tuple
            12-tuple of float, named (u1, v1, r1, u2, v2, r2, ...).  u, v, r
            give the 3D texture coordinates for vertices 1-4.  The vertices
            are specified in the order bottom-left, bottom-right, top-right
            and top-left.
        `target` : int
            The GL texture target (e.g., ``GL_TEXTURE_2D``).
        `level` : int
            The mipmap level of this texture.

    N)        r  r        ?r  r  r  r  r  r  r  r  r   r	   rG   r   r   r	   c                     t          t          |                               ||           || _        || _        t
          j        j        | _        d S rs   )	r   r   r[   r   r   r  r  r  _contextrV   r4   r5   r   r   ru   s        r   r[   zTexture.__init__p  sA    gt%%eV444	1r   c                 V    	 | j                             | j                   d S #  Y d S xY wrs   )r  delete_texturer   rv   s    r   __del__zTexture.__del__v  s5    	M((11111	DDs   # (Fc                    |p| j         }|p| j        }t          }|s|ra|s!t          |          rt          |          rd}n>t	          j        d          r
t          }d}n t	          j        d          r
t          }d}nd}|r|st          d          |r|}	|}
nt          |          }	t          |          }
t                      }t          dt          |                     t          ||j                   t          |t           |           t          |t"          |           t%          |	|
z  dz  z              }t'          |d||	|
dt(          t*          |	  	          | |	|
||j                  }||_        ||_        |rd|_        d	d	d	|d	d	||d	d	|d	f|_        t5                       |	|k    r|
|k    r|S |                    dd||          S )
a"  Create an empty Texture.

        If `rectangle` is ``False`` or the appropriate driver extensions are
        not available, a larger texture than requested will be created, and
        a :py:class:`~pyglet.image.TextureRegion` corresponding to the requested size will be
        returned.

        :Parameters:
            `width` : int
                Width of the texture.
            `height` : int
                Height of the texture.
            `internalformat` : int
                GL constant giving the internal format of the texture; for
                example, ``GL_RGBA``.
            `rectangle` : bool
                ``True`` if a rectangular texture is permitted.  See
                `AbstractImage.get_texture`.
            `force_rectangle` : bool
                ``True`` if a rectangular texture is required.  See
                `AbstractImage.get_texture`.  
                
                .. versionadded:: 1.1.4.
            `min_filter` : int
                The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``
            `mag_filter` : int
                The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``

        :rtype: :py:class:`~pyglet.image.Texture`
        
        .. versionadded:: 1.1
        FGL_ARB_texture_rectangleTGL_NV_texture_rectanglez*Texture rectangle extensions not availabler	   r@   r   r  )r  r  r   rN   r   r  GL_TEXTURE_RECTANGLE_ARBGL_TEXTURE_RECTANGLE_NVr   rL   r  r  r  r   r<   r   r   r  GLubyter  r  r  
min_filter
mag_filterr   
tex_coordsr  r   )r   r4   r5   r   r}   r~   r  r  r   texture_widthtexture_heightr   blankr   s                 r   r7   zTexture.create|  s*   F  93#9
93#9
 
	" 
	"" 	"x 	"8F;K;K 	"!		'(BCC "1 		'(ABB "0 		!	 	O9 	O !MNNN 	3!M#NN)%00M*622NXXar###fbh''' 5zBBB 5zBBBMN:Q>?BBVQ#"N.	 	 	 #m^VRXFF'' 	2$(G!"$b""'R"'"$fb"2G
 				E!!n&>&>N!!!Qv666r   c                 r   |t           t          fvr&t          |          }t          |          }| j        }	n|}|}ddd|dd||dd|df}	|p| j        }|p| j        }t                      }
t          dt          |
                     t          ||
j
                   t          |t          |           t          |t          |           |Ft          ||z  dz  z              }t          |d|||dt           t"          |	  	         t%                        | ||||
j
                  }||_        ||_        |	|_        |S )a  Create a Texture with dimensions at least min_width, min_height.
        On return, the texture will be bound.

        :Parameters:
            `target` : int
                GL constant giving texture target to use, typically
                ``GL_TEXTURE_2D``.
            `min_width` : int
                Minimum width of texture (may be increased to create a power
                of 2).
            `min_height` : int
                Minimum height of texture (may be increased to create a power
                of 2).
            `internalformat` : int
                GL constant giving internal format of texture; for example,
                ``GL_RGBA``.  If unspecified, the texture will not be
                initialised (only the texture name will be created on the
                instance).   If specified, the image will be initialised
                to this format with zero'd data.
            `min_filter` : int
                The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``
            `mag_filter` : int
                The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``

        :rtype: :py:class:`~pyglet.image.Texture`
        r  r	   Nr@   r   )r  r  rL   r  r  r  r  r  r  r   r<   r   r   r  r  r  r  r  r  r  r  )r   r   	min_width
min_heightr   r  r  r4   r5   r  r   r  r   s                r   r   zTexture.create_for_size  sa   : 13KLLL!),,E":..FJJEFb"Rfb*J  93#9
93#9
XXar###fbh''' 5zBBB 5zBBB% 2366E' "2      III#eVVRX66'''r   c                    t          | j        | j                   d}t          }t	          t
                     t          t          d           t          | j	        | j
        z  | j        z  t          |          z  z              }t          | j        | j        |t          |           t!                       t#          | j	        | j
        ||          }| j        dk    r*|                    d|| j
        z  | j	        | j
                  }|S )a$  Get the image data of this texture.

        Changes to the returned instance will not be reflected in this
        texture.

        :Parameters:
            `z` : int
                For 3D textures, the image slice to retrieve.

        :rtype: :py:class:`~pyglet.image.ImageData`
        r]   r	   r   )r   r   r   r  r  r  r  GL_PACK_ALIGNMENTr  r4   r5   imagesrA   glGetTexImager   r  r  r^   r   )rV   r   r   r  bufferr_   s         r   rz   zTexture.get_image_data  s     	dk47+++ 	4555'+++TZ$+5Cc&kkQRUUdk4:!16	; 	; 	;T[&&AA;????1a$+otz4;OODr   c                 6    |r| j         st          d          | S )NzTexture is not a rectangle.)r   r   r|   s      r   r   zTexture.get_texture6  s*     	@4#5 	@ !>???r   c                    | j         }|| j        z
  }|| j        z
  }||d u r| j        p|z   }	||d u r| j        p|z   }
t          dz  g |d         |d         |d         d|||d|d         |d         |d         d|	||d|d	         |d
         |d         d|	|
|d|d         |d         |d         d||
|dR  }t          t                     t          | j	                   t          | j	        | j                   t          t                     t          t          d|           t!          t"          dd           t%                       t'                       d S )N    r   r	   rG   r  r   r@            rH   	   
      )r  r   r   r4   r5   r  glPushAttribGL_ENABLE_BITglEnabler   r   r   r  GL_CLIENT_VERTEX_ARRAY_BITglInterleavedArrays
GL_T4F_V4FglDrawArraysGL_QUADSr  glPopAttrib)rV   r   r   r   r4   r5   trw  y1rx  y2arrays               r   r   zTexture.blit=  sM   O5D=/TZ8596T>1dk;V<2 aDA$!  aD A$ ! ! 	 	 	 	
 aD
 A$
 !
 !     aD B% 2 !#       	]###dk47+++5666J5111Xq!$$$r   c                     t          | j        | j                   |                    | j        | j        |||           d S rs   r   r   r   r   r   r   s        r   r   zTexture.blit_intoV  s<    dk47+++t{DJ1a@@@@@r   c                 6    |                      ||d|||           S rz  )region_classr   s        r   r   zTexture.get_regionZ  s       Aq%>>>r   c                    |                      dd| j        | j                  }d\  }}}}| j        |_        | j        |_        |r||||f\  }}}}| j        | j        z
  |_        |r||||f\  }}}}| j        | j        z
  |_        |dz  }|dk     r|dz  }|dk    rn|dk    r.||||f\  }}}}|j        |j        |j        z
  	 c|_        |_        nx|dk    r4||||f\  }}}}|j        |j        z
  |_        |j        |j        z
  |_        n>|dk    r.||||f\  }}}}|j        |j        z
  |j        	 c|_        |_        n
J d            |d	v r|j        |j        c|_        |_        |                    ||||           |S )
a  Create a copy of this image applying a simple transformation.

        The transformation is applied to the texture coordinates only;
        :py:meth:`~pyglet.image.ImageData.get_image_data` will return the untransformed data.  The
        transformation is applied around the anchor point.

        :Parameters:
            `flip_x` : bool
                If True, the returned image will be flipped horizontally.
            `flip_y` : bool
                If True, the returned image will be flipped vertically.
            `rotate` : int
                Degrees of clockwise rotation of the returned image.  Only 
                90-degree increments are supported.

        :rtype: :py:class:`~pyglet.image.TextureRegion`
        r   r  ih  Z        Fz'Only 90 degree rotations are supported.)r  r  )r   r4   r5   r   r   _set_tex_coords_order)	rV   flip_xflip_yrotate	transformblbrtrtls	            r   get_transformzTexture.get_transform]  s   $ OOAq$*dkBB	#BB!]	!]	 	<R^NBB!%dm!;I 	=R^NBB!%t}!<I#A::cMFQ;;r\\R^NBB")"445 3I	 2 2 s]]R^NBB!*93E!EI!*!1I4F!FIs]]R^NBB 9#55"# 3I	 2 2 DCCC5Y090@)/-IOY-''BB777r   c                    | j         d d         | j         dd         | j         dd         | j         dd          f}||         ||         z   ||         z   ||         z   | _         | j        }||         ||         ||         ||         f| _        d S )Nr   r  r  )r  tex_coords_order)rV   r  r  r  r  r  orders          r   r  zTexture._set_tex_coords_order  s    obqb)oac*oac*oabb)+
 %R.:b>9JrNJZXZ^[%!&rE"IuRy%) Lr   r   r   r   rh  )FFr   )r   r   r   rW   r  r  r  r   r  r   r   r   	GL_LINEARr  r  r[   r  classmethodr  r7   r   rz   r   r   r   r   r  r  rm  rn  s   @r   r   r   Q  sd        * LAJ#EFMAMA""2 2 2 2 2   29$SWX7 X7 X7 [X7t IM= = = [=~   >      2A A A? ? ?4 4 4 4lM M M M M M Mr   r   c                   :     e Zd ZdZ fdZd Zd Zd Zd Z xZ	S )TextureRegionzWA rectangular region of a texture, presented as if it were
    a separate texture.
    c                    t          t          |                               |||j        |j                   || _        || _        || _        || _        |j	        d         }|j	        d         }|j	        d         }	|j	        d         }
|	|z
  }|
|z
  }||j
        z  |z  |z   }||j        z  |z  |z   }||z   |j
        z  |z  |z   }||z   |j        z  |z  |z   }||j        z  |j	        d         z   }||||||||||||f| _	        d S )Nr   r	   r   r  rG   )r   r  r[   r   r   r   r   r   ownerr  r4   r5   r  )rV   r   r   r   r4   r5   r  owner_u1owner_v1owner_u2owner_v2scale_uscale_vu1v1u2v2r1  ru   s                     r   r[   zTextureRegion.__init__  s+   mT""++E65<RRR
#A&#A&#A&#A&X%X%_w&1'(2%i5;&08;&jEL(72X=u/22r1b"aRBAFr   c                     | j                             | j                  }|                    | j        | j        | j        | j                  S rs   )r  rz   r   r   r   r   r4   r5   )rV   rq  s     r   rz   zTextureRegion.get_image_data  s;    Z..tv66
$$TVTVTZMMMr   c                     || j         z  }|| j        z  }|                     ||| j        ||| j                  } |j        | j          |S rs   )r   r   r  r   r  r  r  rV   r   r   r4   r5   regions         r   r   zTextureRegion.get_region  sQ    	TV	TV""1a
KK$$d&;<<r   c                 p    | j                             ||| j        z   || j        z   || j        z              d S rs   )r  r   r   r   r   r   s        r   r   zTextureRegion.blit_into  s6    
VQZTVQZHHHHHr   c                     d S rs   r   rv   s    r   r  zTextureRegion.__del__  s    r   )
r   r   r   rW   r[   rz   r   r   r  rm  rn  s   @r   r  r    s         G G G G G(N N N  I I I      r   r  c                   j    e Zd ZdZdZdZdZeefd            Z	eefd            Z
d Zd Zd Zd	 Zd
S )	Texture3DzA texture with more than one image slice.

    Use `create_for_images` or `create_for_image_grid` classmethod to
    construct.
    r   r   c                    |d         j         }|d         j        }|D ]'}|j         |k    s|j        |k    rt          d          (t          |          }t	          j        dd          st          |          }|                     t          ||          }|d         j	        s|d         j
        r$|d         j	        |_	        |d         j
        |_
        ||_        t          |j         |j        z  |j        z  z              }t          |j        |j                   t!          |j        |j        ||j         |j        |j        dt$          t&          |
  
         g }	t)          |          D ]a\  }
}|                     dd|
|||          }|	                    |           |                    |j        |j        |j	        |j
        |
           bt1                       |	|_        ||_        ||_        |S )Nr   z#Images do not have same dimensions.rG   )r4   r5   r   rA   r   have_versionrL   r   r  r   r   r  r  r   r   r   glTexImage3Dr   r`  r  	enumerater  appendr   r  itemsr   r   )r   r  r   r   r   r+   depthr   r  r   r   items               r   create_for_imageszTexture3D.create_for_images  s   AY_
Qi& 	L 	LE{j((ELK,G,G$%JKKK -H F#Aq)) 	)!%((E%%mZMM!9 	2!3 	2%ay1G%ay1GGMGN:W^KLOOgngj111W^W]#]GNGNA/		 	 	 !&)) 	E 	EHAu##Aq!ZgNNDLL!!'.'-"'.%.!E E E E 				')r   c                 >    |                      |d d          |          S rs   )r  )r   gridr   s      r   create_for_image_gridzTexture3D.create_for_image_grid   s     $$T!!!Wn===r   c                 *    t          | j                  S rs   rA   r   rv   s    r   r   zTexture3D.__len__      4:r   c                     | j         |         S rs   )r   )rV   r   s     r   r   zTexture3D.__getitem__  s    z%  r   c                 B   t          |          t          u rPt          | |         |          D ]7\  }}|                    | j        | j        |j        |j        |j                   8d S |                    | j        | j        |j        |j        | |         j                   d S rs   )	r"  r   zipr   r   r   r   r   r   )rV   r   r<   r  r+   s        r   r   zTexture3D.__setitem__
  s    ;;%"4;66 N Ne%%dk4:&+nendfN N N NN N !!$+tz"'.%.$u+-Q Q Q Q Qr   c                 *    t          | j                  S rs   iterr   rv   s    r   r   zTexture3D.__iter__      DJr   N)r   r   r   rW   r   r   r   r  r  r  r  r   r   r   r   r   r   r   r  r    s         
 JKE6= & & & [&P 8? > > > [>  ! ! !Q Q Q         r   r  c                   D     e Zd ZdZ fdZd Zd Zed             Z xZ	S )TileableTexturez{A texture that can be tiled efficiently.

    Use :py:class:`~pyglet.image.create_for_Image` classmethod to construct.
    c                     t          |          rt          |          st          d          t          t          |                               ||||           d S )Nz8TileableTexture requires dimensions that are powers of 2)rN   r   r   r  r[   r  s        r   r[   zTileableTexture.__init__  sd     	Lhv&6&6 	L JL L Lot$$--eVVRHHHHHr   c                 &    t          d| z            )NzCannot get region of %rry   r   s        r   r   zTileableTexture.get_region#  s    6=>>>r   c                    | j         | j        z  }| j        | j        z  }||| j        z  z   }||| j        z  z   }	||}}
| j        }t          dz  g |||d         d|||d|||d         d||
z   ||d||	|d         d||
z   ||z   |d||	|d         d|||z   |dR  }t          t                     t          | j	                   t          | j	        | j                   t          t                     t          t          d|           t!          t"          dd           t%                       t'                       d	S )
zBlit this texture tiled over the given area.
        
        The image will be tiled with the bottom-left corner of the destination
        rectangle aligned with the anchor point of this texture.
        r  rG   r  r  rH   r  r   r@   N)r   r4   r   r5   r  r  r  r  r  r   r   r   r  r  r  r  r  r  r  r  )rV   r   r   r   r4   r5   r  r  r  r  whr  r  s                 r   
blit_tiledzTileableTexture.blit_tiled&  s:    ]TZ']T[(%$*$$&4;&&f1O2 aD   aD  E	 	 	 	
 
 
 aD
  E q5      bE   1u     	]###dk47+++5666J5111Xq!$$$r   c                    t          |j                  rt          |j                  s|                                }t	          |j                  }t	          |j                  }t          ||z  dz            }t          t          |j        |j        t          |	                    d|j        dz            ||t          |	  	         t          ||d|          }|                                }|                    |           S )Nr@   r]   )rN   r4   r5   rz   rL   c_buffergluScaleImager  r  r   r^   r   )r   r+   r  r  newdatas        r   create_for_imagez TileableTexture.create_for_imageE  s    $$ 	'HU\,B,B 	'((**E)%+66M*5<88N}~=ABBG'+u|*..qAA'(*!# # # m^V%' 'E $$&&##C(((r   )
r   r   r   rW   r[   r   r  r  r  rm  rn  s   @r   r  r    s         
I I I I I? ? ?  > ) ) [) ) ) ) )r   r  c                       e Zd ZdZd ZdS )DepthTexturez0A texture with depth samples (typically 24-bit).c                 t    t          | j        | j                   |                    | j        |||           d S rs   r  r   s        r   r   zDepthTexture.blit_into_  s8    dk47+++tz1a33333r   N)r   r   r   rW   r   r   r   r   r  r  \  s)        ::4 4 4 4 4r   r  c                   6    e Zd ZdZd Zd Zd Zd Zd Zd Z	dS )	BufferManagerzManages the set of framebuffers for a context.

    Use :py:func:`~pyglet.image.get_buffer_manager` to obtain the instance of this class for the
    current context.
    c                    d | _         d | _        t                      }t          t          t          |                     t          t          t          t          gd |j
                 | _        t                      }t          t          t          |                     t          t          |j
                            | _        g | _        d S rs   )color_bufferdepth_bufferGLintr:   GL_AUX_BUFFERSr  GL_AUX0GL_AUX1GL_AUX2GL_AUX3r<   free_aux_buffersGL_STENCIL_BITSlistr   free_stencil_bitsrefs)rV   aux_buffersstencil_bitss      r   r[   zBufferManager.__init__k  s      ggneK&8&8999!(!(!(!(!* +=;+<*<!>
 wwou\':':;;;!%eL,>&?&?!@!@			r   c                 R    t          dz              }t          t          |           |S )zGet the current OpenGL viewport dimensions.

        :rtype: 4-tuple of float.
        :return: Left, top, right and bottom dimensions.
        r@   )r&  r:   GL_VIEWPORT)rV   viewports     r   get_viewportzBufferManager.get_viewport|  s&     AI==k8,,,r   c                     |                                  }|d         }|d         }| j        r || j        j        k    s|| j        j        k    rt	          | | _        | j        S )zZGet the color buffer.

        :rtype: :py:class:`~pyglet.image.ColorBufferImage`
        rG   r   )r6  r$  r4   r5   ColorBufferImagerV   r5  viewport_widthviewport_heights       r   get_color_bufferzBufferManager.get_color_buffer  j    
 $$&&!!"1+! 	<"d&7&===#t'8'??? 0( ;D  r   c                    | j         st          d          | j                             d          |                                 }t	          | }|_        | ffd	}| j                            t          j	        ||                     |S )zGet a free auxiliary buffer.

        If not aux buffers are available, `ImageException` is raised.  Buffers
        are released when they are garbage collected.
        
        :rtype: :py:class:`~pyglet.image.ColorBufferImage`
        z No free aux buffer is available.r   c                 >    |j                             d           d S rz  )r,  insert)refrV   	gl_buffers     r   release_bufferz4BufferManager.get_aux_buffer.<locals>.release_buffer  s"    !((I66666r   )
r,  r   popr6  r8  rB  r0  r  weakrefrA  )rV   r5  r  rC  rB  s       @r   get_aux_bufferzBufferManager.get_aux_buffer  s     $ 	E !CDDD)--a00	$$&&!8,$%) 	7 	7 	7 	7 	7 	7 		V^<<===r   c                     |                                  }|d         }|d         }| j        r || j        j        k    s|| j        j        k    rt	          | | _        | j        S )zZGet the depth buffer.

        :rtype: :py:class:`~pyglet.image.DepthBufferImage`
        rG   r   )r6  r%  r4   r5   DepthBufferImager9  s       r   get_depth_bufferzBufferManager.get_depth_buffer  r=  r   c                 4   | j         st          d          | j                             d          |                                 \  }}}}t	          ||||          }|_        | ffd	}| j                            t          j	        ||                     |S )a7  Get a free bitmask buffer.

        A bitmask buffer is a buffer referencing a single bit in the stencil
        buffer.  If no bits are free, `ImageException` is raised.  Bits are
        released when the bitmask buffer is garbage collected.

        :rtype: :py:class:`~pyglet.image.BufferImageMask`
        z#No free stencil bits are available.r   c                 >    |j                             d           d S rz  )r/  r@  )rA  rV   stencil_bits     r   rC  z5BufferManager.get_buffer_mask.<locals>.release_buffer  s"    "))![99999r   )
r/  r   rD  r6  BufferImageMaskrL  r0  r  rE  rA  )rV   r   r   r4   r5   r  rC  rL  s          @r   get_buffer_maskzBufferManager.get_buffer_mask  s     % 	H !FGGG,0033"//111eV Auf55(%) 	: 	: 	: 	: 	: 	: 		V^<<===r   N)
r   r   r   rW   r[   r6  r<  rF  rI  rN  r   r   r   r"  r"  d  sx           "  ! ! !  .! ! !    r   r"  c                  x    t           j        j        } t          | d          st	                      | _        | j        S )ztGet the buffer manager for the current OpenGL context.
    
    :rtype: :py:class:`~pyglet.image.BufferManager`
    image_buffer_manager)r  r  r  r!   r"  rP  )contexts    r   get_buffer_managerrR    s6    
 i'G7233 7'4$''r   c                   4    e Zd ZdZeZdZdZdZd Z	d Z
d ZdS )BufferImagezAn abstract framebuffer.
    r   r(  Nc                 >    || _         || _        || _        || _        d S rs   )r   r   r4   r5   r   s        r   r[   zBufferImage.__init__  s"    
r   c           	         t          t          | j                  | j        z  | j        z  z              }| j        }| j        }| j        r|| j        j        z  }|| j        j        z  }t          | j	                   t          t                     t          t          d           t          ||| j        | j        | j        t           |           t#                       t%          | j        | j        | j        |          S r  )r  rA   r   r4   r5   r   r   r  glReadBufferrB  r  r  r  r  glReadPixelsr  r  r  r^   )rV   r  r   r   s       r   rz   zBufferImage.get_image_data  s    S--
:T[HILLFF: 	AAT^$$$4555'+++Q4:t{^%5v	? 	? 	?T[$+vFFFr   c                     | j         r-| j                             || j        z   || j        z   ||          S |                     || j        z   || j        z   ||          }| j        |_        | |_         |S rs   )r  r   r   r   ru   rB  r  s         r   r   zBufferImage.get_region  sn    : 	P:((TVQZOOODF
AJvFF>r   )r   r   r   rW   GL_BACKrB  r  r   r  r[   rz   r   r   r   r   rT  rT    sh          I I FE  G G G$    r   rT  c                   (    e Zd ZdZeZdZddZd ZdS )r8  zA color framebuffer.

    This class is used to wrap both the primary color buffer (i.e., the back
    buffer) or any one of the auxiliary buffers.
    r]   Fc                     t                               | j        | j        t          ||          }|                     |j        |j        | j        | j	        d           |S rz  )
r   r7   r4   r5   r  r   r   r   r   r   rV   r}   r~   r   s       r   r   zColorBufferImage.get_texture  sT    ..T['!*O= =W^W]!]DM1	> 	> 	>r   c           
          t          | j                   t          |||| j        z
  || j        z
  | j        | j        | j        | j                   d S rs   	rW  rB  glCopyTexSubImage2Dr   r   r   r   r4   r5   r   s         r   r   z ColorBufferImage.blit_to_texture!  [    T^$$$FE-q4=/@ FDFDJ	E 	E 	E 	E 	Er   Nr   )	r   r   r   rW   r  r  r   r   r   r   r   r   r8  r8    sR         
 IF   E E E E Er   r8  c                   (    e Zd ZdZeZdZddZd ZdS )rH  zThe depth buffer.
    r   Fc           
         |dk    r|dk    s
J d            t          | j                  rt          | j                  st          d          t                              t          | j        | j                  }| j        s| j        r| j        |_        | j        |_        t          | j
                   t          |j        dt          | j        | j        | j        | j        d           |S )NFz$Depth textures cannot be rectangularz<Depth texture requires that buffer dimensions be powers of 2r   )rN   r4   r5   r   r  r   r   r   r   rW  rB  glCopyTexImage2Dr   GL_DEPTH_COMPONENTr   r   r]  s       r   r   zDepthBufferImage.get_texture.  s    E!!o&>&>&>2 '?&>>
## 	P8DK+@+@ 	P NP P P ..}dj$+VV= 	-DM 	-#}G#}GT^$$$+T[	 	 	 r   c           
          t          | j                   t          |||| j        z
  || j        z
  | j        | j        | j        | j                   d S rs   r_  r   s         r   r   z DepthBufferImage.blit_to_textureA  ra  r   Nr   )	r   r   r   rW   re  r  r   r   r   r   r   r   rH  rH  (  sP         "IF   &E E E E Er   rH  c                       e Zd ZdZeZdZdS )rM  z(A single bit of the stencil buffer.
    r   N)r   r   r   rW   GL_STENCIL_INDEXr  r   r   r   r   rM  rM  H  s"          IFFFr   rM  c                   \     e Zd ZdZdZdZ	 	 d fd	ZddZd Zd	 Z	d
 Z
d Zd Zd Z xZS )	ImageGrida  An imaginary grid placed over an image allowing easy access to
    regular regions of that image.

    The grid can be accessed either as a complete image, or as a sequence
    of images.  The most useful applications are to access the grid
    as a :py:class:`~pyglet.image.TextureGrid`::

        image_grid = ImageGrid(...)
        texture_grid = image_grid.get_texture_sequence()

    or as a :py:class:`~pyglet.image.Texture3D`::

        image_grid = ImageGrid(...)
        texture_3d = Texture3D.create_for_image_grid(image_grid)

    r   Nr   c                 $   t          t          |                               |j        |j                   ||j        ||dz
  z  z
  |z  }||j        ||dz
  z  z
  |z  }|| _        || _        || _        || _        || _	        || _
        || _        dS )a  Construct a grid for the given image.

        You can specify parameters for the grid, for example setting
        the padding between cells.  Grids are always aligned to the 
        bottom-left corner of the image.

        :Parameters:
            `image` : AbstractImage
                Image over which to construct the grid.
            `rows` : int
                Number of rows in the grid.
            `columns` : int
                Number of columns in the grid.
            `item_width` : int
                Width of each column.  If unspecified, is calculated such
                that the entire image width is used.
            `item_height` : int
                Height of each row.  If unspecified, is calculated such that
                the entire image height is used.
            `row_padding` : int
                Pixels separating adjacent rows.  The padding is only
                inserted between rows, not at the edges of the grid.
            `column_padding` : int
                Pixels separating adjacent columns.  The padding is only 
                inserted between columns, not at the edges of the grid.
        Nr	   )r   rj  r[   r4   r5   r+   rG  columnsr   r   row_paddingcolumn_padding)	rV   r+   rG  rl  r   r   rm  rn  ru   s	           r   r[   zImageGrid.__init__e  s    : 	i''U\BBB+'A+(FF7RJ <+*BBtKK
	$&&,r   Fc                 8    | j                             ||          S rs   )r+   r   r|   s      r   r   zImageGrid.get_texture  s    z%%iAAAr   c                 4    | j                                         S rs   )r+   rz   rv   s    r   rz   zImageGrid.get_image_data  s    z((***r   c                 F    | j         st          |           | _         | j         S rs   )_texture_gridTextureGridrv   s    r   r   zImageGrid.get_texture_sequence  s&    ! 	3!,T!2!2D!!r   c                      | j         | j        z  S rs   )rG  rl  rv   s    r   r   zImageGrid.__len__  s    y4<''r   c           
      P   | j         sg | _         d}t          | j                  D ]}d}t          | j                  D ]S}| j                             | j                            ||| j        | j                             || j        | j	        z   z  }T|| j        | j
        z   z  }d S d S rz  )_itemsr   rG  rl  r  r+   r   r   r   rn  rm  )rV   r   rv  r   cols        r   _update_itemszImageGrid._update_items  s    { 		9DKATY'' 9 9 .. ? ?CK&&tz'<'<1dot/?(A (A B B B4+>>>AAT%(888		9 		99 9r   c                     |                                   t          |          t          u rA|\  }}|dk    r|dk    r|| j        k     r|| j        k     sJ | j        || j        z  |z            S | j        |         S rz  )rx  r"  tuplerG  rl  rv  )rV   r   rv  columns       r   r   zImageGrid.__getitem__  s    ;;%KC!88!diFT\DYDYDYY;sT\1F:;;;u%%r   c                 R    |                                   t          | j                  S rs   )rx  r  rv  rv   s    r   r   zImageGrid.__iter__  s$    DK   r   )NNr   r   r   )r   r   r   rW   rv  rr  r[   r   rz   r   r   rx  r   r   rm  rn  s   @r   rj  rj  Q  s           FM /3/0)- )- )- )- )- )-VB B B B+ + +" " "
( ( (
9 
9 
9& & &! ! ! ! ! ! !r   rj  c                   T     e Zd ZdZdZdZdZdZdZ fdZ	d Z
d Zd Zd	 Zd
 Z xZS )rs  a^  A texture containing a regular grid of texture regions.

    To construct, create an :py:class:`~pyglet.image.ImageGrid` first::

        image_grid = ImageGrid(...)
        texture_grid = TextureGrid(image_grid)

    The texture grid can be accessed as a single texture, or as a sequence
    of :py:class:`~pyglet.image.TextureRegion`.  When accessing as a sequence, you can specify
    integer indexes, in which the images are arranged in rows from the
    bottom-left to the top-right::

        # assume the texture_grid is 3x3:
        current_texture = texture_grid[3] # get the middle-left image

    You can also specify tuples in the sequence methods, which are addressed
    as ``row, column``::

        # equivalent to the previous example:
        current_texture = texture_grid[1, 0]

    When using tuples in a slice, the returned sequence is over the
    rectangular region defined by the slice::

        # returns center, center-right, center-top, top-right images in that
        # order:
        images = texture_grid[(1,1):]
        # equivalent to
        images = texture_grid[(1,1):(3,3)]

    r   r	   r   c           
         |                                 }t          |t                    r|j        }n|}t	          t
          |                               |j        |j        |j	        |j
        |j        |           g }d}t          |j                  D ]t}d}t          |j                  D ]I}|                    |                     |||j        |j                             ||j        |j        z   z  }J||j        |j        z   z  }u|| _        |j        | _        |j        | _        |j        | _        |j        | _        d S rz  )r   
isinstancer  r  r   rs  r[   r   r   r   r4   r5   r   rG  rl  r  r   r   r   rn  rm  r   )
rV   r  r+   r  r   r   rv  r   rw  ru   s
            r   r[   zTextureGrid.__init__  sF     ""e]++ 	KEEEk4  ))GUWegu{EL%	I 	I 	I ## 	5 	5CAT\** ; ;OOAq$/4;KLLN N NT_t':::!D$444AA
I	|/+r   c                     | ||f         S rs   r   )rV   rv  r{  s      r   r  zTextureGrid.get  s    S&M""r   c                 d   t          |          t          u rt          |j                  t          ur(t          |j                  t          ur| j        |         S d}d}| j        }| j        }t          |j                  t          u r|j        \  }}n9t          |j                  t          u r|j        | j        z  }|j        | j        z  }|dk    r|dk    r|| j        k     r|| j        k     sJ t          |j                  t          u r|j        \  }}n9t          |j                  t          u r|j        | j        z  }|j        | j        z  }|dk    r|dk    r|| j        k    r|| j        k    sJ g }|| j        z  }t          ||          D ]$}|| j        ||z   ||z            z  }|| j        z  }%|S t          |          t          u rA|\  }}	|dk    r|	dk    r|| j        k     r|	| j        k     sJ | j        || j        z  |	z            S t          |          t          u r| j        |         S d S rz  )
r"  r   startrz  stopr   rG  rl  intr   )
rV   r   rn   col1ro   col2resultr   rv  r{  s
             r   r   zTextureGrid.__getitem__  sJ   ;;%EK  --$uz2B2B%2O2Oz%((y|$$--!&JD$$%+&&#-- ;$,6D ;5DqyyTQYY4$)3C3Ct|H[H[H[[
##u,,!&JD$$%*%%,, :5D :4DqyyTQYY4493D3DQUQ]I]I]I]]4<' t,, & &CdjT!d():;;F%AAE{{e###VaxxFaKKC$)OOQUQ]H]H]H]]z#"4v"=>>e##z%(( $#r   c                    t          |          t          u rot          | |         |          D ]V\  }}|j        | j        k    s|j        | j        k    rt          d          |                    ||j	        |j
        d           Wd S |}|j        | j        k    s|j        | j        k    rt          d          |                    | |         |j	        |j
        d           d S )NzImage has incorrect dimensionsr   )r"  r   r  r4   r   r5   r   r   r   r   r   )rV   r   r<   r  r+   s        r   r   zTextureGrid.__setitem__ 	  s    ;;%!$T%[%!8!8 K K;$/11U\TEU5U5U()IJJJJJJJK K
 E{do--AQ1Q1Q$%EFFFOODKKKKKKr   c                 *    t          | j                  S rs   r  rv   s    r   r   zTextureGrid.__len__,	  r	  r   c                 *    t          | j                  S rs   r  rv   s    r   r   zTextureGrid.__iter__/	  r  r   )r   r   r   rW   r   rG  rl  r   r   r[   r  r   r   r   r   rm  rn  s   @r   rs  rs    s         > EDGJK, , , , ,4# # ##) #) #)J
L 
L 
L               r   rs  rZ  rs   )=rW   ri  rE  ctypesior   r   	functoolsr   r  	pyglet.glr   pyglet.utilr   codecsr
   r   r   r   r   r   r   r   	animationr   r   r(  r   	Exceptionr   r-   r0   r7   r>   rE   rL   rN   rP   r2   rb   rq   r   r   r   r^   r   r  r   r  r  r  r  r  r"  rR  rT  r8  rH  rM  rj  rs  r   r   r   <module>r     sT  H^ ^~ 
			                                     > > > > > > > > H H H H H H H H H H F F F F F F F F F F 0 0 0 0 0 0 0 0      	 	 	 	 	Y 	 	 	2  2  2  2 j% % % %P/ / / /.       	 	 	   
. . . . . . . ."6 6 6 6 6\ 6 6 6&6 6 6 6 6, 6 6 6<iD iD iD iD iD iD iD iDX>. >. >. >. >. >. >. >.B    +   ' ' ' ' '_ ' ' '4n n n n n n n nb6L 6L 6L 6L 6Li 6L 6L 6Lr_D _D _D _D _D- _D _D _DDJM JM JM JM JMm JM JM JMZ
) ) ) ) )G ) ) )X % G  G  G  G  G / G  G  G TB) B) B) B) B)g B) B) B)J4 4 4 4 47 4 4 4k k k k k k k k\( ( (/ / / / /- / / /dE E E E E{ E E E.E E E E E{ E E E@    k   d! d! d! d! d!4 d! d! d!Nx  x  x  x  x -!7 x  x  x x       r   