~pygame/pygame/trunk

« back to all changes in this revision

Viewing changes to test/surfarray_test.py

  • Committer: pygame
  • Date: 2017-01-10 00:31:42 UTC
  • Revision ID: git-v1:2eea4f299a2e791f884608d7ed601558634af73c
commit 1639c41a8cb3433046882ede92c80ce69d59016b
Author: Thomas Kluyver <takowl@gmail.com>
Date:   Sun Jan 8 18:46:46 2017 +0000

    Build newer versions of libogg and libvorbis into Linux base images

    Closes #317
    Closes #323

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
if __name__ == '__main__':
 
2
    import sys
 
3
    import os
 
4
    pkg_dir = os.path.split(os.path.abspath(__file__))[0]
 
5
    parent_dir, pkg_name = os.path.split(pkg_dir)
 
6
    is_pygame_pkg = (pkg_name == 'tests' and
 
7
                     os.path.split(parent_dir)[1] == 'pygame')
 
8
    if not is_pygame_pkg:
 
9
        sys.path.insert(0, parent_dir)
 
10
else:
 
11
    is_pygame_pkg = __name__.startswith('pygame.tests.')
 
12
 
 
13
import unittest
 
14
import pygame
 
15
from pygame.locals import *
 
16
 
 
17
 
 
18
import pygame.surfarray
 
19
from numpy import \
 
20
    uint8, uint16, uint32, uint64, zeros, \
 
21
    float32, float64, alltrue, rint, arange
 
22
arraytype = 'numpy'
 
23
 
 
24
class SurfarrayModuleTest (unittest.TestCase):
 
25
 
 
26
    pixels2d = {8: True, 16: True, 24: False, 32: True}
 
27
    pixels3d = {8: False, 16: False, 24: True, 32: True}
 
28
    array2d = {8: True, 16: True, 24: True, 32: True}
 
29
    array3d = {8: False, 16: False, 24: True, 32: True}
 
30
 
 
31
    test_palette = [(0, 0, 0, 255),
 
32
                    (10, 30, 60, 255),
 
33
                    (25, 75, 100, 255),
 
34
                    (100, 150, 200, 255),
 
35
                    (0, 100, 200, 255)]
 
36
    surf_size = (10, 12)
 
37
    test_points = [((0, 0), 1), ((4, 5), 1), ((9, 0), 2),
 
38
                   ((5, 5), 2), ((0, 11), 3), ((4, 6), 3),
 
39
                   ((9, 11), 4), ((5, 6), 4)]
 
40
 
 
41
    def _make_surface(self, bitsize, srcalpha=False, palette=None):
 
42
        if palette is None:
 
43
            palette = self.test_palette
 
44
        flags = 0
 
45
        if srcalpha:
 
46
            flags |= SRCALPHA
 
47
        surf = pygame.Surface(self.surf_size, flags, bitsize)
 
48
        if bitsize == 8:
 
49
            surf.set_palette([c[:3] for c in palette])
 
50
        return surf
 
51
 
 
52
    def _fill_surface(self, surf, palette=None):
 
53
        if palette is None:
 
54
            palette = self.test_palette
 
55
        surf.fill(palette[1], (0, 0, 5, 6))
 
56
        surf.fill(palette[2], (5, 0, 5, 6))
 
57
        surf.fill(palette[3], (0, 6, 5, 6))
 
58
        surf.fill(palette[4], (5, 6, 5, 6))
 
59
 
 
60
    def _make_src_surface(self, bitsize, srcalpha=False, palette=None):
 
61
        surf = self._make_surface(bitsize, srcalpha, palette)
 
62
        self._fill_surface(surf, palette)
 
63
        return surf
 
64
 
 
65
    def _assert_surface(self, surf, palette=None, msg=""):
 
66
        if palette is None:
 
67
            palette = self.test_palette
 
68
        if surf.get_bitsize() == 16:
 
69
            palette = [surf.unmap_rgb(surf.map_rgb(c)) for c in palette]
 
70
        for posn, i in self.test_points:
 
71
            self.failUnlessEqual(surf.get_at(posn), palette[i],
 
72
                                 "%s != %s: flags: %i, bpp: %i, posn: %s%s" %
 
73
                                 (surf.get_at(posn),
 
74
                                  palette[i], surf.get_flags(),
 
75
                                  surf.get_bitsize(), posn, msg))
 
