1"""Draws a full-window quad with two texture units enabled and multi
2texcoords.  Texture unit 0 is a checker pattern of yellow and cyan with
3env mode replace.  Texture unit 1 is a checker pattern of cyan and yellow,
4with env mode modulate.  The result should be flat green (with some variation
5in the center cross).
6
7The test will correctly detect the asbence of multitexturing, or if texture
8coords are not supplied for a unit, but will still pass if the texture
9coordinates for each unit are swapped (the tex coords are identical).
10"""
11
12import unittest
13
14import pyglet
15from pyglet.gl import *
16
17
18class MultiTextureTestCase(unittest.TestCase):
19    def test_multitexture(self):
20        window = pyglet.window.Window(width=64, height=64)
21        window.dispatch_events()
22        w = window.width
23        h = window.height
24
25        pattern0 = pyglet.image.CheckerImagePattern(
26            (255, 255, 0, 255), (0, 255, 255, 255))
27        texture0 = pattern0.create_image(64, 64).get_texture()
28
29        pattern1 = pyglet.image.CheckerImagePattern(
30            (0, 255, 255, 255), (255, 255, 0, 255))
31        texture1 = pattern1.create_image(64, 64).get_texture()
32
33        batch = pyglet.graphics.Batch()
34        batch.add(4, GL_QUADS, None,
35                  ('v2i', [0, 0, w, 0, w, h, 0, h]),
36                  ('0t3f', texture1.tex_coords),
37                  ('1t3f', texture0.tex_coords)
38                  )
39
40        glActiveTexture(GL_TEXTURE0)
41        glEnable(texture0.target)
42        glBindTexture(texture0.target, texture0.id)
43        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
44        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
45        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
46
47        glActiveTexture(GL_TEXTURE1)
48        glEnable(texture1.target)
49        glBindTexture(texture1.target, texture1.id)
50        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
51        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
52        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
53
54        batch.draw()
55        self.assertEqual(self.sample(2, 2), (0, 255, 0))
56        self.assertEqual(self.sample(62, 2), (0, 255, 0))
57        self.assertEqual(self.sample(62, 62), (0, 255, 0))
58        self.assertEqual(self.sample(2, 62), (0, 255, 0))
59
60        window.close()
61
62    def sample(self, x, y):
63        color_buffer = pyglet.image.get_buffer_manager().get_color_buffer()
64        buffer = color_buffer.get_image_data()
65        data = buffer.get_data('RGB', buffer.pitch)
66        i = y * buffer.pitch + x * 3
67        r, g, b = data[i:i + 3]
68        if type(r) is str:
69            r, g, b = list(map(ord, (r, g, b)))
70        return r, g, b
71