Debian Codegraph @

doc/programming_guide/resources.rst

raw
1 .. _guide_resources:
2
3 Application resources
4 =====================
5
6 Previous sections in this guide have described how to load images, media and
7 text documents using pyglet. Applications also usually have the need to load
8 other data files: for example, level descriptions in a game, internationalised
9 strings, and so on.
10
11 Programmers are often tempted to load, for example, an image required by their
12 application with::
13
14 image = pyglet.image.load('logo.png')
15
16 This code assumes ``logo.png`` is in the current working directory.
17 Unfortunately the working directory is not necessarily the same as the
18 directory containing the application script files.
19
20 * Applications started from the command line can start from an arbitrary
21 working directory.
22 * Applications bundled into an egg, Mac OS X package or Windows executable
23 may have their resources inside a ZIP file.
24 * The application might need to change the working directory in order to
25 work with the user's files.
26
27 A common workaround for this is to construct a path relative to the script
28 file instead of the working directory::
29
30 import os
31
32 script_dir = os.path.dirname(__file__)
33 path = os.path.join(script_dir, 'logo.png')
34 image = pyglet.image.load(path)
35
36 This, besides being tedious to write, still does not work for resources within
37 ZIP files, and can be troublesome in projects that span multiple packages.
38
39 The :py:mod:`pyglet.resource` module solves this problem elegantly::
40
41 image = pyglet.resource.image('logo.png')
42
43 The following sections describe exactly how the resources are located, and how
44 the behaviour can be customised.
45
46 Loading resources
47 -----------------
48
49 Use the :py:mod:`pyglet.resource` module when files shipped with the
50 application need to be loaded. For example, instead of writing::
51
52 data_file = open('file.txt')
53
54 use::
55
56 data_file = pyglet.resource.file('file.txt')
57
58 There are also convenience functions for loading media files for pyglet. The
59 following table shows the equivalent resource functions for the standard file
60 functions.
61
62 .. list-table::
63 :header-rows: 1
64
65 * - File function
66 - Resource function
67 - Type
68 * - ``open``
69 - :py:func:`pyglet.resource.file`
70 - File-like object
71 * - :py:func:`pyglet.image.load`
72 - :py:func:`pyglet.resource.image`
73 - :py:class:`~pyglet.image.Texture` or :py:class:`~pyglet.image.TextureRegion`
74 * - :py:func:`pyglet.image.load`
75 - :py:func:`pyglet.resource.texture`
76 - :py:class:`~pyglet.image.Texture`
77 * - :py:func:`pyglet.image.load_animation`
78 - :py:func:`pyglet.resource.animation`
79 - :py:class:`~pyglet.image.Animation`
80 * - :py:func:`pyglet.media.load`
81 - :py:func:`pyglet.resource.media`
82 - :py:class:`~pyglet.media.Source`
83 * - | :py:func:`pyglet.text.load`
84 | mimetype = ``text/plain``
85 - :py:func:`pyglet.resource.text`
86 - :py:class:`~pyglet.text.document.UnformattedDocument`
87 * - | :py:func:`pyglet.text.load`
88 | mimetype = ``text/html``
89 - :py:func:`pyglet.resource.html`
90 - :py:class:`~pyglet.text.document.FormattedDocument`
91 * - | :py:func:`pyglet.text.load`
92 | mimetype = ``text/vnd.pyglet-attributed``
93 - :py:func:`pyglet.resource.attributed`
94 - :py:class:`~pyglet.text.document.FormattedDocument`
95 * - :py:func:`pyglet.font.add_file`
96 - :py:func:`pyglet.resource.add_font`
97 - ``None``
98
99 :py:func:`pyglet.resource.texture` is for loading stand-alone textures.
100 This can be useful when using the texture for a 3D model, or generally
101 working with OpenGL directly.
102
103 :py:func:`pyglet.resource.image` is optimised for loading sprite-like
104 images that can have their texture coordinates adjusted.
105 The resource module attempts to pack small images into larger texture atlases
106 (explained in :ref:`guide_texture-bins-and-atlases`) for efficient rendering
107 (which is why the return type of this function can be
108 :py:class:`~pyglet.image.TextureRegion`).
109 It is also advisable to use the texture atlas classes directly if you wish
110 to have different anchor points on multiple copies of the same image.
111 This is because when loading an image more than once, you will actually get
112 the **same** object back. You can still use the resource module for getting
113 the image location, and described in the next section.
114
115
116 Resource locations
117 ^^^^^^^^^^^^^^^^^^
118
119 Some resource files reference other files by name. For example, an HTML
120 document can contain ``<img src="image.png" />`` elements. In this case your
121 application needs to locate ``image.png`` relative to the original HTML file.
122
123 Use :py:func:`pyglet.resource.location` to get a
124 :py:class:`~pyglet.resource.Location` object describing the location of an
125 application resource. This location might be a file system
126 directory or a directory within a ZIP file.
127 The :py:class:`~pyglet.resource.Location` object can directly open files by
128 name, so your application does not need to distinguish between these cases.
129
130 In the following example, a ``thumbnails.txt`` file is assumed to contain a
131 list of image filenames (one per line), which are then loaded assuming the
132 image files are located in the same directory as the ``thumbnails.txt`` file::
133
134 thumbnails_file = pyglet.resource.file('thumbnails.txt', 'rt')
135 thumbnails_location = pyglet.resource.location('thumbnails.txt')
136
137 for line in thumbnails_file:
138 filename = line.strip()
139 image_file = thumbnails_location.open(filename)
140 image = pyglet.image.load(filename, file=image_file)
141 # Do something with `image`...
142
143 This code correctly ignores other images with the same filename that might
144 appear elsewhere on the resource path.
145
146 Specifying the resource path
147 ----------------------------
148
149 By default, only the script home directory is searched (the directory
150 containing the ``__main__`` module).
151 You can set :py:attr:`pyglet.resource.path` to a list of locations to
152 search in order. This list is indexed, so after modifying it you will
153 need to call :py:func:`pyglet.resource.reindex`.
154
155 Each item in the path list is either a path relative to the script home, or
156 the name of a Python module preceded with an "at" symbol (``@``). For example,
157 if you would like to package all your resources in a ``res`` directory::
158
159 pyglet.resource.path = ['res']
160 pyglet.resource.reindex()
161
162 Items on the path are not searched recursively, so if your resource directory
163 itself has subdirectories, these need to be specified explicitly::
164
165 pyglet.resource.path = ['res', 'res/images', 'res/sounds', 'res/fonts']
166 pyglet.resource.reindex()
167
168 The entries in the resource path always use forward slash characters as path
169 separators even when the operating systems using a different character.
170
171 Specifying module names makes it easy to group code with its resources. The
172 following example uses the directory containing the hypothetical
173 ``gui.skins.default`` for resources::
174
175 pyglet.resource.path = ['@gui.skins.default', '.']
176 pyglet.resource.reindex()
177
178 Multiple loaders
179 ----------------
180
181 A :py:class:`~pyglet.resource.Loader` encapsulates a complete resource path
182 and cache. This lets your application cleanly separate resource loading of
183 different modules.
184 Loaders are constructed for a given search path, andnexposes the same methods
185 as the global :py:mod:`pyglet.resource` module functions.
186
187 For example, if a module needs to load its own graphics but does not want to
188 interfere with the rest of the application's resource loading, it would create
189 its own :py:class:`~pyglet.resource.Loader` with a local search path::
190
191 loader = pyglet.resource.Loader(['@' + __name__])
192 image = loader.image('logo.png')
193
194 This is particularly suitable for "plugin" modules.
195
196 You can also use a :py:class:`~pyglet.resource.Loader` instance to load a set
197 of resources relative to some user-specified document directory.
198 The following example creates a loader for a directory specified on the
199 command line::
200
201 import sys
202 home = sys.argv[1]
203 loader = pyglet.resource.Loader(script_home=[home])
204
205 This is the only way that absolute directories and resources not bundled with
206 an application should be used with :py:mod:`pyglet.resource`.
207
208 Saving user preferences and data
209 --------------------------------
210
211 Because Python applications can be distributed in several ways, including
212 within ZIP files, it is usually not feasible to save user preferences, high
213 score lists, and so on within the application directory (or worse, the working
214 directory). The resource module provides functions for assisting with this.
215
216 The :py:func:`pyglet.resource.get_settings_path` function returns a directory
217 suitable for writing configuration related data. The directory used follows
218 the operating system's convention:
219
220 * ``~/.config/ApplicationName/`` on Linux (depends on `XDG_CONFIG_HOME` environment variable).
221 * ``$HOME\Application Settings\ApplicationName`` on Windows
222 * ``~/Library/Application Support/ApplicationName`` on Mac OS X
223
224 The :py:func:`pyglet.resource.get_data_path` function returns a directory
225 suitable for writing arbitrary data, such as save files. The directory used follows
226 the operating system's convention:
227
228 * ``~/.local/share/ApplicationName/`` on Linux (depends on `XDG_DATA_HOME` environment variable).
229 * ``$HOME\Application Settings\ApplicationName`` on Windows
230 * ``~/Library/Application Support/ApplicationName`` on Mac OS X
231
232 The returned directory names are not guaranteed to exist -- it is the
233 application's responsibility to create them. The following example opens a high
234 score list file for a game called "SuperGame" into the data directory::
235
236 import os
237
238 dir = pyglet.resource.get_data_path('SuperGame')
239 if not os.path.exists(dir):
240 os.makedirs(dir)
241 filename = os.path.join(dir, 'highscores.txt')
242 file = open(filename, 'wt')