ClanLib

Resource API Overview - Part 2

Custom resources

It is possible to add your own resource types to clanlib, or even extend the functionality of already existing resource types.

The resource system uses an interface called CL_ResourceType to identify resource types in the resource files, and instantiate the appropiate data objects for a resource. When a resource is being loaded, the following happens:

This may sound a little advanced, but a small example will show how simple it can look. First we create our data object:

The data object attaches itself to the resource using the name 'map'. We can obtain a pointer to the object by using the CL_Resource::get_data() function:

Note that the above code will not produce a call to ResourceData_Map::on_load_file(). This will first happen when a call is done to CL_Resource::load(). The same thing applies with unloading; if you loaded an object by calling load(), you must also call unload(). The resource class reference counts the loading, so several objects can call load(), but only the first call will actually perform the load.

When the resource manager parses the resource file, it will need to know what resource types exist, and how to attach data objects. In order to do this, the resource manager use a linked list of CL_ResourceType objects. It walks through all the resource type objects, and then asks wether it can attach data to the resource. If no resource type recognizes the resource, the resource manager will throw and exception, telling the program that it has encountered an unknown resource type.

ClanLib contain a template class called CL_RegisterResourceType that allows you to construct simple resource type objects, that just attach a single data object to the resource. Registration of resource types require that you create an instance of CL_ResourceType. The template class is inheriated from CL_ResourceType and is nothing more than a convience class. An example of its usage:

That's it! We have constructed our own custom resource.

Extending existing resource types

It is possible to have several resource type objects for the same resource. This is practical if you want to extend an already existing resource type with more functionality. Each resource type object can attach its own data to the resource object, allowing you to eg. add "animation_data" to a surface type.

The following is a small example of how to extend the surface type with some additional data:

Questions or comments, write to the ClanLib mailing list.