76
 
 
77
    def _make_array3d(self, dtype):
 
78
        return zeros((self.surf_size[0], self.surf_size[1], 3), dtype)
 
79
 
 
80
    def _fill_array2d(self, arr, surf):
 
81
        palette = self.test_palette
 
82
        arr[:5,:6] = surf.map_rgb(palette[1])
 
83
        arr[5:,:6] = surf.map_rgb(palette[2])
 
84
        arr[:5,6:] = surf.map_rgb(palette[3])
 
85
        arr[5:,6:] = surf.map_rgb(palette[4])
 
86
 
 
87
    def _fill_array3d(self, arr):
 
88
        palette = self.test_palette
 
89
        arr[:5,:6] = palette[1][:3]
 
90
        arr[5:,:6] = palette[2][:3]
 
91
        arr[:5,6:] = palette[3][:3]
 
92
        arr[5:,6:] = palette[4][:3]
 
93
 
 
94
    def _make_src_array3d(self, dtype):
 
95
        arr = self._make_array3d(dtype)
 
96
        self._fill_array3d(arr)
 
97
        return arr
 
98
 
 
99
    def _make_array2d(self, dtype):
 
100
        return zeros(self.surf_size, dtype)
 
101
 
 
102
    def setUp(self):
 
103
        # Needed for 8 bits-per-pixel color palette surface tests.
 
104
        pygame.init()
 
105
 
 
106
        # Makes sure the same array package is used each time.
 
107
        if arraytype:
 
108
            pygame.surfarray.use_arraytype(arraytype)
 
109
 
 
110
    def tearDown(self):
 
111
        pygame.quit()
 
112
 
 
113
    def test_array2d(self):
 
114
        if not arraytype:
 
115
            self.fail("no array package installed")
 
116
 
 
117
        sources = [self._make_src_surface(8),
 
118
                   self._make_src_surface(16),
 
119
                   self._make_src_surface(16, srcalpha=True),
 
120
                   self._make_src_surface(24),
 
121
                   self._make_src_surface(32),
 
122
                   self._make_src_surface(32, srcalpha=True)]
 
123
        palette = self.test_palette
 
124
        alpha_color = (0, 0, 0, 128)
 
125
 
 
126
        for surf in sources:
 
127
            arr = pygame.surfarray.array2d(surf)
 
128
            for posn, i in self.test_points:
 
129
                self.failUnlessEqual(arr[posn], surf.get_at_mapped(posn),
 
130
                                     "%s != %s: flags: %i, bpp: %i, posn: %s" %
 
131
                                     (arr[posn],
 
132
                                      surf.get_at_mapped(posn),
 
133
                                      surf.get_flags(), surf.get_bitsize(),
 
134
                                      posn))
 
135
 
 
136
            if surf.get_masks()[3]:
 
137
                surf.fill(alpha_color)
 
138
                arr = pygame.surfarray.array2d(surf)
 
139
                posn = (0, 0)
 
140
                self.failUnlessEqual(arr[posn], surf.get_at_mapped(posn),
 
141
                                     "%s != %s: bpp: %i" %
 
142
                                     (arr[posn],
 
143
                                      surf.get_at_mapped(posn),
 
144
                                      surf.get_bitsize()))
 
145
 
 
146
    def test_array3d(self):
 
147
        if not arraytype:
 
148
            self.fail("no array package installed")
 
149
 
 
150
        sources = [self._make_src_surface(16),
 
151
                   self._make_src_surface(16, srcalpha=True),
 
152
                   self._make_src_surface(24),
 
153
                   self._make_src_surface(32),
 
154
                   self._make_src_surface(32, srcalpha=True)]
 
155
        palette = self.test_palette
 
156
 
 
157
        for surf in sources:
 
158
            arr = pygame.surfarray.array3d(surf)
 
159
            def same_color(ac, sc):
 
160
                return (ac[0] == sc[0] and
 
161
                        ac[1] == sc[1] and
 
162
                        ac[2] == sc[2])
 
163
            for posn, i in self.test_points:
 
