engine/include/resource_manager.h

66 lines
1.6 KiB
C
Raw Normal View History

2023-04-29 14:22:25 +00:00
#ifndef ENGINE_INCLUDE_RESOURCE_MANAGER_H_
#define ENGINE_INCLUDE_RESOURCE_MANAGER_H_
2022-09-02 11:06:59 +00:00
2022-12-01 15:54:28 +00:00
#include <memory>
#include <stdexcept>
2023-04-29 14:22:25 +00:00
#include <string>
#include <unordered_map>
#include <vector>
2023-08-29 21:10:05 +00:00
#include <typeinfo>
#include "log.h"
#include "resources/mesh.h"
2022-09-02 11:06:59 +00:00
2022-10-06 10:30:44 +00:00
namespace engine {
2022-09-02 11:06:59 +00:00
2023-04-29 14:22:25 +00:00
class IResourceManager {
2023-04-29 14:56:49 +00:00
public:
2023-08-29 21:10:05 +00:00
virtual ~IResourceManager(){};
2023-04-29 14:22:25 +00:00
};
template <class T>
class ResourceManager : public IResourceManager {
2023-04-29 14:56:49 +00:00
public:
2023-08-29 21:10:05 +00:00
~ResourceManager() override {
LOG_DEBUG("Destroying resource manager... '{}'", typeid(T).name());
}
2023-04-29 14:56:49 +00:00
std::shared_ptr<T> Add(const std::string& name,
std::unique_ptr<T>&& resource) {
2023-04-29 14:22:25 +00:00
if (resources_.contains(name) == false) {
std::shared_ptr<T> resource_shared(std::move(resource));
resources_.emplace(name, resource_shared);
return resource_shared;
2023-04-29 14:56:49 +00:00
} else {
2023-04-29 14:22:25 +00:00
throw std::runtime_error("Cannot add a resource which already exists");
}
}
2023-04-29 14:56:49 +00:00
void AddPersistent(const std::string& name, std::unique_ptr<T>&& resource) {
2023-04-29 14:22:25 +00:00
persistent_resources_.push_back(Add(name, std::move(resource)));
}
2023-04-29 14:56:49 +00:00
std::shared_ptr<T> Get(const std::string& name) {
2023-04-29 14:22:25 +00:00
if (resources_.contains(name)) {
std::weak_ptr<T> ptr = resources_.at(name);
if (ptr.expired() == false) {
return ptr.lock();
} else {
resources_.erase(name);
}
}
// resource doesn't exist:
throw std::runtime_error("Resource doesn't exist: " + name);
return {};
}
2023-04-29 14:56:49 +00:00
private:
2023-04-29 14:22:25 +00:00
std::unordered_map<std::string, std::weak_ptr<T>> resources_{};
// This array owns persistent resources
std::vector<std::shared_ptr<T>> persistent_resources_{};
};
} // namespace engine
#endif