Beispiel #1
0
    def test_surface_to_array_3d(self):
        try:
            from numpy import empty, dtype
        except ImportError:
            return

        palette = self.test_palette

        dst_dims = self.surf_size + (3, )
        destinations = [empty(dst_dims, t) for t in self.dst_types]
        if (pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN):
            swapped_dst = empty(dst_dims, dtype('>u4'))
        else:
            swapped_dst = empty(dst_dims, dtype('<u4'))

        for surf in self.sources:
            src_bitsize = surf.get_bitsize()
            for dst in destinations:
                dst[...] = 0
                self.assertFalse(surf.get_locked())
                surface_to_array(dst, surf)
                self.assertFalse(surf.get_locked())
                for posn, i in self.test_points:
                    r_surf, g_surf, b_surf, a_surf = surf.get_at(posn)
                    r_arr, g_arr, b_arr = dst[posn]
                    self.assertEqual(
                        r_arr, r_surf, "%i != %i, color: red, flags: %i"
                        ", bpp: %i, posn: %s" %
                        (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(),
                         posn))
                    self.assertEqual(
                        g_arr, g_surf, "%i != %i, color: green, flags: %i"
                        ", bpp: %i, posn: %s" %
                        (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(),
                         posn))
                    self.assertEqual(
                        b_arr, b_surf, "%i != %i, color: blue, flags: %i"
                        ", bpp: %i, posn: %s" %
                        (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(),
                         posn))

            swapped_dst[...] = 0
            self.assertFalse(surf.get_locked())
            surface_to_array(swapped_dst, surf)
            self.assertFalse(surf.get_locked())
            for posn, i in self.test_points:
                r_surf, g_surf, b_surf, a_surf = surf.get_at(posn)
                r_arr, g_arr, b_arr = swapped_dst[posn]
                self.assertEqual(
                    r_arr, r_surf, "%i != %i, color: red, flags: %i"
                    ", bpp: %i, posn: %s" % (r_arr, r_surf, surf.get_flags(),
                                             surf.get_bitsize(), posn))
                self.assertEqual(
                    g_arr, g_surf, "%i != %i, color: green, flags: %i"
                    ", bpp: %i, posn: %s" % (r_arr, r_surf, surf.get_flags(),
                                             surf.get_bitsize(), posn))
                self.assertEqual(
                    b_arr, b_surf, "%i != %i, color: blue, flags: %i"
                    ", bpp: %i, posn: %s" % (r_arr, r_surf, surf.get_flags(),
                                             surf.get_bitsize(), posn))
def pixels_alpha(surface):
    """pygame.numpyarray.pixels_alpha (Surface): return array

    reference pixel alphas into a 2d array

    Create a new 2D array that directly references the alpha values
    (degree of transparency) in a Surface. Any changes to the array will
    affect the pixels in the Surface. This is a fast operation since no
    data is copied.

    This can only work on 32-bit Surfaces with a per-pixel alpha value.

    The Surface this array references will remain locked for the
    lifetime of the array.
    """
    if surface.get_bytesize() != 4:
        raise ValueError("unsupported bit depth for alpha reference array")
    lilendian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN

    # ARGB surface.
    start = 0

    if surface.get_shifts()[3] == 24 and lilendian:
        # RGBA surface.
        start = 3
    elif surface.get_shifts()[3] == 0 and not lilendian:
        start = 3
    else:
        raise ValueError("unsupported colormasks for alpha reference array")

    array = numpy.ndarray \
            (shape=(surface.get_width (), surface.get_height ()),
             dtype=numpy.uint8, buffer=surface.get_buffer (),
             offset=start, strides=(4, surface.get_pitch ()))
    return array
Beispiel #3
0
    def begin_render(self,surface,scene):
        """Begin rendering ``scene`` onto ``dest``.

        If the renderer is already running, an exception is thrown instead.
        Upon starting, the scene will be locked for writing.

        :param pygame.Surface dest: A surface to draw onto.
        :param scene: The scene to draw.
        :type scene: :py:class:`.render.Scene`
        
        """
        def on_complete(x):
            pygame.event.post(pygame.event.Event(
                self.ON_COMPLETE,
                source=self,
                scene=scene,
                surface=surface))
        
        py_format = (surface.get_bitsize(),surface.get_masks())
        if py_format != self.last_channels[0]:
            self.last_channels = (py_format,channels_from_surface(surface))

        super(PygameRenderer,self).begin_render(
            # for some reason, get_view returns a read-only buffer under Python
            # 2.7 on Windows with Pygame 1.9.2a0
            surface.get_view() if IS_PYTHON3 and hasattr(surface,'get_view') else surface.get_buffer(),
            ntracer.render.ImageFormat(
                surface.get_width(),
                surface.get_height(),
                self.last_channels[1],
                surface.get_pitch(),
                pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN),
            scene,
            on_complete)
def pixels_alpha (surface):
    """pygame.numpyarray.pixels_alpha (Surface): return array

    reference pixel alphas into a 2d array

    Create a new 2D array that directly references the alpha values
    (degree of transparency) in a Surface. Any changes to the array will
    affect the pixels in the Surface. This is a fast operation since no
    data is copied.

    This can only work on 32-bit Surfaces with a per-pixel alpha value.

    The Surface this array references will remain locked for the
    lifetime of the array.
    """
    if surface.get_bytesize () != 4:
        raise ValueError("unsupported bit depth for alpha reference array")
    lilendian = pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN

    # ARGB surface.
    start = 0
    
    if surface.get_shifts ()[3] == 24 and lilendian:
        # RGBA surface.
        start = 3
    elif surface.get_shifts ()[3] == 0 and not lilendian:
        start = 3
    else:
        raise ValueError("unsupported colormasks for alpha reference array")

    array = numpy.ndarray \
            (shape=(surface.get_width (), surface.get_height ()),
             dtype=numpy.uint8, buffer=surface.get_buffer (),
             offset=start, strides=(4, surface.get_pitch ()))
    return array
