vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
resource_manager.h
1#pragma once
2
3#include <memory>
4#include <string>
5#include <type_traits>
6#include <unordered_map>
7#include <utility>
8#include <vector>
9
10#include "l_assert.h"
11#include "logger.h"
12
13#include "core/memory/slot_allocator.h"
14#include "core/memory/sparse_set.h"
15#include "core/memory/types.h"
16#include "core/memory/type_registry.h"
17#include "resource/asset_ref.h"
18#include "resource/asset_type.h"
19#include "resource/resource.h"
20#include "resource/resource_handle.h"
21
22namespace Vkm::Engine {
23
24struct FontAsset;
25
33template<typename T>
34inline constexpr bool IS_ENGINE_ASSET = ASSET_TYPE<T> != AssetType::Count || std::is_same_v<T, FontAsset>;
35
46class ResourceManager {
47 public:
48 ResourceManager();
49 ~ResourceManager() = default;
50
51 ResourceManager(const ResourceManager& other) = delete;
52 ResourceManager& operator=(const ResourceManager& other) = delete;
53
54 ResourceManager(ResourceManager && other) = delete;
55 ResourceManager& operator=(ResourceManager && other) = delete;
56
57 public:
71 template<typename ResourceType>
72 auto add(ResourceType && resource) {
73 using T = std::remove_cv_t<std::remove_reference_t<ResourceType>>;
74 static_assert(
75 std::is_base_of_v<Resource, T>,
76 "ResourceManager stores only types deriving from Resource."
77 );
78 auto& slot = getSlot<T>();
79
80 if (resource.m_name.empty()) ensureUniqueName(slot, resource.m_name);
81
82 if (const auto taken = slot.nameIndex.find(resource.m_name); taken != slot.nameIndex.end()) {
83 return replaceAt<T>(slot, taken->second, std::forward<ResourceType>(resource));
84 }
85
86 StorageIndex key = slot.allocator.allocate();
87 std::string indexName = resource.m_name; // non-empty now
88 // Stamped on the stored asset, not the argument: insertion may copy,
89 // and a copy is a duplicate that carries no identity of its own.
90 Resource& stored = storageOf<T>(slot).add(key.index, std::forward<ResourceType>(resource));
91 stored.m_uid = mintUid();
92 stored.m_version = 1;
93 slot.nameIndex.emplace(std::move(indexName), key.index);
94
95 return Handle<T>{key};
96 }
97
106 template<typename ResourceType>
107 auto add(ResourceType && resource, std::string name) {
108 resource.m_name = std::move(name);
109 return add(std::forward<ResourceType>(resource));
110 }
111
128 template<typename T, typename Make>
129 Handle<T> findOrAdd(const std::string& name, Make&& make) {
130 if (const Handle<T> found = findByName<T>(name)) return found;
131 return add(T(std::forward<Make>(make)()), name);
132 }
133
142 template<typename ResourceType>
143 auto addPrivate(ResourceType && resource, std::string name) {
144 resource.m_hidden = true;
145 resource.m_name = std::move(name);
146 return add(std::forward<ResourceType>(resource));
147 }
148
159 template<typename HandleType>
160 void remove(const HandleType& handle) {
161 using T = typename HandleType::resource_t;
162 auto& slot = getSlot<T>();
163 VKM_ASSERT(slot.allocator.has(handle.key), "ResourceManager::remove invalid handle");
164 if (!slot.allocator.has(handle.key)) return;
165
166 const T& res = storageOfConst<T>(slot).get(handle.key.index);
167 dropNameIndex(slot, res.m_name, handle.key.index);
168 storageOf<T>(slot).remove(handle.key.index);
169 slot.allocator.free(handle.key);
170 touch(slot);
171 }
172
182 template<typename HandleType>
183 bool isAlive(const HandleType& handle) const {
184 using T = typename HandleType::resource_t;
185 return getSlotConst<T>().allocator.has(handle.key);
186 }
187
195 template<typename HandleType>
196 const auto& get(const HandleType& handle) const {
197 using T = typename HandleType::resource_t;
198 const auto& slot = getSlotConst<T>();
199 VKM_ASSERT(slot.allocator.has(handle.key), "ResourceManager::get invalid handle");
200 return storageOfConst<T>(slot).get(handle.key.index);
201 }
202
213 template<typename HandleType>
214 const auto* tryGet(const HandleType& handle) const {
215 using T = typename HandleType::resource_t;
216 const TypedSlot& slot = getSlotConst<T>();
217 if (!slot.allocator.has(handle.key)) return static_cast<const T*>(nullptr);
218 return &storageOfConst<T>(slot).get(handle.key.index);
219 }
220
230 template<typename HandleType>
231 auto* tryEdit(const HandleType& handle) {
232 using T = typename HandleType::resource_t;
233 TypedSlot& slot = getSlot<T>();
234 if (!slot.allocator.has(handle.key)) return static_cast<T*>(nullptr);
235 return &storageOf<T>(slot).get(handle.key.index);
236 }
237
248 template<typename HandleType>
249 auto& edit(const HandleType& handle) {
250 using T = typename HandleType::resource_t;
251 auto& slot = getSlot<T>();
252 VKM_ASSERT(slot.allocator.has(handle.key), "ResourceManager::edit invalid handle");
253 return storageOf<T>(slot).get(handle.key.index);
254 }
255
266 template<typename HandleType>
267 void rename(const HandleType& handle, std::string newName) {
268 using T = typename HandleType::resource_t;
269 auto& slot = getSlot<T>();
270 VKM_ASSERT(slot.allocator.has(handle.key), "ResourceManager::rename invalid handle");
271 auto& res = storageOf<T>(slot).get(handle.key.index);
272 // Before the uniqueness check, so renaming to the current name is not a self-collision.
273 dropNameIndex(slot, res.m_name, handle.key.index);
274 ensureUniqueName(slot, newName);
275 res.m_name = std::move(newName);
276 slot.nameIndex[res.m_name] = handle.key.index;
277 }
278
292 template<typename HandleType>
293 void swapValue(const HandleType& handle, typename HandleType::resource_t& value) {
294 using T = typename HandleType::resource_t;
295 static_assert(
296 std::is_base_of_v<Resource, T>,
297 "Resource type must inherit from Resource to use swapValue()."
298 );
299 auto& slot = getSlot<T>();
300 VKM_ASSERT(slot.allocator.has(handle.key), "ResourceManager::swapValue invalid handle");
301 T& target = storageOf<T>(slot).get(handle.key.index);
302 if (&target == &value) return;
303
304 using std::swap;
305 swap(target, value);
306 swap(target.m_version, value.m_version);
307 swap(target.m_uid, value.m_uid);
308 swap(target.m_hidden, value.m_hidden);
309 swap(target.m_name, value.m_name);
310 ++target.m_version;
311 touch(slot);
312 }
313
320 template<typename HandleType>
321 void commit(const HandleType& handle) {
322 using T = typename HandleType::resource_t;
323 static_assert(
324 std::is_base_of_v<Resource, T>,
325 "Resource type must inherit from Resource to use commit()."
326 );
327 auto& slot = getSlot<T>();
328 VKM_ASSERT(slot.allocator.has(handle.key), "ResourceManager::commit invalid handle");
329 ++storageOf<T>(slot).get(handle.key.index).m_version;
330 touch(slot);
331 }
332
340 template<typename T>
341 Handle<T> findByName(const std::string& name) const {
342 const TypedSlot& slot = getSlotConst<T>();
343 auto it = slot.nameIndex.find(name);
344 if (it == slot.nameIndex.end()) return {};
345 return Handle<T>{slot.allocator.handleAt(it->second)};
346 }
347
359 template<typename T>
360 Handle<T> find(const AssetRef<T>& ref) const {
361 return ref.name.empty() ? Handle<T>{} : findByName<T>(ref.name);
362 }
363
371 template<typename T, typename Fn>
372 void forEachOfType(Fn&& fn) const {
373 const TypedSlot& slot = getSlotConst<T>();
374 storageOfConst<T>(slot).forEach([&](uint32_t index, const T& res) {
375 fn(Handle<T>{slot.allocator.handleAt(index)}, res);
376 });
377 }
378
384 template<typename T>
385 size_t countOfType() const {
386 return storageOfConst<T>(getSlotConst<T>()).size();
387 }
388
394 void clear();
395
407 void swap(ResourceManager& other) noexcept;
408
417 uint64_t epoch() const { return m_epoch; }
418
428 uint64_t revision() const { return m_revision; }
429
440 template<typename T>
441 uint64_t revisionOf() const {
442 return getSlotConst<T>().revision;
443 }
444
445 private:
446 struct TypedSlot {
447 SlotAllocator allocator;
448 std::unique_ptr<ISparseSet> storage;
450 std::unordered_map<std::string, uint32_t> nameIndex;
451 uint64_t revision = 0;
452 };
453
455 void touch(TypedSlot& slot) {
456 ++slot.revision;
457 ++m_revision;
458 }
459
460 private:
464 void makeEngineSlots();
465
466 template<typename T>
467 TypedSlot& getSlot() {
468 static_assert(
469 IS_ENGINE_ASSET<T>,
470 "ResourceManager stores the engine's asset types only: a slot for a type a "
471 "gameplay module declares would carry the module's code past its unload."
472 );
473 return m_slots.ensure<T>([] {
474 auto slot = std::make_unique<TypedSlot>();
475 slot->storage = std::make_unique<SparseSet<T>>();
476 return slot;
477 });
478 }
479
481 template<typename T>
482 const TypedSlot& getSlotConst() const {
483 static_assert(IS_ENGINE_ASSET<T>, "ResourceManager stores the engine's asset types only.");
484 return *m_slots.find<T>();
485 }
486
487 template<typename T>
488 static SparseSet<T>& storageOf(TypedSlot& slot) {
489 return static_cast<SparseSet<T>&>(*slot.storage);
490 }
491
492 template<typename T>
493 static const SparseSet<T>& storageOfConst(const TypedSlot& slot) {
494 return static_cast<const SparseSet<T>&>(*slot.storage);
495 }
496
504 static void dropNameIndex(TypedSlot& slot, const std::string& name, uint32_t index) {
505 auto it = slot.nameIndex.find(name);
506 if (it != slot.nameIndex.end() && it->second == index) {
507 slot.nameIndex.erase(it);
508 }
509 }
510
525 template <typename T, typename ResourceType>
526 Handle<T> replaceAt(TypedSlot& slot, uint32_t index, ResourceType && resource) {
527 T& target = storageOf<T>(slot).get(index);
528
529 // First: re-declaring an asset with its own contents hands in target itself, and
530 // constructing from it would move the name away.
531 const uint64_t version = target.m_version;
532 std::string name = std::move(target.m_name);
533
534 // Constructed: Resource has no copy assignment.
535 T incoming(std::forward<ResourceType>(resource));
536 using std::swap;
537 swap(target, incoming);
538
539 target.m_name = std::move(name);
540 target.m_uid = mintUid();
541 target.m_version = version + 1;
542 touch(slot);
543 return Handle<T>{slot.allocator.handleAt(index)};
544 }
545
555 static void ensureUniqueName(const TypedSlot& slot, std::string& name) {
556 if (name.empty()) name = "asset";
557 if (slot.nameIndex.find(name) == slot.nameIndex.end()) return;
558 const std::string base = name;
559 for (int n = 2; ; ++n) {
560 std::string candidate = base + " (" + std::to_string(n) + ")";
561 if (slot.nameIndex.find(candidate) == slot.nameIndex.end()) {
562 name = std::move(candidate);
563 return;
564 }
565 }
566 }
567
576 static uint64_t mintUid();
577
578 private:
579 TypeRegistry<TypedSlot> m_slots;
580
582 uint64_t m_epoch = 1;
583 uint64_t m_revision = 1;
584};
585
586} // namespace Vkm::Engine
size_t countOfType() const
How many resources of type T the graph holds.
Definition resource_manager.h:385
Handle< T > find(const AssetRef< T > &ref) const
Resolve an authored reference to the asset it names.
Definition resource_manager.h:360
bool isAlive(const HandleType &handle) const
Whether handle still names a live resource of its type.
Definition resource_manager.h:183
void swapValue(const HandleType &handle, typename HandleType::resource_t &value)
Exchange the contents of the asset at handle with value, each keeping its identity,...
Definition resource_manager.h:293
const auto & get(const HandleType &handle) const
The resource handle names; asserts it is live (see isAlive(), tryGet()).
Definition resource_manager.h:196
void clear()
Drop every resource but the fonts, by swap() with an empty manager.
void rename(const HandleType &handle, std::string newName)
Rename a resource, keeping findByName consistent.
Definition resource_manager.h:267
Handle< T > findOrAdd(const std::string &name, Make &&make)
The asset under name, or the one make makes, added under it.
Definition resource_manager.h:129
auto * tryEdit(const HandleType &handle)
The asset handle names for editing, or null when it names none.
Definition resource_manager.h:231
void swap(ResourceManager &other) noexcept
Swap the asset graph with another ResourceManager, fonts excepted.
auto & edit(const HandleType &handle)
Mutable access to the resource handle names.
Definition resource_manager.h:249
const auto * tryGet(const HandleType &handle) const
The asset handle names, or null when it names none.
Definition resource_manager.h:214
auto add(ResourceType &&resource, std::string name)
add() under name.
Definition resource_manager.h:107
uint64_t epoch() const
Identity of the current asset graph, bumped by every swap.
Definition resource_manager.h:417
Handle< T > findByName(const std::string &name) const
Find a resource by the name it was added or renamed under, in O(1).
Definition resource_manager.h:341
void forEachOfType(Fn &&fn) const
Visit every live resource of type T; a linear scan for tooling, not hot paths.
Definition resource_manager.h:372
uint64_t revisionOf() const
revision() narrowed to T: moved by every commit, swap, replacement and removal of one of its assets.
Definition resource_manager.h:441
void remove(const HandleType &handle)
Remove a resource: its name mapping, storage and handle slot.
Definition resource_manager.h:160
void commit(const HandleType &handle)
Bump the asset's version, which GLView::sync keys its GPU re-upload on.
Definition resource_manager.h:321
auto addPrivate(ResourceType &&resource, std::string name)
add() under name, setting Resource::isHidden: kept from the user and scene saves.
Definition resource_manager.h:143
auto add(ResourceType &&resource)
Put resource in the graph under its name, stamping its identity.
Definition resource_manager.h:72
uint64_t revision() const
Moved by every commit, swap, replacement and removal of an asset, and every swap of the graph.
Definition resource_manager.h:428
Base class for every asset type, carrying the identity the ResourceManager indexes by.
Definition resource.h:17
Lightweight slot allocator that issues generation-safe handles.
Definition slot_allocator.h:18
StorageIndex handleAt(uint32_t index) const
Rebuild the handle naming a sparse slot, generation included.
Definition slot_allocator.h:93
bool has(StorageIndex id) const
Test whether a handle is still valid.
Definition slot_allocator.h:78
Base & ensure(Make &&make)
The slot for T, created by make the first time it is asked for.
Definition type_registry.h:43
An authored reference to an asset, held as the name it is filed under.
Definition asset_ref.h:23
std::string name
Asset name; empty for none.
Definition asset_ref.h:26
A TrueType font baked to a signed-distance-field atlas.
Definition font_asset.h:48
Opaque, type-safe handle for resources, distinguished by ResourceType.
Definition resource_handle.h:16
Opaque handle pairing a sparse-array index with a generation counter.
Definition types.h:14
uint32_t index
Sparse slot index; 0 is null.
Definition types.h:15