summaryrefslogtreecommitdiff
path: root/src/resourceManager.h
blob: b69ce1ece67bc76ccad4b8d9c5c74357418452db (plain)
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
#ifndef RESOURCE_MANAGER_H
#define RESOURCE_MANAGER_H

#include <map>
#include <string>
#include <memory>
#include <stdexcept>
#include <cassert>


// TODO: I don't like the `load` function here as it forces the `Resource` to
// have a loadFromFile function that they may not have (see TextureFont) or
// they may need to call with several arguments (see SFML shaders). I think
// it's better to load them by hand and capture them in the unique pointer
// inside.
// Maybe make a `manage` function that gets a pointer and captures.

template <typename Resource, typename Identifier>
class ResourceManager{
    private:
        std::map<Identifier,std::unique_ptr<Resource>> resourceMap;
    public:
        void load(Identifier id, const std::string &path);
        void manage(Identifier id, Resource *resource);
        Resource& get(Identifier id);
        const Resource& get(Identifier id) const;
};

template <typename Resource, typename Identifier>
void
ResourceManager<Resource, Identifier>::load(Identifier id,
        const std::string& path){
    auto resource = std::make_unique<Resource>();
    if( !resource->loadFromFile(path) ){
        throw("ResoureManager::load - Failed to load filename: " + path);
    }
    auto inserted = resourceMap.insert(
            std::make_pair(id, std::move(resource))
    );
    assert(inserted.second);
}

template <typename Resource, typename Identifier>
void
ResourceManager<Resource, Identifier>::manage(Identifier id,
        Resource *resource){
    std::unique_ptr<Resource> resource_ptr (resource);
    auto inserted = resourceMap.insert(
            std::make_pair(id, std::move(resource_ptr))
    );
    assert(inserted.second);
}

template <typename Resource, typename Identifier>
Resource&
ResourceManager<Resource, Identifier>::get(Identifier id)
{
    auto found = resourceMap.find(id);
    assert(found != resourceMap.end());

    return *found->second;
}

template <typename Resource, typename Identifier>
const Resource&
ResourceManager<Resource, Identifier>::get(Identifier id) const
{
    auto found = resourceMap.find(id);
    assert(found != resourceMap.end());

    return *found->second;
}

#endif // RESOURCE_MANAGER_H