Beispiel #5
0
    def begin_render(self, surface, scene):
        """Begin rendering ``scene`` onto ``dest``.

        If the renderer is already running, an exception is thrown instead.
        Upon starting, the scene will be locked for writing.

        :param pygame.Surface dest: A surface to draw onto.
        :param scene: The scene to draw.
        :type scene: :py:class:`.render.Scene`
        
        """
        def on_complete(x):
            pygame.event.post(
                pygame.event.Event(self.ON_COMPLETE,
                                   source=self,
                                   scene=scene,
                                   surface=surface))

        py_format = (surface.get_bitsize(), surface.get_masks())
        if py_format != self.last_channels[0]:
            self.last_channels = (py_format, channels_from_surface(surface))

        super(PygameRenderer, self).begin_render(
            # for some reason, get_view returns a read-only buffer under Python
            # 2.7 on Windows with Pygame 1.9.2a0
            surface.get_view() if IS_PYTHON3 and hasattr(surface, 'get_view')
            else surface.get_buffer(),
            ntracer.render.ImageFormat(
                surface.get_width(), surface.get_height(),
                self.last_channels[1], surface.get_pitch(),
                pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN),
            scene,
            on_complete)
Beispiel #6
0
    def test_get_sdl_byteorder(self):

        # __doc__ (as of 2008-06-25) for pygame.base.get_sdl_byteorder:

        # pygame.get_sdl_byteorder(): return int
        # get the byte order of SDL

        self.assert_(pygame.get_sdl_byteorder() + 1)
Beispiel #7
0
    def test_get_sdl_byteorder(self):

        # __doc__ (as of 2008-06-25) for pygame.base.get_sdl_byteorder:

          # pygame.get_sdl_byteorder(): return int
          # get the byte order of SDL

        self.assert_(pygame.get_sdl_byteorder() + 1)
def is_little_endian(warning=False):
	if pygame.version.vernum[1] == 7:
		#byte ordering not available in this verion
		#so cheat and asume little endian
		if warning:
			print "Error: Pygame library too old to detect sdlendian. Assuming Little endian (Intel)"
		return True
	else:
		return pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
Beispiel #9
0
def is_little_endian(warning=False):
    if pygame.version.vernum[1] == 7:
        #byte ordering not available in this verion
        #so cheat and asume little endian
        if warning:
            print "Error: Pygame library too old to detect sdlendian. Assuming Little endian (Intel)"
        return True
    else:
        return pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
def pixels3d (surface):
    """pygame.numpyarray.pixels3d (Surface): return array

    reference pixels into a 3d array

    Create a new 3D array that directly references the pixel values in a
    Surface. Any changes to the array will affect the pixels in the
    Surface. This is a fast operation since no data is copied.

    This will only work on Surfaces that have 24-bit or 32-bit
    formats. Lower pixel formats cannot be referenced.

    The Surface this references will remain locked for the lifetime of
    the array (see the Surface.lock - lock the Surface memory for pixel
    access method).
    """
    bpp = surface.get_bytesize ()
    if bpp < 3 or bpp > 4:
        raise ValueError("unsupported bit depth for 3D reference array")
    lilendian = pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN

    start = 0
    step = 0

    # Check for RGB or BGR surface.
    shifts = surface.get_shifts ()
    if shifts[0] == 16 and shifts[1] == 8 and shifts[2] == 0:
        # RGB 
        if lilendian:
            start = 2
            step = -1
        else:
            start = 0
            step = 1
    elif shifts[2] == 16 and shifts[1] == 8 and shifts[0] == 0:
        # BGR
        if lilendian:
            start = 0
            step = 1
        else:
            start = 2
            step = -1
    else:
        raise ValueError("unsupported colormasks for 3D reference array")

    if bpp == 4 and not lilendian:
        start += 1

    array = numpy.ndarray \
            (shape=(surface.get_width (), surface.get_height (), 3),
             dtype=numpy.uint8, buffer=surface.get_buffer (),
             offset=start, strides=(bpp, surface.get_pitch (),step))
    return array
def pixels3d(surface):
    """pygame.numpyarray.pixels3d (Surface): return array

    reference pixels into a 3d array

    Create a new 3D array that directly references the pixel values in a
    Surface. Any changes to the array will affect the pixels in the
    Surface. This is a fast operation since no data is copied.

    This will only work on Surfaces that have 24-bit or 32-bit
    formats. Lower pixel formats cannot be referenced.

    The Surface this references will remain locked for the lifetime of
    the array (see the Surface.lock - lock the Surface memory for pixel
    access method).
    """
    bpp = surface.get_bytesize()
    if bpp < 3 or bpp > 4:
        raise ValueError("unsupported bit depth for 3D reference array")
    lilendian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN

    start = 0
    step = 0

    # Check for RGB or BGR surface.
    shifts = surface.get_shifts()
    if shifts[0] == 16 and shifts[1] == 8 and shifts[2] == 0:
        # RGB
        if lilendian:
            start = 2
            step = -1
        else:
            start = 0
            step = 1
    elif shifts[2] == 16 and shifts[1] == 8 and shifts[0] == 0:
        # BGR
        if lilendian:
            start = 0
            step = 1
        else:
            start = 2
            step = -1
    else:
        raise ValueError("unsupported colormasks for 3D reference array")

    if bpp == 4 and not lilendian:
        start += 1

    array = numpy.ndarray \
            (shape=(surface.get_width (), surface.get_height (), 3),
             dtype=numpy.uint8, buffer=surface.get_buffer (),
             offset=start, strides=(bpp, surface.get_pitch (),step))
    return array
Beispiel #12
0
 def test_get_array_interface(self):
     surf = pygame.Surface((7, 11), 0, 32)
     d = pygame._view.get_array_interface(surf.get_view("2"))
     self.assertEqual(len(d), 5)
     self.assertEqual(d['version'], 3)
     if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
         byteorder = '<'
     else:
         byteorder = '>'
     self.assertEqual(d['typestr'], byteorder + 'u4')
     self.assertEqual(d['shape'], (7, 11))
     self.assertEqual(d['strides'], (4, 28))
     self.assertEqual(d['data'], (surf._pixels_address, False))
Beispiel #13
0
 def test_array_interface(self):
     mixer.init(22050, -16, 1, allowedchanges=0)
     snd = mixer.Sound(buffer=as_bytes('\x00\x7f') * 20)
     d = snd.__array_interface__
     self.assertTrue(isinstance(d, dict))
     if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
         typestr = '<i2'
     else:
         typestr = '>i2'
     self.assertEqual(d['typestr'], typestr)
     self.assertEqual(d['shape'], (20, ))
     self.assertEqual(d['strides'], (2, ))
     self.assertEqual(d['data'], (snd._samples_address, False))
Beispiel #14
0
 def test_array_interface(self):
     mixer.init(22050, -16, 1, allowedchanges=0)
     snd = mixer.Sound(buffer=b"\x00\x7f" * 20)
     d = snd.__array_interface__
     self.assertTrue(isinstance(d, dict))
     if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
         typestr = "<i2"
     else:
         typestr = ">i2"
     self.assertEqual(d["typestr"], typestr)
     self.assertEqual(d["shape"], (20, ))
     self.assertEqual(d["strides"], (2, ))
     self.assertEqual(d["data"], (snd._samples_address, False))