164
                self.failUnless(same_color(arr[posn], surf.get_at(posn)),
 
165
                                "%s != %s: flags: %i, bpp: %i, posn: %s" %
 
166
                                (tuple(arr[posn]),
 
167
                                 surf.get_at(posn),
 
168
                                 surf.get_flags(), surf.get_bitsize(),
 
169
                                 posn))
 
170
 
 
171
    def test_array_alpha(self):
 
172
        if not arraytype:
 
173
            self.fail("no array package installed")
 
174
 
 
175
        palette = [(0, 0, 0, 0),
 
176
                   (10, 50, 100, 255),
 
177
                   (60, 120, 240, 130),
 
178
                   (64, 128, 255, 0),
 
179
                   (255, 128, 0, 65)]
 
180
        targets = [self._make_src_surface(8, palette=palette),
 
181
                   self._make_src_surface(16, palette=palette),
 
182
                   self._make_src_surface(16, palette=palette, srcalpha=True),
 
183
                   self._make_src_surface(24, palette=palette),
 
184
                   self._make_src_surface(32, palette=palette),
 
185
                   self._make_src_surface(32, palette=palette, srcalpha=True)]
 
186
 
 
187
        for surf in targets:
 
188
            p = palette
 
189
            if surf.get_bitsize() == 16:
 
190
                p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
 
191
            arr = pygame.surfarray.array_alpha(surf)
 
192
            if surf.get_masks()[3]:
 
193
                for (x, y), i in self.test_points:
 
194
                    self.failUnlessEqual(arr[x, y], p[i][3],
 
195
                                         ("%i != %i, posn: (%i, %i), "
 
196
                                          "bitsize: %i" %
 
197
                                          (arr[x, y], p[i][3],
 
198
                                           x, y,
 
199
                                           surf.get_bitsize())))
 
200
            else:
 
201
                self.failUnless(alltrue(arr == 255))
 
202
 
 
203
        # No per-pixel alpha when blanket alpha is None.
 
204
        for surf in targets:
 
205
            blacket_alpha = surf.get_alpha()
 
206
            surf.set_alpha(None)
 
207
            arr = pygame.surfarray.array_alpha(surf)
 
208
            self.failUnless(alltrue(arr == 255),
 
209
                            "bitsize: %i, flags: %i" %
 
210
                            (surf.get_bitsize(), surf.get_flags()))
 
211
            surf.set_alpha(blacket_alpha)
 
212
 
 
213
        # Bug for per-pixel alpha surface when blanket alpha 0.
 
214
        for surf in targets:
 
215
            blanket_alpha = surf.get_alpha()
 
216
            surf.set_alpha(0)
 
217
            arr = pygame.surfarray.array_alpha(surf)
 
218
            if surf.get_masks()[3]:
 
219
                self.failIf(alltrue(arr == 255),
 
220
                            "bitsize: %i, flags: %i" %
 
221
                            (surf.get_bitsize(), surf.get_flags()))
 
222
            else:
 
223
                self.failUnless(alltrue(arr == 255),
 
224
                                "bitsize: %i, flags: %i" %
 
225
                                (surf.get_bitsize(), surf.get_flags()))
 
226
            surf.set_alpha(blanket_alpha)
 
227
 
 
228
    def test_array_colorkey(self):
 
229
        if not arraytype:
 
230
            self.fail("no array package installed")
 
231
 
 
232
        palette = [(0, 0, 0, 0),
 
233
                   (10, 50, 100, 255),
 
234
                   (60, 120, 240, 130),
 
235
                   (64, 128, 255, 0),
 
236
                   (255, 128, 0, 65)]
 
237
        targets = [self._make_src_surface(8, palette=palette),
 
238
                   self._make_src_surface(16, palette=palette),
 
239
                   self._make_src_surface(16, palette=palette, srcalpha=True),
 
240
                   self._make_src_surface(24, palette=palette),
 
241
                   self._make_src_surface(32, palette=palette),
 
242
                   self._make_src_surface(32, palette=palette, srcalpha=True)]
 
243
 
 
244
        for surf in targets:
 
245
            p = palette
 
246
            if surf.get_bitsize() == 16:
 
247
                p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
 
248
            surf.set_colorkey(None)
 
249
            arr = pygame.surfarray.array_colorkey(surf)
 
