Debian Codegraph @

examples/sprite/depth_sprite.py

raw symbols SCIP
1 """An example of sorting sprites in the Z axis based on the Y axis, and a standard projection."""
2 import pyglet
3 from pyglet.gl import *
4 import random
5 import math
6
7 # Standard projection Z is 0 to 255. Keep window within that.
8 # You will have to change window projection if you wish to go beyond this.
9 window = pyglet.window.Window(height=250)
10
11 fragment_source = """#version 150 core
12 in vec4 vertex_colors;
13 in vec3 texture_coords;
14 out vec4 final_colors;
15
16 uniform sampler2D sprite_texture;
17
18 void main()
19 {
20 final_colors = texture(sprite_texture, texture_coords.xy) * vertex_colors;
21
22 // No GL_ALPHA_TEST in core, use shader to discard.
23 if(final_colors.a < 0.01){
24 discard;
25 }
26 }
27 """
28
29
30 class DepthSpriteGroup(pyglet.sprite.SpriteGroup):
31 def set_state(self):
32 self.program.use()
33
34 glActiveTexture(GL_TEXTURE0)
35 glBindTexture(self.texture.target, self.texture.id)
36
37 glEnable(GL_BLEND)
38 glBlendFunc(self.blend_src, self.blend_dest)
39
40 glEnable(GL_DEPTH_TEST)
41 glDepthFunc(GL_LESS)
42
43 def unset_state(self):
44 glDisable(GL_BLEND)
45 glDisable(GL_DEPTH_TEST)
46 self.program.stop()
47
48
49 class DepthSprite(pyglet.sprite.Sprite):
50 group_class = DepthSpriteGroup
51
52
53 # Set example resource path.
54 pyglet.resource.path = ['../resources']
55 pyglet.resource.reindex()
56
57 image = pyglet.resource.image("pyglet.png")
58 batch = pyglet.graphics.Batch()
59
60 sprites = []
61
62 # Reuse vertex source and create new shader with alpha testing.
63 vertex_shader = pyglet.graphics.shader.Shader(pyglet.sprite.vertex_source, "vertex")
64 fragment_shader = pyglet.graphics.shader.Shader(fragment_source, "fragment")
65 depth_shader = pyglet.graphics.shader.ShaderProgram(vertex_shader, fragment_shader)
66
67
68 def make_sprite(zvalue):
69 sprite = DepthSprite(image, x=0, y=0, z=zvalue, batch=batch, program=depth_shader)
70 # Random color multiplier.
71 sprite.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
72 # Add sprites to keep in memory, like a list. Otherwise, they will get GC'd when out of scope.
73 sprites.append(sprite)
74
75
76 sprite_count = 10
77 for i in range(sprite_count):
78 make_sprite(i)
79
80
81 global elapsed
82 elapsed = 0
83
84
85 def update(dt):
86 global elapsed
87 for i, sprite in enumerate(sprites):
88 sprite.update(x=i * .75 * (image.width - 15),
89 y=.25 * window.height * (1 + math.cos(2 * elapsed + i * math.pi / sprite_count)))
90 sprite.z = sprite.y
91 elapsed += dt
92
93
94 pyglet.clock.schedule_interval(update, 1 / 60.0)
95
96
97 @window.event
98 def on_draw():
99 window.clear()
100 batch.draw()
101
102
103 pyglet.app.run()