Debian Codegraph @

doc/programming_guide/migration.rst

raw
1 .. _migration:
2
3 Migrating from pyglet 2.0
4 =========================
5 This page will help you upgrade your project from pyglet 2.0.
6
7 Some of pyglet 2.1's improvements required small breaking changes,
8 including:
9
10 * Arguments for text, UI, and game controller handling
11 * Locations and names for features
12 * Data types and annotations
13 * Changes to math classes
14
15 To report a missing change or a bug, please use `GitHub Issues`_ or
16 another :ref:`contributor communication <contributor-communication>`
17 channel.
18
19 .. _GitHub Issues: https://github.com/pyglet/pyglet/issues
20
21 .. _migration-options:
22
23 Setting pyglet Options
24 ----------------------
25
26 The :py:attr:`pyglet.options` attribute is now a :py:class:`pyglet.Options` instance.
27
28 The Options Object
29 ^^^^^^^^^^^^^^^^^^
30 Although :py:class:`~pyglet.Options` is a :py:func:`dataclass <dataclasses.dataclass>`,
31 you can get and set its attribute values directly via either approach below::
32
33 # "New" 2.1 attribute-style works with type checkers
34 pyglet.options.dpi_scaling = 'real'
35
36 # "Old" dict-style access is backward-compatible to help with porting
37 pyglet.options['dpi_scaling'] = 'real'
38
39
40 Window "HiDPI" support
41 ^^^^^^^^^^^^^^^^^^^^^^
42 In 2.1, :py:attr:`pyglet.options.dpi_scaling <pyglet.Options.dpi_scaling>`
43 accepts strings to configure fine-grained 'HiDPI' behavior.
44
45 What is HiDPI?
46 """"""""""""""
47 Some systems require scaled drawing due to pixel density, settings, or both.
48
49 .. note:: HiDPI stands for High Dots Per *(Square)* Inch.
50
51 In practice, this usually means:
52
53 * Apple's "retina" displays on Macs
54 * Non-Mac displays branded as 4K, 8K, etc
55 * Other displays with non-100% zoom or scaling
56
57 Scaling Modes
58 """""""""""""
59 The pyglet :py:attr:`~pyglet.Options.dpi_scaling` option supports multiple
60 scaling modes.
61
62 Each has pros and cons for different platforms and hardware. For example,
63 the default ``"real"`` mode matches the window, rendering, and input to a
64 computer display's "real" physical pixels.
65
66 On a HiDPI screen, this could mean:
67
68 * projects with the right art styles can look crisply detailed
69 * other projects may look tiny or poorly-scaled
70
71 In the latter case, other scaling modes may help. You will need to
72 experiment to find the best one(s) for your specific needs. Please
73 see the following to get started:
74
75 * :py:attr:`pyglet.options.dpi_scaling <pyglet.Options.dpi_scaling>`
76 * :py:attr:`pyglet.Options`
77 * :py:attr:`Window.dpi <pyglet.window.Window.dpi>`
78 * :py:attr:`Window.scale <pyglet.window.Window.scale>`
79
80 Labels & Text Layouts
81 ---------------------
82
83 Argument Consistency
84 ^^^^^^^^^^^^^^^^^^^^
85
86 The positional arguments for creating :py:class:`pyglet.text` layouts
87 and labels now all *start* with similar argument orders. This helps
88 you:
89
90 * switch between labels and layouts
91 * create custom subclasses
92
93 The order *after* the initial arguments may differ. Please see any
94 relevant API documentation to learn more.
95
96 Layout Arguments
97 """"""""""""""""
98 All :py:mod:`pyglet.text.layout` types now *start* with the same positional
99 argument order::
100
101 TextLayout(document, x, y, z, width, height, anchor_x, anchor_y, rotation, ...)
102 ScrollableTextLayout(document, x, y, z, width, height, anchor_x, anchor_y, rotation, ...)
103 IncrementalTextLayout(document, x, y, z, width, height, anchor_x, anchor_y, rotation, ...)
104
105 These types all take a concrete instance of an
106 :py:class:`~pyglet.text.layout.AbstractDocument` subclass as their
107 first argument. Subsequent arguments may differ.
108
109 Please see the following to learn more:
110
111 * :py:class:`pyglet.text.layout.TextLayout`
112 * :py:class:`pyglet.text.layout.ScrollableTextLayout`
113 * :py:class:`pyglet.text.layout.IncrementalTextLayout`
114
115 Label Arguments
116 """""""""""""""
117 The label classes now also share similar early argument orders.
118
119 Only :py:class:`~pyglet.text.DocumentLabel` is identical to layouts in
120 its initial arguments. The others both take a string ``text`` argument
121 as their first argument::
122
123 DocumentLabel(document, x, y, z, width, height, anchor_x, anchor_y, rotation, ...)
124 Label(text, x, y, z, width, height, anchor_x, anchor_y, rotation, ...)
125 HTMLLabel(text, x, y, z, width, height, anchor_x, anchor_y, rotation, ...)
126
127 As with layouts, the subsequent arguments may vary. Please see the following
128 to learn more:
129
130 * :py:class:`pyglet.text.DocumentLabel`
131 * :py:class:`pyglet.text.Label`
132 * :py:class:`pyglet.text.HTMLLabel`
133
134
135 Replace Bold With Weight
136 ^^^^^^^^^^^^^^^^^^^^^^^^
137
138 The string ``weight`` argument is more flexible than the ``bold`` argument it replaces.
139
140 .. note:: This does not apply to :py:class:`~pyglet.text.HTMLLabel`.
141
142 For :py:class:`pyglet.text.Label` and :py:class:`pyglet.text.DocumentLabel`,
143 their ``weight`` argument now allows choosing a desired font weight. This assumes
144 your specific font and weight combination is:
145
146 #. Loaded
147 #. Supported by the font
148 #. Supported by the rendering back-end
149
150 For known cross-platform ``weight`` strings, please see :py:class:`pyglet.text.Weight`.
151
152 * Constant names and values mimic OpenType and CSS (``"bold"``, ``"thin"``, ``"extrabold"``, etc)
153 * Some rendering back-ends *may* support additional weight string values
154
155 Shapes
156 ------
157 For consistency with the rest of the library, it was decided to represent
158 all angles in degrees instead of radians. Previously we had a mix of both,
159 which lead to some confusion. Using degrees also makes the API consistent
160 with Sprites and other rotatable objects, which have long used degrees.
161
162 The arguments for :py:class:`~pyglet.shapes.Line` have changed slightly.
163 Instead of "width", we now use "thickness". This matches with other shapes
164 that are made up of line segments. For example the :py:class:`~pyglet.shapes.Box`
165 shape, which already uses "width" (and height) to mean it's overall size.
166 Going forward, any shape that is made up of lines should use `thickness`
167 for the thickness/width of those lines.
168
169 .. _migration-controllers:
170
171 Controllers
172 -----------
173
174 Events from analog sticks and directional pads (d-pads) now pass
175 :py:class:`~pyglet.math.Vec2` instances to handler functions.
176
177 Vectors offer helper methods in addition to common math operators (`+`, `-`, `*`,
178 etc). Since this makes many tasks easier, we'll cover the most common ones below.
179
180
181 Handling Diagonals with the D-Pad
182 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
183
184 :py:class:`Vec2.normalize() <pyglet.math.Vec2.normalize>` makes it easy to
185 handle diagonal movement:
186
187 .. code-block:: python
188
189 # In pyglet 2.1, this handles diagonals
190 @controller.event
191 def on_dpad_motion(controller, vector):
192 # Multiplying a vector by an integer or float multiplies all components
193 player_position += vector.normalize() * PLAYER_SPEED
194
195 Without vectors, pre-2.1 code was more verbose:
196
197 .. code-block:: python
198
199 @controller.event
200 def on_dpad_motion(controller, dpleft, dpright, dpup, dpdown):
201 if dpleft:
202 # move left
203 if dpright:
204 # move right
205 if dpright and dpdown:
206 # move diagonally, but you have to normalize the values by yourself
207
208
209 Getting D-Pad Booleans
210 """"""""""""""""""""""
211 If you need boolean data, you can quickly convert from a :py:class:`~pyglet.math.Vec2`
212 like this::
213
214 dpleft, dpright, dpup, dpdown = vector.x < 0, vector.x > 0, vector.y > 0, vector.y < 0
215
216 Handling Analog Stick Drift
217 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
218 Analog sticks can "drift" when near zero, but vectors can help.
219
220 Circular Dead Zones
221 """""""""""""""""""
222 The simplest approach to drift is a circular "dead zone" which ignores input
223 with a :py:meth:`~pyglet.math.Vec2.length` beneath a certain threshold::
224
225 @controller.event
226 def on_stick_motion(controller, name, vector):
227 if vector.length() <= DEADZONE_RADIUS:
228 return
229 elif name == "leftstick":
230 # Do something with the 2D vector
231 elif name == "rightstick":
232 # Do something with the 2D vector
233
234 Non-Circular Sticks
235 """""""""""""""""""
236 :py:meth:`Vec2.normalize <pyglet.math.Vec2.normalize` can also help when
237 an unusual analog stick input could exceed ``1.0`` in length.
238
239 For example, a :py:class:`~pyglet.input.Controller` for a device with a non-circular
240 input range could return a value with a combined :py:meth:`~pyglet.math.Vec2.length`
241 greater than ``1.0``. Normalizating allows concisely clamping the input to ``1.0``::
242
243 # Avoid a "cheating" / bugged controller for movement
244 vector = min(vector, vector.normalize())
245 player.position += vector * PLAYER_SPEED
246
247
248 Accessing Vector Components
249 """"""""""""""""""""""""""
250 You can directly access individual :py:attr:`~pyglet.math.Vec2.x` and
251 :py:attr:`~pyglet.math.Vec2.y` attributes or unpack a vector:
252
253 .. code-block:: python
254
255 # Direct access
256 x = vector2.x
257 y = vector2.y
258
259 # Unpacking-style access
260 x, y = vector2
261
262 Please see the following to learn more about vectors in pyglet 2.1:
263
264 * The :ref:`migration-math` section of this page
265 * :py:class:`pyglet.math.Vec2`
266
267 Gui
268 ---
269
270 Widget Event Dispatching
271 ^^^^^^^^^^^^^^^^^^^^^^^^
272 All widget events now dispatch the widget instance itself as the first argument.
273
274 This is similar to how Controller/Joystick events are implemented. It allows
275 you to reuse a single handler functions across multiple widgets without "forgetting"
276 which widget dispatched an event.
277
278 Button Argument Names
279 ^^^^^^^^^^^^^^^^^^^^^
280
281 The :py:class:`~pyglet.gui.widgets.ToggleButton` and :py:class:`~pyglet.gui.widgets.PushButton`
282 widgets now use ``pressed`` and ``unpressed`` for their image arguments.
283
284 .. _migration-math:
285
286 Math
287 ----
288 The :py:mod:`~pyglet.math` module includes a number of performance and
289 usability changes.
290
291 Immutable Vectors and Matrices
292 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
293
294 All :py:mod:`~pyglet.math` datatypes are now :py:class:`typing.NamedTuple`
295 subclasses. This provides multiple benefits:
296
297 * More consistent creation syntax
298 * Vectors and matrices are now hashable
299
300 * They can be :py:class:`dict` keys or :py:class:`set` members
301 * Combine with ``/``, ``//``, :py:func:`round` or :py:func:`math.floor` for easy spatial hashing
302
303 * Cleaner controller code (see :ref:`migration-controllers`)
304
305 .. important:: The mypy typechecker is incompatible with :py:mod:`pyglet.math`.
306
307 When typechecking, it is a good idea to:
308
309 1. exclude :py:mod:`pyglet.math` from mypy checks
310 2. use pyright instead (pylance in VS Code)
311
312 Vector Changes
313 ^^^^^^^^^^^^^^
314
315 The syntax for the Vec types has changed in several ways.
316 Some of these changes are due to becoming :py:class:`typing.NamedTuple` subclasses, while others
317 were done for general usability. Where possible, we adopt the behavior of GLM/GLSL for most operations,
318 for a more familiar experience for computer graphics programmers.
319
320 * The arguments for ``Vec2.from_polar`` have been reversed for consistency. The ``length`` argument also now defaults
321 to 1.0. This will fail silently, so take care to correct this if you are using this method in your code::
322
323 Vec2.from_polar(angle: 'float', length: 'float' = 1.0)
324
325 * Vector length is now obtained from the new :py:meth:`~pyglet.math.Vec2.length` method. Previously ``len`` or ``abs``
326 could be used, but this is no longer the case. The ``len`` function will now give you the number of items in the
327 vector (ie: 2, 3, or 4), not the vector length. The ``abs`` function will give you a new vector with absolute values::
328
329 >>> vec = Vec2(1, 9)
330 >>> vec.length()
331 9.055385138137417
332 >>> len(vec)
333 2
334 >>>
335 >>> vec = Vec2(-10, 5)
336 >>> abs(vec)
337 Vec2(x=10, y=5)
338
339 * The vector ``heading`` property has been replace with the :py:meth:`~pyglet.math.Vec2.heading` function. This is to
340 better indicate that this is a calculation, not a static attribute. The function call is also marginally faster.
341
342 * The ``mag`` property has been removed. The :py:meth:`~pyglet.math.Vec2.length` function should be used in it's place.
343
344 * The ``Vec2.from_magnitude`` function has been removed. For creating a new vector of a certain magnitude, you can
345 simply multiply a normalized vector by the desired length. For example::
346
347 >>> vec = Vec2(1, 9)
348 >>> vec.normalize()
349 Vec2(x=0.11043152607484653, y=0.9938837346736188)
350 >>> vec.normalize() * 2
351 Vec2(x=0.22086305214969307, y=1.9877674693472376)
352
353
354 Matrix Creation Syntax
355 ^^^^^^^^^^^^^^^^^^^^^^
356
357 :py:class:`~pyglet.math.Mat3` and :py:mod:`pyglet.math.Mat4` now accept arguments
358 directly instead of an iterable.
359
360 If you create your matrices via the helper methods, nothing changes. If you
361 create matrices directly, pyglet 2.1 allows more efficient code:
362
363 .. code-block:: python
364
365 # pyglet 2.1 requires passing the elements directly
366 my_mat4 = pyglet.math.Mat4(1, 2, 3, 4, 5, ...)
367
368 # pyglet 2.0 required an intermediate iterable like a list
369 my_mat4 = pyglet.math.Mat4([1, 2, 3, 4, 5, ...])
370
371 If your pre-existing code has an ``intermediate_iterable``, you can use
372 ``*`` unpacking as a quick fix:
373
374 .. code-block:: python
375
376 # Use * unpacking to unpack the pre-allocated intermediate_iterable
377 my_mat4 = pyglet.math.Mat4(*intermediate_iterable)
378
379
380 Models
381 ------
382 The :py:mod:`~pyglet.model` module has seen some changes. This is an undocumented
383 WIP module for pyglet 2.0, and it remains so pyglet 2.1. That said, it's in a more
384 usable state now. The first change is that :py:meth:`~pyglet.model.load` now returns
385 a ``Scene`` object instead of a ``Model`` object. The Scene is a new, "pure data"
386 intermediate representation of a 3D scene, that closely mimics the layout of the glTF
387 format. The :py:meth:`~pyglet.model.Scene.create_models` method can be used to create
388 ``Model`` instances from the Scene, but the Scene data can also be manually iterated
389 over for more advanced use cases.
390
391 Canvas module
392 -------------
393 The ``pyglet.canvas`` module has been renamed to ``pyglet.display``. The "canvas"
394 concept was a work-in-progress in legacy pyglet, and was never fully fleshed out.
395 It appears to have been meant to allow arbitrary renderable areas, but this type
396 of functionality can now be easily accomplished with Framebuffers. The name ``display``
397 is a more accurate representation of what the code in the module actually relates to.
398 The usage is the same, with just the name change::
399
400 my_display = pyglet.canvas.get_display() # old pyglet 2.0
401 my_display = pyglet.display.get_display() # new pyglet 2.1
402