250
            self.failUnless(alltrue(arr == 255))
 
251
            for i in range(1, len(palette)):
 
252
                surf.set_colorkey(p[i])
 
253
                alphas = [255] * len(p)
 
254
                alphas[i] = 0
 
255
                arr = pygame.surfarray.array_colorkey(surf)
 
256
                for (x, y), j in self.test_points:
 
257
                    self.failUnlessEqual(arr[x, y], alphas[j],
 
258
                                         ("%i != %i, posn: (%i, %i), "
 
259
                                          "bitsize: %i" %
 
260
                                          (arr[x, y], alphas[j],
 
261
                                           x, y,
 
262
                                           surf.get_bitsize())))
 
263
 
 
264
    def test_blit_array(self):
 
265
        if not arraytype:
 
266
            self.fail("no array package installed")
 
267
 
 
268
        # bug 24 at http://pygame.motherhamster.org/bugzilla/
 
269
        if 'numpy' in pygame.surfarray.get_arraytypes():
 
270
            prev = pygame.surfarray.get_arraytype()
 
271
            # This would raise exception:
 
272
            #  File "[...]\pygame\_numpysurfarray.py", line 381, in blit_array
 
273
            #    (array[:,:,1::3] >> losses[1] << shifts[1]) | \
 
274
            # TypeError: unsupported operand type(s) for >>: 'float' and 'int'
 
275
            pygame.surfarray.use_arraytype('numpy')
 
276
            s = pygame.Surface((10,10), 0, 24)
 
277
            a = pygame.surfarray.array3d(s)
 
278
            pygame.surfarray.blit_array(s, a)
 
279
            prev = pygame.surfarray.use_arraytype(prev)
 
280
 
 
281
        # target surfaces
 
282
        targets = [self._make_surface(8),
 
283
                   self._make_surface(16),
 
284
                   self._make_surface(16, srcalpha=True),
 
285
                   self._make_surface(24),
 
286
                   self._make_surface(32),
 
287
                   self._make_surface(32, srcalpha=True),
 
288
                   ]
 
289
        
 
290
        # source arrays
 
291
        arrays3d = []
 
292
        dtypes = [(8, uint8), (16, uint16), (32, uint32)]
 
293
        try:
 
294
            dtypes.append((64, uint64))
 
295
        except NameError:
 
296
            pass
 
297
        arrays3d = [(self._make_src_array3d(dtype), None)
 
298
                    for __, dtype in dtypes]
 
299
        for bitsize in [8, 16, 24, 32]:
 
300
            palette = None
 
301
            if bitsize == 16:
 
302
                s = pygame.Surface((1,1), 0, 16)
 
303
                palette = [s.unmap_rgb(s.map_rgb(c))
 
304
                           for c in self.test_palette]
 
305
            if self.pixels3d[bitsize]:
 
306
                surf = self._make_src_surface(bitsize)
 
307
                arr = pygame.surfarray.pixels3d(surf)
 
308
                arrays3d.append((arr, palette))
 
309
            if self.array3d[bitsize]:
 
310
                surf = self._make_src_surface(bitsize)
 
311
                arr = pygame.surfarray.array3d(surf)
 
312
                arrays3d.append((arr, palette))
 
313
                for sz, dtype in dtypes:
 
314
                    arrays3d.append((arr.astype(dtype), palette))
 
315
 
 
316
        # tests on arrays
 
317
        def do_blit(surf, arr):
 
318
            pygame.surfarray.blit_array(surf, arr)
 
319
 
 
320
        for surf in targets:
 
321
            bitsize = surf.get_bitsize()
 
322
            for arr, palette in arrays3d:
 
323
                surf.fill((0, 0, 0, 0))
 
324
                if bitsize == 8:
 
325
                    self.failUnlessRaises(ValueError, do_blit, surf, arr)
 
326
                else:
 
327
                    pygame.surfarray.blit_array(surf, arr)
 
328
                    self._assert_surface(surf, palette)
 
329
 
 
330
            if self.pixels2d[bitsize]:
 
331
                surf.fill((0, 0, 0, 0))
 
332
                s = self._make_src_surface(bitsize, surf.get_flags() & SRCALPHA)
 
333
                arr = pygame.surfarray.pixels2d(s)
 