Beispiel #15
0
 def test_array_interface(self):
     mixer.init(22050, -16, 1)
     try:
         snd = mixer.Sound(as_bytes('\x00\x7f') * 20)
         d = snd.__array_interface__
         self.assertTrue(isinstance(d, dict))
         if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
             typestr = '<i2'
         else:
             typestr = '>i2'
         self.assertEqual(d['typestr'], typestr)
         self.assertEqual(d['shape'], (20,))
         self.assertEqual(d['strides'], (2,))
         self.assertEqual(d['data'], (snd._samples_address, False))
     finally:
         mixer.quit()
def array2d(surface):
    """pygame.numpyarray.array2d (Surface): return array

    copy pixels into a 2d array

    Copy the pixels from a Surface into a 2D array. The bit depth of the
    surface will control the size of the integer values, and will work
    for any type of pixel format.

    This function will temporarily lock the Surface as pixels are copied
    (see the Surface.lock - lock the Surface memory for pixel access
    method).
    """
    bpp = surface.get_bytesize()
    if bpp <= 0 or bpp > 4:
        raise ValueError("unsupported bit depth for 2D array")

    # Taken from Alex Holkner's pygame-ctypes package. Thanks a lot.
    data = surface.get_buffer().raw

    # Remove extra pitch from each row.
    width = surface.get_width()
    pitchdiff = surface.get_pitch() - width * bpp
    if pitchdiff > 0:
        pattern = re.compile('(%s)%s' % ('.' * width * bpp, '.' * pitchdiff),
                             flags=re.DOTALL)
        data = ''.join(pattern.findall(data))

    if bpp == 3:
        # Pad each triplet of bytes with another zero
        pattern = re.compile('...', flags=re.DOTALL)
        data = '\0'.join(pattern.findall(data))
        if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
            data += '\0'
        else:
            data = '\0' + data
        bpp = 4

    typecode = (numpy.uint8, numpy.uint16, None, numpy.int32)[bpp - 1]
    array = numpy.fromstring(data, typecode)
    array.shape = (surface.get_height(), width)
    array = numpy.transpose(array)
    return array
def array2d (surface):
    """pygame.numpyarray.array2d (Surface): return array

    copy pixels into a 2d array

    Copy the pixels from a Surface into a 2D array. The bit depth of the
    surface will control the size of the integer values, and will work
    for any type of pixel format.

    This function will temporarily lock the Surface as pixels are copied
    (see the Surface.lock - lock the Surface memory for pixel access
    method).
    """
    bpp = surface.get_bytesize ()
    if bpp <= 0 or bpp > 4:
        raise ValueError("unsupported bit depth for 2D array")

    # Taken from Alex Holkner's pygame-ctypes package. Thanks a lot.
    data = surface.get_buffer ().raw
        
    # Remove extra pitch from each row.
    width = surface.get_width ()
    pitchdiff = surface.get_pitch () - width * bpp
    if pitchdiff > 0:
        pattern = re.compile ('(%s)%s' % ('.' * width * bpp, '.' * pitchdiff),
                              flags=re.DOTALL)
        data = ''.join (pattern.findall (data))

    if bpp == 3:
        # Pad each triplet of bytes with another zero
        pattern = re.compile ('...', flags=re.DOTALL)
        data = '\0'.join (pattern.findall (data))
        if pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN:
            data += '\0'
        else:
            data = '\0' + data
        bpp = 4

    typecode = (numpy.uint8, numpy.uint16, None, numpy.int32)[bpp - 1]
    array = numpy.fromstring (data, typecode)
    array.shape = (surface.get_height (), width)
    array = numpy.transpose (array)
    return array
Beispiel #18
0
def pixels_alpha (surface):

	if surface.get_bytesize () != 4:
		raise ValueError("unsupported bit depth for alpha reference array")
	
	lilendian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
	alpha_shift = surface.get_shifts()[3]
	
	if alpha_shift & 7 <> 0:
		raise ValueError("unsupported colormasks for alpha reference array")

	start = alpha_shift >> 3
	if not lilendian:
		start = 3 - start

	array = numpy.ndarray \
			(shape=(surface.get_width (), surface.get_height ()),
			 dtype=numpy.uint8, buffer=surface.get_buffer (),
			 offset=start, strides=(4, surface.get_pitch ()))
	return array
Beispiel #19
0
 def test_surface_to_array_3d(self):
     if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
         masks = (0xff, 0xff00, 0xff0000, 0)
     else:
         masks = (0xff000000, 0xff0000, 0xff00, 0)
     dst = pygame.Surface(self.surf_size, 0, 24, masks=masks)
     for surf in self.sources:
         dst.fill((0, 0, 0, 0))
         src_bitsize = surf.get_bitsize()
         view = dst.get_view('3')
         self.assertFalse(surf.get_locked())
         surface_to_array(view, surf)
         self.assertFalse(surf.get_locked())
         for posn, i in self.test_points:
             sc = surf.get_at(posn)[0:3]
             dc = dst.get_at(posn)[0:3]
             self.assertEqual(
                 dc, sc, "%s != %s: flags: %i"
                 ", bpp: %i, posn: %s" %
                 (dc, sc, surf.get_flags(), surf.get_bitsize(), posn))
         del view
Beispiel #20
0
 def test_surface_to_array_3d(self):
     if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
         masks = (0xff, 0xff00, 0xff0000, 0)
     else:
         masks = (0xff000000, 0xff0000, 0xff00, 0)
     dst = pygame.Surface(self.surf_size, 0, 24, masks=masks)
     for surf in self.sources:
         dst.fill((0, 0, 0, 0))
         src_bitsize = surf.get_bitsize()
         view = dst.get_view('3')
         self.assertFalse(surf.get_locked())
         surface_to_array(view, surf)
         self.assertFalse(surf.get_locked())
         for posn, i in self.test_points:
             sc = surf.get_at(posn)[0:3]
             dc = dst.get_at(posn)[0:3]
             self.assertEqual(dc, sc,
                              "%s != %s: flags: %i"
                              ", bpp: %i, posn: %s" %
                              (dc, sc,
                               surf.get_flags(), surf.get_bitsize(),
                               posn))
         del view
