ClanLib

Custom Resource Types

Extending the resource management system to incorporate a new resource type can be tricky, but with a little guidance, it is fairly straight forward.

Intoduction

For this tutorial we will be using a simple class called Object

Modifing the class

First you will need to add a constructor that will load from the resource management system and an instance of CL_Resource to store our resource information in.

Creating your resourcedata class

Now, before we actually define our new constructor for Object, lets create our new CL_ResourceData derivative class that will actually do the loading. This class is also fairly simple; it needs a constructor that takes a CL_Resource and two functions: on_load() and on_unload(). These functions will be called by the resource manager when the resource is loaded and unloaded respectively.

The constructor tells the resource to attach the data through this instance of CL_ResourceData. Later when you ask your resource manager to load the object it will call the on_load() function which actually reads in your data. Notice that the call to get_attribute takes two parameters in this instance. The first is obviously the variable name, but the second is the default value which is used when the attribute is not found.

The callback function

In order for this to work, we have to create a custom callback function to load your new resource types. The callback function just looks to see if the new resource is of our custom type, and in that event creates a new instance of our resourcedata type.

And then in your initialization routines just add a line like:

Adding object's constructor

Now just add that constructor for Object that we nearly forgot about. This function will just ask the our CL_ResourceManager for the instance of our object, then we tell it load it up. Then just get our our data from the resource, but if it returns no data then the name you specified is not of type Object. Then just get out your data however you like, a copy constuctor or overloaded = operator comes in real handy here.

Finale

The last thing to do is to call your resource. For a resource file looking like:

Just create your object like this:

Thats it!

TODO:

  • Explain how to use the resource manager's provider to load files.
  • Explain how to make the resource manager cache objects.
  • Questions or comments, write to the ClanLib mailing list.