Replaced all std::cout with kDebug.
[tagua/yd.git] / src / loader / context.h
blob9aec748e8730a9b48cbbb2664625d923308ba7ad
1 /*
2 Copyright (c) 2006-2008 Paolo Capriotti <p.capriotti@gmail.com>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9 */
11 #ifndef LOADER__CONTEXT_H
12 #define LOADER__CONTEXT_H
14 #include <map>
15 #include <set>
16 #include <boost/any.hpp>
17 #include <QString>
19 namespace Loader {
21 /**
22 * @class Context <loader/context.h>
23 * @brief A resource loading context
25 * This class offers a set of references in a global cache, to access
26 * a global cache remembering which elements of the cache are being used.
29 class Context {
31 public:
32 class Key {
33 public:
34 QString m_name;
35 const char *m_type;
37 Key(const QString& name, const char *type)
38 : m_name(name)
39 , m_type(type) {
42 bool operator<(const Key& ref) const {
43 return (m_name < ref.m_name) ||
44 ((m_name == ref.m_name) && (strcmp(m_type, ref.m_type) < 0));
48 class Resource {
49 public:
50 int m_ref_count;
51 boost::any m_data;
53 Resource()
54 : m_ref_count(1) {}
56 template<typename T>
57 Resource(const T& data)
58 : m_ref_count(1)
59 , m_data(data) {
63 typedef std::map<Key, Resource> Cache;
64 typedef std::set<Key> KeySet;
66 static Cache s_cache;
67 KeySet m_references;
69 public:
70 /** Destructor (flushes the context) */
71 ~Context();
73 /** Flushes all the references in this context. */
74 void flush();
76 /**
77 * Gets a resource by name.
78 * @param name The resource name
79 * @return The resource pointer, or null if not found.
81 template<typename T>
82 T* get(const QString& name) {
83 Key key(name, typeid(T).name());
84 Cache::iterator it = s_cache.find(key);
86 if(it == s_cache.end())
87 return NULL;
88 if(!m_references.count(key)) {
89 it->second.m_ref_count++;
90 m_references.insert(key);
92 return boost::any_cast<T>(&it->second.m_data);
95 /**
96 * Puts a new resource in the global cache, and makes it
97 * referenced by this context.
98 * @param name The resource name
100 template<typename T>
101 void put(const QString& name, const T& data) {
102 Key key(name, typeid(T).name());
103 Q_ASSERT(!s_cache.count(key));
104 Q_ASSERT(!m_references.count(key));
106 s_cache[key] = Resource(data);
107 m_references.insert(key);
111 } //end namespace Loader
113 #endif //LOADER__CONTEXT_H