Beispiel #21
0
    def test_get_sdl_byteorder(self):
        """Ensure the SDL byte order is valid"""
        byte_order = pygame.get_sdl_byteorder()
        expected_options = (pygame.LIL_ENDIAN, pygame.BIG_ENDIAN)

        self.assertIn(byte_order, expected_options)
    def NEWBUF_test_newbuf(self):
        from ctypes import string_at

        buftools = self.buftools
        Exporter = buftools.Exporter
        Importer = buftools.Importer
        exp = Exporter((10,), 'B', readonly=True)
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            self.assertEqual(d['typestr'], '|u1')
            self.assertEqual(d['shape'], exp.shape)
            self.assertEqual(d['strides'], exp.strides)
            self.assertEqual(d['data'], (exp.buf, True))
        finally:
            d = None
        exp = Exporter((3,), '=h')
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
            f = '{}i{}'.format('<' if lil_endian else '>', exp.itemsize)
            self.assertEqual(d['typestr'], f)
            self.assertEqual(d['shape'], exp.shape)
            self.assertEqual(d['strides'], exp.strides)
            self.assertEqual(d['data'], (exp.buf, False))
        finally:
            d = None

        exp = Exporter((10, 2), '=i')
        b = BufferProxy(exp)
        imp = Importer(b, buftools.PyBUF_RECORDS)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, exp.buf)
        self.assertEqual(imp.ndim, exp.ndim)
        self.assertEqual(imp.format, exp.format)
        self.assertEqual(imp.readonly, exp.readonly)
        self.assertEqual(imp.itemsize, exp.itemsize)
        self.assertEqual(imp.len, exp.len)
        self.assertEqual(imp.shape, exp.shape)
        self.assertEqual(imp.strides, exp.strides)
        self.assertTrue(imp.suboffsets is None)

        d = {'typestr': '|u1',
             'shape': (10,),
             'strides': (1,),
             'data': (9, True)} # 9? Will not reading the data anyway.
        b = BufferProxy(d)
        imp = Importer(b, buftools.PyBUF_SIMPLE)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, 9)
        self.assertEqual(imp.len, 10)
        self.assertEqual(imp.format, None)
        self.assertEqual(imp.itemsize, 1)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.readonly)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
Beispiel #23
0
    def test_surface_to_array_2d(self):
        try:
            from numpy import empty, dtype
        except ImportError:
            return

        palette = self.test_palette
        alpha_color = (0, 0, 0, 128)

        dst_dims = self.surf_size
        destinations = [empty(dst_dims, t) for t in self.dst_types]
        if (pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN):
            swapped_dst = empty(dst_dims, dtype('>u4'))
        else:
            swapped_dst = empty(dst_dims, dtype('<u4'))

        for surf in self.sources:
            src_bytesize = surf.get_bytesize()
            for dst in destinations:
                if dst.itemsize < src_bytesize:
                    self.assertRaises(ValueError, surface_to_array, dst, surf)
                    continue
                dst[...] = 0
                self.assertFalse(surf.get_locked())
                surface_to_array(dst, surf)
                self.assertFalse(surf.get_locked())
                for posn, i in self.test_points:
                    sp = unsigned32(surf.get_at_mapped(posn))
                    dp = dst[posn]
                    self.assertEqual(dp, sp,
                                     "%s != %s: flags: %i"
                                     ", bpp: %i, dtype: %s,  posn: %s" %
                                     (dp, sp,
                                      surf.get_flags(), surf.get_bitsize(),
                                      dst.dtype,
                                      posn))

                if surf.get_masks()[3]:
                    posn = (2, 1)
                    surf.set_at(posn, alpha_color)
                    surface_to_array(dst, surf)
                    sp = unsigned32(surf.get_at_mapped(posn))
                    dp = dst[posn]
                    self.assertEqual(dp, sp, "%s != %s: bpp: %i" %
                                     (dp, sp, surf.get_bitsize()))

            swapped_dst[...] = 0
            self.assertFalse(surf.get_locked())
            surface_to_array(swapped_dst, surf)
            self.assertFalse(surf.get_locked())
            for posn, i in self.test_points:
                sp = unsigned32(surf.get_at_mapped(posn))
                dp = swapped_dst[posn]
                self.assertEqual(dp, sp,
                                 "%s != %s: flags: %i"
                                 ", bpp: %i, dtype: %s,  posn: %s" %
                                 (dp, sp,
                                  surf.get_flags(), surf.get_bitsize(),
                                  dst.dtype,
                                  posn))

            if surf.get_masks()[3]:
                posn = (2, 1)
                surf.set_at(posn, alpha_color)
                self.assertFalse(surf.get_locked())
                surface_to_array(swapped_dst, surf)
                self.assertFalse(surf.get_locked())
                sp = unsigned32(surf.get_at_mapped(posn))
                dp = swapped_dst[posn]
                self.assertEqual(dp, sp, "%s != %s: bpp: %i" %
                                     (dp, sp, surf.get_bitsize()))
Beispiel #24
0
    def test_surface_to_array_2d(self):
        try:
            from numpy import empty, dtype
        except ImportError:
            return

        palette = self.test_palette
        alpha_color = (0, 0, 0, 128)

        dst_dims = self.surf_size
        destinations = [empty(dst_dims, t) for t in self.dst_types]
        if (pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN):
            swapped_dst = empty(dst_dims, dtype('>u4'))
        else:
            swapped_dst = empty(dst_dims, dtype('<u4'))

        for surf in self.sources:
            src_bytesize = surf.get_bytesize()
            for dst in destinations:
                if dst.itemsize < src_bytesize:
                    self.assertRaises(ValueError, surface_to_array, dst, surf)
                    continue
                dst[...] = 0
                self.assertFalse(surf.get_locked())
                surface_to_array(dst, surf)
                self.assertFalse(surf.get_locked())
                for posn, i in self.test_points:
                    sp = unsigned32(surf.get_at_mapped(posn))
                    dp = dst[posn]
                    self.assertEqual(dp, sp,
                                     "%s != %s: flags: %i"
                                     ", bpp: %i, dtype: %s,  posn: %s" %
                                     (dp, sp,
                                      surf.get_flags(), surf.get_bitsize(),
                                      dst.dtype,
                                      posn))

                if surf.get_masks()[3]:
                    posn = (2, 1)
                    surf.set_at(posn, alpha_color)
                    surface_to_array(dst, surf)
                    sp = unsigned32(surf.get_at_mapped(posn))
                    dp = dst[posn]
                    self.assertEqual(dp, sp, "%s != %s: bpp: %i" %
                                     (dp, sp, surf.get_bitsize()))

            swapped_dst[...] = 0
            self.assertFalse(surf.get_locked())
            surface_to_array(swapped_dst, surf)
            self.assertFalse(surf.get_locked())
            for posn, i in self.test_points:
                sp = unsigned32(surf.get_at_mapped(posn))
                dp = swapped_dst[posn]
                self.assertEqual(dp, sp,
                                 "%s != %s: flags: %i"
                                 ", bpp: %i, dtype: %s,  posn: %s" %
                                 (dp, sp,
                                  surf.get_flags(), surf.get_bitsize(),
                                  dst.dtype,
                                  posn))

            if surf.get_masks()[3]:
                posn = (2, 1)
                surf.set_at(posn, alpha_color)
                self.assertFalse(surf.get_locked())
                surface_to_array(swapped_dst, surf)
                self.assertFalse(surf.get_locked())
                sp = unsigned32(surf.get_at_mapped(posn))
                dp = swapped_dst[posn]
                self.assertEqual(dp, sp, "%s != %s: bpp: %i" %
                                     (dp, sp, surf.get_bitsize()))
