Debian Codegraph @

doc/programming_guide/rendering.rst

raw
1 .. _guide_graphics:
2
3 Shaders and Rendering
4 =====================
5
6 At the lowest level, pyglet uses OpenGL to draw graphics in program windows.
7 The OpenGL interface is exposed via the :py:mod:`pyglet.gl` module
8 (see :ref:`guide_gl`)
9
10 .. Note::
11 If you intend to use OpenGL ES with pyglet on devices like the Raspberry
12 Pi, please read the :ref:`programming-guide-opengles` section first.
13
14 For new users, however, using the OpenGL interface directly can be daunting.
15 The :py:mod:`pyglet.graphics` module provides high level abstractions that
16 use vertex arrays and vertex buffer objects internally to deliver high
17 performance. For advanced users, these abstractions can still help to avoid
18 a lot of the OpenGL boilerplate code that would otherwise be necessary to write
19 yourself.
20
21 pyglet's rendering abstractions consist of three major components:
22 "VertexDomains", "VertexLists", and ":py:class:`~pyglet.graphics.shader.ShaderProgram`". These will be explained
23 in more detail in the following sections, but a rough overview is as follows:
24
25 * :py:class:`~pyglet.graphics.shader.ShaderProgram` are at the highest level, and are simple abstractions over
26 standard OpenGL Shader Programs. pyglet does full attribute and uniform
27 introspection, and provides methods for automatically generating buffers
28 that match the attribute formats.
29 * VertexDomains are at the lowest level, and users will generally not need to
30 interact with them directly. They maintain ownership of raw OpenGL vertex
31 array buffers, that match a specific collection of vertex attributes.
32 Buffers are resized automatically as needed. Access to these buffers is
33 usually not done directly, but instead through the use of VertexLists.
34 * VertexLists sit in-between the VertexDomains and the :py:class:`~pyglet.graphics.shader.ShaderProgram`. They
35 provide a simple "view" into a portion of a VertexDomain's buffers. A
36 :py:class:`~pyglet.graphics.shader.ShaderProgram` is able to generate VertexLists directly.
37
38 In summary, the process is as follows:
39
40 1. User creates a :py:class:`~pyglet.graphics.shader.ShaderProgram`. Vertex attribute metadata is introspected
41 automatically.
42 2. User creates a new VertexList with the :py:meth:`~pyglet.graphics.shader.ShaderProgram.vertex_list` method.
43 Users do not need to worry about creating the internal buffers themselves.
44 3. When the VertexList is created in step 2, pyglet automatically matches the
45 :py:class:`~pyglet.graphics.shader.ShaderProgram`'s attributes to an appropriate VertexDomain. (If no existing
46 domain is available, a new one is created). A VertexList is generated from
47 the matching VertexDomain, and returned.
48
49
50 Working with Shaders
51 --------------------
52
53 Drawing anything in modern OpenGL requires a Shader Program. Working with
54 Shader resources directly can be tedious, so the :py:mod:`pyglet.graphics.shader`
55 module provides simplified (but robust) abstractions.
56
57 See the `OpenGL Programming SDK`_ for more information on Shaders and the
58 OpenGL Shader Language (GLSL).
59
60 Creating a Shader Program
61 ^^^^^^^^^^^^^^^^^^^^^^^^^
62
63 To create a Shader Program, first prepare the GLSL source as Python strings.
64 This can be loaded from disk, or simply defined inside of your project. Here
65 is simplistic Vertex and Fragment source::
66
67 vertex_source = """#version 150 core
68 in vec2 position;
69 in vec4 colors;
70 out vec4 vertex_colors;
71
72 uniform WindowBlock
73 {
74 mat4 projection;
75 mat4 view;
76 } window;
77
78 void main()
79 {
80 gl_Position = window.projection * window.view * vec4(position, 0.0, 1.0);
81 vertex_colors = colors;
82 }
83 """
84
85 fragment_source = """#version 150 core
86 in vec4 vertex_colors;
87 out vec4 final_color;
88
89 void main()
90 {
91 final_color = vertex_colors;
92 }
93 """
94
95
96 .. note:: By default, pyglet includes and sets the ``WindowBlock`` uniform when the window is created. If you do not use
97 the ``window.projection`` or ``window.view`` in your vertex shader, you will have to manage the projection
98 yourself or your graphics may not display properly.
99
100 The source strings are then used to create :py:class:`~pyglet.graphics.shader.Shader` objects, which are
101 then linked together in a :py:class:`~pyglet.graphics.shader.ShaderProgram`. Shader objects are automatically
102 detached after linking the :py:class:`~pyglet.graphics.shader.ShaderProgram`, so they can be discarded
103 afterwards (or used again in other :py:class:`~pyglet.graphics.shader.ShaderProgram`)::
104
105 from pyglet.graphics.shader import Shader, ShaderProgram
106
107 vert_shader = Shader(vertex_source, 'vertex')
108 frag_shader = Shader(fragment_source, 'fragment')
109 program = ShaderProgram(vert_shader, frag_shader)
110
111 :py:class:`~pyglet.graphics.shader.ShaderProgram` internally introspects on creation. There are
112 several properties that can be queried to inspect the various vertex attributes, uniforms,
113 and uniform blocks that are available. For example, the `uniforms` and `attributes` properties
114 will return dictionaries showing the metadata for these objects::
115
116 >>> for attribute in program.attributes.items():
117 ... print(attribute)
118 ...
119 ('position', {'type': 35664, 'size': 1, 'location': 0, 'count': 2, 'format': 'f'})
120 ('colors', {'type': 35666, 'size': 1, 'location': 1, 'count': 4, 'format': 'f'})
121
122 >>> for uniform in program.uniforms.items():
123 ... print(uniform)
124 ...
125 ('time', {'location': 2, 'length': 1, 'size': 1})
126
127
128 .. note::
129 Most OpenGL drivers will optimize shaders during compilation. If an
130 attribute or a uniform is not being used, it will often be optimized out.
131
132
133 Uniforms
134 ^^^^^^^^
135
136 Uniforms are variables that can be modified after a :py:class:`~pyglet.graphics.shader.ShaderProgram` has been compiled
137 to change functionality during run time.
138
139 .. warning::
140
141 When setting uniforms, the program must be binded at the time of setting. This restriction does not exist in
142 OpenGL 4.1+, but if you plan to support older contexts (such as 3.3), this must be accounted for.
143
144 Uniforms can be accessed as a key on the :py:class:`~pyglet.graphics.shader.ShaderProgram`
145 itself. For example if your uniform in your shader is::
146
147 uniform float time;
148
149 Then you can set (or get) the value using the uniform name as a key::
150
151 program['time'] = delta_time
152
153
154 Uniform Blocks and Uniform Buffer Objects
155 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
156
157 Pyglet also introspects and makes Uniform Blocks (or Interface Blocks) available, including ways to manage and use Uniform Buffer Objects.
158
159 By default, Pyglet's ``projection`` and ``view`` matrix are both contained in the ``WindowBlock`` uniform block. Which looks like this in the vertex shader::
160
161 uniform WindowBlock
162 {
163 mat4 projection;
164 mat4 view;
165 } window;
166
167 You can view what uniform blocks exist in a :py:class:`~pyglet.graphics.shader.ShaderProgram` using the `uniform_blocks`
168 property. This is a dictionary containing a Uniform Block name key to a :py:class:`~pyglet.graphics.shader.UniformBlock`
169 object value. In the above example, the name would be ``WindowBlock`` while the ``window`` instance identifier is used in the GLSL shader itself.
170
171 Normally with OpenGL, you would have to manually assign a global binding point value to each Uniform Block for each Shader Program, as they are created. With Pyglet, the global binding values and assignments are all taken care of internally.
172
173 Uniform Blocks can be a convenient way to update uniforms of multiple Shader Programs at once, as their data is shared. This allows you to access the same information from multiple Shader Programs without having to bind every program using it, just to modify the uniform values. This can be achieved through a :py:class:`~pyglet.graphics.shader.UniformBufferObject`.
174
175 To modify the uniforms in a :py:class:`~pyglet.graphics.shader.UniformBlock`, you must first create a
176 :py:class:`~pyglet.graphics.shader.UniformBufferObject` using the
177 :py:meth:`~pyglet.graphics.shader.UniformBlock.create_ubo` method.::
178
179 ubo = program.uniform_blocks['WindowBlock'].create_ubo()
180
181 The :py:class:`~pyglet.graphics.shader.UniformBufferObject` can then be used as a context manager for easy
182 access to update its uniforms::
183
184 with ubo as window_block:
185 window_block.projection[:] = new_matrix
186
187 You can also create multiple :py:class:`~pyglet.graphics.shader.UniformBufferObject` instances if you need to swap between different sets of data. Calling :py:meth:`~pyglet.graphics.shader.UniformBufferObject.bind` will bind the buffers data to the associated binding point.
188
189 There may come a point where you don't want a specific :py:class:`~pyglet.graphics.shader.ShaderProgram`, or a group of them, to use the same uniform data set as the rest of your shaders. At this point, you will have to modify the binding point of those Uniform Blocks to one that is unused. This can be done through :py:meth:`~pyglet.graphics.shader.UniformBlock.set_binding`. Once the binding has been set, you will have to create a new :py:class:`~pyglet.graphics.shader.UniformBufferObject` using the :py:meth:`~pyglet.graphics.shader.UniformBlock.create_ubo` method again and supply it with your new data set.
190
191 .. warning:: When assigning custom binding points through py:meth:`~pyglet.graphics.shader.UniformBlock.set_binding`, it is recommended to use an unassigned binding point, as unexpected behavior may occur. A warning will be output if such a collision occurs.
192
193 The maximum binding point value is determined by the hardware. This can be retrieved by calling :py:func:`~pyglet.graphics.shader.get_maximum_binding_count`. It is recommended to use a number
194 higher than the amount of Uniform Blocks in your application to prevent collisions.
195
196 .. note:: Binding point 0 cannot be set, as it is used internally for ``WindowBlock``.
197
198
199 Creating Vertex Lists
200 ^^^^^^^^^^^^^^^^^^^^^
201
202 Once you have a ShaderProgram, you need vertex data to render. As an easier alternative
203 to manually creating and managing vertex buffers, pyglet provides a high level
204 :py:class:`~pyglet.graphics.vertexdomain.VertexList` object. VertexLists are abstractions
205 over OpenGL buffers, with properties for easily accessing the arrays of attribute data.
206
207 The ShaderProgram provides the following two methods:
208 :py:meth:`~pyglet.graphics.shader.ShaderProgram.vertex_list`
209 and
210 :py:meth:`~pyglet.graphics.shader.ShaderProgram.vertex_list_indexed`
211
212 At a minimum, you must provide a `count` and `mode` when creating a VertexList.
213 The `count` is simply the number of vertices you wish to create. The `mode` is
214 the OpenGL primitive type. A ``group`` and ``batch`` parameters are also accepted
215 (described below).
216
217 The mode should be passed using one of the following constants:
218
219 * ``pyglet.gl.GL_POINTS``
220 * ``pyglet.gl.GL_LINES``
221 * ``pyglet.gl.GL_LINE_STRIP``
222 * ``pyglet.gl.GL_TRIANGLES``
223 * ``pyglet.gl.GL_TRIANGLE_STRIP``
224
225 When using ``GL_LINE_STRIP`` and ``GL_TRIANGLE_STRIP``, care must be taken to
226 insert degenerate vertices at the beginning and end of each vertex list.
227 For example, given the vertex list::
228
229 A, B, C, D
230
231 the correct vertex list to provide the vertex list is::
232
233 A, A, B, C, D, D
234
235 .. note:: Because of the way the high level API renders multiple primitives with
236 shared state, ``GL_POLYGON``, ``GL_LINE_LOOP`` and ``GL_TRIANGLE_FAN``
237 cannot be used --- the results are undefined.
238
239 Create a VertexList with three vertices, without initial data::
240
241 vlist = program.vertex_list(3, pyglet.gl.GL_TRIANGLES)
242
243 From examining the ShaderProgram.attributes above, we know `position` and `colors`
244 attributes are available. The underlying arrays can be accessed directly::
245
246 >>> vlist.position
247 <pyglet.graphics.shader.c_float_Array_6 object at 0x7f6d3a30b1c0>
248 >>> vlist.colors
249 <pyglet.graphics.shader.c_float_Array_12 object at 0x7f6d3a30b0c0>
250 >>>
251 >>> vlist.position[:]
252 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
253 >>>
254 >>> vlist.colors[:]
255 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
256
257 The `position` data is a float array with 6 elements. This attribute is a `vec2`
258 in the shader. Looking at the attribute metadata above, we can confirm that
259 `count=2`. Since the VertexList was created with 3 vertices, the length of the array
260 is simply 3 * 2 = 6. Likewise, the `colors` attribute is defined as a `vec4` in the
261 shader, so it's simply 3 * 4 = 12.
262
263 This VertexList was created without any initial data, but it can be set (or updated)
264 on the property by passing a list or tuple of the correct length. For example::
265
266 vlist.position = (100, 300, 200, 250, 200, 350)
267 # or slightly faster to update in-place:
268 vlist.position[:] = (100, 300, 200, 250, 200, 350)
269
270 The default data format is single precision floats, but it is possible to specify a
271 format using a "format string". This is passed on creation as a Python keyword
272 argument. The following formats are available:
273
274 .. list-table::
275 :header-rows: 1
276
277 * - Format
278 - Type
279 - Python type
280 * - ``"b"``
281 - Signed byte
282 - int
283 * - ``"B"``
284 - Unsigned byte
285 - int
286 * - ``"s"``
287 - Signed short
288 - int
289 * - ``"S"``
290 - Unsigned short
291 - int
292 * - ``"i"``
293 - Signed int
294 - int
295 * - ``"I"``
296 - Unsigned int
297 - int
298 * - ``"f"``
299 - Single precision float
300 - float
301 * - ``"d"``
302 - Double precision float
303 - float
304
305
306 For example, if you would like to pass the `position` data as a signed int, you
307 can pass the "i" format string as a Python keyword argument::
308
309 vlist = program.vertex_list(3, pyglet.gl.GL_TRIANGLES, position='i')
310
311 By appending ``"n"`` to the format string, you can also specify that the passed
312 data should be "normalized" to the range ``[0, 1]``. The value is used as-is if
313 the data type is floating-point. If the data type is byte, short or int, the value
314 is divided by the maximum value representable by that type. For example, unsigned
315 bytes are divided by 255 to get the normalised value.
316
317 A common case is to use normalized unsigned bytes for the color data. Simply
318 pass "Bn" as the format::
319
320 vlist = program.vertex_list(3, pyglet.gl.GL_TRIANGLES, colors='Bn')
321
322
323 Passing Initial Data
324 ~~~~~~~~~~~~~~~~~~~~
325
326 Rather than setting the data *after* creation of a VertexList, you can also
327 easily pass initial arrays of data on creation. You do this by passing the format
328 and the data as a tuple, using a keyword argument as above. To set the position
329 and color data on creation::
330
331 vlist = program.vertex_list(3, pyglet.gl.GL_TRIANGLES,
332 position=('f', (200, 400, 300, 350, 300, 450)),
333 colors=('Bn', (255, 0, 0, 255, 0, 255, 0, 255, 75, 75, 255, 255),)
334
335
336 Indexed Rendering
337 ~~~~~~~~~~~~~~~~~
338
339 Vertices can also be drawn out of order and more than once by using the
340 indexed rendering. This requires a list of integers giving the indices into
341 the vertex data. You also use the
342 :py:meth:`~pyglet.graphics.shader.ShaderProgram.vertex_list_indexed` method
343 instead of :py:meth:`~pyglet.graphics.shader.ShaderProgram.vertex_list`. The
344 API is almost identical, except for the required index list.
345
346 The following example creates four vertices, and provides their positional data.
347 By passing an index list of [0, 1, 2, 0, 2, 3], we creates two adjacent triangles,
348 and the shared vertices are reused::
349
350 vlist = program.vertex_list_indexed(4, pyglet.gl.GL_TRIANGLES,
351 [0, 1, 2, 0, 2, 3],
352 position=('i', (100, 100, 150, 100, 150, 150, 100, 150)),
353 )
354
355 Note that the first argument gives the number of vertices in the data, not the
356 number of indices (which is implicit on the length of the index list given in
357 the third argument).
358
359 Resource Management
360 ~~~~~~~~~~~~~~~~~~~
361
362 VertexLists reference data that is stored on the GPU, but they do not own
363 any data themselves. For this reason, it's not strictly necessary to keep a
364 reference to a VertexList after creating it. If you wish to delete the data
365 from the GPU, however, it can only be done with the `VertexList.delete()`
366 method. Likewise, you can only update a VertexList's vertex data if you have
367 kept a reference to it. For that reason, you should keep a reference to any
368 objects that you might want to modify or delete from your scene after creation.
369
370 .. _guide_batched-rendering:
371
372 Batched rendering
373 -----------------
374
375 For optimal OpenGL performance, you should render as many vertex lists as
376 possible in a single ``draw`` call. Internally, pyglet uses
377 :py:class:`~pyglet.graphics.vertexdomain.VertexDomain` and
378 :py:class:`~pyglet.graphics.vertexdomain.IndexedVertexDomain` to keep VertexLists
379 that share the same attribute formats in adjacent areas of memory.
380 The entire domain of vertex lists can then be drawn at once, without calling
381 :py:meth:`~pyglet.graphics.vertexdomain.VertexList.draw` on each individual
382 list.
383
384 It is quite difficult and tedious to write an application that manages vertex
385 domains itself, though. In addition to maintaining a vertex domain for each
386 ShaderProgram and set of attribute formats, domains must also be separated by
387 primitive mode and required OpenGL state.
388
389 The :py:class:`~pyglet.graphics.Batch` class implements this functionality,
390 grouping related vertex lists together and sorting by OpenGL state
391 automatically. A batch is created with no arguments::
392
393 batch = pyglet.graphics.Batch()
394
395 To use a Batch, you simply pass it as a (keyword) argument when creating
396 any of pyglet's high level objects. For example::
397
398 vlist = program.vertex_list(3, pyglet.gl.GL_TRIANGLES, batch=batch)
399 sprite = pyglet.sprite.Sprite(img, x, y, batch=batch)
400
401 To draw all objects contained in the batch at once::
402
403 batch.draw()
404
405 For batches containing many objects, this gives a significant performance
406 improvement over drawing individually. It's generally recommended to always
407 use Batches.
408
409 Setting the OpenGL state
410 ^^^^^^^^^^^^^^^^^^^^^^^^
411
412 Before drawing in OpenGL, it's necessary to set certain state. You might need
413 to activate a :py:class:`~pyglet.graphics.shader.ShaderProgram`, or bind a Texture. For example, to enable and bind
414 a texture requires the following before drawing::
415
416 from pyglet.gl import *
417 glActiveTexture(GL_TEXTURE0)
418 glBindTexture(texture.target, texture.id)
419
420 With a :py:class:`~pyglet.graphics.Group` these state changes can be
421 encapsulated and associated with the vertex lists they affect.
422 Subclass :py:class:`~pyglet.graphics.Group` and override the `Group.set_state`
423 and `Group.unset_state` methods to perform the required state changes::
424
425 class CustomGroup(pyglet.graphics.Group):
426 def __init__(self, texture, shaderprogram):
427 super().__init__()
428 self.texture = texture
429 self.program = shaderprogram
430
431 def set_state(self):
432 self.program.use()
433 glActiveTexture(GL_TEXTURE0)
434 glBindTexture(self.texture.target, self.texture.id)
435
436 def unset_state(self):
437 self.program.stop()
438
439 An instance of this group can now be attached to vertex lists::
440
441 custom_group = CustomGroup()
442 vertex_list = program.vertex_list(2, pyglet.gl.GL_POINTS, batch, custom_group,
443 position=('i', (10, 15, 30, 35)),
444 colors=('Bn', (0, 0, 255, 0, 255, 0))
445 )
446
447 The :py:class:`~pyglet.graphics.Batch` ensures that the appropriate
448 ``set_state`` and ``unset_state`` methods are called before and after
449 the vertex lists that use them.
450
451 Shader state
452 ^^^^^^^^^^^^
453 :py:class:`~pyglet.graphics.shader.ShaderProgram` can be binded (:py:meth:`~pyglet.graphics.shader.ShaderProgram.use`)
454 and unbinded (:py:meth:`~pyglet.graphics.shader.ShaderProgram.stop`) manually. As a convenience method, it can also act
455 as a context manager that handles the binding and unbinding process automatically. This may be useful if you want to
456 ensure the state of a :py:class:`~pyglet.graphics.shader.ShaderProgram` is active during some edge case scenarios while
457 also being more Pythonic.
458
459 For example::
460
461 with shaderprogram as my_shader:
462 my_shader.my_uniform = 1.0
463
464
465 Hierarchical state
466 ^^^^^^^^^^^^^^^^^^
467
468 Groups have a `parent` attribute that allows them to be implicitly organised
469 in a tree structure. If groups **B** and **C** have parent **A**, then the
470 order of ``set_state`` and ``unset_state`` calls for vertex lists in a batch
471 will be::
472
473 A.set_state()
474
475 B.set_state()
476 # Draw B vertices
477 B.unset_state()
478
479 C.set_state()
480 # Draw C vertices
481 C.unset_state()
482
483 A.unset_state()
484
485 This is useful to group state changes into as few calls as possible. For
486 example, if you have a number of vertex lists that all need texturing enabled,
487 but have different bound textures, you could enable and disable texturing in
488 the parent group and bind each texture in the child groups. The following
489 example demonstrates this::
490
491 class TextureEnableGroup(pyglet.graphics.Group):
492 def set_state(self):
493 glActiveTexture(GL_TEXTURE0)
494
495 def unset_state(self):
496 # not necessary
497
498
499 texture_enable_group = TextureEnableGroup()
500
501
502 class TextureBindGroup(pyglet.graphics.Group):
503 def __init__(self, texture):
504 super().__init__(parent=texture_enable_group)
505 assert texture.target = GL_TEXTURE_2D
506 self.texture = texture
507
508 def set_state(self):
509 glBindTexture(GL_TEXTURE_2D, self.texture.id)
510
511 def unset_state(self):
512 # not required
513
514 def __eq__(self, other):
515 return (self.__class__ is other.__class__ and
516 self.texture.id == other.texture.id and
517 self.texture.target == other.texture.target and
518 self.parent == other.parent)
519
520 def __hash__(self):
521 return hash((self.texture.id, self.texture.target))
522
523 program.vertex_list_indexed(4, GL_TRIANGLES, indices, batch, TextureBindGroup(texture1))
524 program.vertex_list_indexed(4, GL_TRIANGLES, indices, batch, TextureBindGroup(texture2))
525 program.vertex_list_indexed(4, GL_TRIANGLES, indices, batch, TextureBindGroup(texture1))
526
527
528 .. note:: The ``__eq__`` method on the group allows the :py:class:`~pyglet.graphics.Batch`
529 to automatically merge the two identical ``TextureBindGroup`` instances.
530 For optimal performance, always take care to ensure your custom Groups have
531 correct ``__eq__`` and ``__hash__`` methods defined.
532
533 Drawing order
534 ^^^^^^^^^^^^^
535
536 :py:class:`~pyglet.graphics.vertexdomain.VertexDomain` does not attempt
537 to keep vertex lists in any particular order. So, any vertex lists sharing
538 the same primitive mode, attribute formats and group will be drawn in an
539 arbitrary order. However, :py:class:`~pyglet.graphics.Group` objects do
540 have an ``order`` parameter that allows :py:class:`~pyglet.graphics.Batch`
541 to sort objects sharing the same parent. In summary, inside of a Batch:
542
543 1. Groups are sorted by their parent (if any). (Parent Groups may also be ordered).
544 2. Groups are sorted by their `order` attribute. There is one draw call per order level.
545
546 A common use pattern is to create several Groups for each level in your scene.
547 For instance, a "background" group that is drawn before the "foreground" group::
548
549 background = pyglet.graphics.Group(0)
550 foreground = pyglet.graphics.Group(1)
551
552 pyglet.sprite.Sprite(image, batch=batch, group=background)
553 pyglet.sprite.Sprite(image, batch=batch, group=foreground)
554
555 By combining hierarchical groups with ordered groups it is possible to
556 describe an entire scene within a single :py:class:`~pyglet.graphics.Batch`,
557 which then renders it as efficiently as possible.
558
559 Visibility
560 ^^^^^^^^^^
561
562 Groups have a boolean ``visible`` property. By setting this to ``False``, any
563 objects in that :py:class:`~pyglet.graphics.Group` will no longer be rendered. A common use case is to
564 create a parent Group specifically for this purpose, often when combined
565 with custom ordering (as described above). For example, you might create
566 a "HUD" Group, which is ordered to draw in front of everything else. The
567 "HUD" Group's visibility can then easily be toggled.
568
569
570 Batches and groups in other modules
571 -----------------------------------
572
573 The :py:class:`~pyglet.sprite.Sprite`, :py:class:`~pyglet.text.Label`,
574 :py:class:`~pyglet.text.layout.TextLayout`, and other default classes all
575 accept ``batch`` and ``group`` parameters in their constructors. This allows
576 you to add any of these higher-level pyglet drawables into arbitrary places in
577 your rendering code.
578
579 For example, multiple sprites can be grouped into a single batch and then
580 drawn at once, instead of calling ``Sprite.draw()`` on each one individually::
581
582 batch = pyglet.graphics.Batch()
583 sprites = [pyglet.sprite.Sprite(image, batch=batch) for i in range(100)]
584
585 batch.draw()
586
587 The ``group`` parameter can be used to set the drawing order (and hence which
588 objects overlap others) within a single batch, as described on the previous page.
589
590 In general you should batch all drawing objects into as few batches as
591 possible, and use groups to manage the draw order and other OpenGL state
592 changes for optimal performance.
593
594 If you are creating your own drawable
595 classes, consider adding ``batch`` and ``group`` parameters in a similar way.
596
597 .. _OpenGL Programming SDK: http://www.opengl.org/sdk