I have learned a few things while programming for an iPod/iPhone. I’ll be applying some of what I learned to legacy of a warlord. The following tweak will definitely help when I allow NPCs to equip and use items.
While profiling code for Legacy of a Warlord. I noticed that I was querying what features exist on an item, a lot! Not that this is a bad thing yet the way I was doing it could use a refactor.
Features in items reside in a MAP data structure, I was using a map count to see if the feature existed.
// old feature check queried map
bool Item::QueryFeature(FEATURE_TYPES t_FeatureCheck) const
{
if (Features.count(t_FeatureCheck)>0){
return true;
}else{
return false;
}
}
I actually didn’t find out how many nanoseconds it took to return a count of the available features, however I am assuming that performing a bit-wise computation on an integer using a mask is magnitudes quicker than counting how many indexes are in a map data structure.
First I added an integer on the item to store a feature mask.
int FeatureMask=0;
// Then there is a enumeration that stores the mask values.
typedef enum FEATURE_TYPES{
FEATURE_LOADERROR= 1«0,
FEATURE_HOLDABLE= 1«1,
FEATURE_TRADABLE= 1«2,
…
FEATURE_USABLE= 1«14
} FEATURE_TYPES;
As an item is generated, I set the flag of the features on the item that were specified in the XML file:
As an example to add display and tradable to the item feature mask.
FeatureMask |= FEATURE_DISPLAY;
FeatureMask |= FEATURE_TRADABLE;
This is the helper function I wrote to return whether a feature exists.
// new feature check to check feature mask
bool Item::QueryFeature(FEATURE_TYPES t_FeatureCheck) const {
if ( (FeatureMask & t_FeatureCheck) != 0 ){
return true;
}else{
return false;
}
}
Now when the render engine needs to determine if the 100 items on the ground are visible it can call QueryFeature(FEATURE_DISPLAY) and know if it has to display the item or hide it. Also, this is called any time an item is created, destroyed, or equipped by any NPC/player.
I will bitmasks to other core engine features that need the speed optimized.
edit: slight correction, the bit masks can easily be set using 1«n instead of 1«(2*n) … oops.