1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| typedef std::pair<long, long> MemoryKey;
// ID, Offset
template<class S>
class MemoryRessource
{
public:
MemoryRessource() {}
MemoryRessource(const std::vector<char>& bytes) :
m_buffer()
{
if(!m_buffer.loadFromMemory(&bytes[0], bytes.size()))
{
std::cout << "Failed to load from memory ! " << std::endl;
throw false;
}
else
{
std::cout << "loadFromMemory: OK. @ address: " << &m_buffer << std::endl;
}
}
~MemoryRessource()
{
std::cout << "Destroying !"<<std::endl;
}
inline S& get() {
std::cout << "Get texture (width=" << m_buffer.getSize().x << "; height=" << m_buffer.getSize().y << ")" << std::endl;
return m_buffer;
}
private:
S m_buffer;
};
class Memory
{
public:
Memory() :
m_nodes(),
m_loaded_gfx(),
m_mtx_loader(PTHREAD_MUTEX_INITIALIZER),
m_percent(0)
{}
~Memory()
{
std::cout << "Call ~Memory() " << std::endl;
}
void loadPackage(const std::string& pack)
{
Reader* own_reader = new Reader();
Node* child = own_reader->Read(pack);
m_nodes.insert(std::make_pair(Filesystem::extractFilename(pack),
std::make_pair(own_reader, child)));
}
void loadGraphic(const long id)
{
try
{
Node& node(m_nodes[m_graphicPackage].second->find(id));
MemoryRessource<sf::Texture>* res = new MemoryRessource<sf::Texture>(node.get(m_nodes[m_graphicPackage].first->stream()));
m_loaded_gfx.insert(std::make_pair(MemoryKey(node.getId(), node.getOffset()), res));
}
catch(bool)
{
throw false;
}
}
Node& operator[] (const std::string& key) { return *(m_nodes[key].second); }
inline sf::Texture& getTexture(const MemoryKey& key) { return m_loaded_gfx[key]->get(); }
inline sf::Texture& getTexture(const long key)
{
for(auto& res : m_loaded_gfx)
{
if(res.first.first == key)
{
return res.second->get();
}
}
/// In case we didn't found id... !
throw false;
}
inline bool isLoaded(const MemoryKey& key) { return m_loaded_gfx.find(key) != m_loaded_gfx.end(); }
inline pthread_mutex_t* getMutex() { return &m_mtx_loader; }
inline long& getPercent() { return m_percent; }
private:
std::map<std::string, std::pair<Reader*, Node*>> m_nodes;
std::map<MemoryKey, MemoryRessource<sf::Texture>*> m_loaded_gfx;
pthread_mutex_t m_mtx_loader;
long m_percent;
const std::string m_graphicPackage = "Graphics";
}; |
Partager