Saturday, April 11, 2009

Refactoring


Nice, big, productive day today. Not a whole lot to show for it visually, but I've been doing a HUGE amount of backend refactoring to remove hacks and make things 'official'. Got the fundamentals of the object system in place, to allow spawning of objects to populate the map. While the objects currently spawnable are all static, the groundwork is lain for extending to cities and areas, NPCs, the player avatar, etc... All in all, I'm pretty happy with the day so far.

I've gotten in the habit of never allowing the pointer returned by new to exist outside of a boost::shared_ptr. Awhile back, I came up with a scheme for resource loading that uses both boost::shared_ptr and boost::weak_ptr.

Often in a game, I will need to load a resource. Images, sound files, animations, etc... Some objects can share usage of a given resource, in which case I need to ensure that a given resource is only loaded once, regardless of how many objects request it. The most elegan solution I have come up with so far is a templated handler class that maintains a map of (std::string > boost::weak_ptr) mappings. The handler is given a string name of the resource to load, and it uses the name to search the map to find an existing weak_ptr to that resource. If no entry exists, the resource has not been requested yet, and the resource is loaded and inserted into the map. If an entry exists, but the pointer is expired, it means that the resource was loaded once but the objects using it have been deleted, so the resource is reloaded.

This has the effect of keeping a reference to a resource, but the resource itself is deleted when no objects are referencing it. The weak_ptr in the list doesn't count as a reference to the resource, so the entry in the map will not keep the resource from being dumped if all other objects that use it are deleted. It's a pretty simple scheme, but elegant.

I've begun the framework as well for generation of sub-region maps. At the moment, I am refactoring the world generation code now that I have a better idea of the kinds of values I need to track for wilderness area generation. I hope to have something to show in the sub-map department soon; today's refactoring should help there immensely, as part of the work I did was also to switch between world map and sub map at will.

I've also spent an hour or two working up some layouts in Blender, in preparation for building city/tower/cave/etc... location icons for the world map. Once upon a time, I was fairly decent with Blender. Those skills, alas, seem to have deserted me and I must get them back. Rest assured that when the missing skills are found, they shall be soundly punished.

No comments: