Engine
Raylib based game framework
Loading...
Searching...
No Matches
ResourceManager.h
1#pragma once
2
3#include "Assert.h"
4
5#include <functional>
6#include <memory>
7#include <string>
8#include <typeindex>
9#include <unordered_map>
10
11class Cache
12{
13public:
14
15 virtual ~Cache() = default;
16};
17
18template <class T>
19class ResourceCache : public Cache
20{
21public:
22
23 ResourceCache(const std::function<T(const char*)>& loadFunction, const std::function<void(T)>& unloadFunction) :
24 m_loadFunction(loadFunction),
25 m_unloadFunction(unloadFunction)
26 {
27 }
28
30 {
31 for (auto& [path, object] : m_map)
32 {
33 m_unloadFunction(*object);
34 }
35 }
36
37 T& Get(const char* path)
38 {
39 auto it = m_map.find(path);
40 if (it != m_map.end())
41 {
42 return *it->second();
43 }
44
45 auto ptr = std::make_unique<T>(std::move(m_loadFunction(path)));
46 auto& ref = *ptr;
47
48 m_map.emplace(path, std::move(ptr));
49
50 return ref;
51 }
52
53 T& Add(const T& object, const char* name)
54 {
55 auto it = m_map.find(name);
56 if (it != m_map.end())
57 {
58 m_unloadFunction(*it->second);
59 }
60
61 auto ptr = std::make_unique<T>(std::move(object));
62 auto& ref = *ptr;
63
64 m_map.emplace(name, std::move(ptr));
65
66 return ref;
67 }
68
69 void Remove(const char* path)
70 {
71 auto it = m_map.find(path);
72 if (it != m_map.end())
73 {
74 m_unloadFunction(*it->second);
75
76 m_map.erase(it);
77 }
78 }
79
80private:
81
82 std::unordered_map<std::string, std::unique_ptr<T>> m_map;
83
84 std::function<T(const char*)> m_loadFunction;
85 std::function<void(T)> m_unloadFunction;
86};
87
89{
90public:
91
92 template <typename T, typename... Args>
93 ResourceCache<T>& AddCache(Args&&... args)
94 {
95 auto it = m_caches.find(typeid(T));
96 Assert(it == m_caches.end(), "Cache of type ", typeid(T).name(), " already exists");
97
98 auto ptr = std::make_unique<ResourceCache<T>>(std::forward<Args>(args)...);
99 ResourceCache<T>& ref = *ptr;
100
101 m_caches.emplace(typeid(T), std::move(ptr));
102
103 return ref;
104 }
105
106 template <typename T>
107 ResourceCache<T>& GetCache()
108 {
109 auto it = m_caches.find(typeid(T));
110 Assert(it != m_caches.end(), "No cache exists holding type ", typeid(T).name());
111
112 return *static_cast<ResourceCache<T>*>(it->second.get());
113 }
114
115 template <typename T>
116 void RemoveCache()
117 {
118 auto it = m_caches.find(typeid(T));
119 if (it != m_caches.end())
120 {
121 m_caches.erase(it);
122 }
123 }
124
125 void ClearCaches();
126
127private:
128
129 std::unordered_map<std::type_index, std::unique_ptr<Cache>> m_caches;
130};
Definition ResourceManager.h:12
Definition ResourceManager.h:20
Definition ResourceManager.h:89