Beispiel #25
0
    def test_surface_to_array_3d(self):
        try:
            from numpy import empty, dtype
        except ImportError:
            return

        palette = self.test_palette

        dst_dims = self.surf_size + (3,)
        destinations = [empty(dst_dims, t) for t in self.dst_types]
        if (pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN):
            swapped_dst = empty(dst_dims, dtype('>u4'))
        else:
            swapped_dst = empty(dst_dims, dtype('<u4'))

        for surf in self.sources:
            src_bitsize = surf.get_bitsize()
            for dst in destinations:
                dst[...] = 0
                self.assertFalse(surf.get_locked())
                surface_to_array(dst, surf)
                self.assertFalse(surf.get_locked())
                for posn, i in self.test_points:
                    r_surf, g_surf, b_surf, a_surf = surf.get_at(posn)
                    r_arr, g_arr, b_arr = dst[posn]
                    self.assertEqual(r_arr, r_surf,
                                     "%i != %i, color: red, flags: %i"
                                     ", bpp: %i, posn: %s" %
                                     (r_arr, r_surf,
                                      surf.get_flags(), surf.get_bitsize(),
                                      posn))
                    self.assertEqual(g_arr, g_surf,
                                     "%i != %i, color: green, flags: %i"
                                     ", bpp: %i, posn: %s" %
                                     (r_arr, r_surf,
                                      surf.get_flags(), surf.get_bitsize(),
                                      posn))
                    self.assertEqual(b_arr, b_surf,
                                     "%i != %i, color: blue, flags: %i"
                                     ", bpp: %i, posn: %s" %
                                     (r_arr, r_surf,
                                      surf.get_flags(), surf.get_bitsize(),
                                      posn))

            swapped_dst[...] = 0
            self.assertFalse(surf.get_locked())
            surface_to_array(swapped_dst, surf)
            self.assertFalse(surf.get_locked())
            for posn, i in self.test_points:
                r_surf, g_surf, b_surf, a_surf = surf.get_at(posn)
                r_arr, g_arr, b_arr = swapped_dst[posn]
                self.assertEqual(r_arr, r_surf,
                                 "%i != %i, color: red, flags: %i"
                                 ", bpp: %i, posn: %s" %
                                 (r_arr, r_surf,
                                  surf.get_flags(), surf.get_bitsize(),
                                  posn))
                self.assertEqual(g_arr, g_surf,
                                 "%i != %i, color: green, flags: %i"
                                 ", bpp: %i, posn: %s" %
                                 (r_arr, r_surf,
                                  surf.get_flags(), surf.get_bitsize(),
                                  posn))
                self.assertEqual(b_arr, b_surf,
                                 "%i != %i, color: blue, flags: %i"
                                 ", bpp: %i, posn: %s" %
                                 (r_arr, r_surf,
                                  surf.get_flags(), surf.get_bitsize(),
                                  posn))
Beispiel #26
0
    def NEWBUF_test_newbuf(self):
        from ctypes import string_at

        from pygame.tests.test_utils import buftools

        Exporter = buftools.Exporter
        Importer = buftools.Importer
        exp = Exporter((10,), "B", readonly=True)
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            self.assertEqual(d["typestr"], "|u1")
            self.assertEqual(d["shape"], exp.shape)
            self.assertEqual(d["strides"], exp.strides)
            self.assertEqual(d["data"], (exp.buf, True))
        finally:
            d = None
        exp = Exporter((3,), "=h")
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
            f = "{}i{}".format("<" if lil_endian else ">", exp.itemsize)
            self.assertEqual(d["typestr"], f)
            self.assertEqual(d["shape"], exp.shape)
            self.assertEqual(d["strides"], exp.strides)
            self.assertEqual(d["data"], (exp.buf, False))
        finally:
            d = None

        exp = Exporter((10, 2), "=i")
        b = BufferProxy(exp)
        imp = Importer(b, buftools.PyBUF_RECORDS)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, exp.buf)
        self.assertEqual(imp.ndim, exp.ndim)
        self.assertEqual(imp.format, exp.format)
        self.assertEqual(imp.readonly, exp.readonly)
        self.assertEqual(imp.itemsize, exp.itemsize)
        self.assertEqual(imp.len, exp.len)
        self.assertEqual(imp.shape, exp.shape)
        self.assertEqual(imp.strides, exp.strides)
        self.assertTrue(imp.suboffsets is None)

        d = {
            "typestr": "|u1",
            "shape": (10,),
            "strides": (1,),
            "data": (9, True),
        }  # 9? Will not reading the data anyway.
        b = BufferProxy(d)
        imp = Importer(b, buftools.PyBUF_SIMPLE)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, 9)
        self.assertEqual(imp.len, 10)
        self.assertEqual(imp.format, None)
        self.assertEqual(imp.itemsize, 1)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.readonly)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
