OpenTTD Source: src/spritecache.cpp Source File

OpenTTD Source 14.0-beta3

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