Author Topic: Fix for reversed images in the cache  (Read 1853 times)


  • Member
  • **
  • Posts: 21
  • Karma: +0/-0
    • View Profile
Fix for reversed images in the cache
« on: Wed, May 4, 2011 »
Hi there,

Jusst thought I'd share this little fix for the _cache in flixel which has reduced object spawn times down from 40ms to 1ms.  I noticed the cache was generating a new sheet each time you loaded one with the 'reverse' flag set.

1. In, if you add:

Code: [Select]
static protected var _cacheReverse:Object;
Code: [Select]
static protected var _cache:Object;
2. And then in the setGameData() function add:

Code: [Select]
_cacheReverse=new Object();
right beneath:

Code: [Select]
_cache=new Object();
3. Finally, change your addBitmap() function to be as follows:
Code: [Select]
* Loads a bitmap from a file, caches it, and generates a horizontally flipped version if necessary.
* @param Graphic The image file that you want to load.
* @param Reverse Whether to generate a flipped version.
* @return The <code>BitmapData</code> we just created.
static public function addBitmap(Graphic:Class, Reverse:Boolean=false, Unique:Boolean=false, Key:String=null):BitmapData
var needReverse:Boolean = false;
var key:String = Key;
if(key == null)
key = String(Graphic);
if (key=="[class SixMap3_Imgplayer]")
// trace ("Let's get into it...");
if(Unique && (_cache[key] != undefined) && (_cache[key] != null))
//Generate a unique key
var inc:uint = 0;
var ukey:String;
do { ukey = key + inc++;
} while((_cache[ukey] != undefined) && (_cache[ukey] != null));
key = ukey;

var gotFromCache:Boolean=false;

//If there is no data for this key, generate the requested graphic
_cache[key] = (new Graphic).bitmapData;
if(Reverse) needReverse = true;

var pixels:BitmapData;
if (!gotFromCache || !Reverse) pixels = _cache[key];
if (gotFromCache && Reverse) needReverse=true;
else if(!needReverse && Reverse && (pixels.width == (new Graphic).bitmapData.width))
needReverse = true;

if (!gotFromCache)
var newPixels:BitmapData = new BitmapData(pixels.width<<1,pixels.height,true,0x00000000);
var mtx:Matrix = new Matrix();
pixels = newPixels;


return pixels;

It's messy, but it works, and it was the fix for an issue which almost stopped my last game being released (massive chugging when spawning a lot of objects.)  This is going to affect people worst when they have multiple sprites on one sheet, as each time the whole sheet will be reversed without this code.

This may well have been fixed in 2.5 which I haven't checked yet... so if it is... my bad!

Adam Atomic

  • Founder
  • Key Contributor
  • *****
  • Posts: 852
  • Karma: +0/-0
  • new dad
    • View Profile
    • Adam Atomic
Re: Fix for reversed images in the cache
« Reply #1 on: Wed, May 4, 2011 »
yea i added a reverse flag for the key that should have helped with that...