334
                pygame.surfarray.blit_array(surf, arr)
 
335
                self._assert_surface(surf)
 
336
 
 
337
            if self.array2d[bitsize]:
 
338
                s = self._make_src_surface(bitsize, surf.get_flags() & SRCALPHA)
 
339
                arr = pygame.surfarray.array2d(s)
 
340
                for sz, dtype in dtypes:
 
341
                    surf.fill((0, 0, 0, 0))
 
342
                    if sz >= bitsize:
 
343
                        pygame.surfarray.blit_array(surf, arr.astype(dtype))
 
344
                        self._assert_surface(surf)
 
345
                    else:
 
346
                        self.failUnlessRaises(ValueError, do_blit,
 
347
                                              surf, self._make_array2d(dtype))
 
348
 
 
349
        # Check alpha for 2D arrays
 
350
        surf = self._make_surface(16, srcalpha=True)
 
351
        arr = zeros(surf.get_size(), uint16)
 
352
        arr[...] = surf.map_rgb((0, 128, 255, 64))
 
353
        color = surf.unmap_rgb(arr[0, 0])
 
354
        pygame.surfarray.blit_array(surf, arr)
 
355
        self.failUnlessEqual(surf.get_at((5, 5)), color)
 
356
 
 
357
        surf = self._make_surface(32, srcalpha=True)
 
358
        arr = zeros(surf.get_size(), uint32)
 
359
        color = (0, 111, 255, 63)
 
360
        arr[...] = surf.map_rgb(color)
 
361
        pygame.surfarray.blit_array(surf, arr)
 
362
        self.failUnlessEqual(surf.get_at((5, 5)), color)
 
363
 
 
364
        # Check shifts
 
365
        arr3d = self._make_src_array3d(uint8)
 
366
 
 
367
        shift_tests = [(16,
 
368
                        [12, 0, 8, 4],
 
369
                        [0xf000, 0xf, 0xf00, 0xf0]),
 
370
                       (24,
 
371
                        [16, 0, 8, 0],
 
372
                        [0xff0000, 0xff, 0xff00, 0]),
 
373
                       (32,
 
374
                        [0, 16, 24, 8],
 
375
                        [0xff, 0xff0000, 0xff000000, 0xff00])]
 
376
 
 
377
        for bitsize, shifts, masks in shift_tests:
 
378
            surf = self._make_surface(bitsize, srcalpha=(shifts[3] != 0))
 
379
            palette = None
 
380
            if bitsize == 16:
 
381
                palette = [surf.unmap_rgb(surf.map_rgb(c))
 
382
                           for c in self.test_palette]
 
383
            surf.set_shifts(shifts)
 
384
            surf.set_masks(masks)
 
385
            pygame.surfarray.blit_array(surf, arr3d)
 
386
            self._assert_surface(surf, palette)
 
387
 
 
388
        # Invalid arrays
 
389
        surf = pygame.Surface((1,1), 0, 32)
 
390
        t = 'abcd'
 
391
        self.failUnlessRaises(ValueError, do_blit, surf, t)
 
392
 
 
393
        surf_size = self.surf_size
 
394
        surf = pygame.Surface(surf_size, 0, 32)
 
395
        arr = zeros([surf_size[0], surf_size[1] + 1, 3], uint32)
 
396
        self.failUnlessRaises(ValueError, do_blit, surf, arr)
 
397
        arr = zeros([surf_size[0] + 1, surf_size[1], 3], uint32)
 
398
        self.failUnlessRaises(ValueError, do_blit, surf, arr)
 
399
 
 
400
        surf = pygame.Surface((1, 4), 0, 32)
 
401
        arr = zeros((4,), uint32)
 
402
        self.failUnlessRaises(ValueError, do_blit, surf, arr)
 
403
        arr.shape = (1, 1, 1, 4)
 
404
        self.failUnlessRaises(ValueError, do_blit, surf, arr)
 
405
 
 
406
        # Issue #81: round from float to int
 
407
        try:
 
408
            rint
 
409
        except NameError:
 
410
            pass
 
411
        else:
 
412
            surf = pygame.Surface((10, 10), pygame.SRCALPHA, 32)
 
413
            w, h = surf.get_size()
 
414
            length = w * h
 
