-
Notifications
You must be signed in to change notification settings - Fork 25
/
layers.py
374 lines (325 loc) · 10.4 KB
/
layers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
from typing import Tuple, Optional, Any
import importlib
import weakref
import numpy as np
import moderngl
import pygame.image
from .clock import default_clock
from .atlas import Atlas
from .primitives.sprites import Sprite
from .primitives.circles import Circle, line_vao, shape_vao
from .primitives.polygons import Polygon, Rect, PolyLine
from .primitives.text import Label, FontAtlas, text_vao
from .primitives.particles import ParticleGroup, ParticleVAO
from .loaders import images
from .shaders import ShaderManager
class FontManager:
def __init__(self, ctx):
self.ctx = ctx
self.font_atlases = {}
def get(self, font_name):
try:
return self.font_atlases[font_name]
except KeyError:
fa = self.font_atlases[font_name] = FontAtlas(self.ctx, font_name)
return fa
def update(self):
"""Send any dirty textures to the GL."""
for f in self.font_atlases.values():
f._update()
class Layer:
def __init__(self, ctx, group):
self.ctx = ctx
self.group = group
self.arrays = weakref.WeakValueDictionary()
self.visible = True
self.objects = set()
self._dirty = set()
self.effect = self.effect_has_camera = None
self.parallax = 1.0
def clear(self):
"""Remove everything from the layer."""
# We need to release GL buffers we hold; everything else can be
# destroyed by the GC.
for a in self.arrays.values():
a.release()
self.arrays.clear()
self.objects.clear()
self._dirty.clear()
def _draw(self, camera):
"""Render the layer."""
if not self.visible:
return
for o in self._dirty:
o._update()
self._dirty.clear()
if self.effect:
if self.effect_has_camera is not camera:
self.effect._set_camera(camera)
self.effect_has_camera = camera
self.effect.draw(lambda: self._draw_inner(camera))
else:
self._draw_inner(camera)
identity = np.identity(4, dtype='f4')
def _draw_inner(self, camera):
self.group.shadermgr.set_proj(camera._getproj(self.parallax))
for a in self.arrays.values():
a.render(camera)
def set_effect(self, name: str, **kwargs) -> Any:
"""Set the post processing effect to use for the layer.
Return the effect object, which can be used to change parameters for
the effect.
"""
mod = importlib.import_module(f'wasabi2d.effects.{name}')
cls = getattr(mod, name.title())
self.effect = cls(self.ctx, **kwargs)
self.effect_has_camera = None
return self.effect
def clear_effect(self):
self.effect = None
def add_sprite(
self,
image,
*,
pos=(0, 0),
angle=0,
anchor_x='center',
anchor_y='center',
color=(1, 1, 1, 1),
scale=1.0
):
spr = Sprite(
layer=self,
image=image,
anchor_x=anchor_x,
anchor_y=anchor_y,
)
spr.pos = pos
spr.angle = angle
spr.color = color
spr.scale = scale
self.objects.add(spr)
return spr
def _get_or_create_vao(self, k, constructor):
"""Get a VAO identified by key k, or construct it using constructor."""
vao = self.arrays.get(k)
if not vao:
vao = self.arrays[k] = constructor(self.ctx, self.group.shadermgr)
return vao
def _lines_vao(self):
"""Get a VAO for objects made of line strips."""
return self._get_or_create_vao('lines', line_vao)
def _fill_vao(self):
"""Get a VAO for objects made of colored triangles."""
return self._get_or_create_vao('shapes', shape_vao)
def _load_texture(self, name):
"""Load a texture."""
img = images.load(name)
data = pygame.image.tostring(img, "RGBA", 1)
tex = self.ctx.texture(img.get_size(), 4, data=data)
tex.build_mipmaps(max_level=2)
return tex
def _text_vao(self, font):
"""Get a VAO for objects made of font glyphs."""
return self._get_or_create_vao(('text', font), text_vao)
def add_circle(self,
*,
radius: float,
pos: Tuple[float, float] = (0, 0),
color: Tuple[float, float, float, float] = (1, 1, 1, 1),
fill: bool = True,
stroke_width: float = 1.0,
) -> Circle:
c = Circle(
layer=self,
radius=radius,
pos=pos,
color=color,
stroke_width=stroke_width,
)
if fill:
c._migrate_fill(self._fill_vao())
else:
c._migrate_stroke(self._lines_vao())
self.objects.add(c)
return c
def add_star(
self,
*,
points: int,
inner_radius: float = 1.0,
outer_radius: float = None,
pos: Tuple[float, float] = (0, 0),
fill: bool = True,
color: Tuple[float, float, float, float] = (1, 1, 1, 1),
stroke_width: float = 1.0,
) -> Circle:
assert points >= 3, "Stars must have at least 3 points."
if outer_radius is None:
outer_radius = inner_radius * 2
c = Circle(
layer=self,
segments=2 * points + 1,
radius=1.0,
pos=pos,
color=color,
stroke_width=stroke_width,
)
if fill:
c._migrate_fill(self._fill_vao())
else:
c._migrate_stroke(self._lines_vao())
self.objects.add(c)
c.orig_verts[::2, :2] *= outer_radius
c.orig_verts[1::2, :2] *= inner_radius
return c
def add_polygon(self,
vertices,
*,
pos: Tuple[float, float] = (0, 0),
color: Tuple[float, float, float, float] = (1, 1, 1, 1),
fill: bool = True,
stroke_width: float = 1.0,
) -> Polygon:
c = Polygon(
layer=self,
vertices=vertices,
pos=pos,
color=color,
stroke_width=stroke_width,
)
self.objects.add(c)
if fill:
c._migrate_fill(self._fill_vao())
else:
c._migrate_stroke(self._lines_vao())
return c
def add_line(self,
vertices,
*,
pos: Tuple[float, float] = (0, 0),
color: Tuple[float, float, float, float] = (1, 1, 1, 1),
stroke_width: float = 1.0,
) -> PolyLine:
"""Add a line strip.
To create a single line segment of two points, pass two vertices!
"""
c = PolyLine(
layer=self,
vertices=vertices,
pos=pos,
color=color,
stroke_width=stroke_width,
)
self.objects.add(c)
c._migrate_stroke(self._lines_vao())
return c
def add_rect(
self,
width: float,
height: float,
*,
pos: Tuple[float, float] = (0, 0),
color: Tuple[float, float, float, float] = (1, 1, 1, 1),
fill: bool = True,
stroke_width: float = 1) -> Rect:
c = Rect(
layer=self,
width=width,
height=height,
pos=pos,
color=color,
stroke_width=stroke_width,
)
self.objects.add(c)
if fill:
c._migrate_fill(self._fill_vao())
else:
c._migrate_stroke(self._lines_vao())
return c
def add_label(self,
text: str,
*,
font: Optional[str] = None,
align: str = 'left',
fontsize: int = 20,
pos: Tuple[float, float] = (0, 0),
color: Tuple[float, float, float, float] = (1, 1, 1, 1),
) -> Rect:
fa = self.group.fontmgr.get(font)
c = Label(
text,
fa,
self,
align=align,
fontsize=fontsize,
pos=pos,
color=color
)
self.objects.add(c)
return c
def add_particle_group(
self,
texture=None,
clock=default_clock,
**kwargs
) -> ParticleGroup:
"""Create a group of particles.
We do not actually emit any particles at this time.
"""
c = ParticleGroup(
layer=self,
clock=default_clock,
**kwargs
)
vao = self.arrays[c] = ParticleVAO(
c,
mode=moderngl.POINTS,
ctx=self.ctx,
prog=self.group.shadermgr.load('primitives/particle')
)
if texture is None:
tex = self.ctx.texture((1, 1), 4, data=b'\xff' * 4)
else:
tex = self._load_texture(texture)
tex.repeat_x = tex.repeat_y = False
vao.tex = tex
vao.color_tex = c.color_tex
self.objects.add(c)
c._migrate(vao)
return c
def add_tile_map(self, *args, **kwargs):
"""Create a tile map in the layer."""
from .primitives.tile_map import TileMap
tiles = TileMap(self, *args, **kwargs)
self.objects.add(tiles)
return tiles
class LayerGroup(dict):
def __new__(cls, ctx):
return dict.__new__(cls)
def __init__(self, ctx):
self.ctx = ctx
if 'shadermgr' in ctx.extra:
self.shadermgr = ctx.extra['shadermgr']
else:
self.shadermgr = ShaderManager(self.ctx)
self.fontmgr = FontManager(self.ctx)
self.atlas = Atlas(ctx)
def __missing__(self, k):
if not isinstance(k, (float, int)):
raise TypeError("Layer indices must be numbers")
layer = self[k] = Layer(self.ctx, self)
return layer
def _update(self, proj):
# TODO: dirtymgr to manage these
self.atlas._update()
self.fontmgr.update()
# TODO: let the chain handle this
self.shadermgr.set_proj(proj)
def clear(self):
"""Clear the layer group.
We override this to explicitly release resources.
"""
for v in self.values():
v.clear()
super().clear()