TSR_ECS/src/tsr/assets.hpp
2023-12-08 18:28:01 +01:00

50 lines
1.3 KiB
C++

#pragma once
#include <string>
#include <map>
#include <memory>
#include <stdexcept>
#include "tsr.hpp"
namespace TSR {
template <class T>
using AssetPtr = std::shared_ptr<T>;
class Asset {
public:
virtual ~Asset() {}
};
class AssetMap {
static std::map<std::string, std::weak_ptr<Asset>> s_assets;
public:
//AssetMap(Game& game_ref) : m_game_ref(game_ref) {}
template <class T>
static AssetPtr<T> Get(const std::string& name) {
try {
AssetPtr<Asset> asset_ptr;
auto asset_it = s_assets.find(name);
if (asset_it == s_assets.end() || asset_it->second.expired()) {
asset_ptr = AssetPtr<Asset>(new T(name)); //std::make_shared<T>(m_fs_ref, name);
s_assets[name] = asset_ptr;
}
else {
asset_ptr = asset_it->second.lock();
}
auto t_ptr = std::dynamic_pointer_cast<T>(asset_ptr);
if (!t_ptr) Throw("(AM) Asset type mismatch");
return t_ptr;
}
catch (std::exception ex) {
Throw(std::string("(AM) Error loading \"") + name + std::string("\":\n") + std::string(ex.what()));
}
}
};
}