Beispiel #27
0
 def NEWBUF_export_check(self):
     freq, fmt, channels = mixer.get_init()
     if channels == 1:
         ndim = 1
     else:
         ndim = 2
     itemsize = abs(fmt) // 8
     formats = {8: 'B', -8: 'b',
                16: '=H', -16: '=h',
                32: '=I', -32: '=i',  # 32 and 64 for future consideration
                64: '=Q', -64: '=q'}
     format = formats[fmt]
     buftools = self.buftools
     Exporter = buftools.Exporter
     Importer = buftools.Importer
     is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
     fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
     shape = (10, channels)[:ndim]
     strides = (channels * itemsize, itemsize)[2 - ndim:]
     exp = Exporter(shape, format=frev + 'i')
     snd = mixer.Sound(array=exp)
     buflen = len(exp) * itemsize * channels
     imp = Importer(snd, buftools.PyBUF_SIMPLE)
     self.assertEqual(imp.ndim, 0)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertTrue(imp.shape is None)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_WRITABLE)
     self.assertEqual(imp.ndim, 0)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertTrue(imp.shape is None)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_FORMAT)
     self.assertEqual(imp.ndim, 0)
     self.assertEqual(imp.format, format)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertTrue(imp.shape is None)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_ND)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertEqual(imp.shape, shape)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_STRIDES)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertEqual(imp.shape, shape)
     self.assertEqual(imp.strides, strides)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_FULL_RO)
     self.assertEqual(imp.ndim, ndim)
     self.assertEqual(imp.format, format)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, 2)
     self.assertEqual(imp.shape, shape)
     self.assertEqual(imp.strides, strides)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_FULL_RO)
     self.assertEqual(imp.ndim, ndim)
     self.assertEqual(imp.format, format)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertEqual(imp.shape, exp.shape)
     self.assertEqual(imp.strides, strides)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_C_CONTIGUOUS)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.strides, strides)
     imp = Importer(snd, buftools.PyBUF_ANY_CONTIGUOUS)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.strides, strides)
     if (ndim == 1):
         imp = Importer(snd, buftools.PyBUF_F_CONTIGUOUS)
         self.assertEqual(imp.ndim, 1)
         self.assertTrue(imp.format is None)
         self.assertEqual(imp.strides, strides)
     else:
         self.assertRaises(BufferError, Importer, snd,
                           buftools.PyBUF_F_CONTIGUOUS)
def blit_array (surface, array):
    """pygame.numpyarray.blit_array (Surface, array): return None

    blit directly from a array values

    Directly copy values from an array into a Surface. This is faster
    than converting the array into a Surface and blitting. The array
    must be the same dimensions as the Surface and will completely
    replace all pixel values.

    This function will temporarily lock the Surface as the new values
    are copied.
    """
    bpp = surface.get_bytesize ()
    if bpp <= 0 or bpp > 4:
        raise ValueError("unsupported bit depth for surface")
    
    shape = array.shape
    width = surface.get_width ()

    typecode = (numpy.uint8, numpy.uint16, None, numpy.uint32)[bpp - 1]
    array = array.astype (typecode)

    # Taken from from Alex Holkner's pygame-ctypes package. Thanks a
    # lot.
    if len(shape) == 3 and shape[2] == 3:
        array = numpy.transpose (array, (1, 0, 2))
        shifts = surface.get_shifts ()
        losses = surface.get_losses ()
        array = (array[:,:,::3] >> losses[0] << shifts[0]) | \
                (array[:,:,1::3] >> losses[1] << shifts[1]) | \
                (array[:,:,2::3] >> losses[2] << shifts[2])
    elif len (shape) == 2:
        array = numpy.transpose (array)
    else:
        raise ValueError("must be a valid 2d or 3d array")

    if width != shape[0] or surface.get_height () != shape[1]:
        raise ValueError("array must match the surface dimensions")

    itemsize = array.itemsize
    data = array.tostring ()

    if itemsize > bpp:
        # Trim bytes from each element, keep least significant byte(s)
        pattern = '%s(%s)' % ('.' * (itemsize - bpp), '.' * bpp)
        if pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN:
            pattern = '(%s)%s' % ('.' * bpp, '.' * (itemsize - bpp))
        data = ''.join (re.compile (pattern, flags=re.DOTALL).findall (data))
    elif itemsize < bpp:
        # Add pad bytes to each element, at most significant end
        pad = '\0' * (bpp - itemsize)
        pixels = re.compile ('.' * itemsize, flags=re.DOTALL).findall (data)
        data = pad.join (pixels)
        if pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN:
            data = data + pad
        else:
            data = pad + data

    # Add zeros pad for pitch correction
    pitchdiff = surface.get_pitch () - width * bpp
    if pitchdiff > 0:
        pad = '\0' * pitchdiff
        rows = re.compile ('.' * width * bpp, flags=re.DOTALL).findall (data)
        data = pad.join (rows) + pad

    surface.get_buffer ().write (data, 0)
