spritecache.cpp

Go to the documentation of this file.
00001 /* $Id: spritecache.cpp 15556 2009-02-23 17:54:02Z 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 
00158       return sc->ptr;
00159     }
00160     /* If the PNG couldn't be loaded, fall back to 8bpp grfs */
00161 #else
00162     static bool show_once = true;
00163     if (show_once) {
00164       DEBUG(misc, 0, "You are running a 32bpp blitter, but this build is without libpng support; falling back to 8bpp graphics");
00165       show_once = false;
00166     }
00167 #endif /* WITH_PNG */
00168   }
00169 
00170   FioSeekToFile(file_slot, file_pos);
00171 
00172   /* Read the size and type */
00173   int num  = FioReadWord();
00174   byte type = FioReadByte();
00175 
00176   /* Type 0xFF indicates either a colourmap or some other non-sprite info */
00177   assert((type == 0xFF) == (sprite_type == ST_RECOLOUR));
00178   if (type == 0xFF) {
00179     /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
00180      * number of recolour sprites that are 17 bytes that only exist in DOS
00181      * GRFs which are the same as 257 byte recolour sprites, but with the last
00182      * 240 bytes zeroed.  */
00183     static const int RECOLOUR_SPRITE_SIZE = 257;
00184     byte *dest = (byte *)AllocSprite(max(RECOLOUR_SPRITE_SIZE, num));
00185 
00186     sc->ptr = dest;
00187 
00188     if (_palette_remap_grf[sc->file_slot]) {
00189       byte *dest_tmp = AllocaM(byte, max(RECOLOUR_SPRITE_SIZE, num));
00190 
00191       /* Only a few recolour sprites are less than 257 bytes */
00192       if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
00193       FioReadBlock(dest_tmp, num);
00194 
00195       /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
00196       for (int i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
00197         dest[i] = _palette_remap[dest_tmp[_palette_reverse_remap[i - 1] + 1]];
00198       }
00199     } else {
00200       FioReadBlock(dest, num);
00201     }
00202 
00203     return sc->ptr;
00204   }
00205 
00206   /* Ugly hack to work around the problem that the old landscape
00207    *  generator assumes that those sprites are stored uncompressed in
00208    *  the memory, and they are only read directly by the code, never
00209    *  send to the blitter. So do not send it to the blitter (which will
00210    *  result in a data array in the format the blitter likes most), but
00211    *  read the data directly from disk and store that as sprite.
00212    * Ugly: yes. Other solution: no. Blame the original author or
00213    *  something ;) The image should really have been a data-stream
00214    *  (so type = 0xFF basicly). */
00215   if (sprite_type == ST_MAPGEN) {
00216     uint height = FioReadByte();
00217     uint width  = FioReadWord();
00218     Sprite *sprite;
00219     byte *dest;
00220 
00221     num = width * height;
00222     sprite = (Sprite *)AllocSprite(sizeof(*sprite) + num);
00223     sc->ptr = sprite;
00224     sprite->height = height;
00225     sprite->width  = width;
00226     sprite->x_offs = FioReadWord();
00227     sprite->y_offs = FioReadWord();
00228 
00229     dest = sprite->data;
00230     while (num > 0) {
00231       int8 i = FioReadByte();
00232       if (i >= 0) {
00233         num -= i;
00234         for (; i > 0; --i) *dest++ = FioReadByte();
00235       } else {
00236         const byte *rel = dest - (((i & 7) << 8) | FioReadByte());
00237         i = -(i >> 3);
00238         num -= i;
00239         for (; i > 0; --i) *dest++ = *rel++;
00240       }
00241     }
00242 
00243     sc->type = sprite_type;
00244 
00245     return sc->ptr;
00246   }
00247 
00248   assert(sprite_type == ST_NORMAL || sprite_type == ST_FONT);
00249 
00250   SpriteLoaderGrf sprite_loader;
00251   SpriteLoader::Sprite sprite;
00252 
00253   if (!sprite_loader.LoadSprite(&sprite, file_slot, file_pos, sprite_type)) {
00254     if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
00255     return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL);
00256   }
00257   sc->ptr = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, &AllocSprite);
00258 
00259   return sc->ptr;
00260 }
00261 
00262 
00263 bool LoadNextSprite(int load_index, byte file_slot, uint file_sprite_id)
00264 {
00265   size_t file_pos = FioGetPos();
00266 
00267   SpriteType type = ReadSpriteHeaderSkipData();
00268 
00269   if (type == ST_INVALID) return false;
00270 
00271   if (load_index >= MAX_SPRITES) {
00272     usererror("Tried to load too many sprites (#%d; max %d)", load_index, MAX_SPRITES);
00273   }
00274 
00275   bool is_mapgen = IsMapgenSpriteID(load_index);
00276 
00277   if (is_mapgen) {
00278     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?");
00279     type = ST_MAPGEN;
00280   }
00281 
00282   SpriteCache *sc = AllocateSpriteCache(load_index);
00283   sc->file_slot = file_slot;
00284   sc->file_pos = file_pos;
00285   sc->ptr = NULL;
00286   sc->lru = 0;
00287   sc->id = file_sprite_id;
00288   sc->type = type;
00289   sc->warned = false;
00290 
00291   return true;
00292 }
00293 
00294 
00295 void DupSprite(SpriteID old_spr, SpriteID new_spr)
00296 {
00297   SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
00298   SpriteCache *scold = GetSpriteCache(old_spr);
00299 
00300   scnew->file_slot = scold->file_slot;
00301   scnew->file_pos = scold->file_pos;
00302   scnew->ptr = NULL;
00303   scnew->id = scold->id;
00304   scnew->type = scold->type;
00305   scnew->warned = false;
00306 }
00307 
00308 
00309 #define S_FREE_MASK 1
00310 
00311 static inline MemBlock *NextBlock(MemBlock *block)
00312 {
00313   return (MemBlock*)((byte*)block + (block->size & ~S_FREE_MASK));
00314 }
00315 
00316 static size_t GetSpriteCacheUsage()
00317 {
00318   size_t tot_size = 0;
00319   MemBlock *s;
00320 
00321   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
00322     if (!(s->size & S_FREE_MASK)) tot_size += s->size;
00323   }
00324 
00325   return tot_size;
00326 }
00327 
00328 
00329 void IncreaseSpriteLRU()
00330 {
00331   /* Increase all LRU values */
00332   if (_sprite_lru_counter > 16384) {
00333     SpriteID i;
00334 
00335     DEBUG(sprite, 3, "Fixing lru %d, inuse=%d", _sprite_lru_counter, GetSpriteCacheUsage());
00336 
00337     for (i = 0; i != _spritecache_items; i++) {
00338       SpriteCache *sc = GetSpriteCache(i);
00339       if (sc->ptr != NULL) {
00340         if (sc->lru >= 0) {
00341           sc->lru = -1;
00342         } else if (sc->lru != -32768) {
00343           sc->lru--;
00344         }
00345       }
00346     }
00347     _sprite_lru_counter = 0;
00348   }
00349 
00350   /* Compact sprite cache every now and then. */
00351   if (++_compact_cache_counter >= 740) {
00352     CompactSpriteCache();
00353     _compact_cache_counter = 0;
00354   }
00355 }
00356 
00359 static void CompactSpriteCache()
00360 {
00361   MemBlock *s;
00362 
00363   DEBUG(sprite, 3, "Compacting sprite cache, inuse=%d", GetSpriteCacheUsage());
00364 
00365   for (s = _spritecache_ptr; s->size != 0;) {
00366     if (s->size & S_FREE_MASK) {
00367       MemBlock *next = NextBlock(s);
00368       MemBlock temp;
00369       SpriteID i;
00370 
00371       /* Since free blocks are automatically coalesced, this should hold true. */
00372       assert(!(next->size & S_FREE_MASK));
00373 
00374       /* If the next block is the sentinel block, we can safely return */
00375       if (next->size == 0) break;
00376 
00377       /* Locate the sprite belonging to the next pointer. */
00378       for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
00379         assert(i != _spritecache_items);
00380       }
00381 
00382       GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
00383       /* Swap this and the next block */
00384       temp = *s;
00385       memmove(s, next, next->size);
00386       s = NextBlock(s);
00387       *s = temp;
00388 
00389       /* Coalesce free blocks */
00390       while (NextBlock(s)->size & S_FREE_MASK) {
00391         s->size += NextBlock(s)->size & ~S_FREE_MASK;
00392       }
00393     } else {
00394       s = NextBlock(s);
00395     }
00396   }
00397 }
00398 
00399 static void DeleteEntryFromSpriteCache()
00400 {
00401   SpriteID i;
00402   uint best = UINT_MAX;
00403   MemBlock *s;
00404   int cur_lru;
00405 
00406   DEBUG(sprite, 3, "DeleteEntryFromSpriteCache, inuse=%d", GetSpriteCacheUsage());
00407 
00408   cur_lru = 0xffff;
00409   for (i = 0; i != _spritecache_items; i++) {
00410     SpriteCache *sc = GetSpriteCache(i);
00411     if (sc->ptr != NULL && sc->lru < cur_lru) {
00412       cur_lru = sc->lru;
00413       best = i;
00414     }
00415   }
00416 
00417   /* Display an error message and die, in case we found no sprite at all.
00418    * This shouldn't really happen, unless all sprites are locked. */
00419   if (best == UINT_MAX) error("Out of sprite memory");
00420 
00421   /* Mark the block as free (the block must be in use) */
00422   s = (MemBlock*)GetSpriteCache(best)->ptr - 1;
00423   assert(!(s->size & S_FREE_MASK));
00424   s->size |= S_FREE_MASK;
00425   GetSpriteCache(best)->ptr = NULL;
00426 
00427   /* And coalesce adjacent free blocks */
00428   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
00429     if (s->size & S_FREE_MASK) {
00430       while (NextBlock(s)->size & S_FREE_MASK) {
00431         s->size += NextBlock(s)->size & ~S_FREE_MASK;
00432       }
00433     }
00434   }
00435 }
00436 
00437 void *AllocSprite(size_t mem_req)
00438 {
00439   mem_req += sizeof(MemBlock);
00440 
00441   /* Align this to an uint32 boundary. This also makes sure that the 2 least
00442    * bits are not used, so we could use those for other things. */
00443   mem_req = Align(mem_req, sizeof(uint32));
00444 
00445   for (;;) {
00446     MemBlock *s;
00447 
00448     for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
00449       if (s->size & S_FREE_MASK) {
00450         size_t cur_size = s->size & ~S_FREE_MASK;
00451 
00452         /* Is the block exactly the size we need or
00453          * big enough for an additional free block? */
00454         if (cur_size == mem_req ||
00455             cur_size >= mem_req + sizeof(MemBlock)) {
00456           /* Set size and in use */
00457           s->size = mem_req;
00458 
00459           /* Do we need to inject a free block too? */
00460           if (cur_size != mem_req) {
00461             NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
00462           }
00463 
00464           return s->data;
00465         }
00466       }
00467     }
00468 
00469     /* Reached sentinel, but no block found yet. Delete some old entry. */
00470     DeleteEntryFromSpriteCache();
00471   }
00472 }
00473 
00481 static const void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc)
00482 {
00483   static const char *sprite_types[] = {
00484     "normal",        // ST_NORMAL
00485     "map generator", // ST_MAPGEN
00486     "character",     // ST_FONT
00487     "recolour",      // ST_RECOLOUR
00488   };
00489 
00490   SpriteType available = sc->type;
00491   if (requested == ST_FONT && available == ST_NORMAL) {
00492     if (sc->ptr == NULL) sc->type = ST_FONT;
00493     return GetRawSprite(sprite, sc->type);
00494   }
00495 
00496   byte warning_level = sc->warned ? 6 : 0;
00497   sc->warned = true;
00498   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]);
00499 
00500   switch (requested) {
00501     case ST_NORMAL:
00502       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?");
00503       /* FALLTHROUGH */
00504     case ST_FONT:
00505       return GetRawSprite(SPR_IMG_QUERY, ST_NORMAL);
00506     case ST_RECOLOUR:
00507       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?");
00508       return GetRawSprite(PALETTE_TO_DARK_BLUE, ST_RECOLOUR);
00509     case ST_MAPGEN:
00510       /* this shouldn't happen, overriding of ST_MAPGEN sprites is checked in LoadNextSprite()
00511        * (the only case the check fails is when these sprites weren't even loaded...) */
00512     default:
00513       NOT_REACHED();
00514   }
00515 }
00516 
00517 const void *GetRawSprite(SpriteID sprite, SpriteType type)
00518 {
00519   assert(IsMapgenSpriteID(sprite) == (type == ST_MAPGEN));
00520   assert(type < ST_INVALID);
00521 
00522   if (!SpriteExists(sprite)) {
00523     DEBUG(sprite, 1, "Tried to load non-existing sprite #%d. Probable cause: Wrong/missing NewGRFs", sprite);
00524 
00525     /* SPR_IMG_QUERY is a BIG FAT RED ? */
00526     sprite = SPR_IMG_QUERY;
00527   }
00528 
00529   SpriteCache *sc = GetSpriteCache(sprite);
00530 
00531   if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc);
00532 
00533   /* Update LRU */
00534   sc->lru = ++_sprite_lru_counter;
00535 
00536   void *p = sc->ptr;
00537 
00538   /* Load the sprite, if it is not loaded, yet */
00539   if (p == NULL) p = ReadSprite(sc, sprite, type);
00540 
00541   return p;
00542 }
00543 
00544 
00545 void GfxInitSpriteMem()
00546 {
00547   /* initialize sprite cache heap */
00548   if (_spritecache_ptr == NULL) _spritecache_ptr = (MemBlock*)MallocT<byte>(_sprite_cache_size * 1024 * 1024);
00549 
00550   /* A big free block */
00551   _spritecache_ptr->size = ((_sprite_cache_size * 1024 * 1024) - sizeof(MemBlock)) | S_FREE_MASK;
00552   /* Sentinel block (identified by size == 0) */
00553   NextBlock(_spritecache_ptr)->size = 0;
00554 
00555   /* Reset the spritecache 'pool' */
00556   free(_spritecache);
00557   _spritecache_items = 0;
00558   _spritecache = NULL;
00559 
00560   _compact_cache_counter = 0;
00561 }
00562 
00563 /* static */ ReusableBuffer<SpriteLoader::CommonPixel> SpriteLoader::Sprite::buffer;

Generated on Sun Mar 15 22:49:50 2009 for openttd by  doxygen 1.5.6