415
            for dtype in [float32, float64]:
 
416
                surf.fill((255, 255, 255, 0))
 
417
                farr = arange(0, length, dtype=dtype)
 
418
                farr.shape = w, h
 
419
                pygame.surfarray.blit_array(surf, farr)
 
420
                for x in range(w):
 
421
                    for y in range(h):
 
422
                        self.assertEqual(surf.get_at_mapped((x, y)),
 
423
                                         int(rint(farr[x, y])))
 
424
            
 
425
    def test_get_arraytype(self):
 
426
        if not arraytype:
 
427
            self.fail("no array package installed")
 
428
 
 
429
        self.failUnless((pygame.surfarray.get_arraytype() in
 
430
                         ['numpy']),
 
431
                        ("unknown array type %s" %
 
432
                         pygame.surfarray.get_arraytype()))
 
433
 
 
434
    def test_get_arraytypes(self):
 
435
        if not arraytype:
 
436
            self.fail("no array package installed")
 
437
 
 
438
        arraytypes = pygame.surfarray.get_arraytypes()
 
439
        self.failUnless('numpy' in arraytypes)
 
440
 
 
441
        for atype in arraytypes:
 
442
            self.failUnless(atype in ['numpy'],
 
443
                            "unknown array type %s" % atype)
 
444
 
 
445
    def test_make_surface(self):
 
446
        if not arraytype:
 
447
            self.fail("no array package installed")
 
448
 
 
449
        # How does one properly test this with 2d arrays. It makes no sense
 
450
        # since the pixel format is not entirely dependent on element size.
 
451
        # Just make sure the surface pixel size is at least as large as the
 
452
        # array element size I guess.
 
453
        #
 
454
        for bitsize, dtype in [(8, uint8), (16, uint16), (24, uint32)]:
 
455
## Even this simple assertion fails for 2d arrays. Where's the problem?
 
456
##            surf = pygame.surfarray.make_surface(self._make_array2d(dtype))
 
457
##            self.failUnless(surf.get_bitsize() >= bitsize,
 
458
##                            "not %i >= %i)" % (surf.get_bitsize(), bitsize))
 
459
##
 
460
            surf = pygame.surfarray.make_surface(self._make_src_array3d(dtype))
 
461
            self._assert_surface(surf)
 
462
 
 
463
        # Issue #81: round from float to int
 
464
        try:
 
465
            rint
 
466
        except NameError:
 
467
            pass
 
468
        else:
 
469
            w = 9
 
470
            h = 11
 
471
            length = w * h
 
472
            for dtype in [float32, float64]:
 
473
                farr = arange(0, length, dtype=dtype)
 
474
                farr.shape = w, h
 
475
                surf = pygame.surfarray.make_surface(farr)
 
476
                for x in range(w):
 
477
                    for y in range(h):
 
478
                        self.assertEqual(surf.get_at_mapped((x, y)),
 
479
                                         int(rint(farr[x, y])))
 
480
            
 
481
    def test_map_array(self):
 
482
        if not arraytype:
 
483
            self.fail("no array package installed")
 
484
 
 
485
        arr3d = self._make_src_array3d(uint8)
 
486
        targets = [self._make_surface(8),
 
487
                   self._make_surface(16),
 
488
                   self._make_surface(16, srcalpha=True),
 
489
                   self._make_surface(24),
 
490
                   self._make_surface(32),
 
491
                   self._make_surface(32, srcalpha=True)]
 
492
        palette = self.test_palette
 
493
 
 
494
        for surf in targets:
 
495
            arr2d = pygame.surfarray.map_array(surf, arr3d)
 
496
            for posn, i in self.test_points:
 
497
                self.failUnlessEqual(arr2d[posn], surf.map_rgb(palette[i]),
 
498
                                     "%i != %i, bitsize: %i, flags: %i" %
 
499
                                     (arr2d[posn], surf.map_rgb(palette[i]),
 
500
                                      surf.get_bitsize(), surf.get_flags()))
 
501
 
 
502
        # Exception checks
 
503
        self.failUnlessRaises(ValueError, pygame.surfarray.map_array,
 
504
                              self._make_surface(32),
 
505
                              self._make_array2d(uint8))
 
506
 
 
507
    def test_pixels2d(self):
 
