spritecache.cpp

Go to the documentation of this file.
00001 /* $Id: spritecache.cpp 24004 2012-03-04 16:38:05Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "fileio_func.h"
00014 #include "spriteloader/grf.hpp"
00015 #include "gfx_func.h"
00016 #include "zoom_func.h"
00017 #include "settings_type.h"
00018 #include "blitter/factory.hpp"
00019 #include "core/math_func.hpp"
00020 #include "core/mem_func.hpp"
00021 
00022 #include "table/sprites.h"
00023 #include "table/palette_convert.h"
00024 
00025 /* Default of 4MB spritecache */
00026 uint _sprite_cache_size = 4;
00027 
00028 typedef SimpleTinyEnumT<SpriteType, byte> SpriteTypeByte;
00029 
00030 struct SpriteCache {
00031   void *ptr;
00032   size_t file_pos;
00033   uint32 id;
00034   uint16 file_slot;
00035   int16 lru;
00036   SpriteTypeByte type; 
00037   bool warned;         
00038   byte container_ver;  
00039 };
00040 
00041 
00042 static uint _spritecache_items = 0;
00043 static SpriteCache *_spritecache = NULL;
00044 
00045 
00046 static inline SpriteCache *GetSpriteCache(uint index)
00047 {
00048   return &_spritecache[index];
00049 }
00050 
00051 static inline bool IsMapgenSpriteID(SpriteID sprite)
00052 {
00053   return IsInsideMM(sprite, 4845, 4882);
00054 }
00055 
00056 static SpriteCache *AllocateSpriteCache(uint index)
00057 {
00058   if (index >= _spritecache_items) {
00059     /* Add another 1024 items to the 'pool' */
00060     uint items = Align(index + 1, 1024);
00061 
00062     DEBUG(sprite, 4, "Increasing sprite cache to %u items (" PRINTF_SIZE " bytes)", items, items * sizeof(*_spritecache));
00063 
00064     _spritecache = ReallocT(_spritecache, items);
00065 
00066     /* Reset the new items and update the count */
00067     memset(_spritecache + _spritecache_items, 0, (items - _spritecache_items) * sizeof(*_spritecache));
00068     _spritecache_items = items;
00069   }
00070 
00071   return GetSpriteCache(index);
00072 }
00073 
00074 
00075 struct MemBlock {
00076   size_t size;
00077   byte data[];
00078 };
00079 
00080 static uint _sprite_lru_counter;
00081 static MemBlock *_spritecache_ptr;
00082 static int _compact_cache_counter;
00083 
00084 static void CompactSpriteCache();
00085 static void *AllocSprite(size_t mem_req);
00086 
00093 bool SkipSpriteData(byte type, uint16 num)
00094 {
00095   if (type & 2) {
00096     FioSkipBytes(num);
00097   } else {
00098     while (num > 0) {
00099       int8 i = FioReadByte();
00100       if (i >= 0) {
00101         int size = (i == 0) ? 0x80 : i;
00102         if (size > num) return false;
00103         num -= size;
00104         FioSkipBytes(size);
00105       } else {
00106         i = -(i >> 3);
00107         num -= i;
00108         FioReadByte();
00109       }
00110     }
00111   }
00112   return true;
00113 }
00114 
00115 /* Check if the given Sprite ID exists */
00116 bool SpriteExists(SpriteID id)
00117 {
00118   /* Special case for Sprite ID zero -- its position is also 0... */
00119   if (id == 0) return true;
00120   if (id >= _spritecache_items) return false;
00121   return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file_slot == 0);
00122 }
00123 
00129 SpriteType GetSpriteType(SpriteID sprite)
00130 {
00131   if (!SpriteExists(sprite)) return ST_INVALID;
00132   return GetSpriteCache(sprite)->type;
00133 }
00134 
00140 uint GetOriginFileSlot(SpriteID sprite)
00141 {
00142   if (!SpriteExists(sprite)) return 0;
00143   return GetSpriteCache(sprite)->file_slot;
00144 }
00145 
00154 uint GetMaxSpriteID()
00155 {
00156   return _spritecache_items;
00157 }
00158 
00159 static bool ResizeSpriteIn(SpriteLoader::Sprite *sprite, ZoomLevel src, ZoomLevel tgt)
00160 {
00161   uint8 scaled_1 = UnScaleByZoom(1, (ZoomLevel)(tgt - src));
00162 
00163   /* Check for possible memory overflow. */
00164   if (sprite[src].width * scaled_1 > UINT16_MAX || sprite[src].height * scaled_1 > UINT16_MAX) return false;
00165 
00166   sprite[tgt].width  = sprite[src].width  * scaled_1;
00167   sprite[tgt].height = sprite[src].height * scaled_1;
00168   sprite[tgt].x_offs = sprite[src].x_offs * scaled_1;
00169   sprite[tgt].y_offs = sprite[src].y_offs * scaled_1;
00170 
00171   sprite[tgt].AllocateData(tgt, sprite[tgt].width * sprite[tgt].height);
00172 
00173   SpriteLoader::CommonPixel *dst = sprite[tgt].data;
00174   for (int y = 0; y < sprite[tgt].height; y++) {
00175     const SpriteLoader::CommonPixel *src_ln = &sprite[src].data[y / scaled_1 * sprite[src].width];
00176     for (int x = 0; x < sprite[tgt].width; x++) {
00177       *dst = src_ln[x / scaled_1];
00178       dst++;
00179     }
00180   }
00181 
00182   return true;
00183 }
00184 
00185 static void ResizeSpriteOut(SpriteLoader::Sprite *sprite, ZoomLevel zoom)
00186 {
00187   /* Algorithm based on 32bpp_Optimized::ResizeSprite() */
00188   sprite[zoom].width  = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].width,  zoom);
00189   sprite[zoom].height = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].height, zoom);
00190   sprite[zoom].x_offs = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].x_offs, zoom);
00191   sprite[zoom].y_offs = UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].y_offs, zoom);
00192 
00193   sprite[zoom].AllocateData(zoom, sprite[zoom].height * sprite[zoom].width);
00194 
00195   SpriteLoader::CommonPixel *dst = sprite[zoom].data;
00196   const SpriteLoader::CommonPixel *src = sprite[zoom - 1].data;
00197   const SpriteLoader::CommonPixel *src_end = src + sprite[zoom - 1].height * sprite[zoom - 1].width;
00198 
00199   for (uint y = 0; y < sprite[zoom].height; y++) {
00200     const SpriteLoader::CommonPixel *src_ln = src + sprite[zoom - 1].width;
00201     assert(src_ln <= src_end);
00202     for (uint x = 0; x < sprite[zoom].width; x++) {
00203       assert(src < src_ln);
00204       if (src + 1 != src_ln && (src + 1)->a != 0) {
00205         *dst = *(src + 1);
00206       } else {
00207         *dst = *src;
00208       }
00209       dst++;
00210       src += 2;
00211     }
00212     src = src_ln + sprite[zoom - 1].width;
00213   }
00214 }
00215 
00216 static bool PadSingleSprite(SpriteLoader::Sprite *sprite, ZoomLevel zoom, uint pad_left, uint pad_top, uint pad_right, uint pad_bottom)
00217 {
00218   uint width  = sprite->width + pad_left + pad_right;
00219   uint height = sprite->height + pad_top + pad_bottom;
00220 
00221   if (width > UINT16_MAX || height > UINT16_MAX) return false;
00222 
00223   /* Copy source data and reallocate sprite memory. */
00224   SpriteLoader::CommonPixel *src_data = MallocT<SpriteLoader::CommonPixel>(sprite->width * sprite->height);
00225   MemCpyT(src_data, sprite->data, sprite->width * sprite->height);
00226   sprite->AllocateData(zoom, width * height);
00227 
00228   /* Copy with padding to destination. */
00229   SpriteLoader::CommonPixel *src = src_data;
00230   SpriteLoader::CommonPixel *data = sprite->data;
00231   for (uint y = 0; y < height; y++) {
00232     if (y < pad_top || pad_bottom + y >= height) {
00233       /* Top/bottom padding. */
00234       MemSetT(data, 0, width);
00235       data += width;
00236     } else {
00237       if (pad_left > 0) {
00238         /* Pad left. */
00239         MemSetT(data, 0, pad_left);
00240         data += pad_left;
00241       }
00242 
00243       /* Copy pixels. */
00244       MemCpyT(data, src, sprite->width);
00245       src += sprite->width;
00246       data += sprite->width;
00247 
00248       if (pad_right > 0) {
00249         /* Pad right. */
00250         MemSetT(data, 0, pad_right);
00251         data += pad_right;
00252       }
00253     }
00254   }
00255   free(src_data);
00256 
00257   /* Update sprite size. */
00258   sprite->width   = width;
00259   sprite->height  = height;
00260   sprite->x_offs -= pad_left;
00261   sprite->y_offs -= pad_top;
00262 
00263   return true;
00264 }
00265 
00266 static bool PadSprites(SpriteLoader::Sprite *sprite, uint8 sprite_avail)
00267 {
00268   /* Get minimum top left corner coordinates. */
00269   int min_xoffs = INT32_MAX;
00270   int min_yoffs = INT32_MAX;
00271   for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
00272     if (HasBit(sprite_avail, zoom)) {
00273       min_xoffs = min(min_xoffs, ScaleByZoom(sprite[zoom].x_offs, zoom));
00274       min_yoffs = min(min_yoffs, ScaleByZoom(sprite[zoom].y_offs, zoom));
00275     }
00276   }
00277 
00278   /* Get maximum dimensions taking necessary padding at the top left into account. */
00279   int max_width  = INT32_MIN;
00280   int max_height = INT32_MIN;
00281   for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
00282     if (HasBit(sprite_avail, zoom)) {
00283       max_width  = max(max_width, ScaleByZoom(sprite[zoom].width + sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom), zoom));
00284       max_height = max(max_height, ScaleByZoom(sprite[zoom].height + sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom), zoom));
00285     }
00286   }
00287 
00288   /* Pad sprites where needed. */
00289   for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
00290     if (HasBit(sprite_avail, zoom)) {
00291       /* Scaling the sprite dimensions in the blitter is done with rounding up,
00292        * so a negative padding here is not an error. */
00293       int pad_left   = max(0, sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom));
00294       int pad_top    = max(0, sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom));
00295       int pad_right  = max(0, UnScaleByZoom(max_width, zoom) - sprite[zoom].width - pad_left);
00296       int pad_bottom = max(0, UnScaleByZoom(max_height, zoom) - sprite[zoom].height - pad_top);
00297 
00298       if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) {
00299         if (!PadSingleSprite(&sprite[zoom], zoom, pad_left, pad_top, pad_right, pad_bottom)) return false;
00300       }
00301     }
00302   }
00303 
00304   return true;
00305 }
00306 
00307 static bool ResizeSprites(SpriteLoader::Sprite *sprite, uint8 sprite_avail, uint32 file_slot, uint32 file_pos)
00308 {
00309   /* Create a fully zoomed image if it does not exist */
00310   ZoomLevel first_avail = static_cast<ZoomLevel>(FIND_FIRST_BIT(sprite_avail));
00311   if (first_avail != ZOOM_LVL_NORMAL) {
00312     if (!ResizeSpriteIn(sprite, first_avail, ZOOM_LVL_NORMAL)) return false;
00313     SetBit(sprite_avail, ZOOM_LVL_NORMAL);
00314   }
00315 
00316   /* Pad sprites to make sizes match. */
00317   if (!PadSprites(sprite, sprite_avail)) return false;
00318 
00319   /* Create other missing zoom levels */
00320   for (ZoomLevel zoom = ZOOM_LVL_OUT_2X; zoom != ZOOM_LVL_END; zoom++) {
00321     if (HasBit(sprite_avail, zoom)) {
00322       /* Check that size and offsets match the fully zoomed image. */
00323       assert(sprite[zoom].width  == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].width,  zoom));
00324       assert(sprite[zoom].height == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].height, zoom));
00325       assert(sprite[zoom].x_offs == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].x_offs, zoom));
00326       assert(sprite[zoom].y_offs == UnScaleByZoom(sprite[ZOOM_LVL_NORMAL].y_offs, zoom));
00327     }
00328 
00329     /* Zoom level is not available, or unusable, so create it */
00330     if (!HasBit(sprite_avail, zoom)) ResizeSpriteOut(sprite, zoom);
00331   }
00332 
00333   return  true;
00334 }
00335 
00342 static void *ReadRecolourSprite(uint16 file_slot, uint num)
00343 {
00344   /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
00345    * number of recolour sprites that are 17 bytes that only exist in DOS
00346    * GRFs which are the same as 257 byte recolour sprites, but with the last
00347    * 240 bytes zeroed.  */
00348   static const uint RECOLOUR_SPRITE_SIZE = 257;
00349   byte *dest = (byte *)AllocSprite(max(RECOLOUR_SPRITE_SIZE, num));
00350 
00351   if (_palette_remap_grf[file_slot]) {
00352     byte *dest_tmp = AllocaM(byte, max(RECOLOUR_SPRITE_SIZE, num));
00353 
00354     /* Only a few recolour sprites are less than 257 bytes */
00355     if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
00356     FioReadBlock(dest_tmp, num);
00357 
00358     /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
00359     for (uint i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
00360       dest[i] = _palmap_w2d[dest_tmp[_palmap_d2w[i - 1] + 1]];
00361     }
00362   } else {
00363     FioReadBlock(dest, num);
00364   }
00365 
00366   return dest;
00367 }
00368 
00377 static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, AllocatorProc *allocator)
00378 {
00379   uint8 file_slot = sc->file_slot;
00380   size_t file_pos = sc->file_pos;
00381 
00382   assert(sprite_type != ST_RECOLOUR);
00383   assert(IsMapgenSpriteID(id) == (sprite_type == ST_MAPGEN));
00384   assert(sc->type == sprite_type);
00385 
00386   DEBUG(sprite, 9, "Load sprite %d", id);
00387 
00388   SpriteLoader::Sprite sprite[ZOOM_LVL_COUNT];
00389   uint8 sprite_avail = 0;
00390   sprite[ZOOM_LVL_NORMAL].type = sprite_type;
00391 
00392   SpriteLoaderGrf sprite_loader(sc->container_ver);
00393   if (sprite_type != ST_MAPGEN && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 32) {
00394     /* Try for 32bpp sprites first. */
00395     sprite_avail = sprite_loader.LoadSprite(sprite, file_slot, file_pos, sprite_type, true);
00396   }
00397   if (sprite_avail == 0) {
00398     sprite_avail = sprite_loader.LoadSprite(sprite, file_slot, file_pos, sprite_type, false);
00399   }
00400 
00401   if (sprite_avail == 0) {
00402     if (sprite_type == ST_MAPGEN) return NULL;
00403     if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
00404     return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator);
00405   }
00406 
00407   if (sprite_type == ST_MAPGEN) {
00408     /* Ugly hack to work around the problem that the old landscape
00409      *  generator assumes that those sprites are stored uncompressed in
00410      *  the memory, and they are only read directly by the code, never
00411      *  send to the blitter. So do not send it to the blitter (which will
00412      *  result in a data array in the format the blitter likes most), but
00413      *  extract the data directly and store that as sprite.
00414      * Ugly: yes. Other solution: no. Blame the original author or
00415      *  something ;) The image should really have been a data-stream
00416      *  (so type = 0xFF basicly). */
00417     uint num = sprite[ZOOM_LVL_NORMAL].width * sprite[ZOOM_LVL_NORMAL].height;
00418 
00419     Sprite *s = (Sprite *)allocator(sizeof(*s) + num);
00420     s->width  = sprite[ZOOM_LVL_NORMAL].width;
00421     s->height = sprite[ZOOM_LVL_NORMAL].height;
00422     s->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
00423     s->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
00424 
00425     SpriteLoader::CommonPixel *src = sprite[ZOOM_LVL_NORMAL].data;
00426     byte *dest = s->data;
00427     while (num-- > 0) {
00428       *dest++ = src->m;
00429       src++;
00430     }
00431 
00432     return s;
00433   }
00434 
00435   if (sprite_type == ST_NORMAL) {
00436     if (!ResizeSprites(sprite, sprite_avail, file_slot, sc->id)) {
00437       if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?");
00438       return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator);
00439     }
00440   }
00441   return BlitterFactoryBase::GetCurrentBlitter()->Encode(sprite, allocator);
00442 }
00443 
00444 
00446 static std::map<uint32, size_t> _grf_sprite_offsets;
00447 
00453 size_t GetGRFSpriteOffset(uint32 id)
00454 {
00455   return _grf_sprite_offsets.find(id) != _grf_sprite_offsets.end() ? _grf_sprite_offsets[id] : SIZE_MAX;
00456 }
00457 
00462 void ReadGRFSpriteOffsets(byte container_version)
00463 {
00464   _grf_sprite_offsets.clear();
00465 
00466   if (container_version >= 2) {
00467     /* Seek to sprite section of the GRF. */
00468     size_t data_offset = FioReadDword();
00469     size_t old_pos = FioGetPos();
00470     FioSeekTo(data_offset, SEEK_CUR);
00471 
00472     /* Loop over all sprite section entries and store the file
00473      * offset for each newly encountered ID. */
00474     uint32 id, prev_id = 0;
00475     while ((id = FioReadDword()) != 0) {
00476       if (id != prev_id) _grf_sprite_offsets[id] = FioGetPos() - 4;
00477       prev_id = id;
00478       FioSkipBytes(FioReadDword());
00479     }
00480 
00481     /* Continue processing the data section. */
00482     FioSeekTo(old_pos, SEEK_SET);
00483   }
00484 }
00485 
00486 
00495 bool LoadNextSprite(int load_index, byte file_slot, uint file_sprite_id, byte container_version)
00496 {
00497   size_t file_pos = FioGetPos();
00498 
00499   /* Read sprite header. */
00500   uint32 num = container_version >= 2 ? FioReadDword() : FioReadWord();
00501   if (num == 0) return false;
00502   byte grf_type = FioReadByte();
00503 
00504   SpriteType type;
00505   void *data = NULL;
00506   if (grf_type == 0xFF) {
00507     /* Some NewGRF files have "empty" pseudo-sprites which are 1
00508      * byte long. Catch these so the sprites won't be displayed. */
00509     if (num == 1) {
00510       FioReadByte();
00511       return false;
00512     }
00513     type = ST_RECOLOUR;
00514     data = ReadRecolourSprite(file_slot, num);
00515   } else if (container_version >= 2 && grf_type == 0xFD) {
00516     if (num != 4) {
00517       /* Invalid sprite section include, ignore. */
00518       FioSkipBytes(num);
00519       return false;
00520     }
00521     /* It is not an error if no sprite with the provided ID is found in the sprite section. */
00522     file_pos = GetGRFSpriteOffset(FioReadDword());
00523     type = ST_NORMAL;
00524   } else {
00525     FioSkipBytes(7);
00526     type = SkipSpriteData(grf_type, num - 8) ? ST_NORMAL : ST_INVALID;
00527     /* Inline sprites are not supported for container version >= 2. */
00528     if (container_version >= 2) return false;
00529   }
00530 
00531   if (type == ST_INVALID) return false;
00532 
00533   if (load_index >= MAX_SPRITES) {
00534     usererror("Tried to load too many sprites (#%d; max %d)", load_index, MAX_SPRITES);
00535   }
00536 
00537   bool is_mapgen = IsMapgenSpriteID(load_index);
00538 
00539   if (is_mapgen) {
00540     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?");
00541     type = ST_MAPGEN;
00542   }
00543 
00544   SpriteCache *sc = AllocateSpriteCache(load_index);
00545   sc->file_slot = file_slot;
00546   sc->file_pos = file_pos;
00547   sc->ptr = data;
00548   sc->lru = 0;
00549   sc->id = file_sprite_id;
00550   sc->type = type;
00551   sc->warned = false;
00552   sc->container_ver = container_version;
00553 
00554   return true;
00555 }
00556 
00557 
00558 void DupSprite(SpriteID old_spr, SpriteID new_spr)
00559 {
00560   SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
00561   SpriteCache *scold = GetSpriteCache(old_spr);
00562 
00563   scnew->file_slot = scold->file_slot;
00564   scnew->file_pos = scold->file_pos;
00565   scnew->ptr = NULL;
00566   scnew->id = scold->id;
00567   scnew->type = scold->type;
00568   scnew->warned = false;
00569   scnew->container_ver = scold->container_ver;
00570 }
00571 
00578 static const size_t S_FREE_MASK = sizeof(size_t) - 1;
00579 
00580 /* to make sure nobody adds things to MemBlock without checking S_FREE_MASK first */
00581 assert_compile(sizeof(MemBlock) == sizeof(size_t));
00582 /* make sure it's a power of two */
00583 assert_compile((sizeof(size_t) & (sizeof(size_t) - 1)) == 0);
00584 
00585 static inline MemBlock *NextBlock(MemBlock *block)
00586 {
00587   return (MemBlock*)((byte*)block + (block->size & ~S_FREE_MASK));
00588 }
00589 
00590 static size_t GetSpriteCacheUsage()
00591 {
00592   size_t tot_size = 0;
00593   MemBlock *s;
00594 
00595   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
00596     if (!(s->size & S_FREE_MASK)) tot_size += s->size;
00597   }
00598 
00599   return tot_size;
00600 }
00601 
00602 
00603 void IncreaseSpriteLRU()
00604 {
00605   /* Increase all LRU values */
00606   if (_sprite_lru_counter > 16384) {
00607     SpriteID i;
00608 
00609     DEBUG(sprite, 3, "Fixing lru %u, inuse=" PRINTF_SIZE, _sprite_lru_counter, GetSpriteCacheUsage());
00610 
00611     for (i = 0; i != _spritecache_items; i++) {
00612       SpriteCache *sc = GetSpriteCache(i);
00613       if (sc->ptr != NULL) {
00614         if (sc->lru >= 0) {
00615           sc->lru = -1;
00616         } else if (sc->lru != -32768) {
00617           sc->lru--;
00618         }
00619       }
00620     }
00621     _sprite_lru_counter = 0;
00622   }
00623 
00624   /* Compact sprite cache every now and then. */
00625   if (++_compact_cache_counter >= 740) {
00626     CompactSpriteCache();
00627     _compact_cache_counter = 0;
00628   }
00629 }
00630 
00635 static void CompactSpriteCache()
00636 {
00637   MemBlock *s;
00638 
00639   DEBUG(sprite, 3, "Compacting sprite cache, inuse=" PRINTF_SIZE, GetSpriteCacheUsage());
00640 
00641   for (s = _spritecache_ptr; s->size != 0;) {
00642     if (s->size & S_FREE_MASK) {
00643       MemBlock *next = NextBlock(s);
00644       MemBlock temp;
00645       SpriteID i;
00646 
00647       /* Since free blocks are automatically coalesced, this should hold true. */
00648       assert(!(next->size & S_FREE_MASK));
00649 
00650       /* If the next block is the sentinel block, we can safely return */
00651       if (next->size == 0) break;
00652 
00653       /* Locate the sprite belonging to the next pointer. */
00654       for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
00655         assert(i != _spritecache_items);
00656       }
00657 
00658       GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
00659       /* Swap this and the next block */
00660       temp = *s;
00661       memmove(s, next, next->size);
00662       s = NextBlock(s);
00663       *s = temp;
00664 
00665       /* Coalesce free blocks */
00666       while (NextBlock(s)->size & S_FREE_MASK) {
00667         s->size += NextBlock(s)->size & ~S_FREE_MASK;
00668       }
00669     } else {
00670       s = NextBlock(s);
00671     }
00672   }
00673 }
00674 
00679 static void DeleteEntryFromSpriteCache(uint item)
00680 {
00681   /* Mark the block as free (the block must be in use) */
00682   MemBlock *s = (MemBlock*)GetSpriteCache(item)->ptr - 1;
00683   assert(!(s->size & S_FREE_MASK));
00684   s->size |= S_FREE_MASK;
00685   GetSpriteCache(item)->ptr = NULL;
00686 
00687   /* And coalesce adjacent free blocks */
00688   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
00689     if (s->size & S_FREE_MASK) {
00690       while (NextBlock(s)->size & S_FREE_MASK) {
00691         s->size += NextBlock(s)->size & ~S_FREE_MASK;
00692       }
00693     }
00694   }
00695 }
00696 
00697 static void DeleteEntryFromSpriteCache()
00698 {
00699   uint best = UINT_MAX;
00700   int cur_lru;
00701 
00702   DEBUG(sprite, 3, "DeleteEntryFromSpriteCache, inuse=" PRINTF_SIZE, GetSpriteCacheUsage());
00703 
00704   cur_lru = 0xffff;
00705   for (SpriteID i = 0; i != _spritecache_items; i++) {
00706     SpriteCache *sc = GetSpriteCache(i);
00707     if (sc->type != ST_RECOLOUR && sc->ptr != NULL && sc->lru < cur_lru) {
00708       cur_lru = sc->lru;
00709       best = i;
00710     }
00711   }
00712 
00713   /* Display an error message and die, in case we found no sprite at all.
00714    * This shouldn't really happen, unless all sprites are locked. */
00715   if (best == UINT_MAX) error("Out of sprite memory");
00716 
00717   DeleteEntryFromSpriteCache(best);
00718 }
00719 
00720 static void *AllocSprite(size_t mem_req)
00721 {
00722   mem_req += sizeof(MemBlock);
00723 
00724   /* Align this to correct boundary. This also makes sure at least one
00725    * bit is not used, so we can use it for other things. */
00726   mem_req = Align(mem_req, S_FREE_MASK + 1);
00727 
00728   for (;;) {
00729     MemBlock *s;
00730 
00731     for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
00732       if (s->size & S_FREE_MASK) {
00733         size_t cur_size = s->size & ~S_FREE_MASK;
00734 
00735         /* Is the block exactly the size we need or
00736          * big enough for an additional free block? */
00737         if (cur_size == mem_req ||
00738             cur_size >= mem_req + sizeof(MemBlock)) {
00739           /* Set size and in use */
00740           s->size = mem_req;
00741 
00742           /* Do we need to inject a free block too? */
00743           if (cur_size != mem_req) {
00744             NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
00745           }
00746 
00747           return s->data;
00748         }
00749       }
00750     }
00751 
00752     /* Reached sentinel, but no block found yet. Delete some old entry. */
00753     DeleteEntryFromSpriteCache();
00754   }
00755 }
00756 
00766 static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, AllocatorProc *allocator)
00767 {
00768   static const char * const sprite_types[] = {
00769     "normal",        // ST_NORMAL
00770     "map generator", // ST_MAPGEN
00771     "character",     // ST_FONT
00772     "recolour",      // ST_RECOLOUR
00773   };
00774 
00775   SpriteType available = sc->type;
00776   if (requested == ST_FONT && available == ST_NORMAL) {
00777     if (sc->ptr == NULL) sc->type = ST_FONT;
00778     return GetRawSprite(sprite, sc->type, allocator);
00779   }
00780 
00781   byte warning_level = sc->warned ? 6 : 0;
00782   sc->warned = true;
00783   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]);
00784 
00785   switch (requested) {
00786     case ST_NORMAL:
00787       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?");
00788       /* FALL THROUGH */
00789     case ST_FONT:
00790       return GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator);
00791     case ST_RECOLOUR:
00792       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?");
00793       return GetRawSprite(PALETTE_TO_DARK_BLUE, ST_RECOLOUR, allocator);
00794     case ST_MAPGEN:
00795       /* this shouldn't happen, overriding of ST_MAPGEN sprites is checked in LoadNextSprite()
00796        * (the only case the check fails is when these sprites weren't even loaded...) */
00797     default:
00798       NOT_REACHED();
00799   }
00800 }
00801 
00810 void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator)
00811 {
00812   assert(IsMapgenSpriteID(sprite) == (type == ST_MAPGEN));
00813   assert(type < ST_INVALID);
00814 
00815   if (!SpriteExists(sprite)) {
00816     DEBUG(sprite, 1, "Tried to load non-existing sprite #%d. Probable cause: Wrong/missing NewGRFs", sprite);
00817 
00818     /* SPR_IMG_QUERY is a BIG FAT RED ? */
00819     sprite = SPR_IMG_QUERY;
00820   }
00821 
00822   SpriteCache *sc = GetSpriteCache(sprite);
00823 
00824   if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc, allocator);
00825 
00826   if (allocator == NULL) {
00827     /* Load sprite into/from spritecache */
00828 
00829     /* Update LRU */
00830     sc->lru = ++_sprite_lru_counter;
00831 
00832     /* Load the sprite, if it is not loaded, yet */
00833     if (sc->ptr == NULL) sc->ptr = ReadSprite(sc, sprite, type, AllocSprite);
00834 
00835     return sc->ptr;
00836   } else {
00837     /* Do not use the spritecache, but a different allocator. */
00838     return ReadSprite(sc, sprite, type, allocator);
00839   }
00840 }
00841 
00842 
00843 static void GfxInitSpriteCache()
00844 {
00845   /* initialize sprite cache heap */
00846   if (_spritecache_ptr == NULL) _spritecache_ptr = (MemBlock*)MallocT<byte>(_sprite_cache_size * 1024 * 1024);
00847 
00848   /* A big free block */
00849   _spritecache_ptr->size = ((_sprite_cache_size * 1024 * 1024) - sizeof(MemBlock)) | S_FREE_MASK;
00850   /* Sentinel block (identified by size == 0) */
00851   NextBlock(_spritecache_ptr)->size = 0;
00852 }
00853 
00854 void GfxInitSpriteMem()
00855 {
00856   GfxInitSpriteCache();
00857 
00858   /* Reset the spritecache 'pool' */
00859   free(_spritecache);
00860   _spritecache_items = 0;
00861   _spritecache = NULL;
00862 
00863   _compact_cache_counter = 0;
00864 }
00865 
00870 void GfxClearSpriteCache()
00871 {
00872   /* Clear sprite ptr for all cached items */
00873   for (uint i = 0; i != _spritecache_items; i++) {
00874     SpriteCache *sc = GetSpriteCache(i);
00875     if (sc->type != ST_RECOLOUR && sc->ptr != NULL) DeleteEntryFromSpriteCache(i);
00876   }
00877 }
00878 
00879 /* static */ ReusableBuffer<SpriteLoader::CommonPixel> SpriteLoader::Sprite::buffer[ZOOM_LVL_COUNT];