Game Development Reference
In-Depth Information
m_name=name;
std::transform(m_name.begin(), m_name.end(),
m_name.begin(), (int(*)(int)) std::tolower);
}
};
You might wonder why a string-based identifier is used here rather than some kind of
defined ID. The reason is that game assets tend to change incredibly fast during devel-
opment, and you don
twanttohaveahugelistofIDsthatwillbechangingconstantly,
perhaps forcing a recompile of your game every time an artist adds a new texture.
Speed is typically not a big problem here, since string lookups will likely not happen
that often after a resource is loaded, which you can control. In short, this is one of
those cases where a little CPU time is traded for a huge development convenience.
Another quick nod to development convenience is to convert the resource name to
lowercase. Doing so keeps you from having to set up rules for artists and other con-
tent providers that they probably won
'
t remember to follow anyway!
Two phases are involved in using a resource cache: creating the resource and using it.
When you create a resource, you are simply creating an identifier for the resource. It
doesn
'
t really do much of anything. The heavy lifting happens when you send the
resource into the resource cache to gain access to the bits or a resource handle. Han-
dles should always be managed by a
shared_ptr
so the bits are guaranteed to be
good as long as you need them. Here
'
s an example of how to use the
Resource
class to grab a handle and get to the bits:
'
Resource resource(“Brick.bmp”);
shared_ptr<ResHandle> texture = g_pApp->m_ResCache->GetHandle(&resource);
int size = texture->GetSize();
char *brickBitmap = (char *) texture->Buffer();
If the resource is already loaded in the cache, these lines of code execute extremely
quickly. If the resource is not loaded, you have a cache miss on your hands, and the
resource cache will make room if necessary, allocate memory for the resource, and
finally load the resource from the resource file. The bits are available as long as the
ResHandle
remains in scope, since it is managed by a
shared_ptr
. Once the
ResHandle
structure goes out of scope, the resource cache may retain the bits if
there
s room to keep them.
Now you
'
'
'
ve already seen how a
resource is defined through the
Resource
structure. There are a few other parts of a
resource cache, and I
re ready to see how the resource cache is coded. You
'
ll go over each one in detail:
n
IResourceFile
interface and
ResourceZipFile
, the resource file