//This file is part of Photon (http://photon.sourceforge.net) //Copyright (C) 2004-2005 James Turk // // Author: // James Turk (jpt2433@rit.edu) // // Version: // $Id: ResourceManager.hpp,v 1.5 2005/06/13 05:38:06 cozman Exp $ #ifndef PHOTON_RESOURCEMANAGER_HPP #define PHOTON_RESOURCEMANAGER_HPP #include #include #include #include "types.hpp" #include "exceptions.hpp" namespace photon { class Resource { public: static const uint InvalidID=0xffffffff; Resource() : refCount(0) { } uint refCount; std::string name; std::string path; }; // Class: ResourceManager // Templated base class for managing resources like textures and music. // // All ResourceManager work is done behind the scenes, it and all classes // derived from it are therefore left without public documentation. template class ResourceManager : public boost::noncopyable { public: ResourceManager(); virtual ~ResourceManager(); uint getResID(const std::string& name); void delRef(uint id); void cleanUp(); uint newResource(const std::string& name, const std::string& path); private: virtual void loadResource(resT &res, const std::string& path)=0; virtual void freeResource(resT &res)=0; void deleteResource(uint id); protected: std::vector resVec_; }; // implementation (damn you templor, cruel god of templates!) template ResourceManager::ResourceManager() { } template ResourceManager::~ResourceManager() { } template uint ResourceManager::getResID(const std::string& name) { uint id(0); // loop through resources until the resource name in question is found for(typename std::vector::iterator i=resVec_.begin(); i != resVec_.end() && i->name != name; ++i) { ++id; // increment id } if(id == resVec_.size()) // not found -> throw a ResourceException { throw ResourceException("Failed to find resource \"" + name + "\""); } return id; } template void ResourceManager::delRef(uint id) { // if decremented count is <= 0, delete resource if(id < resVec_.size() && --resVec_[id].refCount <= 0) { deleteResource(id); } } template void ResourceManager::cleanUp() { // delete resources, until none are left for(typename std::vector::iterator i=resVec_.begin(); i != resVec_.end(); ++i) { freeResource(*i); } } template uint ResourceManager::newResource(const std::string& name, const std::string& path) { resT res; res.name = name; res.path = path; try { // attempt to load loadResource(res, path); } catch(ResourceException& e) { // rethrow any exceptions with specific information throw ResourceException("Could not load " + path + " as " + name + ": " + e.what()); } resVec_.push_back(res); // add resource to resVec & return return static_cast(resVec_.size()-1); } template void ResourceManager::deleteResource(uint id) { // check boundaries if(id >= resVec_.size()) { throw RangeException("Attempt to delete invalid resource."); } freeResource(resVec_[id]); // free the resource and erase it from the vec resVec_.erase(resVec_.begin()+id); } } #endif //PHOTON_RESOURCEMANAGER_HPP