Beispiel #29
0
    def NEWBUF_test_PgDict_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
        buftools = self.buftools
        Importer = buftools.Importer
        a = BufferProxy({'typestr': '|u4',
                         'shape': (10, 2),
                         'data': (9, False)}) # 9? No data accesses.
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertEqual(b.shape, (10, 2))
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        a = BufferProxy({'typestr': fsys + 'i2',
                         'shape': (5, 10),
                         'strides': (24, 2),
                         'data': (42, False)}) # 42? No data accesses.
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 2)
        self.assertEqual(b.format, '=h')
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        a = BufferProxy({'typestr': frev + 'i2',
                         'shape': (3, 5, 10),
                         'strides': (120, 24, 2),
                         'data': (1000000, True)}) # 1000000? No data accesses.
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 3)
        self.assertEqual(b.format, frev + 'h')
        self.assertEqual(b.len, 300)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (3, 5, 10))
        self.assertEqual(b.strides, (120, 24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, 1000000)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
def blit_array(surface, array):
    """pygame.numpyarray.blit_array (Surface, array): return None

    blit directly from a array values

    Directly copy values from an array into a Surface. This is faster
    than converting the array into a Surface and blitting. The array
    must be the same dimensions as the Surface and will completely
    replace all pixel values.

    This function will temporarily lock the Surface as the new values
    are copied.
    """
    bpp = surface.get_bytesize()
    if bpp <= 0 or bpp > 4:
        raise ValueError("unsupported bit depth for surface")

    shape = array.shape
    width = surface.get_width()

    typecode = (numpy.uint8, numpy.uint16, None, numpy.uint32)[bpp - 1]
    array = array.astype(typecode)

    # Taken from from Alex Holkner's pygame-ctypes package. Thanks a
    # lot.
    if len(shape) == 3 and shape[2] == 3:
        array = numpy.transpose(array, (1, 0, 2))
        shifts = surface.get_shifts()
        losses = surface.get_losses()
        array = (array[:,:,::3] >> losses[0] << shifts[0]) | \
                (array[:,:,1::3] >> losses[1] << shifts[1]) | \
                (array[:,:,2::3] >> losses[2] << shifts[2])
    elif len(shape) == 2:
        array = numpy.transpose(array)
    else:
        raise ValueError("must be a valid 2d or 3d array")

    if width != shape[0] or surface.get_height() != shape[1]:
        raise ValueError("array must match the surface dimensions")

    itemsize = array.itemsize
    data = array.tostring()

    if itemsize > bpp:
        # Trim bytes from each element, keep least significant byte(s)
        pattern = '%s(%s)' % ('.' * (itemsize - bpp), '.' * bpp)
        if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
            pattern = '(%s)%s' % ('.' * bpp, '.' * (itemsize - bpp))
        data = ''.join(re.compile(pattern, flags=re.DOTALL).findall(data))
    elif itemsize < bpp:
        # Add pad bytes to each element, at most significant end
        pad = '\0' * (bpp - itemsize)
        pixels = re.compile('.' * itemsize, flags=re.DOTALL).findall(data)
        data = pad.join(pixels)
        if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
            data = data + pad
        else:
            data = pad + data

    # Add zeros pad for pitch correction
    pitchdiff = surface.get_pitch() - width * bpp
    if pitchdiff > 0:
        pad = '\0' * pitchdiff
        rows = re.compile('.' * width * bpp, flags=re.DOTALL).findall(data)
        data = pad.join(rows) + pad

    surface.get_buffer().write(data, 0)
Beispiel #31
0
import pygame as pg

pg.init()
try:
    raise pg.error("ASD")
except RuntimeError:
    print("RTE")

print(pg.get_sdl_version())
print(pg.get_sdl_byteorder())
Beispiel #32
0
    def NEWBUF_test_PgObject_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy
        import ctypes

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
        buftools = self.buftools
        Importer = buftools.Importer
        e = arrinter.Exporter((10, 2), typekind='f',
                              itemsize=ctypes.sizeof(ctypes.c_double))
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, e.nd)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        e = arrinter.Exporter((5, 10), typekind='i', itemsize=2,
                              strides=(24, 2))
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, e.nd)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, e.nd)
        self.assertEqual(b.format, '=h')
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_WRITABLE)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_WRITABLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        e = arrinter.Exporter((3, 5, 10), typekind='i', itemsize=2,
                              strides=(120, 24, 2),
                              flags=arrinter.PAI_ALIGNED)
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, e.nd)
        self.assertEqual(b.format, frev + 'h')
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, e.data)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
 def NEWBUF_export_check(self):
     freq, fmt, channels = mixer.get_init()
     if channels == 1:
         ndim = 1
     else:
         ndim = 2
     itemsize = abs(fmt) // 8
     formats = {
         8: 'B',
         -8: 'b',
         16: '=H',
         -16: '=h',
         32: '=I',
         -32: '=i',  # 32 and 64 for future consideration
         64: '=Q',
         -64: '=q'
     }
     format = formats[fmt]
     buftools = self.buftools
     Exporter = buftools.Exporter
     Importer = buftools.Importer
     is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
     fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
     shape = (10, channels)[:ndim]
     strides = (channels * itemsize, itemsize)[2 - ndim:]
     exp = Exporter(shape, format=frev + 'i')
     snd = mixer.Sound(array=exp)
     buflen = len(exp) * itemsize * channels
     imp = Importer(snd, buftools.PyBUF_SIMPLE)
     self.assertEqual(imp.ndim, 0)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertTrue(imp.shape is None)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_WRITABLE)
     self.assertEqual(imp.ndim, 0)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertTrue(imp.shape is None)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_FORMAT)
     self.assertEqual(imp.ndim, 0)
     self.assertEqual(imp.format, format)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertTrue(imp.shape is None)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_ND)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertEqual(imp.shape, shape)
     self.assertTrue(imp.strides is None)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_STRIDES)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertEqual(imp.shape, shape)
     self.assertEqual(imp.strides, strides)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_FULL_RO)
     self.assertEqual(imp.ndim, ndim)
     self.assertEqual(imp.format, format)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, 2)
     self.assertEqual(imp.shape, shape)
     self.assertEqual(imp.strides, strides)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_FULL_RO)
     self.assertEqual(imp.ndim, ndim)
     self.assertEqual(imp.format, format)
     self.assertEqual(imp.len, buflen)
     self.assertEqual(imp.itemsize, itemsize)
     self.assertEqual(imp.shape, exp.shape)
     self.assertEqual(imp.strides, strides)
     self.assertTrue(imp.suboffsets is None)
     self.assertFalse(imp.readonly)
     self.assertEqual(imp.buf, snd._samples_address)
     imp = Importer(snd, buftools.PyBUF_C_CONTIGUOUS)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.strides, strides)
     imp = Importer(snd, buftools.PyBUF_ANY_CONTIGUOUS)
     self.assertEqual(imp.ndim, ndim)
     self.assertTrue(imp.format is None)
     self.assertEqual(imp.strides, strides)
     if (ndim == 1):
         imp = Importer(snd, buftools.PyBUF_F_CONTIGUOUS)
         self.assertEqual(imp.ndim, 1)
         self.assertTrue(imp.format is None)
         self.assertEqual(imp.strides, strides)
     else:
         self.assertRaises(BufferError, Importer, snd,
                           buftools.PyBUF_F_CONTIGUOUS)