508
        if not arraytype:
 
509
            self.fail("no array package installed")
 
510
 
 
511
        sources = [self._make_surface(8),
 
512
                   self._make_surface(16, srcalpha=True),
 
513
                   self._make_surface(32, srcalpha=True)]
 
514
 
 
515
        for surf in sources:
 
516
            self.failIf(surf.get_locked())
 
517
            arr = pygame.surfarray.pixels2d(surf)
 
518
            self.failUnless(surf.get_locked())
 
519
            self._fill_array2d(arr, surf)
 
520
            surf.unlock()
 
521
            self.failUnless(surf.get_locked())
 
522
            del arr
 
523
            self.failIf(surf.get_locked())
 
524
            self.failUnlessEqual(surf.get_locks(), ())
 
525
            self._assert_surface(surf)
 
526
 
 
527
        # Error checks
 
528
        self.failUnlessRaises(ValueError,
 
529
                              pygame.surfarray.pixels2d,
 
530
                              self._make_surface(24))
 
531
 
 
532
    def test_pixels3d(self):
 
533
        if not arraytype:
 
534
            self.fail("no array package installed")
 
535
 
 
536
        sources = [self._make_surface(24),
 
537
                   self._make_surface(32)]
 
538
 
 
539
        for surf in sources:
 
540
            self.failIf(surf.get_locked())
 
541
            arr = pygame.surfarray.pixels3d(surf)
 
542
            self.failUnless(surf.get_locked())
 
543
            self._fill_array3d(arr)
 
544
            surf.unlock()
 
545
            self.failUnless(surf.get_locked())
 
546
            del arr
 
547
            self.failIf(surf.get_locked())
 
548
            self.failUnlessEqual(surf.get_locks(), ())
 
549
            self._assert_surface(surf)
 
550
 
 
551
        # Alpha check
 
552
        color = (1, 2, 3, 0)
 
553
        surf = self._make_surface(32, srcalpha=True)
 
554
        arr = pygame.surfarray.pixels3d(surf)
 
555
        arr[0,0] = color[:3]
 
556
        self.failUnlessEqual(surf.get_at((0, 0)), color)
 
557
 
 
558
        # Error checks
 
559
        def do_pixels3d(surf):
 
560
            pygame.surfarray.pixels3d(surf)
 
561
 
 
562
        self.failUnlessRaises(ValueError,
 
563
                              do_pixels3d,
 
564
                              self._make_surface(8))
 
565
        self.failUnlessRaises(ValueError,
 
566
                              do_pixels3d,
 
567
                              self._make_surface(16))
 
568
 
 
569
    def test_pixels_alpha(self):
 
570
        if not arraytype:
 
571
            self.fail("no array package installed")
 
572
 
 
573
        palette = [(0, 0, 0, 0),
 
574
                   (127, 127, 127, 0),
 
575
                   (127, 127, 127, 85),
 
576
                   (127, 127, 127, 170),
 
577
                   (127, 127, 127, 255)]
 
578
        alphas = [0, 45, 86, 99, 180]
 
579
 
 
580
        surf = self._make_src_surface(32, srcalpha=True, palette=palette)
 
581
 
 
582
        self.failIf(surf.get_locked())
 
583
        arr = pygame.surfarray.pixels_alpha(surf)
 
584
        self.failUnless(surf.get_locked())
 
585
        surf.unlock()
 
586
        self.failUnless(surf.get_locked())
 
587
 
 
588
        for (x, y), i in self.test_points:
 
589
            self.failUnlessEqual(arr[x, y], palette[i][3])
 
590
 
 
591
        for (x, y), i in self.test_points:
 
592
            alpha = alphas[i]
 
593
            arr[x, y] = alpha
 
594
            color = (127, 127, 127, alpha)
 
595
            self.failUnlessEqual(surf.get_at((x, y)), color,
 
596
                                 "posn: (%i, %i)" % (x, y))
 
597
 
 
598
        del arr
 
599
        self.failIf(surf.get_locked())
 
600
        self.failUnlessEqual(surf.get_locks(), ())
 
601
 
 
602
        # Check exceptions.
 
603
        def do_pixels_alpha(surf):
 
604
            pygame.surfarray.pixels_alpha(surf)
 
