OpenTTD Source: src/spritecache.cpp Source File

OpenTTD Source 13.2.1

spritecache.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD 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, version 2.
4 * OpenTTD 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.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10 #include "stdafx.h"
11 #include "random_access_file_type.h"
12 #include "spriteloader/grf.hpp"
13 #include "gfx_func.h"
14 #include "error.h"
15 #include "zoom_func.h"
16 #include "settings_type.h"
17 #include "blitter/factory.hpp"
18 #include "core/math_func.hpp"
19 #include "core/mem_func.hpp"
20 #include "video/video_driver.hpp"
21
22 #include "table/sprites.h"
23 #include "table/strings.h"
24 #include "table/palette_convert.h"
25
26 #include "safeguards.h"
27
28 /* Default of 4MB spritecache */
29 uint _sprite_cache_size = 4;
30
31 struct SpriteCache {
32 void *ptr;
33 size_t file_pos;
34 SpriteFile *file;
35 uint32 id;
36 int16 lru;
37 SpriteType type;
38 bool warned;
39 byte control_flags;
40 };
41
42
43 static uint _spritecache_items = 0;
44 static SpriteCache *_spritecache = nullptr;
45 static std::vector<std::unique_ptr<SpriteFile>> _sprite_files;
46
47 static inline SpriteCache *GetSpriteCache(uint index)
48 {
49 return &_spritecache[index];
50 }
51
52 static inline bool IsMapgenSpriteID(SpriteID sprite)
53 {
54 return IsInsideMM(sprite, 4845, 4882);
55 }
56
57 static SpriteCache *AllocateSpriteCache(uint index)
58 {
59 if (index >= _spritecache_items) {
60 /* Add another 1024 items to the 'pool' */
61 uint items = Align(index + 1, 1024);
62
63 Debug(sprite, 4, "Increasing sprite cache to {} items ({} bytes)", items, items * sizeof(*_spritecache));
64
65 _spritecache = ReallocT(_spritecache, items);
66
67 /* Reset the new items and update the count */
68 memset(_spritecache + _spritecache_items, 0, (items - _spritecache_items) * sizeof(*_spritecache));
69 _spritecache_items = items;
70 }
71
72 return GetSpriteCache(index);
73 }
74
80 static SpriteFile *GetCachedSpriteFileByName(const std::string &filename) {
81 for (auto &f : _sprite_files) {
82 if (f->GetFilename() == filename) {
83 return f.get();
84 }
85 }
86 return nullptr;
87 }
88
96 SpriteFile &OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
97 {
98 SpriteFile *file = GetCachedSpriteFileByName(filename);
99 if (file == nullptr) {
100 file = _sprite_files.emplace_back(new SpriteFile(filename, subdir, palette_remap)).get();
101 } else {
102 file->SeekToBegin();
103 }
104 return *file;
105 }
106
107 struct MemBlock {
108 size_t size;
109 byte data[];
110 };
111
112 static uint _sprite_lru_counter;
113 static MemBlock *_spritecache_ptr;
114 static uint _allocated_sprite_cache_size = 0;
115 static int _compact_cache_counter;
116
117 static void CompactSpriteCache();
118 static void *AllocSprite(size_t mem_req);
119
126 bool SkipSpriteData(SpriteFile &file, byte type, uint16 num)
127 {
128 if (type & 2) {
129 file.SkipBytes(num);
130 } else {
131 while (num > 0) {
132 int8 i = file.ReadByte();
133 if (i >= 0) {
134 int size = (i == 0) ? 0x80 : i;
135 if (size > num) return false;
136 num -= size;
137 file.SkipBytes(size);
138 } else {
139 i = -(i >> 3);
140 num -= i;
141 file.ReadByte();
142 }
143 }
144 }
145 return true;
146 }
147
148 /* Check if the given Sprite ID exists */
149 bool SpriteExists(SpriteID id)
150 {
151 if (id >= _spritecache_items) return false;
152
153 /* Special case for Sprite ID zero -- its position is also 0... */
154 if (id == 0) return true;
155 return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file == nullptr);
156 }
157
163 SpriteType GetSpriteType(SpriteID sprite)
164 {
165 if (!SpriteExists(sprite)) return ST_INVALID;
166 return GetSpriteCache(sprite)->type;
167 }
168
174 SpriteFile *GetOriginFile(SpriteID sprite)
175 {
176 if (!SpriteExists(sprite)) return nullptr;
177 return GetSpriteCache(sprite)->file;
178 }
179
185 uint32 GetSpriteLocalID(SpriteID sprite)
186 {
187 if (!SpriteExists(sprite)) return 0;
188 return GetSpriteCache(sprite)->id;
189 }
190
198 uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
199 {
200 SpriteFile *file = GetCachedSpriteFileByName(filename);
201 if (file == nullptr) return 0;
202
203 uint count = 0;
204 for (SpriteID i = begin; i != end; i++) {
205 if (SpriteExists(i)) {
206 SpriteCache *sc = GetSpriteCache(i);
207 if (sc->file == file) count++;
208 }
209 }
210 return count;
211 }
212
221 uint GetMaxSpriteID()
222 {
223 return _spritecache_items;
224 }
225
226 static bool ResizeSpriteIn(SpriteLoader::Sprite *sprite, ZoomLevel src, ZoomLevel tgt)
227 {
228 uint8 scaled_1 = ScaleByZoom(1, (ZoomLevel)(src - tgt));
229
230 /* Check for possible memory overflow. */
231 if (sprite[src].width * scaled_1 > UINT16_MAX || sprite[src].height * scaled_1 > UINT16_MAX) return false;
232
233 sprite[tgt].width = sprite[src].width * scaled_1;
234 sprite[tgt].height = sprite[src].height * scaled_1;
235 sprite[tgt].x_offs = sprite[src].x_offs * scaled_1;
236 sprite[tgt].y_offs = sprite[src].y_offs * scaled_1;
237 sprite[tgt].colours = sprite[src].colours;
238
239 sprite[tgt].AllocateData(tgt, sprite[tgt].width * sprite[tgt].height);
240
241 SpriteLoader::CommonPixel *dst = sprite[tgt].data;
242 for (int y = 0; y < sprite[tgt].height; y++) {
243 const SpriteLoader::CommonPixel *src_ln = &sprite[src].data[y / scaled_1 * sprite[src].width];
244 for (int x = 0; x < sprite[tgt].width; x++) {
245 *dst = src_ln[x / scaled_1];
246 dst++;
247 }
248 }
249
250 return true;
251 }
252
253 static void ResizeSpriteOut(SpriteLoader::Sprite *sprite, ZoomLevel zoom)
254 {
255 /* Algorithm based on 32bpp_Optimized::ResizeSprite() */
256 sprite[zoom].width = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].width, zoom);
257 sprite[zoom].height = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].height, zoom);
258 sprite[zoom].x_offs = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].x_offs, zoom);
259 sprite[zoom].y_offs = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].y_offs, zoom);
260 sprite[zoom].colours = sprite[ZOOM_LVL_NORMAL].colours;
261
262 sprite[zoom].AllocateData(zoom, sprite[zoom].height * sprite[zoom].width);
263
264 SpriteLoader::CommonPixel *dst = sprite[zoom].data;
265 const SpriteLoader::CommonPixel *src = sprite[zoom - 1].data;
266 [[maybe_unused]] const SpriteLoader::CommonPixel *src_end = src + sprite[zoom - 1].height * sprite[zoom - 1].width;
267
268 for (uint y = 0; y < sprite[zoom].height; y++) {
269 const SpriteLoader::CommonPixel *src_ln = src + sprite[zoom - 1].width;
270 assert(src_ln <= src_end);
271 for (uint x = 0; x < sprite[zoom].width; x++) {
272 assert(src < src_ln);
273 if (src + 1 != src_ln && (src + 1)->a != 0) {
274 *dst = *(src + 1);
275 } else {
276 *dst = *src;
277 }
278 dst++;
279 src += 2;
280 }
281 src = src_ln + sprite[zoom - 1].width;
282 }
283 }
284
285 static bool PadSingleSprite(SpriteLoader::Sprite *sprite, ZoomLevel zoom, uint pad_left, uint pad_top, uint pad_right, uint pad_bottom)
286 {
287 uint width = sprite->width + pad_left + pad_right;
288 uint height = sprite->height + pad_top + pad_bottom;
289
290 if (width > UINT16_MAX || height > UINT16_MAX) return false;
291
292 /* Copy source data and reallocate sprite memory. */
293 SpriteLoader::CommonPixel *src_data = MallocT<SpriteLoader::CommonPixel>(sprite->width * sprite->height);
294 MemCpyT(src_data, sprite->data, sprite->width * sprite->height);
295 sprite->AllocateData(zoom, width * height);
296
297 /* Copy with padding to destination. */
298 SpriteLoader::CommonPixel *src = src_data;
299 SpriteLoader::CommonPixel *data = sprite->data;
300 for (uint y = 0; y < height; y++) {
301 if (y < pad_top || pad_bottom + y >= height) {
302 /* Top/bottom padding. */
303 MemSetT(data, 0, width);
304 data += width;
305 } else {
306 if (pad_left > 0) {
307 /* Pad left. */
308 MemSetT(data, 0, pad_left);
309 data += pad_left;
310 }
311
312 /* Copy pixels. */
313 MemCpyT(data, src, sprite->width);
314 src += sprite->width;
315 data += sprite->width;
316
317 if (pad_right > 0) {
318 /* Pad right. */
319 MemSetT(data, 0, pad_right);
320 data += pad_right;
321 }
322 }
323 }
324 free(src_data);
325
326 /* Update sprite size. */
327 sprite->width = width;
328 sprite->height = height;
329 sprite->x_offs -= pad_left;
330 sprite->y_offs -= pad_top;
331
332 return true;
333 }
334
335 static bool PadSprites(SpriteLoader::Sprite *sprite, uint8 sprite_avail, SpriteEncoder *encoder)
336 {
337 /* Get minimum top left corner coordinates. */
338 int min_xoffs = INT32_MAX;
339 int min_yoffs = INT32_MAX;
340 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
341 if (HasBit(sprite_avail, zoom)) {
342 min_xoffs = std::min(min_xoffs, ScaleByZoom(sprite[zoom].x_offs, zoom));
343 min_yoffs = std::min(min_yoffs, ScaleByZoom(sprite[zoom].y_offs, zoom));
344 }
345 }
346
347 /* Get maximum dimensions taking necessary padding at the top left into account. */
348 int max_width = INT32_MIN;
349 int max_height = INT32_MIN;
350 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
351 if (HasBit(sprite_avail, zoom)) {
352 max_width = std::max(max_width, ScaleByZoom(sprite[zoom].width + sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom), zoom));
353 max_height = std::max(max_height, ScaleByZoom(sprite[zoom].height + sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom), zoom));
354 }
355 }
356
357 /* Align height and width if required to match the needs of the sprite encoder. */
358 uint align = encoder->GetSpriteAlignment();
359 if (align != 0) {
360 max_width = Align(max_width, align);
361 max_height = Align(max_height, align);
362 }
363
364 /* Pad sprites where needed. */
365 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
366 if (HasBit(sprite_avail, zoom)) {
367 /* Scaling the sprite dimensions in the blitter is done with rounding up,
368 * so a negative padding here is not an error. */
369 int pad_left = std::max(0, sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom));
370 int pad_top = std::max(0, sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom));
371 int pad_right = std::max(0, UnScaleByZoom(max_width, zoom) - sprite[zoom].width - pad_left);
372 int pad_bottom = std::max(0, UnScaleByZoom(max_height, zoom) - sprite[zoom].height - pad_top);
373
374 if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) {
375 if (!PadSingleSprite(&sprite[zoom], zoom, pad_left, pad_top, pad_right, pad_bottom)) return false;
376 }
377 }
378 }
379
380 return true;
381 }
382
383 static bool ResizeSprites(SpriteLoader::Sprite *sprite, uint8 sprite_avail, SpriteEncoder *encoder)
384 {
385 /* Create a fully zoomed image if it does not exist */
386 ZoomLevel first_avail = static_cast<ZoomLevel>(FIND_FIRST_BIT(sprite_avail));
387 if (first_avail != ZOOM_LVL_NORMAL) {
388 if (!ResizeSpriteIn(sprite, first_avail, ZOOM_LVL_NORMAL)) return false;
389 SetBit(sprite_avail, ZOOM_LVL_NORMAL);
390 }
391
392 /* Pad sprites to make sizes match. */
393 if (!PadSprites(sprite, sprite_avail, encoder)) return false;
394
395 /* Create other missing zoom levels */
396 for (ZoomLevel zoom = ZOOM_LVL_OUT_2X; zoom != ZOOM_LVL_END; zoom++) {
397 if (HasBit(sprite_avail, zoom)) {
398 /* Check that size and offsets match the fully zoomed image. */
399 assert(sprite[zoom].width == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].width, zoom));
400 assert(sprite[zoom].height == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].height, zoom));
401 assert(sprite[zoom].x_offs == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].x_offs, zoom));
402 assert(sprite[zoom].y_offs == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].y_offs, zoom));
403 }
404
405 /* Zoom level is not available, or unusable, so create it */
406 if (!HasBit(sprite_avail, zoom)) ResizeSpriteOut(sprite, zoom);
407 }
408
409 return true;
410 }
411
418 static void *ReadRecolourSprite(SpriteFile &file, uint num)
419 {
420 /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
421 * number of recolour sprites that are 17 bytes that only exist in DOS
422 * GRFs which are the same as 257 byte recolour sprites, but with the last
423 * 240 bytes zeroed. */
424 static const uint RECOLOUR_SPRITE_SIZE = 257;
425 byte *dest = (byte *)AllocSprite(std::max(RECOLOUR_SPRITE_SIZE, num));
426
427 if (file.NeedsPaletteRemap()) {
428 byte *dest_tmp = AllocaM(byte, std::max(RECOLOUR_SPRITE_SIZE, num));
429
430 /* Only a few recolour sprites are less than 257 bytes */
431 if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
432 file.ReadBlock(dest_tmp, num);
433
434 /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
435 for (uint i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
436 dest[i] = _palmap_w2d[dest_tmp[_palmap_d2w[i - 1] + 1]];
437 }
438 } else {
439 file.ReadBlock(dest, num);
440 }
441
442 return dest;
443 }
444
454 static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, AllocatorProc *allocator, SpriteEncoder *encoder)
455 {
456 /* Use current blitter if no other sprite encoder is given. */
457 if (encoder == nullptr) encoder = BlitterFactory::GetCurrentBlitter();
458
459 SpriteFile &file = *sc->file;
460 size_t file_pos = sc->file_pos;
461
462 assert(sprite_type != ST_RECOLOUR);
463 assert(IsMapgenSpriteID(id) == (sprite_type == ST_MAPGEN));
464 assert(sc->type == sprite_type);
465
466 Debug(sprite, 9, "Load sprite {}", id);
467
468 SpriteLoader::Sprite sprite[ZOOM_LVL_COUNT];
469 uint8 sprite_avail = 0;
470 sprite[ZOOM_LVL_NORMAL].type = sprite_type;
471
472 SpriteLoaderGrf sprite_loader(file.GetContainerVersion());
473 if (sprite_type != ST_MAPGEN && encoder->Is32BppSupported()) {
474 /* Try for 32bpp sprites first. */
475 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, true, sc->control_flags);
476 }
477 if (sprite_avail == 0) {
478 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, false, sc->control_flags);
479 }
480
481 if (sprite_avail == 0) {
482 if (sprite_type == ST_MAPGEN) return nullptr;
483 if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
484 return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator, encoder);
485 }
486
487 if (sprite_type == ST_MAPGEN) {
488 /* Ugly hack to work around the problem that the old landscape
489 * generator assumes that those sprites are stored uncompressed in
490 * the memory, and they are only read directly by the code, never
491 * send to the blitter. So do not send it to the blitter (which will
492 * result in a data array in the format the blitter likes most), but
493 * extract the data directly and store that as sprite.
494 * Ugly: yes. Other solution: no. Blame the original author or
495 * something ;) The image should really have been a data-stream
496 * (so type = 0xFF basically). */
497 uint num = sprite[ZOOM_LVL_NORMAL].width * sprite[ZOOM_LVL_NORMAL].height;
498
499 Sprite *s = (Sprite *)allocator(sizeof(*s) + num);
500 s->width = sprite[ZOOM_LVL_NORMAL].width;
501 s->height = sprite[ZOOM_LVL_NORMAL].height;
502 s->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
503 s->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
504
505 SpriteLoader::CommonPixel *src = sprite[ZOOM_LVL_NORMAL].data;
506 byte *dest = s->data;
507 while (num-- > 0) {
508 *dest++ = src->m;
509 src++;
510 }
511
512 return s;
513 }
514
515 if (!ResizeSprites(sprite, sprite_avail, encoder)) {
516 if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?");
517 return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator, encoder);
518 }
519
520 if (sprite->type == ST_FONT && ZOOM_LVL_GUI != ZOOM_LVL_NORMAL) {
521 /* Make ZOOM_LVL_NORMAL be ZOOM_LVL_GUI */
522 sprite[ZOOM_LVL_NORMAL].width = sprite[ZOOM_LVL_GUI].width;
523 sprite[ZOOM_LVL_NORMAL].height = sprite[ZOOM_LVL_GUI].height;
524 sprite[ZOOM_LVL_NORMAL].x_offs = sprite[ZOOM_LVL_GUI].x_offs;
525 sprite[ZOOM_LVL_NORMAL].y_offs = sprite[ZOOM_LVL_GUI].y_offs;
526 sprite[ZOOM_LVL_NORMAL].data = sprite[ZOOM_LVL_GUI].data;
527 sprite[ZOOM_LVL_NORMAL].colours = sprite[ZOOM_LVL_GUI].colours;
528 }
529
530 return encoder->Encode(sprite, allocator);
531 }
532
533 struct GrfSpriteOffset {
534 size_t file_pos;
535 byte control_flags;
536 };
537
539 static std::map<uint32, GrfSpriteOffset> _grf_sprite_offsets;
540
546 size_t GetGRFSpriteOffset(uint32 id)
547 {
548 return _grf_sprite_offsets.find(id) != _grf_sprite_offsets.end() ? _grf_sprite_offsets[id].file_pos : SIZE_MAX;
549 }
550
555 void ReadGRFSpriteOffsets(SpriteFile &file)
556 {
557 _grf_sprite_offsets.clear();
558
559 if (file.GetContainerVersion() >= 2) {
560 /* Seek to sprite section of the GRF. */
561 size_t data_offset = file.ReadDword();
562 size_t old_pos = file.GetPos();
563 file.SeekTo(data_offset, SEEK_CUR);
564
565 GrfSpriteOffset offset = { 0, 0 };
566
567 /* Loop over all sprite section entries and store the file
568 * offset for each newly encountered ID. */
569 uint32 id, prev_id = 0;
570 while ((id = file.ReadDword()) != 0) {
571 if (id != prev_id) {
572 _grf_sprite_offsets[prev_id] = offset;
573 offset.file_pos = file.GetPos() - 4;
574 offset.control_flags = 0;
575 }
576 prev_id = id;
577 uint length = file.ReadDword();
578 if (length > 0) {
579 byte colour = file.ReadByte() & SCC_MASK;
580 length--;
581 if (length > 0) {
582 byte zoom = file.ReadByte();
583 length--;
584 if (colour != 0 && zoom == 0) { // ZOOM_LVL_OUT_4X (normal zoom)
585 SetBit(offset.control_flags, (colour != SCC_PAL) ? SCCF_ALLOW_ZOOM_MIN_1X_32BPP : SCCF_ALLOW_ZOOM_MIN_1X_PAL);
586 SetBit(offset.control_flags, (colour != SCC_PAL) ? SCCF_ALLOW_ZOOM_MIN_2X_32BPP : SCCF_ALLOW_ZOOM_MIN_2X_PAL);
587 }
588 if (colour != 0 && zoom == 2) { // ZOOM_LVL_OUT_2X (2x zoomed in)
589 SetBit(offset.control_flags, (colour != SCC_PAL) ? SCCF_ALLOW_ZOOM_MIN_2X_32BPP : SCCF_ALLOW_ZOOM_MIN_2X_PAL);
590 }
591 }
592 }
593 file.SkipBytes(length);
594 }
595 if (prev_id != 0) _grf_sprite_offsets[prev_id] = offset;
596
597 /* Continue processing the data section. */
598 file.SeekTo(old_pos, SEEK_SET);
599 }
600 }
601
602
611 bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
612 {
613 size_t file_pos = file.GetPos();
614
615 /* Read sprite header. */
616 uint32 num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
617 if (num == 0) return false;
618 byte grf_type = file.ReadByte();
619
620 SpriteType type;
621 void *data = nullptr;
622 byte control_flags = 0;
623 if (grf_type == 0xFF) {
624 /* Some NewGRF files have "empty" pseudo-sprites which are 1
625 * byte long. Catch these so the sprites won't be displayed. */
626 if (num == 1) {
627 file.ReadByte();
628 return false;
629 }
630 type = ST_RECOLOUR;
631 data = ReadRecolourSprite(file, num);
632 } else if (file.GetContainerVersion() >= 2 && grf_type == 0xFD) {
633 if (num != 4) {
634 /* Invalid sprite section include, ignore. */
635 file.SkipBytes(num);
636 return false;
637 }
638 /* It is not an error if no sprite with the provided ID is found in the sprite section. */
639 auto iter = _grf_sprite_offsets.find(file.ReadDword());
640 if (iter != _grf_sprite_offsets.end()) {
641 file_pos = iter->second.file_pos;
642 control_flags = iter->second.control_flags;
643 } else {
644 file_pos = SIZE_MAX;
645 }
646 type = ST_NORMAL;
647 } else {
648 file.SkipBytes(7);
649 type = SkipSpriteData(file, grf_type, num - 8) ? ST_NORMAL : ST_INVALID;
650 /* Inline sprites are not supported for container version >= 2. */
651 if (file.GetContainerVersion() >= 2) return false;
652 }
653
654 if (type == ST_INVALID) return false;
655
656 if (load_index >= MAX_SPRITES) {
657 usererror("Tried to load too many sprites (#%d; max %d)", load_index, MAX_SPRITES);
658 }
659
660 bool is_mapgen = IsMapgenSpriteID(load_index);
661
662 if (is_mapgen) {
663 if (type != ST_NORMAL) usererror("Uhm, would you be so kind not to load a NewGRF that changes the type of the map generator sprites?");
664 type = ST_MAPGEN;
665 }
666
667 SpriteCache *sc = AllocateSpriteCache(load_index);
668 sc->file = &file;
669 sc->file_pos = file_pos;
670 sc->ptr = data;
671 sc->lru = 0;
672 sc->id = file_sprite_id;
673 sc->type = type;
674 sc->warned = false;
675 sc->control_flags = control_flags;
676
677 return true;
678 }
679
680
681 void DupSprite(SpriteID old_spr, SpriteID new_spr)
682 {
683 SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
684 SpriteCache *scold = GetSpriteCache(old_spr);
685
686 scnew->file = scold->file;
687 scnew->file_pos = scold->file_pos;
688 scnew->ptr = nullptr;
689 scnew->id = scold->id;
690 scnew->type = scold->type;
691 scnew->warned = false;
692 }
693
700 static const size_t S_FREE_MASK = sizeof(size_t) - 1;
701
702 /* to make sure nobody adds things to MemBlock without checking S_FREE_MASK first */
703 static_assert(sizeof(MemBlock) == sizeof(size_t));
704 /* make sure it's a power of two */
705 static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0);
706
707 static inline MemBlock *NextBlock(MemBlock *block)
708 {
709 return (MemBlock*)((byte*)block + (block->size & ~S_FREE_MASK));
710 }
711
712 static size_t GetSpriteCacheUsage()
713 {
714 size_t tot_size = 0;
715 MemBlock *s;
716
717 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
718 if (!(s->size & S_FREE_MASK)) tot_size += s->size;
719 }
720
721 return tot_size;
722 }
723
724
725 void IncreaseSpriteLRU()
726 {
727 /* Increase all LRU values */
728 if (_sprite_lru_counter > 16384) {
729 SpriteID i;
730
731 Debug(sprite, 3, "Fixing lru {}, inuse={}", _sprite_lru_counter, GetSpriteCacheUsage());
732
733 for (i = 0; i != _spritecache_items; i++) {
734 SpriteCache *sc = GetSpriteCache(i);
735 if (sc->ptr != nullptr) {
736 if (sc->lru >= 0) {
737 sc->lru = -1;
738 } else if (sc->lru != -32768) {
739 sc->lru--;
740 }
741 }
742 }
743 _sprite_lru_counter = 0;
744 }
745
746 /* Compact sprite cache every now and then. */
747 if (++_compact_cache_counter >= 740) {
748 CompactSpriteCache();
749 _compact_cache_counter = 0;
750 }
751 }
752
757 static void CompactSpriteCache()
758 {
759 MemBlock *s;
760
761 Debug(sprite, 3, "Compacting sprite cache, inuse={}", GetSpriteCacheUsage());
762
763 for (s = _spritecache_ptr; s->size != 0;) {
764 if (s->size & S_FREE_MASK) {
765 MemBlock *next = NextBlock(s);
766 MemBlock temp;
767 SpriteID i;
768
769 /* Since free blocks are automatically coalesced, this should hold true. */
770 assert(!(next->size & S_FREE_MASK));
771
772 /* If the next block is the sentinel block, we can safely return */
773 if (next->size == 0) break;
774
775 /* Locate the sprite belonging to the next pointer. */
776 for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
777 assert(i != _spritecache_items);
778 }
779
780 GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
781 /* Swap this and the next block */
782 temp = *s;
783 memmove(s, next, next->size);
784 s = NextBlock(s);
785 *s = temp;
786
787 /* Coalesce free blocks */
788 while (NextBlock(s)->size & S_FREE_MASK) {
789 s->size += NextBlock(s)->size & ~S_FREE_MASK;
790 }
791 } else {
792 s = NextBlock(s);
793 }
794 }
795 }
796
801 static void DeleteEntryFromSpriteCache(uint item)
802 {
803 /* Mark the block as free (the block must be in use) */
804 MemBlock *s = (MemBlock*)GetSpriteCache(item)->ptr - 1;
805 assert(!(s->size & S_FREE_MASK));
806 s->size |= S_FREE_MASK;
807 GetSpriteCache(item)->ptr = nullptr;
808
809 /* And coalesce adjacent free blocks */
810 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
811 if (s->size & S_FREE_MASK) {
812 while (NextBlock(s)->size & S_FREE_MASK) {
813 s->size += NextBlock(s)->size & ~S_FREE_MASK;
814 }
815 }
816 }
817 }
818
819 static void DeleteEntryFromSpriteCache()
820 {
821 uint best = UINT_MAX;
822 int cur_lru;
823
824 Debug(sprite, 3, "DeleteEntryFromSpriteCache, inuse={}", GetSpriteCacheUsage());
825
826 cur_lru = 0xffff;
827 for (SpriteID i = 0; i != _spritecache_items; i++) {
828 SpriteCache *sc = GetSpriteCache(i);
829 if (sc->type != ST_RECOLOUR && sc->ptr != nullptr && sc->lru < cur_lru) {
830 cur_lru = sc->lru;
831 best = i;
832 }
833 }
834
835 /* Display an error message and die, in case we found no sprite at all.
836 * This shouldn't really happen, unless all sprites are locked. */
837 if (best == UINT_MAX) error("Out of sprite memory");
838
839 DeleteEntryFromSpriteCache(best);
840 }
841
842 static void *AllocSprite(size_t mem_req)
843 {
844 mem_req += sizeof(MemBlock);
845
846 /* Align this to correct boundary. This also makes sure at least one
847 * bit is not used, so we can use it for other things. */
848 mem_req = Align(mem_req, S_FREE_MASK + 1);
849
850 for (;;) {
851 MemBlock *s;
852
853 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
854 if (s->size & S_FREE_MASK) {
855 size_t cur_size = s->size & ~S_FREE_MASK;
856
857 /* Is the block exactly the size we need or
858 * big enough for an additional free block? */
859 if (cur_size == mem_req ||
860 cur_size >= mem_req + sizeof(MemBlock)) {
861 /* Set size and in use */
862 s->size = mem_req;
863
864 /* Do we need to inject a free block too? */
865 if (cur_size != mem_req) {
866 NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
867 }
868
869 return s->data;
870 }
871 }
872 }
873
874 /* Reached sentinel, but no block found yet. Delete some old entry. */
875 DeleteEntryFromSpriteCache();
876 }
877 }
878
882 void *SimpleSpriteAlloc(size_t size)
883 {
884 return MallocT<byte>(size);
885 }
886
896 static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, AllocatorProc *allocator)
897 {
898 static const char * const sprite_types[] = {
899 "normal", // ST_NORMAL
900 "map generator", // ST_MAPGEN
901 "character", // ST_FONT
902 "recolour", // ST_RECOLOUR
903 };
904
905 SpriteType available = sc->type;
906 if (requested == ST_FONT && available == ST_NORMAL) {
907 if (sc->ptr == nullptr) sc->type = ST_FONT;
908 return GetRawSprite(sprite, sc->type, allocator);
909 }
910
911 byte warning_level = sc->warned ? 6 : 0;
912 sc->warned = true;
913 Debug(sprite, warning_level, "Tried to load {} sprite #{} as a {} sprite. Probable cause: NewGRF interference", sprite_types[available], sprite, sprite_types[requested]);
914
915 switch (requested) {
916 case ST_NORMAL:
917 if (sprite == SPR_IMG_QUERY) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'query' sprite a non-normal sprite?");
918 FALLTHROUGH;
919 case ST_FONT:
920 return GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator);
921 case ST_RECOLOUR:
922 if (sprite == PALETTE_TO_DARK_BLUE) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'PALETTE_TO_DARK_BLUE' sprite a non-remap sprite?");
923 return GetRawSprite(PALETTE_TO_DARK_BLUE, ST_RECOLOUR, allocator);
924 case ST_MAPGEN:
925 /* this shouldn't happen, overriding of ST_MAPGEN sprites is checked in LoadNextSprite()
926 * (the only case the check fails is when these sprites weren't even loaded...) */
927 default:
928 NOT_REACHED();
929 }
930 }
931
941 void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator, SpriteEncoder *encoder)
942 {
943 assert(type != ST_MAPGEN || IsMapgenSpriteID(sprite));
944 assert(type < ST_INVALID);
945
946 if (!SpriteExists(sprite)) {
947 Debug(sprite, 1, "Tried to load non-existing sprite #{}. Probable cause: Wrong/missing NewGRFs", sprite);
948
949 /* SPR_IMG_QUERY is a BIG FAT RED ? */
950 sprite = SPR_IMG_QUERY;
951 }
952
953 SpriteCache *sc = GetSpriteCache(sprite);
954
955 if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc, allocator);
956
957 if (allocator == nullptr && encoder == nullptr) {
958 /* Load sprite into/from spritecache */
959
960 /* Update LRU */
961 sc->lru = ++_sprite_lru_counter;
962
963 /* Load the sprite, if it is not loaded, yet */
964 if (sc->ptr == nullptr) sc->ptr = ReadSprite(sc, sprite, type, AllocSprite, nullptr);
965
966 return sc->ptr;
967 } else {
968 /* Do not use the spritecache, but a different allocator. */
969 return ReadSprite(sc, sprite, type, allocator, encoder);
970 }
971 }
972
973
974 static void GfxInitSpriteCache()
975 {
976 /* initialize sprite cache heap */
977 int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
978 uint target_size = (bpp > 0 ? _sprite_cache_size * bpp / 8 : 1) * 1024 * 1024;
979
980 /* Remember 'target_size' from the previous allocation attempt, so we do not try to reach the target_size multiple times in case of failure. */
981 static uint last_alloc_attempt = 0;
982
983 if (_spritecache_ptr == nullptr || (_allocated_sprite_cache_size != target_size && target_size != last_alloc_attempt)) {
984 delete[] reinterpret_cast<byte *>(_spritecache_ptr);
985
986 last_alloc_attempt = target_size;
987 _allocated_sprite_cache_size = target_size;
988
989 do {
990 try {
991 /* Try to allocate 50% more to make sure we do not allocate almost all available. */
992 _spritecache_ptr = reinterpret_cast<MemBlock *>(new byte[_allocated_sprite_cache_size + _allocated_sprite_cache_size / 2]);
993 } catch (std::bad_alloc &) {
994 _spritecache_ptr = nullptr;
995 }
996
997 if (_spritecache_ptr != nullptr) {
998 /* Allocation succeeded, but we wanted less. */
999 delete[] reinterpret_cast<byte *>(_spritecache_ptr);
1000 _spritecache_ptr = reinterpret_cast<MemBlock *>(new byte[_allocated_sprite_cache_size]);
1001 } else if (_allocated_sprite_cache_size < 2 * 1024 * 1024) {
1002 usererror("Cannot allocate spritecache");
1003 } else {
1004 /* Try again to allocate half. */
1005 _allocated_sprite_cache_size >>= 1;
1006 }
1007 } while (_spritecache_ptr == nullptr);
1008
1009 if (_allocated_sprite_cache_size != target_size) {
1010 Debug(misc, 0, "Not enough memory to allocate {} MiB of spritecache. Spritecache was reduced to {} MiB.", target_size / 1024 / 1024, _allocated_sprite_cache_size / 1024 / 1024);
1011
1012 ErrorMessageData msg(STR_CONFIG_ERROR_OUT_OF_MEMORY, STR_CONFIG_ERROR_SPRITECACHE_TOO_BIG);
1013 msg.SetDParam(0, target_size);
1014 msg.SetDParam(1, _allocated_sprite_cache_size);
1015 ScheduleErrorMessage(msg);
1016 }
1017 }
1018
1019 /* A big free block */
1020 _spritecache_ptr->size = (_allocated_sprite_cache_size - sizeof(MemBlock)) | S_FREE_MASK;
1021 /* Sentinel block (identified by size == 0) */
1022 NextBlock(_spritecache_ptr)->size = 0;
1023 }
1024
1025 void GfxInitSpriteMem()
1026 {
1027 GfxInitSpriteCache();
1028
1029 /* Reset the spritecache 'pool' */
1030 free(_spritecache);
1031 _spritecache_items = 0;
1032 _spritecache = nullptr;
1033
1034 _compact_cache_counter = 0;
1035 _sprite_files.clear();
1036 }
1037
1042 void GfxClearSpriteCache()
1043 {
1044 /* Clear sprite ptr for all cached items */
1045 for (uint i = 0; i != _spritecache_items; i++) {
1046 SpriteCache *sc = GetSpriteCache(i);
1047 if (sc->type != ST_RECOLOUR && sc->ptr != nullptr) DeleteEntryFromSpriteCache(i);
1048 }
1049
1050 VideoDriver::GetInstance()->ClearSystemSprites();
1051 }
1052
1053 /* static */ ReusableBuffer<SpriteLoader::CommonPixel> SpriteLoader::Sprite::buffer[ZOOM_LVL_COUNT];
SpriteLoader::CommonPixel::m
uint8 m
Remap-channel.
Definition: spriteloader.hpp:39
SCC_PAL
@ SCC_PAL
Sprite has palette data.
Definition: spriteloader.hpp:25
ReadRecolourSprite
static void * ReadRecolourSprite(SpriteFile &file, uint num)
Load a recolour sprite into memory.
Definition: spritecache.cpp:418
SpriteFile::NeedsPaletteRemap
bool NeedsPaletteRemap() const
Whether a palette remap is needed when loading sprites from this file.
Definition: sprite_file_type.hpp:32
IsInsideMM
static constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:230
factory.hpp
ZOOM_LVL_OUT_2X
@ ZOOM_LVL_OUT_2X
Zoomed 2 times out.
Definition: zoom_type.h:23
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:105
ST_FONT
@ ST_FONT
A sprite used for fonts.
Definition: gfx_type.h:310
ReusableBuffer< SpriteLoader::CommonPixel >
mem_func.hpp
Sprite::data
byte data[]
Sprite data.
Definition: spritecache.h:22
HandleInvalidSpriteRequest
static void * HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, AllocatorProc *allocator)
Handles the case when a sprite of different type is requested than is present in the SpriteCache.
Definition: spritecache.cpp:896
SpriteLoader::Sprite::AllocateData
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
Definition: spriteloader.hpp:62
ZOOM_LVL_END
@ ZOOM_LVL_END
End for iteration.
Definition: zoom_type.h:28
Blitter::GetScreenDepth
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
math_func.hpp
S_FREE_MASK
static const size_t S_FREE_MASK
S_FREE_MASK is used to mask-out lower bits of MemBlock::size If they are non-zero,...
Definition: spritecache.cpp:700
ZOOM_LVL_COUNT
@ ZOOM_LVL_COUNT
Number of zoom levels.
Definition: zoom_type.h:30
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
Sprite::height
uint16 height
Height of the sprite.
Definition: spritecache.h:18
zoom_func.h
Sprite::x_offs
int16 x_offs
Number of pixels to shift the sprite to the right.
Definition: spritecache.h:20
ZoomLevel
ZoomLevel
All zoom levels we know.
Definition: zoom_type.h:19
SpriteLoader::Sprite::buffer
static ReusableBuffer< SpriteLoader::CommonPixel > buffer[ZOOM_LVL_COUNT]
Allocated memory to pass sprite data around.
Definition: spriteloader.hpp:65
_palmap_w2d
const byte _palmap_w2d[]
Converting from the Windows palette to the DOS palette.
SCCF_ALLOW_ZOOM_MIN_2X_32BPP
@ SCCF_ALLOW_ZOOM_MIN_2X_32BPP
Allow use of sprite min zoom setting at 2x in 32bpp mode.
Definition: spritecache.h:29
ST_NORMAL
@ ST_NORMAL
The most basic (normal) sprite.
Definition: gfx_type.h:308
SpriteEncoder::Encode
virtual Sprite * Encode(const SpriteLoader::Sprite *sprite, AllocatorProc *allocator)=0
Convert a sprite from the loader to our own format.
DeleteEntryFromSpriteCache
static void DeleteEntryFromSpriteCache(uint item)
Delete a single entry from the sprite cache.
Definition: spritecache.cpp:801
GetSpriteType
SpriteType GetSpriteType(SpriteID sprite)
Get the sprite type of a given sprite.
Definition: spritecache.cpp:163
SpriteFile::GetContainerVersion
byte GetContainerVersion() const
Get the version number of container type used by the file.
Definition: sprite_file_type.hpp:38
VideoDriver::ClearSystemSprites
virtual void ClearSystemSprites()
Clear all cached sprites.
Definition: video_driver.hpp:108
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition: random_access_file.cpp:138
MemCpyT
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
grf.hpp
RandomAccessFile::ReadByte
byte ReadByte()
Read a byte from the file.
Definition: random_access_file.cpp:100
ZOOM_LVL_BEGIN
@ ZOOM_LVL_BEGIN
Begin for iteration.
Definition: zoom_type.h:21
random_access_file_type.h
ST_INVALID
@ ST_INVALID
Pseudosprite or other unusable sprite, used only internally.
Definition: gfx_type.h:312
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
gfx_func.h
RandomAccessFile::SkipBytes
void SkipBytes(int n)
Skip n bytes ahead in the file.
Definition: random_access_file.cpp:148
SpriteLoader::Sprite::data
SpriteLoader::CommonPixel * data
The sprite itself.
Definition: spriteloader.hpp:55
LoadNextSprite
bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition: spritecache.cpp:611
Align
static T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition: math_func.hpp:35
SpriteCache::warned
bool warned
True iff the user has been warned about incorrect use of this sprite.
Definition: spritecache.cpp:38
MAX_SPRITES
@ MAX_SPRITES
Maximum number of sprites that can be loaded at a given time.
Definition: sprites.h:1547
SpriteLoader::Sprite::type
SpriteType type
The sprite type.
Definition: spriteloader.hpp:53
GfxClearSpriteCache
void GfxClearSpriteCache()
Remove all encoded sprites from the sprite cache without discarding sprite location information.
Definition: spritecache.cpp:1042
SpriteEncoder::GetSpriteAlignment
virtual uint GetSpriteAlignment()
Get the value which the height and width on a sprite have to be aligned by.
Definition: spriteloader.hpp:103
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32 id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition: spritecache.cpp:546
SpriteLoader::CommonPixel
Definition of a common pixel in OpenTTD's realm.
Definition: spriteloader.hpp:34
SpriteFile::SeekToBegin
void SeekToBegin()
Seek to the begin of the content, i.e.
Definition: sprite_file_type.hpp:43
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:141
safeguards.h
SCCF_ALLOW_ZOOM_MIN_1X_PAL
@ SCCF_ALLOW_ZOOM_MIN_1X_PAL
Allow use of sprite min zoom setting at 1x in palette mode.
Definition: spritecache.h:26
Sprite::width
uint16 width
Width of the sprite.
Definition: spritecache.h:19
SpriteCache::control_flags
byte control_flags
Control flags, see SpriteCacheCtrlFlags.
Definition: spritecache.cpp:39
SpriteLoader::Sprite::x_offs
int16 x_offs
The x-offset of where the sprite will be drawn.
Definition: spriteloader.hpp:51
SpriteLoaderGrf
Sprite loader for graphics coming from a (New)GRF.
Definition: grf.hpp:16
settings_type.h
ErrorMessageData
The data of the error message.
Definition: error.h:29
sprites.h
SpriteCache::file
SpriteFile * file
The file the sprite in this entry can be found in.
Definition: spritecache.cpp:34
error.h
SpriteEncoder
Interface for something that can encode a sprite.
Definition: spriteloader.hpp:84
UnScaleByZoom
static int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_NORMAL) When shifting right,...
Definition: zoom_func.h:34
stdafx.h
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition: video_driver.hpp:202
RandomAccessFile::ReadWord
uint16 ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: random_access_file.cpp:117
RandomAccessFile::ReadDword
uint32 ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: random_access_file.cpp:127
SpriteLoader::Sprite::colours
SpriteColourComponent colours
The colour components of the sprite with useful information.
Definition: spriteloader.hpp:54
SpriteCache
Definition: spritecache.cpp:31
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition: random_access_file.cpp:73
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition: sprite_file_type.hpp:19
palette_convert.h
SpriteEncoder::Is32BppSupported
virtual bool Is32BppSupported()=0
Can the sprite encoder make use of RGBA sprites?
_grf_sprite_offsets
static std::map< uint32, GrfSpriteOffset > _grf_sprite_offsets
Map from sprite numbers to position in the GRF file.
Definition: spritecache.cpp:539
SpriteLoader::Sprite::width
uint16 width
Width of the sprite.
Definition: spriteloader.hpp:50
SCC_MASK
@ SCC_MASK
Mask of valid colour bits.
Definition: spriteloader.hpp:26
GetOriginFile
SpriteFile * GetOriginFile(SpriteID sprite)
Get the SpriteFile of a given sprite.
Definition: spritecache.cpp:174
ScaleByZoom
static int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZOOM_LVL_NORMAL) When shifting right,...
Definition: zoom_func.h:22
GetRawSprite
void * GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator, SpriteEncoder *encoder)
Reads a sprite (from disk or sprite cache).
Definition: spritecache.cpp:941
GrfSpriteOffset
Definition: spritecache.cpp:533
video_driver.hpp
GetMaxSpriteID
uint GetMaxSpriteID()
Get a reasonable (upper bound) estimate of the maximum SpriteID used in OpenTTD; there will be no spr...
Definition: spritecache.cpp:221
CompactSpriteCache
static void CompactSpriteCache()
Called when holes in the sprite cache should be removed.
Definition: spritecache.cpp:757
SpriteCache::type
SpriteType type
In some cases a single sprite is misused by two NewGRFs. Once as real sprite and once as recolour spr...
Definition: spritecache.cpp:37
SpriteType
SpriteType
Types of sprites that might be loaded.
Definition: gfx_type.h:307
ScheduleErrorMessage
void ScheduleErrorMessage(const ErrorMessageData &data)
Schedule an error.
Definition: error_gui.cpp:451
GetSpriteLocalID
uint32 GetSpriteLocalID(SpriteID sprite)
Get the GRF-local sprite id of a given sprite.
Definition: spritecache.cpp:185
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
Sprite::y_offs
int16 y_offs
Number of pixels to shift the sprite downwards.
Definition: spritecache.h:21
ReallocT
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:111
SpriteLoader::Sprite
Structure for passing information from the sprite loader to the blitter.
Definition: spriteloader.hpp:48
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, byte type, uint16 num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:126
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:134
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition: random_access_file.cpp:83
SCCF_ALLOW_ZOOM_MIN_2X_PAL
@ SCCF_ALLOW_ZOOM_MIN_2X_PAL
Allow use of sprite min zoom setting at 2x in palette mode.
Definition: spritecache.h:28
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
ReadSprite
static void * ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, AllocatorProc *allocator, SpriteEncoder *encoder)
Read a sprite from disk.
Definition: spritecache.cpp:454
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
MemSetT
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition: spritecache.cpp:555
ZOOM_LVL_NORMAL
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition: zoom_type.h:22
GetCachedSpriteFileByName
static SpriteFile * GetCachedSpriteFileByName(const std::string &filename)
Get the cached SpriteFile given the name of the file.
Definition: spritecache.cpp:80
ST_RECOLOUR
@ ST_RECOLOUR
Recolour sprite.
Definition: gfx_type.h:311
SpriteLoader::Sprite::y_offs
int16 y_offs
The y-offset of where the sprite will be drawn.
Definition: spriteloader.hpp:52
SpriteLoader::Sprite::height
uint16 height
Height of the sprite.
Definition: spriteloader.hpp:49
SpriteLoaderGrf::LoadSprite
uint8 LoadSprite(SpriteLoader::Sprite *sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, byte control_flags)
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
Definition: grf.cpp:351
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
SimpleSpriteAlloc
void * SimpleSpriteAlloc(size_t size)
Sprite allocator simply using malloc.
Definition: spritecache.cpp:882
FIND_FIRST_BIT
#define FIND_FIRST_BIT(x)
Returns the first non-zero bit in a 6-bit value (from right).
Definition: bitmath_func.hpp:200
Sprite
Data structure describing a sprite.
Definition: spritecache.h:17
OpenCachedSpriteFile
SpriteFile & OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
Open/get the SpriteFile that is cached for use in the sprite cache.
Definition: spritecache.cpp:96
MemBlock
Definition: spritecache.cpp:107
GetSpriteCountForFile
uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
Count the sprites which originate from a specific file in a range of SpriteIDs.
Definition: spritecache.cpp:198
ST_MAPGEN
@ ST_MAPGEN
Special sprite for the map generator.
Definition: gfx_type.h:309
SCCF_ALLOW_ZOOM_MIN_1X_32BPP
@ SCCF_ALLOW_ZOOM_MIN_1X_32BPP
Allow use of sprite min zoom setting at 1x in 32bpp mode.
Definition: spritecache.h:27
_palmap_d2w
static const byte _palmap_d2w[]
Converting from the DOS palette to the Windows palette.
Definition: palette_convert.h:47
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132