Beispiel #34
0
    def _NEWBUF_export_check(self):
        freq, fmt, channels = mixer.get_init()
        ndim = 1 if (channels == 1) else 2
        itemsize = abs(fmt) // 8
        formats = {
            8: "B",
            -8: "b",
            16: "=H",
            -16: "=h",
            32: "=I",
            -32: "=i",  # 32 and 64 for future consideration
            64: "=Q",
            -64: "=q",
        }
        format = formats[fmt]
        from pygame.tests.test_utils import buftools

        Exporter = buftools.Exporter
        Importer = buftools.Importer
        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ("<", ">") if is_lil_endian else (">", "<")
        shape = (10, channels)[:ndim]
        strides = (channels * itemsize, itemsize)[2 - ndim:]
        exp = Exporter(shape, format=frev + "i")
        snd = mixer.Sound(array=exp)
        buflen = len(exp) * itemsize * channels
        imp = Importer(snd, buftools.PyBUF_SIMPLE)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.format is None)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, itemsize)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_WRITABLE)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.format is None)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, itemsize)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_FORMAT)
        self.assertEqual(imp.ndim, 0)
        self.assertEqual(imp.format, format)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, itemsize)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_ND)
        self.assertEqual(imp.ndim, ndim)
        self.assertTrue(imp.format is None)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, itemsize)
        self.assertEqual(imp.shape, shape)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_STRIDES)
        self.assertEqual(imp.ndim, ndim)
        self.assertTrue(imp.format is None)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, itemsize)
        self.assertEqual(imp.shape, shape)
        self.assertEqual(imp.strides, strides)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_FULL_RO)
        self.assertEqual(imp.ndim, ndim)
        self.assertEqual(imp.format, format)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, 2)
        self.assertEqual(imp.shape, shape)
        self.assertEqual(imp.strides, strides)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_FULL_RO)
        self.assertEqual(imp.ndim, ndim)
        self.assertEqual(imp.format, format)
        self.assertEqual(imp.len, buflen)
        self.assertEqual(imp.itemsize, itemsize)
        self.assertEqual(imp.shape, exp.shape)
        self.assertEqual(imp.strides, strides)
        self.assertTrue(imp.suboffsets is None)
        self.assertFalse(imp.readonly)
        self.assertEqual(imp.buf, snd._samples_address)
        imp = Importer(snd, buftools.PyBUF_C_CONTIGUOUS)
        self.assertEqual(imp.ndim, ndim)
        self.assertTrue(imp.format is None)
        self.assertEqual(imp.strides, strides)
        imp = Importer(snd, buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertEqual(imp.ndim, ndim)
        self.assertTrue(imp.format is None)
        self.assertEqual(imp.strides, strides)
        if ndim == 1:
            imp = Importer(snd, buftools.PyBUF_F_CONTIGUOUS)
            self.assertEqual(imp.ndim, 1)
            self.assertTrue(imp.format is None)
            self.assertEqual(imp.strides, strides)
        else:
            self.assertRaises(BufferError, Importer, snd,
                              buftools.PyBUF_F_CONTIGUOUS)
Beispiel #35
0
    def test_PgDict_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ("<", ">") if is_lil_endian else (">", "<")
        buftools = self.buftools
        Importer = buftools.Importer
        a = BufferProxy({
            "typestr": "|u4",
            "shape": (10, 2),
            "data": (9, False)
        })  # 9? No data accesses.
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertEqual(b.shape, (10, 2))
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        a = BufferProxy({
            "typestr": fsys + "i2",
            "shape": (5, 10),
            "strides": (24, 2),
            "data": (42, False),
        })  # 42? No data accesses.
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 2)
        self.assertEqual(b.format, "=h")
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        a = BufferProxy({
            "typestr": frev + "i2",
            "shape": (3, 5, 10),
            "strides": (120, 24, 2),
            "data": (1000000, True),
        })  # 1000000? No data accesses.
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 3)
        self.assertEqual(b.format, frev + "h")
        self.assertEqual(b.len, 300)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (3, 5, 10))
        self.assertEqual(b.strides, (120, 24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, 1000000)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
Beispiel #36
0
    def NEWBUF_test_PgObject_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy
        import ctypes

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
        buftools = self.buftools
        Importer = buftools.Importer
        e = arrinter.Exporter((10, 2),
                              typekind='f',
                              itemsize=ctypes.sizeof(ctypes.c_double))
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, e.nd)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        e = arrinter.Exporter((5, 10),
                              typekind='i',
                              itemsize=2,
                              strides=(24, 2))
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, e.nd)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, e.nd)
        self.assertEqual(b.format, '=h')
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_WRITABLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_WRITABLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        e = arrinter.Exporter((3, 5, 10),
                              typekind='i',
                              itemsize=2,
                              strides=(120, 24, 2),
                              flags=arrinter.PAI_ALIGNED)
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, e.nd)
        self.assertEqual(b.format, frev + 'h')
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, e.data)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
    def NEWBUF_test_newbuf(self):
        from ctypes import string_at

        from pygame.tests.test_utils import buftools
        Exporter = buftools.Exporter
        Importer = buftools.Importer
        exp = Exporter((10, ), 'B', readonly=True)
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            self.assertEqual(d['typestr'], '|u1')
            self.assertEqual(d['shape'], exp.shape)
            self.assertEqual(d['strides'], exp.strides)
            self.assertEqual(d['data'], (exp.buf, True))
        finally:
            d = None
        exp = Exporter((3, ), '=h')
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
            f = '{}i{}'.format('<' if lil_endian else '>', exp.itemsize)
            self.assertEqual(d['typestr'], f)
            self.assertEqual(d['shape'], exp.shape)
            self.assertEqual(d['strides'], exp.strides)
            self.assertEqual(d['data'], (exp.buf, False))
        finally:
            d = None

        exp = Exporter((10, 2), '=i')
        b = BufferProxy(exp)
        imp = Importer(b, buftools.PyBUF_RECORDS)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, exp.buf)
        self.assertEqual(imp.ndim, exp.ndim)
        self.assertEqual(imp.format, exp.format)
        self.assertEqual(imp.readonly, exp.readonly)
        self.assertEqual(imp.itemsize, exp.itemsize)
        self.assertEqual(imp.len, exp.len)
        self.assertEqual(imp.shape, exp.shape)
        self.assertEqual(imp.strides, exp.strides)
        self.assertTrue(imp.suboffsets is None)

        d = {
            'typestr': '|u1',
            'shape': (10, ),
            'strides': (1, ),
            'data': (9, True)
        }  # 9? Will not reading the data anyway.
        b = BufferProxy(d)
        imp = Importer(b, buftools.PyBUF_SIMPLE)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, 9)
        self.assertEqual(imp.len, 10)
        self.assertEqual(imp.format, None)
        self.assertEqual(imp.itemsize, 1)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.readonly)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
Beispiel #38
0
    def NEWBUF_test_PgDict_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
        buftools = self.buftools
        Importer = buftools.Importer
        a = BufferProxy({
            'typestr': '|u4',
            'shape': (10, 2),
            'data': (9, False)
        })  # 9? No data accesses.
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertEqual(b.shape, (10, 2))
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        a = BufferProxy({
            'typestr': fsys + 'i2',
            'shape': (5, 10),
            'strides': (24, 2),
            'data': (42, False)
        })  # 42? No data accesses.
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 2)
        self.assertEqual(b.format, '=h')
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        a = BufferProxy({
            'typestr': frev + 'i2',
            'shape': (3, 5, 10),
            'strides': (120, 24, 2),
            'data': (1000000, True)
        })  # 1000000? No data accesses.
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 3)
        self.assertEqual(b.format, frev + 'h')
        self.assertEqual(b.len, 300)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (3, 5, 10))
        self.assertEqual(b.strides, (120, 24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, 1000000)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)