/
spritecache.py
353 lines (282 loc) · 13.6 KB
/
spritecache.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
__license__ = """
NML is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
NML is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with NML; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA."""
import array, json, os
from nml import generic
keep_orphaned = True
cache_root_dir = None
class SpriteCache:
"""
Cache for compressed sprites.
@ivar cache_filename: Filename of cache data file.
@type cache_filename: C{str}
@ivar cache_index_filename: Filename of cache index file.
@type cache_index_filename: C{str}
@ivar cache_time: Date of cache files. The cache is invalid, if the source image files are newer.
@type cache_time: C{int}
@ivar cached_sprites: Cache contents
@type cached_sprites: C{dict} mapping cache keys to cache items.
Cache file format description:
Format of cache index is JSON (JavaScript Object Notation), which is
easily readable by both humans (for debugging) and machines. Format is as follows:
A list of dictionaries, each corresponding to a sprite, with the following keys
- rgb_file: filename of the 32bpp sprite (string)
- rgb_rect: (uncropped) rectangle of the 32bpp sprite (list with 4 elements (x,y,w,h))
- mask_file, mask_rect: same as above, but for 8bpp sprite
- mask_pal: palette of mask file, 'DEFAULT' or 'LEGACY'. Not present if 'mask_file' is not present.
- crop: List of 4 positive integers, indicating how much to crop if cropping is enabled
Order is (left, right, top, bottom), it is not present if cropping is disabled
- info: Info byte of the sprite
- pixel_stats: Dictionary with statistics about pixels:
'total': Total amount of pixels.
'alpha': Amount of semi-transparent pixels in 32bpp.
'white': Amount of pure-white pixels in 8bpp.
'anim': Amount of animated pixels in 8bpp.
- offset: Offset into the cache file for this sprite
- size: Length of this sprite in the cache file
Either rgb_file/rect, mask_file/rect, or both must be specified, depending on the sprite
The cache should contain the sprite data, but not the header (sizes/offsets and such)
For easy lookup, this information is stored in a dictionary
Tuples are used because these are hashable
The key is a (rgb_file, rgb_rect, mask_file, mask_rect, do_crop, palette)-tuple
The rectangles are 4-tuples, non-existent items (e.g. no rgb) are None
do_crop is a boolean indicating if this sprite has been cropped
palette is a string identifier
The value that this key maps to is a 6-tuple, containing:
- the sprite data (as a byte array)
- The 'info' byte of the sprite
- The cropping information (see above) (None if 'do_crop' in the key is false)
- The pixel_stats dictionary with statistics.
- Whether the sprite exists in the old (loaded)cache
- whether the sprite is used by the current GRF
The cache file itself is simply the binary sprite data with no
meta-information or padding. Offsets and sizes for the various sprites
are in the cacheindex file.
"""
def __init__(self, sources=None):
self.sources = sources
self.cache_time = 0
self.cached_sprites = {}
def open_cache_index_file(self, write=False):
return _open_cache_file(self.sources, ".cacheindex", 'w' if write else 'r')
def open_cache_file(self, write=False):
return _open_cache_file(self.sources, ".cache", 'wb' if write else 'rb')
def get_item(self, cache_key, palette):
"""
Get item from cache.
@param cache_key: Sprite metadata key, as returned by RealSprite.get_cache_key
@type cache_key: C{tuple}
@param palette: Palette identifier, one of palette.palette_name
@type palette: C{str}
@return: Cache item
@rtype: C{tuple} or C{None}
"""
if cache_key[2] is not None:
key = cache_key + (palette, )
else:
key = cache_key + (None, )
return self.cached_sprites.get(key, None)
def add_item(self, cache_key, palette, item):
"""
Add item to cache.
@param cache_key: Sprite metadata key, as returned by RealSprite.get_cache_key
@type cache_key: C{tuple}
@param palette: Palette identifier, one of palette.palette_name
@type palette: C{str}
@param item: Cache item
@type item: C{tuple}
"""
if cache_key[2] is not None:
key = cache_key + (palette, )
else:
key = cache_key + (None, )
self.cached_sprites[key] = item
def count_orphaned(self):
"""
Count number of items in cache, which have not been used.
@return: Number of unused items.
@type: C{int}
"""
return sum(not item[5] for item in self.cached_sprites.values())
def read_cache(self):
"""
Read the *.grf.cache[index] files.
"""
index_file = self.open_cache_index_file()
cache_file = self.open_cache_file()
if not (index_file and cache_file):
return
cache_data = array.array('B')
cache_size = os.fstat(cache_file.fileno()).st_size
cache_data.fromfile(cache_file, cache_size)
assert cache_size == len(cache_data)
self.cache_time = os.path.getmtime(self.cache_filename)
source_mtime = dict()
try:
# Just assert and print a generic message on errors, as the cache data should be correct
# Not asserting could lead to errors later on
# Also, it doesn't make sense to inform the user about things he shouldn't know about and can't fix
sprite_index = json.load(index_file)
assert isinstance(sprite_index, list)
for sprite in sprite_index:
assert isinstance(sprite, dict)
# load RGB (32bpp) data
rgb_key = (None, None)
if 'rgb_file' in sprite and 'rgb_rect' in sprite:
assert isinstance(sprite['rgb_file'], str)
assert isinstance(sprite['rgb_rect'], list) and len(sprite['rgb_rect']) == 4
assert all(isinstance(num, int) for num in sprite['rgb_rect'])
rgb_key = (sprite['rgb_file'], tuple(sprite['rgb_rect']))
# load Mask (8bpp) data
mask_key = (None, None)
if 'mask_file' in sprite and 'mask_rect' in sprite:
assert isinstance(sprite['mask_file'], str)
assert isinstance(sprite['mask_rect'], list) and len(sprite['mask_rect']) == 4
assert all(isinstance(num, int) for num in sprite['mask_rect'])
mask_key = (sprite['mask_file'], tuple(sprite['mask_rect']))
palette_key = None
if 'mask_pal' in sprite:
palette_key = sprite['mask_pal']
# Compose key
assert any(i is not None for i in rgb_key + mask_key)
key = rgb_key + mask_key + ('crop' in sprite, palette_key)
assert key not in self.cached_sprites
# Read size/offset from cache
assert 'offset' in sprite and 'size' in sprite
offset, size = sprite['offset'], sprite['size']
assert isinstance(offset, int) and isinstance(size, int)
assert offset >= 0 and size > 0
assert offset + size <= cache_size
data = cache_data[offset:offset+size]
# Read info / cropping data from cache
assert 'info' in sprite and isinstance(sprite['info'], int)
info = sprite['info']
if 'crop' in sprite:
assert isinstance(sprite['crop'], list) and len(sprite['crop']) == 4
assert all(isinstance(num, int) for num in sprite['crop'])
crop = tuple(sprite['crop'])
else:
crop = None
if 'pixel_stats' in sprite:
assert isinstance(sprite['pixel_stats'], dict)
pixel_stats = sprite['pixel_stats']
else:
pixel_stats = {}
# Compose value
value = (data, info, crop, pixel_stats, True, False)
# Check if cache item is still valid
is_valid = True
if rgb_key[0] is not None:
mtime = source_mtime.get(rgb_key[0])
if mtime is None:
mtime = os.path.getmtime(generic.find_file(rgb_key[0]))
source_mtime[rgb_key[0]] = mtime
if mtime > self.cache_time:
is_valid = False
if mask_key[0] is not None:
mtime = source_mtime.get(mask_key[0])
if mtime is None:
mtime = os.path.getmtime(generic.find_file(mask_key[0]))
source_mtime[mask_key[0]] = mtime
if mtime > self.cache_time:
is_valid = False
# Drop items from older spritecache format without palette entry
if (mask_key[0] is None) != (palette_key is None):
is_valid = False
if is_valid:
self.cached_sprites[key] = value
except:
generic.print_warning(self.cache_index_filename + " contains invalid data, ignoring. Please remove the file and file a bug report if this warning keeps appearing")
self.cached_sprites = {} # Clear cache
index_file.close()
cache_file.close()
def write_cache(self):
"""
Write the cache data to the .cache[index] files.
"""
if cache_root_dir is None:
return
index_data = []
sprite_data = array.array('B')
offset = 0
old_cache_valid = True
for key, value in self.cached_sprites.items():
# Unpack key/value
rgb_file, rgb_rect, mask_file, mask_rect, do_crop, mask_pal = key
data, info, crop_rect, pixel_stats, in_old_cache, in_use = value
assert do_crop == (crop_rect is not None)
assert (mask_file is None) == (mask_pal is None)
# If this cache information is exactly the same as the old cache, then we don't bother writing later on
if not in_use and not keep_orphaned:
old_cache_valid = False
continue
if not in_old_cache:
old_cache_valid = False
# Create dictionary with information
sprite = {}
if rgb_file is not None:
sprite['rgb_file'] = rgb_file
sprite['rgb_rect'] = tuple(rgb_rect)
if mask_file is not None:
sprite['mask_file'] = mask_file
sprite['mask_rect'] = tuple(mask_rect)
sprite['mask_pal'] = mask_pal
size = len(data)
sprite['offset'] = offset
sprite['size'] = size
sprite['info'] = info
if do_crop: sprite['crop'] = tuple(crop_rect)
sprite['pixel_stats'] = pixel_stats
index_data.append(sprite)
sprite_data.extend(data)
offset += size
if old_cache_valid: return
index_output = json.JSONEncoder(sort_keys = True).encode(index_data)
with self.open_cache_index_file(write=True) as index_file:
index_file.write(index_output)
with self.open_cache_file(write=True) as cache_file:
sprite_data.tofile(cache_file)
def _open_cache_file(sources, extension, mode):
"""
Open a file in the cache directory.
@param sources: List of source files, the cache file depends on / belongs to.
@type sources: C{list} or C{tuple} of C{str} or similar.
@param extension: File extension for the cache file including leading ".".
@type extension: C{str}
@param mode: Mode to use in open() - 'r', 'w', 'rb' or 'wb'
@type mode: C{str}
@return: Filename for cache file.
@rtype: C{io.IOBase}, or C{None} if the file can't be opened.
"""
if cache_root_dir = None or not sources:
return None
filepath = ""
for part in sources:
if part is None:
continue
path, name = os.path.split(part)
if len(filename) == 0:
# Make sure that the path does not leave the cache dir
path = os.path.normpath(path).replace(os.path.pardir, "__")
filepath = os.path.join(cache_root_dir, path, name)
else:
# In case of multiple source files, ignore the path component for all but the first
filepath += "_" + name
filepath += extension
try:
if 'w' in mode:
os.makedirs(os.dirname(filepath), exist_ok=True)
return open(filepath, mode)
except OSError:
if 'w' in mode:
generic.print_warning(f"Can't create cache file {filepath}. Check permissions, or use --cache-dir or --no-cache.")
return None