605
 
 
606
        targets = [(8, False),
 
607
                   (16, False),
 
608
                   (16, True),
 
609
                   (24, False),
 
610
                   (32, False)]
 
611
 
 
612
        for bitsize, srcalpha in targets:
 
613
            self.failUnlessRaises(ValueError, do_pixels_alpha,
 
614
                                  self._make_surface(bitsize, srcalpha))
 
615
 
 
616
    def test_pixels_red(self):
 
617
        self._test_pixels_rgb('red', 0)
 
618
 
 
619
    def test_pixels_green(self):
 
620
        self._test_pixels_rgb('green', 1)
 
621
 
 
622
    def test_pixels_blue(self):
 
623
        self._test_pixels_rgb('blue', 2)
 
624
 
 
625
    def _test_pixels_rgb(self, operation, mask_posn):
 
626
        method_name = "pixels_" + operation
 
627
        if not arraytype:
 
628
            self.fail("no array package installed")
 
629
 
 
630
        pixels_rgb = getattr(pygame.surfarray, method_name)
 
631
        palette = [(0, 0, 0, 255),
 
632
                   (5, 13, 23, 255),
 
633
                   (29, 31, 37, 255),
 
634
                   (131, 157, 167, 255),
 
635
                   (179, 191, 251, 255)]
 
636
        plane = [c[mask_posn] for c in palette]
 
637
 
 
638
        surf24 = self._make_src_surface(24, srcalpha=False, palette=palette)
 
639
        surf32 = self._make_src_surface(32, srcalpha=False, palette=palette)
 
640
        surf32a = self._make_src_surface(32, srcalpha=True, palette=palette)
 
641
 
 
642
        for surf in [surf24, surf32, surf32a]:
 
643
            self.failIf(surf.get_locked())
 
644
            arr = pixels_rgb(surf)
 
645
            self.failUnless(surf.get_locked())
 
646
            surf.unlock()
 
647
            self.failUnless(surf.get_locked())
 
648
 
 
649
            for (x, y), i in self.test_points:
 
650
                self.failUnlessEqual(arr[x, y], plane[i])
 
651
 
 
652
            del arr
 
653
            self.failIf(surf.get_locked())
 
654
            self.failUnlessEqual(surf.get_locks(), ())
 
655
 
 
656
        # Check exceptions.
 
657
        targets = [(8, False),
 
658
                   (16, False),
 
659
                   (16, True)]
 
660
 
 
661
        for bitsize, srcalpha in targets:
 
662
            self.failUnlessRaises(ValueError, pixels_rgb,
 
663
                                  self._make_surface(bitsize, srcalpha))
 
664
 
 
665
    def test_use_arraytype(self):
 
666
        if not arraytype:
 
667
            self.fail("no array package installed")
 
668
 
 
669
        def do_use_arraytype(atype):
 
670
            pygame.surfarray.use_arraytype(atype)
 
671
 
 
672
        pygame.surfarray.use_arraytype('numpy')
 
673
        self.failUnlessEqual(pygame.surfarray.get_arraytype(), 'numpy')
 
674
 
 
675
        self.failUnlessRaises(ValueError, do_use_arraytype, 'not an option')
 
676
 
 
677
    def test_surf_lock (self):
 
678
        if not arraytype:
 
679
            self.fail("no array package installed")
 
680
 
 
681
        sf = pygame.Surface ((5, 5), 0, 32)
 
682
        for atype in pygame.surfarray.get_arraytypes ():
 
683
            pygame.surfarray.use_arraytype (atype)
 
684
            
 
685
            ar = pygame.surfarray.pixels2d (sf)
 
686
            self.assertEquals (sf.get_locked (), True)
 
687
                
 
688
            sf.unlock ()
 
689
            self.assertEquals (sf.get_locked (), True)
 
690
                
 
691
            del ar
 
692
            self.assertEquals (sf.get_locked (), False)
 
693
            self.assertEquals (sf.get_locks (), ())
 
694
 
 
695
        #print ("test_surf_lock - end")
 
696
 
 
697
 
 
698
if __name__ == '__main__':
 
699
    if not arraytype:
 
700
        print ("No array package is installed. Cannot run unit tests.")
 
701
    else:
 
702
        unittest.main()