# spritecache.cpp

Go to the documentation of this file.

    00001 /* $Id: spritecache.cpp 15428 2009-02-09 02:57:15Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "gfx_type.h"
    00007 #include "fileio_func.h"
    00008 #include "spriteloader/grf.hpp"
    00009 #include "core/alloc_func.hpp"
    00010 #include "gfx_func.h"
    00011 #ifdef WITH_PNG
    00012 #include "spriteloader/png.hpp"
    00013 #endif /* WITH_PNG */
    00014 #include "blitter/factory.hpp"
    00015 #include "core/math_func.hpp"
    00016
    00017 #include "table/sprites.h"
    00018
    00019 /* Default of 4MB spritecache */
    00020 uint _sprite_cache_size = 4;
    00021
    00022 typedef SimpleTinyEnumT<SpriteType, byte> SpriteTypeByte;
    00023
    00024 struct SpriteCache {
    00025   void *ptr;
    00026   size_t file_pos;
    00027   uint32 id;
    00028   uint16 file_slot;
    00029   int16 lru;
    00030   SpriteTypeByte type;
    00031   bool warned;
    00032 };
    00033
    00034
    00035 static uint _spritecache_items = 0;
    00036 static SpriteCache *_spritecache = NULL;
    00037
    00038
    00039 static inline SpriteCache *GetSpriteCache(uint index)
    00040 {
    00041   return &_spritecache[index];
    00042 }
    00043
    00044 static inline bool IsMapgenSpriteID(SpriteID sprite)
    00045 {
    00046   return IsInsideMM(sprite, 4845, 4882);
    00047 }
    00048
    00049 static SpriteCache *AllocateSpriteCache(uint index)
    00050 {
    00051   if (index >= _spritecache_items) {
    00052     /* Add another 1024 items to the 'pool' */
    00053     uint items = Align(index + 1, 1024);
    00054
    00055     DEBUG(sprite, 4, "Increasing sprite cache to %d items (%d bytes)", items, items * sizeof(*_spritecache));
    00056
    00057     _spritecache = ReallocT(_spritecache, items);
    00058
    00059     /* Reset the new items and update the count */
    00060     memset(_spritecache + _spritecache_items, 0, (items - _spritecache_items) * sizeof(*_spritecache));
    00061     _spritecache_items = items;
    00062   }
    00063
    00064   return GetSpriteCache(index);
    00065 }
    00066
    00067
    00068 struct MemBlock {
    00069   size_t size;
    00070   byte data[VARARRAY_SIZE];
    00071 };
    00072
    00073 static uint _sprite_lru_counter;
    00074 static MemBlock *_spritecache_ptr;
    00075 static int _compact_cache_counter;
    00076
    00077 static void CompactSpriteCache();
    00078
    00084 void SkipSpriteData(byte type, uint16 num)
    00085 {
    00086   if (type & 2) {
    00087     FioSkipBytes(num);
    00088   } else {
    00089     while (num > 0) {
    00090       int8 i = FioReadByte();
    00091       if (i >= 0) {
    00092         int size = (i == 0) ? 0x80 : i;
    00093         num -= size;
    00094         FioSkipBytes(size);
    00095       } else {
    00096         i = -(i >> 3);
    00097         num -= i;
    00098         FioReadByte();
    00099       }
    00100     }
    00101   }
    00102 }
    00103
    00108 static SpriteType ReadSpriteHeaderSkipData()
    00109 {
    00110   uint16 num = FioReadWord();
    00111
    00112   if (num == 0) return ST_INVALID;
    00113
    00114   byte type = FioReadByte();
    00115   if (type == 0xFF) {
    00116     FioSkipBytes(num);
    00117     /* Some NewGRF files have "empty" pseudo-sprites which are 1
    00118      * byte long. Catch these so the sprites won't be displayed. */
    00119     return (num == 1) ? ST_INVALID : ST_RECOLOUR;
    00120   }
    00121
    00122   FioSkipBytes(7);
    00123   SkipSpriteData(type, num - 8);
    00124
    00125   return ST_NORMAL;
    00126 }
    00127
    00128 /* Check if the given Sprite ID exists */
    00129 bool SpriteExists(SpriteID id)
    00130 {
    00131   /* Special case for Sprite ID zero -- its position is also 0... */
    00132   if (id == 0) return true;
    00133   if (id >= _spritecache_items) return false;
    00134   return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file_slot == 0);
    00135 }
    00136
    00137 void *AllocSprite(size_t);
    00138
    00139 static void *ReadSprite(SpriteCache *sc, SpriteID id, SpriteType sprite_type)
    00140 {
    00141   uint8 file_slot = sc->file_slot;
    00142   size_t file_pos = sc->file_pos;
    00143
    00144   assert(IsMapgenSpriteID(id) == (sprite_type == ST_MAPGEN));
    00145   assert(sc->type == sprite_type);
    00146
    00147   DEBUG(sprite, 9, "Load sprite %d", id);
    00148
    00149   if (sprite_type == ST_NORMAL && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 32) {
    00150 #ifdef WITH_PNG
    00151     /* Try loading 32bpp graphics in case we are 32bpp output */
    00152     SpriteLoaderPNG sprite_loader;
    00153     SpriteLoader::Sprite sprite;
    00154
    00155     if (sprite_loader.LoadSprite(&sprite, file_slot, sc->id, sprite_type)) {
    00156       sc->ptr = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, &AllocSprite);
    00157       free(sprite.data);
    00158
    00159       return sc->ptr;
    00160     }
    00161     /* If the PNG couldn't be loaded, fall back to 8bpp grfs */
    00162 #else
    00163     static bool show_once = true;
    00164     if (show_once) {
    00165       DEBUG(misc, 0, "You are running a 32bpp blitter, but this build is without libpng support; falling back to 8bpp graphics");
    00166       show_once = false;
    00167     }
    00168 #endif /* WITH_PNG */
    00169   }
    00170
    00171   FioSeekToFile(file_slot, file_pos);
    00172
    00173   /* Read the size and type */
    00174   int num  = FioReadWord();
    00175   byte type = FioReadByte();
    00176
    00177   /* Type 0xFF indicates either a colourmap or some other non-sprite info */
    00178   assert((type == 0xFF) == (sprite_type == ST_RECOLOUR));
    00179   if (type == 0xFF) {
    00180     /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
    00181      * number of recolour sprites that are 17 bytes that only exist in DOS
    00182      * GRFs which are the same as 257 byte recolour sprites, but with the last
    00183      * 240 bytes zeroed.  */
    00184     static const int RECOLOUR_SPRITE_SIZE = 257;
    00185     byte *dest = (byte *)AllocSprite(max(RECOLOUR_SPRITE_SIZE, num));
    00186
    00187     sc->ptr = dest;
    00188
    00189     if (_palette_remap_grf[sc->file_slot]) {
    00190       byte *dest_tmp = AllocaM(byte, max(RECOLOUR_SPRITE_SIZE, num));
    00191
    00192       /* Only a few recolour sprites are less than 257 bytes */
    00193       if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
    00194       FioReadBlock(dest_tmp, num);
    00195
    00196       /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
    00197       for (int i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
    00198         dest[i] = _palette_remap[dest_tmp[_palette_reverse_remap[i - 1] + 1]];
    00199       }
    00200     } else {
    00201       FioReadBlock(dest, num);
    00202     }
    00203
    00204     return sc->ptr;
    00205   }
    00206
    00207   /* Ugly hack to work around the problem that the old landscape
    00208    *  generator assumes that those sprites are stored uncompressed in
    00209    *  the memory, and they are only read directly by the code, never
    00210    *  send to the blitter. So do not send it to the blitter (which will
    00211    *  result in a data array in the format the blitter likes most), but
    00212    *  read the data directly from disk and store that as sprite.
    00213    * Ugly: yes. Other solution: no. Blame the original author or
    00214    *  something ;) The image should really have been a data-stream
    00215    *  (so type = 0xFF basicly). */
    00216   if (sprite_type == ST_MAPGEN) {
    00217     uint height = FioReadByte();
    00218     uint width  = FioReadWord();
    00219     Sprite *sprite;
    00220     byte *dest;
    00221
    00222     num = width * height;
    00223     sprite = (Sprite *)AllocSprite(sizeof(*sprite) + num);
    00224     sc->ptr = sprite;
    00225     sprite->height = height;
    00226     sprite->width  = width;
    00227     sprite->x_offs = FioReadWord();
    00228     sprite->y_offs = FioReadWord();
    00229
    00230     dest = sprite->data;
    00231     while (num > 0) {
    00232       int8 i = FioReadByte();
    00233       if (i >= 0) {
    00234         num -= i;
    00235         for (; i > 0; --i) *dest++ = FioReadByte();
    00236       } else {
    00237         const byte *rel = dest - (((i & 7) << 8) | FioReadByte());
    00238         i = -(i >> 3);
    00239         num -= i;
    00240         for (; i > 0; --i) *dest++ = *rel++;
    00241       }
    00242     }
    00243
    00244     sc->type = sprite_type;
    00245
    00246     return sc->ptr;
    00247   }
    00248
    00249   assert(sprite_type == ST_NORMAL || sprite_type == ST_FONT);
    00250
    00251   SpriteLoaderGrf sprite_loader;
    00252   SpriteLoader::Sprite sprite;
    00253
    00254   if (!sprite_loader.LoadSprite(&sprite, file_slot, file_pos, sprite_type)) {
    00255     if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
    00256     return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL);
    00257   }
    00258   sc->ptr = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, &AllocSprite);
    00259   free(sprite.data);
    00260
    00261   return sc->ptr;
    00262 }
    00263
    00264
    00265 bool LoadNextSprite(int load_index, byte file_slot, uint file_sprite_id)
    00266 {
    00267   size_t file_pos = FioGetPos();
    00268
    00269   SpriteType type = ReadSpriteHeaderSkipData();
    00270
    00271   if (type == ST_INVALID) return false;
    00272
    00273   if (load_index >= MAX_SPRITES) {
    00274     usererror("Tried to load too many sprites (#%d; max %d)", load_index, MAX_SPRITES);
    00275   }
    00276
    00277   bool is_mapgen = IsMapgenSpriteID(load_index);
    00278
    00279   if (is_mapgen) {
    00280     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?");
    00281     type = ST_MAPGEN;
    00282   }
    00283
    00284   SpriteCache *sc = AllocateSpriteCache(load_index);
    00285   sc->file_slot = file_slot;
    00286   sc->file_pos = file_pos;
    00287   sc->ptr = NULL;
    00288   sc->lru = 0;
    00289   sc->id = file_sprite_id;
    00290   sc->type = type;
    00291   sc->warned = false;
    00292
    00293   return true;
    00294 }
    00295
    00296
    00297 void DupSprite(SpriteID old_spr, SpriteID new_spr)
    00298 {
    00299   SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
    00300   SpriteCache *scold = GetSpriteCache(old_spr);
    00301
    00302   scnew->file_slot = scold->file_slot;
    00303   scnew->file_pos = scold->file_pos;
    00304   scnew->ptr = NULL;
    00305   scnew->id = scold->id;
    00306   scnew->type = scold->type;
    00307   scnew->warned = false;
    00308 }
    00309
    00310
    00311 #define S_FREE_MASK 1
    00312
    00313 static inline MemBlock *NextBlock(MemBlock *block)
    00314 {
    00315   return (MemBlock*)((byte*)block + (block->size & ~S_FREE_MASK));
    00316 }
    00317
    00318 static size_t GetSpriteCacheUsage()
    00319 {
    00320   size_t tot_size = 0;
    00321   MemBlock *s;
    00322
    00323   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
    00324     if (!(s->size & S_FREE_MASK)) tot_size += s->size;
    00325   }
    00326
    00327   return tot_size;
    00328 }
    00329
    00330
    00331 void IncreaseSpriteLRU()
    00332 {
    00333   /* Increase all LRU values */
    00334   if (_sprite_lru_counter > 16384) {
    00335     SpriteID i;
    00336
    00337     DEBUG(sprite, 3, "Fixing lru %d, inuse=%d", _sprite_lru_counter, GetSpriteCacheUsage());
    00338
    00339     for (i = 0; i != _spritecache_items; i++) {
    00340       SpriteCache *sc = GetSpriteCache(i);
    00341       if (sc->ptr != NULL) {
    00342         if (sc->lru >= 0) {
    00343           sc->lru = -1;
    00344         } else if (sc->lru != -32768) {
    00345           sc->lru--;
    00346         }
    00347       }
    00348     }
    00349     _sprite_lru_counter = 0;
    00350   }
    00351
    00352   /* Compact sprite cache every now and then. */
    00353   if (++_compact_cache_counter >= 740) {
    00354     CompactSpriteCache();
    00355     _compact_cache_counter = 0;
    00356   }
    00357 }
    00358
    00361 static void CompactSpriteCache()
    00362 {
    00363   MemBlock *s;
    00364
    00365   DEBUG(sprite, 3, "Compacting sprite cache, inuse=%d", GetSpriteCacheUsage());
    00366
    00367   for (s = _spritecache_ptr; s->size != 0;) {
    00368     if (s->size & S_FREE_MASK) {
    00369       MemBlock *next = NextBlock(s);
    00370       MemBlock temp;
    00371       SpriteID i;
    00372
    00373       /* Since free blocks are automatically coalesced, this should hold true. */
    00374       assert(!(next->size & S_FREE_MASK));
    00375
    00376       /* If the next block is the sentinel block, we can safely return */
    00377       if (next->size == 0) break;
    00378
    00379       /* Locate the sprite belonging to the next pointer. */
    00380       for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
    00381         assert(i != _spritecache_items);
    00382       }
    00383
    00384       GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
    00385       /* Swap this and the next block */
    00386       temp = *s;
    00387       memmove(s, next, next->size);
    00388       s = NextBlock(s);
    00389       *s = temp;
    00390
    00391       /* Coalesce free blocks */
    00392       while (NextBlock(s)->size & S_FREE_MASK) {
    00393         s->size += NextBlock(s)->size & ~S_FREE_MASK;
    00394       }
    00395     } else {
    00396       s = NextBlock(s);
    00397     }
    00398   }
    00399 }
    00400
    00401 static void DeleteEntryFromSpriteCache()
    00402 {
    00403   SpriteID i;
    00404   uint best = UINT_MAX;
    00405   MemBlock *s;
    00406   int cur_lru;
    00407
    00408   DEBUG(sprite, 3, "DeleteEntryFromSpriteCache, inuse=%d", GetSpriteCacheUsage());
    00409
    00410   cur_lru = 0xffff;
    00411   for (i = 0; i != _spritecache_items; i++) {
    00412     SpriteCache *sc = GetSpriteCache(i);
    00413     if (sc->ptr != NULL && sc->lru < cur_lru) {
    00414       cur_lru = sc->lru;
    00415       best = i;
    00416     }
    00417   }
    00418
    00419   /* Display an error message and die, in case we found no sprite at all.
    00420    * This shouldn't really happen, unless all sprites are locked. */
    00421   if (best == UINT_MAX) error("Out of sprite memory");
    00422
    00423   /* Mark the block as free (the block must be in use) */
    00424   s = (MemBlock*)GetSpriteCache(best)->ptr - 1;
    00425   assert(!(s->size & S_FREE_MASK));
    00426   s->size |= S_FREE_MASK;
    00427   GetSpriteCache(best)->ptr = NULL;
    00428
    00429   /* And coalesce adjacent free blocks */
    00430   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
    00431     if (s->size & S_FREE_MASK) {
    00432       while (NextBlock(s)->size & S_FREE_MASK) {
    00433         s->size += NextBlock(s)->size & ~S_FREE_MASK;
    00434       }
    00435     }
    00436   }
    00437 }
    00438
    00439 void *AllocSprite(size_t mem_req)
    00440 {
    00441   mem_req += sizeof(MemBlock);
    00442
    00443   /* Align this to an uint32 boundary. This also makes sure that the 2 least
    00444    * bits are not used, so we could use those for other things. */
    00445   mem_req = Align(mem_req, sizeof(uint32));
    00446
    00447   for (;;) {
    00448     MemBlock *s;
    00449
    00450     for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
    00451       if (s->size & S_FREE_MASK) {
    00452         size_t cur_size = s->size & ~S_FREE_MASK;
    00453
    00454         /* Is the block exactly the size we need or
    00455          * big enough for an additional free block? */
    00456         if (cur_size == mem_req ||
    00457             cur_size >= mem_req + sizeof(MemBlock)) {
    00458           /* Set size and in use */
    00459           s->size = mem_req;
    00460
    00461           /* Do we need to inject a free block too? */
    00462           if (cur_size != mem_req) {
    00463             NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
    00464           }
    00465
    00466           return s->data;
    00467         }
    00468       }
    00469     }
    00470
    00471     /* Reached sentinel, but no block found yet. Delete some old entry. */
    00472     DeleteEntryFromSpriteCache();
    00473   }
    00474 }
    00475
    00483 static const void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc)
    00484 {
    00485   static const char *sprite_types[] = {
    00486     "normal",        // ST_NORMAL
    00487     "map generator", // ST_MAPGEN
    00488     "character",     // ST_FONT
    00489     "recolour",      // ST_RECOLOUR
    00490   };
    00491
    00492   SpriteType available = sc->type;
    00493   if (requested == ST_FONT && available == ST_NORMAL) {
    00494     if (sc->ptr == NULL) sc->type = ST_FONT;
    00495     return GetRawSprite(sprite, sc->type);
    00496   }
    00497
    00498   byte warning_level = sc->warned ? 6 : 0;
    00499   sc->warned = true;
    00500   DEBUG(sprite, warning_level, "Tried to load %s sprite #%d as a %s sprite. Probable cause: NewGRF interference", sprite_types[available], sprite, sprite_types[requested]);
    00501
    00502   switch (requested) {
    00503     case ST_NORMAL:
    00504       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?");
    00505       /* FALLTHROUGH */
    00506     case ST_FONT:
    00507       return GetRawSprite(SPR_IMG_QUERY, ST_NORMAL);
    00508     case ST_RECOLOUR:
    00509       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?");
    00510       return GetRawSprite(PALETTE_TO_DARK_BLUE, ST_RECOLOUR);
    00511     case ST_MAPGEN:
    00512       /* this shouldn't happen, overriding of ST_MAPGEN sprites is checked in LoadNextSprite()
    00513        * (the only case the check fails is when these sprites weren't even loaded...) */
    00514     default:
    00515       NOT_REACHED();
    00516   }
    00517 }
    00518
    00519 const void *GetRawSprite(SpriteID sprite, SpriteType type)
    00520 {
    00521   assert(IsMapgenSpriteID(sprite) == (type == ST_MAPGEN));
    00522   assert(type < ST_INVALID);
    00523
    00524   if (!SpriteExists(sprite)) {
    00525     DEBUG(sprite, 1, "Tried to load non-existing sprite #%d. Probable cause: Wrong/missing NewGRFs", sprite);
    00526
    00527     /* SPR_IMG_QUERY is a BIG FAT RED ? */
    00528     sprite = SPR_IMG_QUERY;
    00529   }
    00530
    00531   SpriteCache *sc = GetSpriteCache(sprite);
    00532
    00533   if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc);
    00534
    00535   /* Update LRU */
    00536   sc->lru = ++_sprite_lru_counter;
    00537
    00538   void *p = sc->ptr;
    00539
    00540   /* Load the sprite, if it is not loaded, yet */
    00541   if (p == NULL) p = ReadSprite(sc, sprite, type);
    00542
    00543   return p;
    00544 }
    00545
    00546
    00547 void GfxInitSpriteMem()
    00548 {
    00549   /* initialize sprite cache heap */
    00550   if (_spritecache_ptr == NULL) _spritecache_ptr = (MemBlock*)MallocT<byte>(_sprite_cache_size * 1024 * 1024);
    00551
    00552   /* A big free block */
    00553   _spritecache_ptr->size = ((_sprite_cache_size * 1024 * 1024) - sizeof(MemBlock)) | S_FREE_MASK;
    00554   /* Sentinel block (identified by size == 0) */
    00555   NextBlock(_spritecache_ptr)->size = 0;
    00556
    00557   /* Reset the spritecache 'pool' */
    00558   free(_spritecache);
    00559   _spritecache_items = 0;
    00560   _spritecache = NULL;
    00561
    00562   _compact_cache_counter = 0;
    00563 }