engine/include/resource_manager.hpp

59 lines
1.3 KiB
C++
Raw Normal View History

2022-09-02 11:06:59 +00:00
#pragma once
#include <unordered_map>
#include <vector>
2022-12-01 15:54:28 +00:00
#include <string>
#include <memory>
#include <stdexcept>
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-01-05 13:21:33 +00:00
class IResourceManager {
public:
virtual ~IResourceManager() = default;
};
2022-12-01 15:54:28 +00:00
template <class T>
2023-01-05 13:21:33 +00:00
class ResourceManager : public IResourceManager {
2022-09-02 11:06:59 +00:00
2022-10-06 10:30:44 +00:00
public:
2022-12-20 23:51:04 +00:00
std::shared_ptr<T> add(const std::string& name, std::unique_ptr<T>&& resource)
2022-12-01 15:54:28 +00:00
{
if (m_resources.contains(name) == false) {
2022-12-20 23:51:04 +00:00
std::shared_ptr<T> resourceSharedPtr(std::move(resource));
m_resources.emplace(name, resourceSharedPtr);
return resourceSharedPtr;
2022-09-02 11:06:59 +00:00
}
else {
2022-12-01 15:54:28 +00:00
throw std::runtime_error("Cannot add a resource which already exists");
2022-09-02 11:06:59 +00:00
}
2022-12-01 15:54:28 +00:00
}
2022-10-06 10:30:44 +00:00
void addPersistent(const std::string& name, std::unique_ptr<T>&& resource)
{
m_persistentResources.push_back(add(name, std::move(resource)));
}
2022-12-20 23:51:04 +00:00
std::shared_ptr<T> get(const std::string& name)
2022-12-01 15:54:28 +00:00
{
if (m_resources.contains(name)) {
2022-12-20 23:51:04 +00:00
std::weak_ptr<T> ptr = m_resources.at(name);
if (ptr.expired() == false) {
return ptr.lock();
2023-01-05 13:21:33 +00:00
} else {
m_resources.erase(name);
2022-12-20 23:51:04 +00:00
}
2022-12-01 15:54:28 +00:00
}
2023-01-05 13:21:33 +00:00
// resource doesn't exist:
throw std::runtime_error("Resource doesn't exist: " + name);
2022-12-01 15:54:28 +00:00
return {};
2022-09-02 11:06:59 +00:00
}
2022-10-06 10:30:44 +00:00
2022-12-01 15:54:28 +00:00
private:
2022-12-20 23:51:04 +00:00
std::unordered_map<std::string, std::weak_ptr<T>> m_resources{};
std::vector<std::shared_ptr<T>> m_persistentResources{}; // This array owns persistent resources
2022-09-02 11:06:59 +00:00
2022-12-01 15:54:28 +00:00
};
2022-09-02 11:06:59 +00:00
2022-12-15 10:07:22 +00:00
}