spritecache.cpp

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