Changeset 9869 in orxonox.OLD for trunk/src/lib/util
- Timestamp:
- Oct 3, 2006, 12:19:30 AM (18 years ago)
- Location:
- trunk/src/lib/util
- Files:
-
- 7 deleted
- 29 edited
- 18 copied
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/lib/util/Makefile.am
r9406 r9869 2 2 include $(MAINSRCDIR)/defs/include_paths.am 3 3 4 noinst_LIBRARIES = libORXlibutil.a 4 noinst_LIBRARIES = \ 5 libORXlibutil.a \ 6 libORXexecutor.a 7 8 libORXexecutor_a_SOURCES = \ 9 executor/executor_substring.cc 5 10 6 11 libORXlibutil_a_SOURCES = \ … … 9 14 helper_functions.cc \ 10 15 multi_type.cc \ 11 executor/executor.cc \ 12 executor/executor_functional.cc \ 13 executor/executor_lua.cc \ 16 debug_buffer.cc \ 14 17 \ 15 18 loading/resource_manager.cc \ … … 18 21 loading/load_param.cc \ 19 22 loading/load_param_description.cc \ 23 loading/load_param_class_description.cc \ 20 24 loading/factory.cc \ 21 loading/ dynamic_loader.cc \25 loading/fast_factory.cc \ 22 26 \ 23 27 filesys/file.cc \ … … 25 29 filesys/net_link.cc \ 26 30 \ 27 preferences.cc \28 31 threading.cc \ 29 32 timer.cc 33 34 # loading/dynamic_loader.cc 30 35 31 36 … … 35 40 color.h \ 36 41 helper_functions.h \ 42 debug.h \ 43 debug_buffer.h \ 44 \ 45 \ 37 46 executor/executor.h \ 38 executor/executor_functional.h \39 47 executor/executor_xml.h \ 40 executor/executor_lua.h \ 48 executor/executor_substring.h \ 49 executor/executor_generic.h \ 50 executor/executor_member.h \ 51 executor/executor_const_member.h \ 52 executor/executor_static.h \ 53 \ 41 54 executor/functor_list.h \ 55 executor/functor_generic.h \ 56 executor/functor_member.h \ 57 executor/functor_const_member.h \ 58 executor/functor_static.h \ 59 \ 42 60 \ 43 61 filesys/file.h \ … … 45 63 filesys/net_link.h \ 46 64 \ 47 preferences.h \48 65 threading.h \ 49 66 timer.h \ … … 53 70 loading/game_loader.h \ 54 71 loading/load_param.h \ 72 loading/load_param_xml.h \ 55 73 loading/load_param_description.h \ 74 loading/load_param_class_description.h \ 56 75 loading/factory.h \ 76 loading/fast_factory.h \ 57 77 loading/dynamic_loader.h \ 58 78 \ -
trunk/src/lib/util/color.cc
r8986 r9869 30 30 //! Black Color 31 31 const Color Color::black(0,0,0,1); 32 //! Orx Color 33 const Color Color::orx(.2, .5, .7, .8); //!< TODO Define the ORX-color :) 34 35 32 33 /** 34 * @brief slerps the Color in the HSV color space into the direction of c 35 * @param c the Color to slerp to 36 * @param v the Value to slerp 0 means stay at *this, 1 means at c. 37 */ 36 38 void Color::slerpHSV(const Color& c, float v) 37 39 { … … 52 54 } 53 55 56 /** 57 * @brief simple slerp wrapper. 58 * @param from from this color 59 * @param to to this one 60 * @param v how much 61 * @see void Color::slerpHSV(const Color& c, float v) 62 */ 54 63 Color Color::slerpHSVColor(const Color& from, const Color& to, float v) 55 64 { … … 59 68 } 60 69 61 70 /** 71 * @brief nice and simple debug output for the colors (colorless :) ) 72 */ 62 73 void Color::debug() const 63 74 { … … 214 225 215 226 216 // Needed by rgb2hsv() 227 /** 228 * @returns the maximum of r g and a. 229 * @param r Red. 230 * @param g Green 231 * @param b Blue 232 */ 217 233 float Color::maxrgb(float r, float g, float b) 218 234 { … … 227 243 } 228 244 229 230 // Needed by rgb2hsv() 245 /** 246 * @returns the minimum of r g and a. 247 * @param r Red. 248 * @param g Green 249 * @param b Blue 250 */ 231 251 float Color::minrgb(float r,float g,float b) 232 252 { -
trunk/src/lib/util/color.h
r9656 r9869 14 14 #include "vector.h" 15 15 16 //! a very abstract Class that helps transforming Colors into different Systems 16 //! A Class that handles Colors. 17 /** 18 * A Color is a collection of 4 values: 19 * <ul> 20 * <li>Red</li> 21 * <li>Green</li> 22 * <li>Blue</li> 23 * <li>Alpha</li> 24 * </ul> 25 * With these four values any color of the entire spectrum can be defined. 26 * 27 * By default a Color lies between 0 and 1 for each component. 28 * for example [1,0,0,.5] means red and half visible. 29 */ 17 30 class Color 18 31 { 19 32 public: 33 /** @param r red, @param g green @param b blue @param a alpha @brief constructs a Color. */ 20 34 Color(float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 1.0f) { _rgba[0] = r; _rgba[1] = g; _rgba[2] = b; _rgba[3] = a; }; 35 /** @param c Color @brief copy constructor */ 21 36 Color(const Color& c) { _rgba[0] = c.r(); _rgba[1] = c.g(); _rgba[2] = c.b(); _rgba[3] = c.a(); } 22 37 38 /** @param c the Color to set to this color @returns the copied color */ 23 39 inline const Color& operator=(const Color& c) { _rgba[0] = c.r(); _rgba[1] = c.g(); _rgba[2] = c.b(); _rgba[3] = c.a(); return *this; }; 40 /** @param c the color to compare @returns true on match. @brief compares two colors */ 24 41 inline bool operator==(const Color& c) const { return (r() == c.r() && g() == c.g() && b() == c.b() && a() == c.a()); }; 25 42 43 /** @returns the i'th Value of the Color @param i part of the color 0:r, 1:g, 2:b, 3:a */ 26 44 inline float& operator[](unsigned int i) { return _rgba[i]; } 45 /** @returns a Constant Value of the color. @param i part of the color 0:r, 1:g, 2:b, 3:a */ 27 46 inline const float& operator[](unsigned int i) const { return _rgba[i]; } 28 47 48 /** @returns the red part. */ 29 49 inline float r() const { return _rgba[0]; } 50 /** @returns the reference to the red part */ 30 51 inline float& r() { return _rgba[0]; } 52 /** @returns the green part. */ 31 53 inline float g() const { return _rgba[1]; } 54 /** @returns the reference to the green part */ 32 55 inline float& g() { return _rgba[1]; } 56 /** @returns the blue part */ 33 57 inline float b() const { return _rgba[2]; } 58 /** @returns the reference to the blue part */ 34 59 inline float& b() { return _rgba[2]; } 60 /** @returns the alpha part */ 35 61 inline float a() const { return _rgba[3]; } 62 /** @returns the reference to the alpha part */ 36 63 inline float& a() { return _rgba[3]; } 37 64 38 65 39 40 66 /** @param r red, @param g green @param b blue @param a alpha @brief sets the color. */ 41 67 void setColor(float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 1.0f) { _rgba[0] = r; _rgba[1] = g; _rgba[2] = b; _rgba[3] = a; }; 68 /** @param c the color to set. @brief sets the color. */ 42 69 void setColor(const Color& c) { r() = c.r(); g()= c.g(); b() = c.b(); a() = c.a(); }; 43 70 71 /** @returns the distance to the color @param c the color to calculate the distance to. */ 44 72 inline float dist(const Color& c) const { return (sqrt((r()-c.r())*(r()-c.r()) + (g()-c.g())*(g()-c.g()) + (b()-c.b())*(b()-c.b()) + (a()-c.a())*(a()-c.a()))); } 45 73 /// Maths 74 /** @param c the color to add to this one @returns the two added colors */ 46 75 inline const Color& operator+=(const Color& c) { r()+=c.r(); g()+=c.g(); b()+=c.b(); a()+=c.a(); return *this; }; 76 /** @returns the result of the added colors @param c the color to add */ 47 77 inline Color operator+(const Color& c) const { return Color(r()+c.r(), g()+c.g(), b()+c.b(), a()+c.a()); }; 78 /** @param c the color to substract to this one @returns the two substracted colors */ 48 79 inline const Color& operator-=(const Color& c) { r()-=c.r(); g()-=c.g(); b()-=c.b(); a()-=c.a(); return *this; }; 80 /** @returns the result of the substracted colors @param c the color to substract */ 49 81 inline Color operator-(const Color& c) const { return Color(r()-c.r(), g()-c.g(), b()-c.b(), a()-c.a()); }; 82 /** @param v the multiplier @returns the Color multiplied by v */ 50 83 inline const Color& operator*=(float v) { r()*=v, g()*=v, b()*=v, a()*=v; return *this; }; 84 /** @param v the multiplier @returns a multiplied color */ 51 85 inline Color operator*(float v) const { return Color(r()*v, g()*v, b()*v, a()*v); }; 52 86 87 /** @param c the color to slerp to @param v how much to slerp [0:1] @brief moves the color into the direction of another color */ 53 88 void slerp(const Color& c, float v) { *this += (c - *this) * v; }; 54 89 void slerpHSV(const Color& c, float v); 55 56 90 static Color slerpHSVColor(const Color& from, const Color& to, float v); 57 91 … … 75 109 static const Color white; 76 110 static const Color black; 77 static const Color orx;78 111 79 112 private: 80 float _rgba[4]; //!< Color Values 81 82 /* float _r; //!< Red Value. 83 float _g; //!< Green Value. 84 float _b; //!< Blue Value. 85 float _a; //!< Alpha Value.*/ 113 float _rgba[4]; //!< Color Values [r,g,b,a] (red green blue alpha) 86 114 }; 87 115 -
trunk/src/lib/util/count_pointer.h
r8761 r9869 9 9 { 10 10 public: 11 explicit CountPointer(X* p = 0) // allocate a new counter 12 : itsCounter(0) { if (p) itsCounter = new counter(p); } 13 virtual ~CountPointer() { release(); } 14 CountPointer(const CountPointer& r) { acquire(r.itsCounter); } 15 CountPointer& operator=(const CountPointer& r) 11 explicit CountPointer(X* p = NULL) // allocate a new counter 12 : itsCounter(NULL) { if (p) itsCounter = new counter(p); } 13 ~CountPointer() { release(); } 14 CountPointer(const CountPointer& r) { acquire(r.itsCounter); } 15 CountPointer& operator=(const CountPointer& r) 16 { 17 if (this != &r) 16 18 { 17 if (this != &r) { 18 release(); 19 acquire(r.itsCounter); 20 } 21 return *this; 19 release(); 20 acquire(r.itsCounter); 22 21 } 23 bool operator==(const CountPointer& r) const { return this->itsCounter->ptr == r.itsCounter->ptr; }; 24 X& operator*() const { return *itsCounter->ptr; } 25 X* operator->() const { return itsCounter->ptr; } 26 X* get() const { return itsCounter ? itsCounter->ptr : 0; } 27 bool unique() const { return (itsCounter ? itsCounter->count == 1 : true); } 28 virtual unsigned int count() const { return (this->itsCounter ? itsCounter->count : 0); } 22 return *this; 23 } 24 bool operator==(const CountPointer& r) const { return this->itsCounter->ptr == r.itsCounter->ptr; }; 25 inline X& operator*() const { return *itsCounter->ptr; } 26 inline X* operator->() const { return itsCounter->ptr; } 27 inline bool unique() const { return (itsCounter ? itsCounter->count == 1 : true); } 28 inline bool isNull() const { return (!itsCounter); } 29 30 unsigned int count() const { return (this->itsCounter ? itsCounter->count : 0); } 29 31 private: 30 32 31 struct counter { 32 counter(X* p = 0, unsigned c = 1) : ptr(p), count(c) {} 33 X* ptr; 34 unsigned count; 35 }* itsCounter; 33 struct counter 34 { 35 counter(X* p = NULL, unsigned c = 1) : ptr(p), count(c) {} 36 X* ptr; 37 unsigned count; 38 } 39 * itsCounter; 36 40 37 void acquire(counter* c) 41 void acquire(counter* c) 42 { 43 // increment the count 44 itsCounter = c; 45 if (c) ++c->count; 46 } 47 48 void release() 49 { 50 // decrement the count, delete if it is 0 51 if (itsCounter) 38 52 { 39 // increment the count 40 itsCounter = c; 41 if (c) ++c->count; 53 if (--itsCounter->count == 0) 54 { 55 delete itsCounter->ptr; 56 delete itsCounter; 57 } 58 itsCounter = NULL; 42 59 } 43 44 void release() 45 { 46 // decrement the count, delete if it is 0 47 if (itsCounter) { 48 if (--itsCounter->count == 0) { 49 delete itsCounter->ptr; 50 delete itsCounter; 51 } 52 itsCounter = 0; 53 } 54 } 60 } 55 61 }; 56 62 -
trunk/src/lib/util/executor/executor.h
r8894 r9869 9 9 #include "base_object.h" 10 10 11 #include "helper_functions.h"12 11 #include "multi_type.h" 13 #include "substring.h" 14 #include "functor_list.h" //< MUST BE INCLUDED HERE AT LEAST ONCE. 15 16 //! an enumerator for the definition of the Type. 17 typedef enum { 18 Executor_Objective = 1, 19 Executor_Static = 2, 20 21 Executor_NoLoadString = 8, 22 } Executor_Type; 12 13 //! The maximum Count of Arguments of the Executor 14 /** This is Hardcoded, for each Executor. */ 15 #define EXECUTOR_MAX_ARGUMENTS 7 16 17 18 /** @returns the Type of an Argument taken by the Executor */ 19 template<typename type> inline MT_Type ExecutorParamType() { return MT_EXT1; }; 20 /** @returns the Type of an Argument taken by the Executor in this case MT_BOOL */ 21 template<> inline MT_Type ExecutorParamType<bool>() { return MT_BOOL; }; 22 /** @returns the Type of an Argument taken by the Executor in this case MT_INT*/ 23 template<> inline MT_Type ExecutorParamType<int>() { return MT_INT; }; 24 /** @returns the Type of an Argument taken by the Executor in this case MT_UINT*/ 25 template<> inline MT_Type ExecutorParamType<unsigned int>() { return MT_UINT; }; 26 /** @returns the Type of an Argument taken by the Executor in this case MT_FLOAT*/ 27 template<> inline MT_Type ExecutorParamType<float>() { return MT_FLOAT; }; 28 /** @returns the Type of an Argument taken by the Executor in this case MT_CHAR*/ 29 template<> inline MT_Type ExecutorParamType<char>() { return MT_CHAR; }; 30 /** @returns the Type of an Argument taken by the Executor in this case MT_STRING*/ 31 template<> inline MT_Type ExecutorParamType<const std::string&>() { return MT_STRING; }; 23 32 24 33 //////////////// … … 36 45 * Functions with many types (@see functor_list.h) 37 46 */ 38 class Executor : public BaseObject 47 template <typename CallType, class BaseClass = BaseObject> class Executor 39 48 { 40 public: 41 virtual ~Executor(); 42 43 virtual Executor* clone () const = 0; 44 // virtual bool operator==(const Executor* executor) const = 0; 45 46 // SETTING up the EXECUTOR 47 Executor* defaultValues(const MultiType& value0 = MT_NULL, const MultiType& value1 = MT_NULL, 48 const MultiType& value2 = MT_NULL, const MultiType& value3 = MT_NULL, 49 const MultiType& value4 = MT_NULL, const MultiType& param5 = MT_NULL, 50 const MultiType& param6 = MT_NULL); 51 /** @param i the i'th defaultValue, @returns reference to the MultiType */ 52 inline MultiType& getDefaultValue(unsigned int i) { return defaultValue[i]; }; 53 54 // EXECUTE 55 /** executes a Command. @param objec the Object, @param count how many values, @param values the Values */ 56 virtual void operator()(BaseObject* object, int& count, void* values) const = 0; 57 /** executes a Command @param object the object to apply this to @param parameters the parameters the command takes */ 58 virtual void operator()(BaseObject* object, const SubString& sub = SubString()) const = 0; 59 60 // RETRIEVE INFORMATION 61 /** @returns the Type of this Function (either static or objective) */ 62 inline long getType() const { return this->functorType; }; 63 /** @returns the Count of Parameters this Executor takes */ 64 inline unsigned int getParamCount() const { return this->paramCount; }; 65 66 static void debug(); 67 68 protected: 69 Executor(const MultiType& param0 = MT_NULL, const MultiType& param1 = MT_NULL, 70 const MultiType& param2 = MT_NULL, const MultiType& param3 = MT_NULL, 71 const MultiType& param4 = MT_NULL, const MultiType& param5 = MT_NULL, 72 const MultiType& param6 = MT_NULL); 73 74 void cloning(Executor* executor) const; 75 76 protected: 77 short functorType; //!< The type of Function we've got (either static or objective). 78 unsigned int paramCount; //!< the count of parameters. 79 MultiType defaultValue[7]; //!< Default Values. 49 public: 50 //! an enumerator for the definition of the Type. 51 typedef enum { 52 FunctionMember, //!< The function is neither Static nor Constant 53 FunctionStatic, //!< The Function is Static and pointing to either a Static Member or a C-style function. 54 FunctionConstMember, //!< The Function is Constant and pointing to a Member that does not change the Object. 55 } FunctionType; 56 57 public: 58 virtual ~Executor() {}; 59 60 // RETRIEVE INFORMATION 61 /** @param i the i'th defaultValue, @returns reference to the MultiType */ 62 inline MultiType& getDefaultValue(unsigned int i) { return defaultValue[i]; }; 63 /** @returns the default Values as a List */ 64 inline const MultiType* const getDefaultValues() { return defaultValue; }; 65 66 /** @returns the Type of this Function (either static or objective) */ 67 inline FunctionType getType() const { return this->functionType; }; 68 69 /** @returns the Count of Parameters this Executor takes */ 70 inline unsigned int getParamCount() const { return this->paramCount; }; 71 /** @returns true if the Executor has a return Value. */ 72 inline bool hasRetVal() const { return bRetVal; }; 73 74 /** executes a Command. @param object the Object, @param values The Value of type CallType to pass to the Executor. */ 75 virtual void operator()(BaseClass* object, CallType& values) const = 0; 76 77 /** 78 * @brief set the default values of the executor 79 * @param value0 the first default value 80 * @param value1 the second default value 81 * @param value2 the third default value 82 * @param value3 the fourth default value 83 * @param value4 the fifth default value 84 * @param value5 the sixth default value 85 * @param value6 the seventh default value 86 * @returns itself 87 * @note: THIS FUNCTION WILL BE REPLACED BY A CONFIGURATOR (most probably). 88 */ 89 Executor* defaultValues(const MultiType& value0 = MT_NULL, const MultiType& value1 = MT_NULL, 90 const MultiType& value2 = MT_NULL, const MultiType& value3 = MT_NULL, 91 const MultiType& value4 = MT_NULL, const MultiType& value5 = MT_NULL, 92 const MultiType& value6 = MT_NULL) 93 { 94 const MultiType* value[5]; 95 value[0] = &value0; 96 value[1] = &value1; 97 value[2] = &value2; 98 value[3] = &value3; 99 value[4] = &value4; 100 value[5] = &value5; 101 value[6] = &value6; 102 for (unsigned int i = 0; i < this->paramCount; i++) 103 { 104 if (*value[i] != MT_NULL) 105 { 106 this->defaultValue[i].setValueOf(*value[i]); 107 this->defaultValue[i].storeString(); 108 } 109 } 110 return this; 111 } 112 113 /** @returns the Clone as a new Copy of the Executor. */ 114 virtual Executor<CallType, BaseClass>* clone () const = 0; 115 116 117 protected: 118 //! Now follows a List of Executor Constructors, to be fast in creating. 119 //! Creates an Executor with no Argument. 120 Executor(bool hasRetVal, FunctionType functionType = FunctionMember) 121 : bRetVal(hasRetVal), paramCount(0), functionType(functionType) 122 { }; 123 124 //! Creates an Executor with 1 Argument. 125 Executor(bool hasRetVal, const MultiType& param0, 126 FunctionType functionType = FunctionMember) 127 : bRetVal(hasRetVal), paramCount(1), functionType(functionType) 128 { 129 this->defaultValue[0] = param0; 130 }; 131 132 //! Creates an Executor with 2 Arguments. 133 Executor(bool hasRetVal, const MultiType& param0, const MultiType& param1, 134 FunctionType functionType = FunctionMember) 135 : bRetVal(hasRetVal), paramCount(2), functionType(functionType) 136 { 137 this->defaultValue[0] = param0; 138 this->defaultValue[1] = param1; 139 }; 140 141 //! Creates an Executor with 3 Arguments. 142 Executor(bool hasRetVal, const MultiType& param0, const MultiType& param1, 143 const MultiType& param2, 144 FunctionType functionType = FunctionMember) 145 : bRetVal(hasRetVal), paramCount(3), functionType(functionType) 146 { 147 this->defaultValue[0] = param0; 148 this->defaultValue[1] = param1; 149 this->defaultValue[2] = param2; 150 }; 151 152 //! Creates an Executor with 4 Arguments. 153 Executor(bool hasRetVal, const MultiType& param0, const MultiType& param1, 154 const MultiType& param2, const MultiType& param3, 155 FunctionType functionType = FunctionMember) 156 : bRetVal(hasRetVal), paramCount(4), functionType(functionType) 157 { 158 this->defaultValue[0] = param0; 159 this->defaultValue[1] = param1; 160 this->defaultValue[2] = param2; 161 this->defaultValue[3] = param3; 162 }; 163 164 //! Creates an Executor with 5 Arguments. 165 Executor(bool hasRetVal, const MultiType& param0, const MultiType& param1, 166 const MultiType& param2, const MultiType& param3, 167 const MultiType& param4, 168 FunctionType functionType = FunctionMember) 169 : bRetVal(hasRetVal), paramCount(5), functionType(functionType) 170 { 171 this->defaultValue[0] = param0; 172 this->defaultValue[1] = param1; 173 this->defaultValue[2] = param2; 174 this->defaultValue[3] = param3; 175 this->defaultValue[4] = param4; 176 }; 177 178 //! Creates an Executor with 6 Arguments. 179 Executor(bool hasRetVal, const MultiType& param0, const MultiType& param1, 180 const MultiType& param2, const MultiType& param3, 181 const MultiType& param4, const MultiType& param5, 182 FunctionType functionType = FunctionMember) 183 : bRetVal(hasRetVal), paramCount(6), functionType(functionType) 184 { 185 this->defaultValue[0] = param0; 186 this->defaultValue[1] = param1; 187 this->defaultValue[2] = param2; 188 this->defaultValue[3] = param3; 189 this->defaultValue[4] = param4; 190 this->defaultValue[5] = param5; 191 }; 192 193 //! Creates an Executor with 7 Arguments. 194 Executor(bool hasRetVal, const MultiType& param0, const MultiType& param1, 195 const MultiType& param2, const MultiType& param3, 196 const MultiType& param4, const MultiType& param5, 197 const MultiType& param6, 198 FunctionType functionType = FunctionMember) 199 : bRetVal(hasRetVal), paramCount(7), functionType(functionType) 200 { 201 this->defaultValue[0] = param0; 202 this->defaultValue[1] = param1; 203 this->defaultValue[2] = param2; 204 this->defaultValue[3] = param3; 205 this->defaultValue[4] = param4; 206 this->defaultValue[5] = param5; 207 this->defaultValue[6] = param6; 208 }; 209 210 protected: 211 const bool bRetVal; //!< True if the Executor has a return Value. 212 const unsigned int paramCount; //!< the count of parameters. 213 MultiType defaultValue[7]; //!< Default Values. 214 215 const FunctionType functionType; //!< What Type of Function it is. 80 216 }; 81 217 82 #include "executor/executor_functional.h"83 #define EXECUTOR_FUNCTIONAL_USE_CONST84 #include "executor/executor_functional.h"85 #define EXECUTOR_FUNCTIONAL_USE_STATIC86 #include "executor/executor_functional.h"87 88 218 #endif /* _EXECUTOR_H */ -
trunk/src/lib/util/executor/executor_xml.h
r8362 r9869 19 19 * What must be defined is a XML-root to search the ParameterName under an a Function to call. 20 20 */ 21 template<class T > class ExecutorXML : public Executor21 template<class T, class BaseClass = BaseObject> class ExecutorXML : public Executor<const TiXmlElement*> 22 22 { 23 24 23 public: 24 /** 25 25 * @brief Constructor of a ExecutorXML 26 27 28 29 30 ExecutorXML(void(T::*function)(const TiXmlElement*), const TiXmlElement* root, const char*paramName)31 : Executor (MT_EXT1)32 33 PRINTF(4)("Loading %s from XML-element %p\n", paramName, root);26 * @param function a Function to call 27 * @param root The XML root to search paramName under 28 * @param paramName the ParameterName the search in root, and lookup the TiXmlElement from 29 */ 30 ExecutorXML(void(T::*function)(const TiXmlElement*), const TiXmlElement* root, const std::string& paramName) 31 : Executor<const TiXmlElement*>(false, MT_EXT1) 32 { 33 PRINTF(4)("Loading %s from XML-element %p\n", paramName.c_str(), root); 34 34 35 if (likely(root != NULL && paramName!= NULL))36 37 38 35 if (likely(root != NULL)) 36 this->element = root->FirstChildElement(paramName); 37 else 38 this->element = NULL; 39 39 40 this->functionPointer = function;41 this->functorType = Executor_Objective | Executor_NoLoadString;42 40 this->paramName = paramName; 41 this->functionPointer = function; 42 } 43 43 44 /** 45 * @brief clones an ExecutorXML, used to copy this Element. 46 * @returns a _new_ Copy of this Executor 47 */ 48 virtual Executor* clone () const 49 { 50 ExecutorXML<T>* executor = new ExecutorXML<T>(); 51 this->cloning(executor); 52 executor->functionPointer = this->functionPointer; 53 executor->element = this->element; 54 return executor; 55 } 44 /** 45 * @brief clones an ExecutorXML, used to copy this Element. 46 * @returns a _new_ Copy of this Executor 47 */ 48 virtual Executor<const TiXmlElement*>* clone () const 49 { 50 return new ExecutorXML<T>(functionPointer, element, paramName); 51 } 56 52 57 /** 58 * @brief executes the Command on BaseObject 59 * @param object the BaseObject to execute this Executor on 60 * @param loadString ignored in this case 61 */ 62 virtual void operator()(BaseObject* object, const SubString& = SubString()) const 63 { 64 if (object != NULL && this->element != NULL) 65 (dynamic_cast<T*>(object)->*(functionPointer))(this->element); 66 } 53 /** 54 * @brief executes the Command on BaseObject 55 * @param object the BaseObject to execute this Executor on 56 * @param element ignored in this case 57 */ 58 virtual void operator()(BaseObject* object, const TiXmlElement*& element) const 59 { 60 assert (object != NULL); 61 if (this->element != NULL) 62 (dynamic_cast<T*>(object)->*(functionPointer))(this->element); 63 } 67 64 68 virtual void operator()(BaseObject* object, int& count, void* values) const 69 { 70 PRINTF(1)("missuse of XML-operator, OR IMPLEMENT.\n"); 71 } 72 73 private: 74 /** 75 * @brief used for the copy-(Clone)-constructor 76 */ 77 ExecutorXML() : Executor() { }; 78 79 80 private: 81 void (T::*functionPointer)(const TiXmlElement*); //!< The functionPointer to the function to be called 82 const TiXmlElement* element; //!< The XML-element to call. 65 private: 66 void (T::*functionPointer)(const TiXmlElement*); //!< The functionPointer to the function to be called. 67 const TiXmlElement* element; //!< The XML-element to call. 68 std::string paramName; //!< The Name of the Parameter this Executor should call. 83 69 }; 84 70 -
trunk/src/lib/util/executor/functor_list.h
r9406 r9869 1 /*! 2 * @file functor_list.h 3 * all the Different types of Functions one can include by using a simple createExecutor call 4 * with a FunctionPointer as Argument 5 */ 1 6 /* 2 7 orxonox - the future of 3D-vertical-scrollers … … 8 13 the Free Software Foundation; either version 2, or (at your option) 9 14 any later version. 10 */11 12 /*!13 * @file functors_list.h14 * all the Different types of Functions one can include15 15 */ 16 17 /**18 useable FunctionParameters are:19 l_INT: int20 l_LONG: long21 l_SHORT: short22 l_FLOAT: float23 l_STRING: const std::string&24 l_XML_ELEM: TiXmlElement*25 */26 27 #ifndef __FUNCTOR_PARAMETERS__28 #define __FUNCTOR_PARAMETERS__29 30 //! defines the maximum count of arguments function pointers might have31 #define FUNCTOR_MAX_ARGUMENTS 732 #include "multi_type.h"33 34 35 #define l_BOOL_TYPE bool //!< The type of an BOOL36 #define l_BOOL_FUNC isBool //!< The function to call to parse BOOL37 #define l_BOOL_PARAM MT_BOOL //!< the type of the parameter BOOL38 #define l_BOOL_DEFAULT false //!< a default Value for an BOOL39 #define l_BOOL_DEFGRAB(i) this->defaultValue[i].getBool()40 41 #define l_INT_TYPE int //!< The type of an INT42 #define l_INT_FUNC isInt //!< The function to call to parse INT43 #define l_INT_PARAM MT_INT //!< the type of the parameter INT44 #define l_INT_DEFAULT 0 //!< a default Value for an INT45 #define l_INT_DEFGRAB(i) this->defaultValue[i].getInt()46 47 #define l_UINT_TYPE unsigned int //!< The type of an UINT48 #define l_UINT_FUNC isInt //!< The function to call to parse UINT49 #define l_UINT_PARAM MT_INT //!< the type of the parameter UINT50 #define l_UINT_DEFAULT 0 //!< a default Value for an UINT51 #define l_UINT_DEFGRAB(i) (unsigned int)this->defaultValue[i].getInt()52 53 #define l_LONG_TYPE long //!< The type of a LONG54 #define l_LONG_FUNC isInt //!< The function to parse a LONG55 #define l_LONG_PARAM MT_INT //!< the type of the parameter LONG56 #define l_LONG_DEFAULT 0 //!< a default Value for a LONG57 #define l_LONG_DEFGRAB(i) (long)this->defaultValue[i].getInt()58 59 // #define l_SHORT_TYPE short //!< The type of a SHORT60 // #define l_SHORT_FUNC atoi //!< The function to parse a SHORT61 // #define l_SHORT_NAME "short" //!< The name of a SHORT62 // #define l_SHORT_PARAM ParameterShort //!< the type of the parameter SHORT63 // #define l_SHORT_DEFAULT 0 //!< a default Value for a SHORT64 65 #define l_FLOAT_TYPE float //!< The type of a FLOAT66 #define l_FLOAT_FUNC isFloat //!< The function to parse a FLOAT67 #define l_FLOAT_PARAM MT_FLOAT //!< the type of the parameter FLOAT68 #define l_FLOAT_DEFAULT 0.0 //!< a default Value for a FLOAT69 #define l_FLOAT_DEFGRAB(i) this->defaultValue[i].getFloat()70 71 //#define l_VECTOR_TYPE const Vector& //!< The type of a VECTOR72 //#define l_VECTOR_FUNC isVector //!< The function to parse a VECTOR73 //#define l_VECTOR_NAME "Vector[x/y/z]" //!< The name of a VECTOR74 //#define l_VECTOR_DEFAULT Vector(0,0,0) //!< Default value for a VECTOR75 76 #define l_STRING_TYPE const std::string& //!< The type of a STRING77 #define l_STRING_FUNC isString //!< The function to parse a STRING78 #define l_STRING_PARAM MT_STRING //!< the type of the parameter STRING79 #define l_STRING_DEFAULT "" //!< a default Value for an STRING80 #define l_STRING_DEFGRAB(i) this->defaultValue[i].getString()81 82 #define l_XML_ELEM_TYPE const TiXmlElement* //!< The type of an XML_ELEM83 #define l_XML_ELEM_FUNC //!< The function to parse an XML_ELEM84 //#define l_XML_ELEM_PARAM Parameter //!< the type of the parameter XML_ELEM85 #define l_XML_ELEM_DEFAULT NULL //!< The dafault Value for an XML_ELEM86 87 #endif /* __FUNCTOR_PARAMETERS__ */88 16 89 17 90 18 #ifdef FUNCTOR_LIST 91 92 FUNCTOR_LIST(0)(); 19 FUNCTOR_LIST(0)(FUNCTOR_CALL_TYPE); 93 20 //! makes functions with one string 94 FUNCTOR_LIST(1)( l_STRING);21 FUNCTOR_LIST(1)(FUNCTOR_CALL_TYPE, const std::string&); 95 22 //! makes functions with two strings 96 FUNCTOR_LIST(2)( l_STRING, l_STRING);23 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, const std::string&, const std::string&); 97 24 //! makes functions with three strings 98 FUNCTOR_LIST(3)( l_STRING, l_STRING, l_STRING);25 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, const std::string&, const std::string&, const std::string&); 99 26 //! makes functions with four strings 100 FUNCTOR_LIST(4)( l_STRING, l_STRING, l_STRING, l_STRING);27 FUNCTOR_LIST(4)(FUNCTOR_CALL_TYPE, const std::string&, const std::string&, const std::string&, const std::string&); 101 28 102 29 103 30 //! makes functions with one bool 104 FUNCTOR_LIST(1)( l_BOOL);31 FUNCTOR_LIST(1)(FUNCTOR_CALL_TYPE, bool); 105 32 106 33 //! makes functions with one int 107 FUNCTOR_LIST(1)( l_INT);34 FUNCTOR_LIST(1)(FUNCTOR_CALL_TYPE, int); 108 35 //! makes functions with two ints 109 FUNCTOR_LIST(2)( l_INT, l_INT);36 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, int, int); 110 37 //! makes functions with three ints 111 FUNCTOR_LIST(3)( l_INT, l_INT, l_INT);38 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, int, int, int); 112 39 //! makes functions with four ints 113 FUNCTOR_LIST(4)( l_INT, l_INT, l_INT, l_INT);40 FUNCTOR_LIST(4)(FUNCTOR_CALL_TYPE, int, int, int, int); 114 41 115 42 116 43 //! makes functions with one unsigned int 117 FUNCTOR_LIST(1)( l_UINT);44 FUNCTOR_LIST(1)(FUNCTOR_CALL_TYPE, unsigned int); 118 45 //! makes functions with two unsigned ints 119 FUNCTOR_LIST(2)( l_UINT, l_UINT);46 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, unsigned int, unsigned int); 120 47 //! makes functions with three unsigned ints 121 FUNCTOR_LIST(3)( l_UINT, l_UINT, l_UINT);48 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, unsigned int, unsigned int, unsigned int); 122 49 //! makes functions with four unsigned ints 123 FUNCTOR_LIST(4)( l_UINT, l_UINT, l_UINT, l_UINT);50 FUNCTOR_LIST(4)(FUNCTOR_CALL_TYPE, unsigned int, unsigned int, unsigned int, unsigned int); 124 51 125 52 //! makes functions with one float 126 FUNCTOR_LIST(1)( l_FLOAT);53 FUNCTOR_LIST(1)(FUNCTOR_CALL_TYPE, float); 127 54 //! makes functions with two floats 128 FUNCTOR_LIST(2)( l_FLOAT, l_FLOAT);55 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, float, float); 129 56 //! makes functions with three floats 130 FUNCTOR_LIST(3)( l_FLOAT, l_FLOAT, l_FLOAT);57 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, float, float, float); 131 58 //! makes functions with four floats 132 FUNCTOR_LIST(4)( l_FLOAT, l_FLOAT, l_FLOAT, l_FLOAT);59 FUNCTOR_LIST(4)(FUNCTOR_CALL_TYPE, float, float, float, float); 133 60 //! makes functions with four floats 134 FUNCTOR_LIST(5)( l_FLOAT, l_FLOAT, l_FLOAT, l_FLOAT, l_FLOAT);61 FUNCTOR_LIST(5)(FUNCTOR_CALL_TYPE, float, float, float, float, float); 135 62 136 63 //! mixed values: 137 FUNCTOR_LIST(2)(l_STRING, l_INT); 138 FUNCTOR_LIST(2)(l_STRING, l_FLOAT); 139 FUNCTOR_LIST(2)(l_UINT, l_LONG); 140 FUNCTOR_LIST(2)(l_STRING, l_UINT); 64 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, const std::string&, bool); 65 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, const std::string&, int); 66 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, const std::string&, float); 67 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, unsigned int, long); 68 FUNCTOR_LIST(2)(FUNCTOR_CALL_TYPE, const std::string&, unsigned int); 141 69 142 FUNCTOR_LIST(3)( l_STRING, l_FLOAT, l_UINT);143 FUNCTOR_LIST(4)( l_STRING, l_FLOAT, l_UINT, l_UINT);144 FUNCTOR_LIST(3)( l_STRING, l_INT, l_UINT);145 FUNCTOR_LIST(3)( l_STRING, l_UINT, l_UINT);70 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, const std::string&, float, unsigned int); 71 FUNCTOR_LIST(4)(FUNCTOR_CALL_TYPE, const std::string&, float, unsigned int, unsigned int); 72 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, const std::string&, int, unsigned int); 73 FUNCTOR_LIST(3)(FUNCTOR_CALL_TYPE, const std::string&, unsigned int, unsigned int); 146 74 147 FUNCTOR_LIST(5)( l_FLOAT, l_FLOAT, l_FLOAT, l_FLOAT, l_STRING);75 FUNCTOR_LIST(5)(FUNCTOR_CALL_TYPE, float, float, float, float, const std::string&); 148 76 149 77 #endif /* FUNCTOR_LIST */ -
trunk/src/lib/util/filesys/directory.cc
r8523 r9869 41 41 #include <sys/stat.h> 42 42 #include <dirent.h> 43 const char Directory::delimiter = '/'; 43 44 #else 44 45 #include <windows.h> 45 46 #include <winbase.h> 47 const char Direcotry::delimiter = '\\'; 46 48 #endif 47 49 … … 63 65 */ 64 66 Directory::Directory(const Directory& directory) 65 : File(directory)67 : File(directory) 66 68 { 67 69 this->_opened = directory._opened; … … 166 168 #endif 167 169 } 170 171 172 Directory Directory::operator+(const Directory& dir) const 173 { 174 return Directory(*this) += dir; 175 } 176 177 /** 178 * @param dir the Directory to append to this one (say this one is "/var", then dir can be "log") 179 * @returns The Directory appended by dir. 180 * 181 * @note the Directoy will again be closed even if it was opened previously! 182 */ 183 Directory& Directory::operator+=(const Directory& dir) 184 { 185 this->setFileName(this->name() + Directory::delimiter + dir.name()); 186 return *this; 187 } 188 189 /** 190 * @brief Traverses the Directory tree one step up. (Parent Directory) 191 * @returns a Reference to the Directory. 192 */ 193 Directory& Directory::operator--() 194 { 195 } 196 197 198 /** 199 * @brief Traverses the Directory tree one step up. (Parent Directory) 200 * @param int the PostFix iterator 201 * @returns a Reference to the Directory. 202 */ 203 Directory& Directory::operator--(int) 204 { 205 } 206 207 /** 208 * @returns The Parent Directory. 209 */ 210 Directory Directory::parentDir() const 211 { 212 213 } 214 215 File operator+(const Directory& dir, const File& file) 216 { 217 return File(dir.name() + Directory::delimiter + file.name()); 218 } -
trunk/src/lib/util/filesys/directory.h
r8333 r9869 29 29 #include <vector> 30 30 31 //! A Directory is a Special file, that contains multiple Files. 32 /** 33 * @example Correct usage 34 * Directory dir("/var/log"); 35 * dir.open(); 36 * if (dir.fileNameInDir("emerge.log")) 37 * { // do stuff; } 38 */ 31 39 class Directory : public File 32 40 { … … 41 49 bool create(); 42 50 51 Directory operator+(const Directory& dir) const; 52 Directory& operator+=(const Directory& dir); 53 Directory& operator--(); 54 Directory& operator--(int); 55 Directory parentDir() const; 56 57 43 58 /** @returns if the Directory was opened */ 44 59 bool isOpen() const { return this->_opened; } … … 50 65 const std::string& operator[](unsigned int fileNumber) const { return this->_fileNames[fileNumber]; }; 51 66 /** @returns a formated string containing the FileName, prepended with the directory-Name */ 52 std::string fileNameInDir(unsigned int fileNumber) const { return this->name() + "/"+ _fileNames[fileNumber]; };67 std::string fileNameInDir(unsigned int fileNumber) const { return this->name() + Directory::delimiter + _fileNames[fileNumber]; }; 53 68 /** @returns a File pointing to the File @param fileNumber the fileNumber (must not bigger than fileCount()) */ 54 69 File getFile(unsigned int fileNumber) const { return File(fileNameInDir(fileNumber)); }; 70 71 public: 72 static const char delimiter; //!< A Delimiter (*nix: '/', windows: '\\') 55 73 56 74 private: … … 58 76 std::vector<std::string> _fileNames; //!< The List of Files contained in the directory. (will be filled when open was called.) 59 77 }; 78 79 File operator+(const Directory& dir, const File& file); 60 80 61 81 #endif /* __DIRECTORY_H_ */ -
trunk/src/lib/util/filesys/file.cc
r8619 r9869 326 326 } 327 327 328 /** 329 * @brief converts an Absolute Filename to a Relative one 330 * @param absFileName the FileName to convert. The Relative path will be stored in absFileName. 331 */ 328 332 void File::absToRel(std::string& absFileName) 329 333 { -
trunk/src/lib/util/loading/dynamic_loader.cc
r9406 r9869 24 24 25 25 26 26 ObjectListDefinition(DynamicLoader); 27 27 28 28 /** … … 31 31 */ 32 32 DynamicLoader::DynamicLoader (const std::string& libName) 33 : Factory( NULL, CL_NULL)33 : Factory(libName) 34 34 { 35 this-> setClassID(CL_DYNAMIC_LOADER, "DynamicLoader");35 this->registerObject(this, DynamicLoader::_objectList); 36 36 37 37 this->handle = NULL; -
trunk/src/lib/util/loading/dynamic_loader.h
r7193 r9869 19 19 class DynamicLoader : public Factory 20 20 { 21 ObjectListDeclaration(DynamicLoader); 21 22 22 23 public: -
trunk/src/lib/util/loading/factory.cc
r9675 r9869 15 15 #define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOADING 16 16 17 #include " util/loading/factory.h"17 #include "factory.h" 18 18 #include "debug.h" 19 19 //#include "shell_command.h" 20 20 21 21 ObjectListDefinition(Factory); 22 22 23 23 //SHELL_COMMAND(create, Factory, fabricate); … … 28 28 * set everything to zero and define factoryName 29 29 */ 30 Factory::Factory (const std::string& factoryName, ClassIDclassID)31 : classID(classID), className(factoryName)30 Factory::Factory (const ClassID& classID) 31 : _classID(classID) 32 32 { 33 this->setClassID(CL_FACTORY, "Factory"); 34 this->setName(factoryName); 33 PRINTF(4)("Factory::create(%s::%d)\n", classID.name().c_str(), classID.id()); 34 //this->registerObject(this, Factory::_objectList); 35 this->setName(classID.name()); 35 36 36 if( Factory::factoryList == NULL) 37 Factory::factoryList = new std::list<Factory*>; 38 39 Factory::factoryList->push_back(this); 37 Factory::_factoryIDMap[classID] = this; 38 Factory::_factoryStringMap[classID.name()] = this; 40 39 } 41 40 42 /** @brief a reference to the First Factory */ 43 std::list<Factory*>* Factory::factoryList = NULL; 41 /** @brief A Map of all Factories ordered by ID. */ 42 Factory::FactoryIDMap Factory::_factoryIDMap; 43 44 /** @brief A Map of all Factories ordered by Name. */ 45 Factory::FactoryStringMap Factory::_factoryStringMap; 44 46 45 47 /** … … 48 50 Factory::~Factory () 49 51 { 50 // printf("%s\n", this->factoryName); 51 // Factory* tmpDel = this->next; 52 // this->next = NULL; 53 } 52 FactoryIDMap::iterator it = Factory::_factoryIDMap.find(this->_classID); 53 if (it != Factory::_factoryIDMap.end() && (*it).second == this) 54 Factory::_factoryIDMap.erase(it); 54 55 55 /** 56 * @brief deletes all the Factories. (cleanup) 57 */ 58 void Factory::deleteFactories() 59 { 60 if (Factory::factoryList != NULL) 61 { 62 while(!Factory::factoryList->empty()) 63 { 64 delete Factory::factoryList->front(); 65 Factory::factoryList->pop_front(); 66 } 67 delete Factory::factoryList; 68 Factory::factoryList = NULL; 69 } 56 FactoryStringMap::iterator stringIt = Factory::_factoryStringMap.find(this->_classID.name()); 57 if (stringIt != Factory::_factoryStringMap.end() && (*stringIt).second == this) 58 Factory::_factoryStringMap.erase(stringIt); 70 59 } 71 60 … … 74 63 * @returns true on match, false otherwise 75 64 */ 76 bool Factory::operator==( ClassIDclassID) const65 bool Factory::operator==(int classID) const 77 66 { 78 return (this-> classID == classID);67 return (this->_classID == classID); 79 68 } 80 69 81 /**82 * @brief Compares the Factories Name against a given ClassName83 * @param className the Name of the Class to Query84 * @returns true on match, false otherwise.85 */86 bool Factory::operator==(const char* className) const87 {88 return (className != NULL && this->className == className);89 }90 70 91 71 /** … … 96 76 bool Factory::operator==(const std::string& className) const 97 77 { 98 return (this-> className== className);78 return (this->_classID.name() == className); 99 79 } 100 80 … … 107 87 BaseObject* Factory::fabricate(const TiXmlElement* root) 108 88 { 109 assert (root != NULL && Factory::factoryList != NULL); 110 111 std::list<Factory*>::const_iterator factory; 112 for (factory = Factory::factoryList->begin(); factory != Factory::factoryList->end(); factory++) 113 if (*(*factory) == root->Value()) 114 { 115 PRINTF(2)("Create a new Object of type %s\n", (*factory)->getCName()); 116 return (*factory)->fabricateObject(root); 117 } 118 119 PRINTF(2)("Could not Fabricate an Object of Class '%s'\n", root->Value()); 120 return NULL; 89 FactoryStringMap::const_iterator it = Factory::_factoryStringMap.find(root->Value()); 90 if (it != Factory::_factoryStringMap.end()) 91 { 92 PRINTF(2)("Create a new Object of type %s\n", (*it).second->getCName()); 93 return (*it).second->fabricateObject(root); 94 } 95 else 96 { 97 PRINTF(2)("Could not Fabricate an Object of Class '%s'\n", root->Value()); 98 return NULL; 99 } 121 100 } 122 101 … … 129 108 BaseObject* Factory::fabricate(const std::string& className) 130 109 { 131 if (Factory::factoryList == NULL) 110 FactoryStringMap::const_iterator it = Factory::_factoryStringMap.find(className); 111 if (it != Factory::_factoryStringMap.end()) 112 { 113 PRINTF(2)("Create a new Object of type %s\n", (*it).second->getCName()); 114 return (*it).second->fabricateObject(NULL); 115 } 116 else 117 { 118 PRINTF(2)("Could not Fabricate an Object of Class '%s'\n", className.c_str()); 132 119 return NULL; 133 134 std::list<Factory*>::const_iterator factory; 135 for (factory = Factory::factoryList->begin(); factory != Factory::factoryList->end(); factory++) 136 if (*(*factory) == className) 137 { 138 PRINTF(4)("Create a new Object of type %s\n", (*factory)->getCName()); 139 return (*factory)->fabricateObject(NULL); 140 } 141 PRINTF(2)("Could not Fabricate an Object of Class '%s'\n", className.c_str()); 142 return NULL; 120 } 143 121 } 144 145 122 146 123 /** … … 149 126 * @returns a new Object of Type classID on match, NULL otherwise 150 127 */ 151 BaseObject* Factory::fabricate( ClassIDclassID)128 BaseObject* Factory::fabricate(const ClassID& classID) 152 129 { 153 if (Factory::factoryList == NULL) 130 FactoryIDMap::const_iterator it = Factory::_factoryIDMap.find(classID); 131 if (it != Factory::_factoryIDMap.end()) 132 { 133 PRINTF(4)("Create a new Object of type %s\n", (*it).second->getCName()); 134 return (*it).second->fabricateObject(NULL); 135 } 136 else 137 { 138 PRINTF(2)("Could not Fabricate an Object of ClassID '%d'\n", classID.id()); 154 139 return NULL; 140 } 141 } 155 142 156 std::list<Factory*>::const_iterator factory;157 for (factory = Factory::factoryList->begin(); factory != Factory::factoryList->end(); factory++)158 if (*(*factory) == classID)159 {160 PRINTF(4)("Create a new Object of type %s\n", (*factory)->getCName());161 return (*factory)->fabricateObject(NULL);162 143 163 } 164 PRINTF(2)("Could not Fabricate an Object of ClassID '0x%h'\n", classID); 165 return NULL; 144 /** 145 * @brief print out some nice litte debug information about the Factory. 146 */ 147 void Factory::debug() const 148 { 149 PRINTF(0)("Factory of class '%s' with ClassID: %d\n", this->_classID.name().c_str(), this->_classID.id()); 166 150 } 151 152 /** 153 * @brief Prints out some nice Debug information about all factories 154 */ 155 void Factory::debugAll() 156 { 157 PRINTF(0)("Debugging all %d Factories\n", Factory::_factoryStringMap.size()); 158 Factory::FactoryStringMap::const_iterator it; 159 for (it = Factory::_factoryStringMap.begin(); it != Factory::_factoryStringMap.end(); ++it) 160 (*it).second->debug(); 161 } -
trunk/src/lib/util/loading/factory.h
r8148 r9869 20 20 21 21 22 #ifndef _ FACTORY_H23 #define _ FACTORY_H22 #ifndef __FACTORY_H 23 #define __FACTORY_H 24 24 25 25 class BaseObject; … … 27 27 #include "parser/tinyxml/tinyxml.h" 28 28 #include "base_object.h" 29 #include <vector> 30 #include <list> 29 #include <map> 31 30 32 31 /** … … 34 33 * this should be used at the beginning of all the Classes that should be loadable (in the cc-file) 35 34 */ 36 #define CREATE_FACTORY(CLASS_NAME , CLASS_ID) \37 tFactory<CLASS_NAME> * global_##CLASS_NAME##_Factory = new tFactory<CLASS_NAME>(#CLASS_NAME, CLASS_ID)35 #define CREATE_FACTORY(CLASS_NAME) \ 36 tFactory<CLASS_NAME> global_##CLASS_NAME##_Factory = tFactory<CLASS_NAME>(CLASS_NAME::staticClassID()) 38 37 39 38 //! The Factory is a loadable object handler 40 class Factory : public BaseObject { 41 42 public: 39 class Factory : public BaseObject 40 { 41 //! Declare the ObjectList at the BaseObject List 42 ObjectListDeclaration(Factory); 43 public: 43 44 virtual ~Factory (); 44 45 45 static void deleteFactories(); 46 static BaseObject* fabricate(const std::string& className); 47 static BaseObject* fabricate(const ClassID& classID); 48 static BaseObject* fabricate(const TiXmlElement* root); 46 49 47 static BaseObject* fabricate(const std::string& className); 48 static BaseObject* fabricate(ClassID classID); 49 static BaseObject* fabricate(const TiXmlElement* root = NULL); 50 bool operator==(int classID) const; 51 bool operator==(const std::string& className) const; 52 /** @param classID the ID to compare @returns true if the ID's match */ 53 bool operator==(const ClassID& classID) const { return _classID == classID; }; 50 54 51 55 52 bool operator==(ClassID classID) const; 53 bool operator==(const char* className) const; 54 bool operator==(const std::string& className) const; 56 void debug() const; 57 static void debugAll(); 55 58 56 protected: 57 Factory (const std::string& factoryName, ClassID classID); 58 virtual BaseObject* fabricateObject(const TiXmlElement* root = NULL) const = 0; 59 protected: 60 Factory (const ClassID& id); 61 /** 62 * @brief The core function of the Factory. Creates objects of the Factories Type. 63 * @param root The TiXmlElement of the Factory. 64 * @returns the created Object in BaseType* format. 65 */ 66 virtual BaseObject* fabricateObject(const TiXmlElement* root = NULL) const = 0; 59 67 60 protected: 61 const ClassID classID; //!< The Class-Identifyer of the Factory. 62 const std::string className; //!< The name of the Class. 63 static std::list<Factory*>* factoryList; //!< List of Registered Factories 68 private: 69 //! Copy Constructor is hidden. 70 Factory (const Factory&) {}; 71 72 protected: 73 /** The Type of the FactoryMap that is sorted by ID */ 74 typedef std::map<const ClassID, Factory*> FactoryIDMap; 75 /** The Type of the FactoryMap that is sorted by Name */ 76 typedef std::map<std::string, Factory*> FactoryStringMap; 77 78 const ClassID _classID; //!< The Class-Identifyer of the Factory. 79 static FactoryIDMap _factoryIDMap; //!< List of Registered Factories 80 static FactoryStringMap _factoryStringMap; //!< List of Registered Factories 64 81 }; 65 82 … … 70 87 template<class T> class tFactory : public Factory 71 88 { 72 public: 73 /** 74 * @brief creates a new type Factory to enable the loading of T 75 * @param factoryName the Name of the Factory to load. 76 * @param classID the ID of the Class to be created. 77 */ 78 tFactory (const char* factoryName, ClassID classID) 79 : Factory(factoryName, classID) 89 public: 90 /** 91 * @brief creates a new type Factory to enable the loading of T 92 * @param classID the ID of the Class to be created. 93 */ 94 tFactory (const ClassID& classID) 95 : Factory(classID) 80 96 { } 97 /** 98 * @brief copy constructor 99 * @param factory the Factory to copy 100 */ 101 tFactory (const tFactory& factory) : Factory(factory._classID) {}; 81 102 82 private: 83 /** 84 * @brief fabricates an Object of type T, with the constructor T::T(const TiXmlElemnt*) 85 * @param root the TiXmlElement T should load parameters from. 86 * @return the newly fabricated T. 87 */ 88 virtual BaseObject* fabricateObject(const TiXmlElement* root = NULL) const 89 { 90 return new T(root); 91 } 103 /** 104 * @brief fabricates an Object of type T, with the constructor T::T(const TiXmlElemnt*) 105 * @param root the TiXmlElement T should load parameters from. 106 * @return the newly fabricated T. 107 */ 108 virtual BaseObject* fabricateObject(const TiXmlElement* root = NULL) const 109 { 110 return new T(root); 111 } 92 112 }; 93 113 -
trunk/src/lib/util/loading/game_loader.cc
r9110 r9869 20 20 #include "game_loader.h" 21 21 #include "util/loading/load_param.h" 22 23 #include " shell_command.h"22 #include "util/loading/resource_manager.h" 23 #include "debug.h" 24 24 #include "campaign.h" 25 25 26 #include "util/loading/resource_manager.h"27 28 26 #include "key_mapper.h" 29 27 30 31 32 SHELL_COMMAND(quit, GameLoader, stop) 33 ->describe("quits the game") 34 ->setAlias("orxoquit"); 35 28 ObjectListDefinition(GameLoader); 36 29 37 30 GameLoader* GameLoader::singletonRef = NULL; … … 43 36 GameLoader::GameLoader () 44 37 { 45 this-> setClassID(CL_GAME_LOADER, "GameLoader");38 this->registerObject(this, GameLoader::_objectList); 46 39 this->setName("GameLoader"); 47 40 this->bRun = true; … … 57 50 delete this->currentCampaign; 58 51 this->currentCampaign = NULL; 59 52 60 53 GameLoader::singletonRef = NULL; 61 54 } … … 90 83 { 91 84 ErrorMessage errorCode; 92 std::string campaignName = Resource Manager::getFullName(fileName);85 std::string campaignName = Resources::ResourceManager::getInstance()->prependAbsoluteMainPath(fileName); 93 86 if (!campaignName.empty()) 94 87 { … … 110 103 { 111 104 ErrorMessage errorCode; 112 std::string campaignName = Resource Manager::getFullName(fileName);105 std::string campaignName = Resources::ResourceManager::getInstance()->prependAbsoluteMainPath(fileName); 113 106 if (!campaignName.empty()) 114 107 { -
trunk/src/lib/util/loading/game_loader.h
r7868 r9869 38 38 class GameLoader : public EventListener 39 39 { 40 public: 40 ObjectListDeclaration(GameLoader); 41 public: 41 42 virtual ~GameLoader (); 42 43 /** this class is a singleton class @returns an instance of itself */ -
trunk/src/lib/util/loading/load_param.cc
r9406 r9869 16 16 #define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOADING 17 17 18 #include "util/loading/load_param.h" 19 #include "load_param_description.h" 20 21 #include <stdarg.h> 22 18 #include "load_param.h" 19 #include "load_param_class_description.h" 20 #include "compiler.h" 21 #include "debug.h" 23 22 /** 24 * Constructs a new LoadParameter23 * @brief Constructs a new LoadParameter 25 24 * @param root the XML-element to load this Parameter from 26 25 * @param paramName the Parameter to load 27 * @param object the BaseObject, to load this parameter on to (will be cast to executor's Parameter) 28 * @param executor the Executor, that executes the loading procedure. 26 * @param inLoadCycle If we are in a LoadCycle (loading differs.). 29 27 */ 30 CLoadParam::CLoadParam(const TiXmlElement* root, const std::string& paramName, BaseObject* object, Executor* executor, bool inLoadCycle)31 : object(object), paramName(paramName)28 LoadParamBase::LoadParamBase(const TiXmlElement* root, const std::string& paramName, bool inLoadCycle) 29 : paramName(paramName), inLoadCycle(inLoadCycle) 32 30 { 33 this->inLoadCycle = inLoadCycle;34 35 31 // determin the LoadString. 36 32 if (likely(!inLoadCycle)) … … 40 36 else 41 37 this->loadElem = NULL; 38 } 42 39 43 // set the Executor.44 this->executor = executor;45 40 46 //if (this->executor) 47 // this->executor->setName(paramName); 41 /** 42 * @param classID the ID of the class. This is needed to identify into what class this Parameter belongs. 43 * @param descriptionText The text to set as a description for this Parameter 44 * @returns a pointer to itself. 45 */ 46 void LoadParamBase::describe(const ClassID& classID, const std::string& descriptionText) 47 { 48 PRINTF(5)("Describing Class '%s'(id:%d) Parameter '%s': description '%s'\n", 49 classID.name().c_str(), classID.id(), paramName.c_str(), descriptionText.c_str()); 50 51 if (LoadParamClassDescription::descriptionsCaptured()) 52 LoadParamClassDescription::describeClass(classID, paramName, descriptionText); 48 53 } 49 54 50 55 /** 51 * This is a VERY SPECIAL deconsrtuctor. 52 * It is made, so that it loads the Parameters on destruction. 53 * meaning, if an Executor a valid Object exist, and all 54 * Execution-Conditions are met, they are executed here. 56 * @brief sets the Values of the Description to a usefull text. 55 57 */ 56 CLoadParam::~CLoadParam()58 void LoadParamBase::setDescriptionValues(const ClassID& classID, unsigned int paramCount, const MultiType* const defaultValues, bool retVal) 57 59 { 58 if (likely(this->executor != NULL)) 59 { 60 std::string loadString = ""; 61 if (this->loadElem != NULL && this->loadElem->ToText()) 62 loadString = this->loadElem->Value(); 63 if (likely(this->object != NULL) && 64 ( !loadString.empty() || 65 ((this->executor->getType() & Executor_NoLoadString) == Executor_NoLoadString))) 66 { 67 PRINTF(4)("Loading value '%s' with Parameters '%s' onto: %s::%s\n", this->paramName.c_str(), loadString.c_str(), this->object->getClassCName(), this->object->getCName()); 68 (*this->executor)(this->object, SubString(loadString, ",", SubString::WhiteSpaces, false, '\\')); 69 } 70 delete this->executor; 71 } 60 if(LoadParamClassDescription::descriptionsCaptured()) 61 LoadParamClassDescription::setValuesOf(classID, paramName, paramCount, defaultValues, retVal); 72 62 } 73 74 /**75 * @brief set the default values of the executor76 * @param value0 the first default value77 * @param value1 the second default value78 * @param value2 the third default value79 * @param value3 the fourth default value80 * @param value4 the fifth default value81 */82 CLoadParam& CLoadParam::defaultValues(const MultiType& value0, const MultiType& value1,83 const MultiType& value2, const MultiType& value3,84 const MultiType& value4)85 {86 assert(this->executor != NULL);87 this->executor->defaultValues(value0, value1, value2, value3, value4);88 89 return *this;90 }91 92 93 94 /**95 * @param descriptionText The text to set as a description for this Parameter96 * @returns a pointer to itself.97 */98 CLoadParam& CLoadParam::describe(const std::string& descriptionText)99 {100 if (LoadClassDescription::parametersDescription && this->paramDesc && this->paramDesc->getDescription().empty())101 {102 this->paramDesc->setDescription(descriptionText);103 }104 return *this;105 }106 107 // const LoadParamDescription* LoadParamDescription::getClass(const char* className)108 // {109 // tIterator<LoadClassDescription>* iterator = LoadClassDescription::classList->getIterator();110 // LoadClassDescription* enumClassDesc = iterator->firstElement();111 // while (enumClassDesc)112 // {113 // if (!strcmp(enumClassDesc->className, classNameBegin, className))114 // {115 // delete iterator;116 // return enumClassDesc;117 // }118 // enumClassDesc = iterator->nextElement();119 // }120 // delete iterator;121 //122 // return NULL;123 // }124 125 126 127 128 /*129 * @param object The object this Parameter is loaded too.130 * @param root: the XML-element to load this option from.131 * @param paramName: The name of the parameter loaded.132 * @param paramCount: how many parameters this loading-function takes133 * @param multi: if false LoadParam assumes only one occurence of this parameter in root, if true it assumes multiple occurences.134 * @param ...: the parameter information (1. Parameter, 2. Default Value for the Parameter, ...)135 */136 /*LoadParam::LoadParam(const TiXmlElement* root, BaseObject* object, const char* paramName,137 int paramCount, bool multi, const void* pointerToParam, ...)138 {139 this->setClassID(CL_LOAD_PARAM, "LoadParam");140 this->executor = NULL;141 142 this->loadString = NULL;143 this->pointerToParam = pointerToParam;144 145 if (paramCount == 0 || this->pointerToParam != NULL)146 this->loadString = "none";147 else148 {149 if (likely(!multi))150 this->loadString = grabParameter(root, paramName);151 else152 {153 if (!strcmp(root->Value(), paramName))154 {155 const TiXmlNode* val = root->FirstChild();156 if( val->ToText())157 this->loadString = val->Value();158 }159 }160 }161 162 this->paramDesc = NULL;163 if (LoadClassDescription::parametersDescription)164 {165 // locating the class166 this->classDesc = LoadClassDescription::addClass(object->getClassCName());167 168 if ((this->paramDesc = this->classDesc->addParam(paramName)) != NULL)169 {170 171 this->paramDesc->paramCount = paramCount;172 this->paramDesc->types = new int[paramCount];173 this->paramDesc->defaultValues = new char*[paramCount];174 175 va_list types;176 va_start (types, pointerToParam);177 char defaultVal[512];178 for(int i = 0; i < paramCount; i++)179 {180 defaultVal[0] = '\0';181 // parameters parsed182 int tmpType = va_arg (types, int);183 this->paramDesc->types[i] = tmpType;184 switch (tmpType)185 {186 case MT_INT:187 sprintf(defaultVal, "%d", va_arg(types, int));188 break;189 // case MT_LONG:190 // sprintf(defaultVal, "%0.3f", va_arg(types, l_LONG_TYPE));191 // break;192 case MT_FLOAT:193 sprintf(defaultVal, "%0.3f", va_arg(types, double));194 break;195 case MT_STRING:196 sprintf(defaultVal, "%s", va_arg(types, l_STRING_TYPE));197 break;198 case MT_EXT1:199 sprintf(defaultVal, "");200 break;201 }202 this->paramDesc->defaultValues[i] = new char[strlen(defaultVal)+1];203 strcpy(this->paramDesc->defaultValues[i], defaultVal);204 }205 va_end(types);206 207 int argCount = 0;208 }209 }210 }*/211 212 213 214 215 216 217 218 219 63 220 64 … … 227 71 * @returns the Value of the parameter if found, NULL otherwise 228 72 */ 229 std::string grabParameter(const TiXmlElement* root, const std::string& parameterName)73 std::string LoadParamBase::grabParameter(const TiXmlElement* root, const std::string& parameterName) 230 74 { 231 const TiXmlElement* element; 232 const TiXmlNode* node; 233 234 if (root == NULL) 235 return ""; 236 237 element = root->FirstChildElement( parameterName); 238 if( element == NULL) return ""; 239 240 node = element->FirstChild(); 241 while( node != NULL) 75 const TiXmlElement* const element = grabParameterElement(root, parameterName); 76 if (element != NULL) 77 return element->Value(); 78 else 242 79 { 243 if( node->ToText()) return node->Value();244 node = node->NextSibling();80 static std::string empty(""); 81 return empty; 245 82 } 246 return "";247 83 } 248 84 … … 252 88 * @returns the Element of the parameter if found, NULL otherwise 253 89 */ 254 const TiXmlElement* grabParameterElement(const TiXmlElement* root, const std::string& parameterName)90 const TiXmlElement* LoadParamBase::grabParameterElement(const TiXmlElement* root, const std::string& parameterName) 255 91 { 256 92 const TiXmlElement* element; … … 271 107 return NULL; 272 108 } 273 274 275 -
trunk/src/lib/util/loading/load_param.h
r8048 r9869 22 22 #define _LOAD_PARAM_H 23 23 24 #include "base_object.h" 24 #include "util/executor/executor_substring.h" 25 #include "util/executor/executor_member.h" 26 #include "util/executor/functor_member.h" 25 27 26 #include "executor/executor.h" 27 #include "executor/executor_xml.h" 28 #include "parser/tinyxml/tinyxml.h" 28 29 29 30 // Forward Declaration // 30 31 class LoadClassDescription; 31 32 class LoadParamDescription; 32 class MultiType; 33 33 class TiXmlElement; 34 34 35 35 /** 36 36 * Loads a Parameter from ROOT named PARAMETER_NAME 37 * onto OBJECT of CLASS, trough theFUNCTION37 * onto OBJECT of CLASS, trough FUNCTION 38 38 * @param ROOT the TiXmlElement to load the Parameter from 39 39 * @param PARAMETER_NAME the Name of the Parameter to load … … 43 43 */ 44 44 #define LoadParam(ROOT, PARAMETER_NAME, OBJECT, CLASS, FUNCTION) \ 45 CLoadParam (ROOT, PARAMETER_NAME, OBJECT, createExecutor<CLASS>(&CLASS::FUNCTION), false)45 CLoadParam<CLASS>(ROOT, PARAMETER_NAME, OBJECT, createExecutor<CLASS, CLASS>(&CLASS::FUNCTION), false) 46 46 47 /** 48 * @brief Does essentially the same as LoadParam, but within a Cycle in an ordered fashion. 49 * 50 * This Function looks in each Element, if the PARAMETER_NAME matches, and loads onto OBJECT 51 * of CLASS the ROOT through FUNCTION 52 * 53 * @see LoadParam(ROOT, PARAMETER_NAME, OBJECT, CLASS, FUNCTION) 54 */ 47 55 #define LoadParam_CYCLE(ROOT, PARAMETER_NAME, OBJECT, CLASS, FUNCTION) \ 48 CLoadParam(ROOT, PARAMETER_NAME, OBJECT, createExecutor<CLASS>(&CLASS::FUNCTION), true) 49 50 #define LoadParamXML(ROOT, PARAMETER_NAME, OBJECT, CLASS, FUNCTION) \ 51 CLoadParam(ROOT, PARAMETER_NAME, OBJECT, new ExecutorXML<CLASS>(&CLASS::FUNCTION, ROOT, PARAMETER_NAME), false) 52 53 #define LoadParamXML_CYCLE(ROOT, PARAMETER_NAME, OBJECT, CLASS, FUNCTION) \ 54 CLoadParam(ROOT, PARAMETER_NAME, OBJECT, new ExecutorXML<CLASS>(&CLASS::FUNCTION, ROOT, PARAMETER_NAME), true) 55 56 CLoadParam<CLASS>(ROOT, PARAMETER_NAME, OBJECT, createExecutor<CLASS, CLASS>(&CLASS::FUNCTION), true) 56 57 57 58 /** … … 78 79 } 79 80 81 80 82 /************************** 81 83 **** REAL DECLARATIONS **** 82 84 **************************/ 83 //! abstract Base class for a Loadable parameter84 class CLoadParam : public BaseObject85 //!< A BaseClass for all LoadParam's. 86 class LoadParamBase 85 87 { 86 public: 87 CLoadParam(const TiXmlElement* root, const std::string& paramName, BaseObject* object, Executor* executor, bool inLoadCycle = false); 88 virtual ~CLoadParam(); 88 protected: 89 LoadParamBase(const TiXmlElement* root, const std::string& paramName, bool inLoadCycle = false); 89 90 90 CLoadParam& describe(const std::string& descriptionText); 91 CLoadParam& defaultValues(const MultiType& value0 = MT_NULL, const MultiType& value1 = MT_NULL, 92 const MultiType& value2 = MT_NULL, const MultiType& value3 = MT_NULL, 93 const MultiType& value4 = MT_NULL); 94 CLoadParam& attribute(const std::string& attributeName, const Executor& executor); 91 protected: 92 void describe(const ClassID& classID, const std::string& descriptionText); 93 void setDescriptionValues(const ClassID& classID, unsigned int paramCount, const MultiType* const defaultValues, bool retVal = false); 94 95 public: 96 static std::string grabParameter(const TiXmlElement* root, const std::string& parameterName); 97 static const TiXmlElement* grabParameterElement(const TiXmlElement* root, const std::string& parameterName); 98 99 protected: 100 const std::string paramName; //!< The Name of the Parameter this LoadParams applies to. 101 bool inLoadCycle; //!< If the Parameter is in a LoadCycle. 102 103 const TiXmlElement* loadElem; //!< The Element to load. 104 }; 95 105 96 106 97 private: 98 bool inLoadCycle; 99 Executor* executor; 100 BaseObject* object; 101 const std::string paramName; 107 //! The Loading Class of the LoadParam, that acctually executes the loading process. 108 template <class OperateClass> class CLoadParam : public LoadParamBase 109 { 110 public: 111 /** 112 * @brief generates a LoadParam based on: 113 * @param root the Root Element to load onto the object. @param paramName the Parameter name that is loaded. 114 * @param object the Object to apply the changes on. @param executor the Functional Object, that actually executes the function Call. 115 * @param inLoadCycle If we are inside of a loading cycle. (Loading will be different here) 116 */ 117 CLoadParam(const TiXmlElement* root, const std::string& paramName, OperateClass* object, Executor<const SubString, OperateClass>* executor, bool inLoadCycle = false) 118 : LoadParamBase(root, paramName, inLoadCycle) 119 { 120 assert (executor != NULL); 121 this->object = object; 122 this->executor = executor; 123 } 124 virtual ~CLoadParam() 125 { 126 std::string loadString; 127 if (this->loadElem != NULL && this->loadElem->ToText()) 128 { 129 loadString = this->loadElem->Value(); 130 if (!loadString.empty()) 131 { 132 /* PRINTF(4)("Loading value '%s' with Parameters '%s' onto: %s::%s\n", 133 this->paramName.c_str(), loadString.c_str(), this->object->getClassCName(), this->object->getCName());*/ 134 (*this->executor)(this->object, SubString(loadString, ",", SubString::WhiteSpaces, false, '\\')); 135 } 136 } 137 this->setDescriptionValues(OperateClass::staticClassID(), executor->getParamCount(), executor->getDefaultValues(), executor->hasRetVal()); 138 delete this->executor; 139 } 140 /** 141 * @brief set the default values of the executor 142 * @param value0 the first default value @param value1 the second default value 143 * @param value2 the third default value @param value3 the fourth default value 144 * @param value4 the fifth default value 145 */ 146 CLoadParam& defaultValues(const MultiType& value0 = MT_NULL, const MultiType& value1 = MT_NULL, 147 const MultiType& value2 = MT_NULL, const MultiType& value3 = MT_NULL, 148 const MultiType& value4 = MT_NULL) 149 { this->executor->defaultValues(value0, value1, value2, value3, value4); return *this; }; 150 //! Describes a LoadParam 151 CLoadParam& describe(const std::string& descriptionText) { LoadParamBase::describe(OperateClass::staticClassID(), descriptionText); return *this; }; 152 // CLoadParam& attribute(const std::string& attributeName, const Executor<SubString>& executor); 102 153 103 LoadClassDescription* classDesc; //!< The LoadClassDescription of this CLoadParameter 104 LoadParamDescription* paramDesc; //!< The LoadParameterDescription of this LoadParameter 105 const TiXmlElement* loadElem; //!< The Element to load. 106 const void* pointerToParam; //!< A Pointer to a Parameter. 107 108 MultiType* defaultValue; 154 private: 155 Executor<const SubString, OperateClass>* executor; //!< The Executor, that actually executes the Loading process. 156 OperateClass* object; //!< The Object this LoadParam operates on. 109 157 }; 110 158 111 // helper function112 113 std::string grabParameter(const TiXmlElement* root, const std::string& parameterName);114 const TiXmlElement* grabParameterElement(const TiXmlElement* root, const std::string& parameterName);115 116 159 #endif /* _LOAD_PARAM_H */ -
trunk/src/lib/util/loading/load_param_description.cc
r8362 r9869 17 17 18 18 #include "multi_type.h" 19 #include <stdarg.h>20 19 #include "debug.h" 21 20 22 21 /** 22 * @brief Creates a Description of a LoadParam 23 23 * @param paramName the name of the parameter to load 24 24 */ 25 25 LoadParamDescription::LoadParamDescription(const std::string& paramName) 26 { 27 this->types = NULL; 28 this->defaultValues = NULL; 29 this->paramName = paramName; 30 } 31 32 /** 33 * removes all the alocated memory 34 */ 35 LoadParamDescription::~LoadParamDescription() 36 { 37 if (this->defaultValues != NULL) 38 { 39 for(int i = 0; i < this->paramCount; i++) 40 { 41 delete[] this->defaultValues[i]; 42 } 43 } 44 45 delete[] this->types; 46 delete[] this->defaultValues; 47 } 26 : _name(paramName), _parameterCount(0) 27 { } 48 28 49 29 /** … … 52 32 void LoadParamDescription::setDescription(const std::string& descriptionText) 53 33 { 54 this-> description = descriptionText;34 this->_description = descriptionText; 55 35 } 56 36 57 37 /** 58 * prints out this parameter, its input method and the description (if availiable) 38 * @brief sets the Values of the LoadParam in the Description. 39 * @param paramCount the count of arguments the underlying paramDescription takes. 40 * @param defaultValues the default Values the underlying parameter takes. 41 * @param retVal if the underlying parameter has a return value 59 42 */ 60 void LoadParamDescription::print() const 43 void LoadParamDescription::setValues(unsigned int paramCount, 44 const MultiType* const defaultValues, 45 bool retVal) 61 46 { 62 PRINT(3)(" <%s>", this->paramName.c_str());63 for ( int i = 0; i < this->paramCount; i++)47 this->_parameterCount = paramCount; 48 for (unsigned int i = 0; i < paramCount; ++i) 64 49 { 65 if (i > 0) 66 PRINT(3)(","); 67 // FIXME 68 // switch (this->types[i]) 69 // { 70 // default: 71 // PRINTF(3)("none"); 72 // break; 73 // case ParameterBool: 74 // PRINT(3)("bool"); 75 // break; 76 // case ParameterChar: 77 // PRINT(3)("char"); 78 // break; 79 // case ParameterString: 80 // PRINT(3)("string"); 81 // break; 82 // case ParameterInt: 83 // PRINT(3)("int"); 84 // break; 85 // case ParameterUInt: 86 // PRINT(3)("Uint"); 87 // break; 88 // case ParameterFloat: 89 // PRINT(3)("float"); 90 // break; 91 // case ParameterLong: 92 // PRINT(3)("long"); 93 // break; 94 // case ParameterXML: 95 // PRINT(3)("XML"); 96 // break; 97 // } 50 this->_defaultValues.push_back(defaultValues[i].getString()); 51 this->_types.push_back(MultiType::MultiTypeToString(defaultValues[i].getType())); 98 52 } 99 PRINT(3)("</%s>", this->paramName.c_str());100 if (!this->description.empty())101 PRINT(3)(" -- %s", this->description.c_str());102 // default values103 if (this->paramCount > 0)104 {105 PRINT(3)(" (Default: ");106 for (int i = 0; i < this->paramCount; i++)107 {108 if (i > 0)109 PRINT(3)(", ");110 if (this->types[i] & MT_STRING)111 { // leave brackets !!112 PRINT(3)("\"%s\"", this->defaultValues[i]);113 }114 else115 {116 PRINT(3)("%s", this->defaultValues[i]);117 }118 }119 PRINT(3)(")");120 }121 PRINT(3)("\n");122 }123 53 124 /**125 * A list, that holds all the classes that are loadable (classes not objects!!)126 */127 std::list<LoadClassDescription*>* LoadClassDescription::classList = NULL;128 129 /**130 * if the description of Parameters should be executed131 */132 bool LoadClassDescription::parametersDescription = false;133 134 /**135 * @param className the name of the class to be loadable136 */137 LoadClassDescription::LoadClassDescription(const std::string& className)138 {139 this->className = className;140 141 if (LoadClassDescription::classList == NULL)142 LoadClassDescription::classList = new std::list<LoadClassDescription*>;143 144 LoadClassDescription::classList->push_back(this);145 }146 147 /**148 * deletes a classDescription (deletes all the parameterDescriptions as well149 */150 LoadClassDescription::~LoadClassDescription()151 {152 std::list<LoadParamDescription*>::iterator it = this->paramList.begin();153 while (!this->paramList.empty())154 {155 delete this->paramList.front();156 this->paramList.pop_front();157 }158 }159 160 void LoadClassDescription::deleteAllDescriptions()161 {162 if (LoadClassDescription::classList != NULL)163 {164 while (!LoadClassDescription::classList->empty())165 {166 delete LoadClassDescription::classList->front();167 LoadClassDescription::classList->pop_front();168 }169 delete LoadClassDescription::classList;170 }171 LoadClassDescription::classList = NULL;172 54 } 173 55 174 56 175 57 /** 176 * adds a class to the list of loadable classes 177 * @param className The name of the class to add 178 179 this function searches for the className string, and if found just returns the appropriate Class. 180 Otherwise it returns a new classDescription 58 * @brief prints out this parameter, its input method and the description (if availiable) 59 * @param stream the stream to print to. 60 * @param withComments if the comments should be appended. 181 61 */ 182 LoadClassDescription* LoadClassDescription::addClass(const std::string& className) 62 void LoadParamDescription::print(FILE* stream, bool withComments) const 183 63 { 184 if (LoadClassDescription::classList != NULL) 64 fprintf(stream, " <%s>", this->_name.c_str()); 65 for (unsigned int i = 0; i < this->_parameterCount; i++) 185 66 { 186 std::list<LoadClassDescription*>::iterator it = LoadClassDescription::classList->begin(); 187 while (it != LoadClassDescription::classList->end()) 67 if (i > 0) 68 fprintf(stream, ","); 69 fprintf(stream, "%s", this->_types[i].c_str()); 70 } 71 fprintf(stream, "</%s>", this->_name.c_str()); 72 // here the comments are printed out. 73 if (withComments) 74 { 75 if (!this->_description.empty()) 76 fprintf(stream, " <!-- %s", this->_description.c_str()); 77 // default values 78 if (this->_parameterCount > 0) 188 79 { 189 if ((*it)->className == className) 80 fprintf(stream, " (Default: "); 81 for (unsigned int i = 0; i < this->_parameterCount; i++) 190 82 { 191 return (*it); 83 if (i > 0) 84 fprintf(stream, ", "); 85 if (this->_types[i] == "string") 86 { // leave brackets !! 87 fprintf(stream, "\"%s\"", this->_defaultValues[i].c_str()); 88 } 89 else 90 { 91 fprintf(stream, "%s", this->_defaultValues[i].c_str()); 92 } 192 93 } 193 it++;94 fprintf(stream, ")"); 194 95 } 96 if (!this->_description.empty() || this->_parameterCount > 0) 97 fprintf(stream, " -->"); 195 98 } 196 return new LoadClassDescription(className);99 fprintf(stream, "\n"); 197 100 } 198 101 199 /**200 * does the same as addClass(const std::string& className), but with params201 * @param paramName the name of the parameter to add.202 */203 LoadParamDescription* LoadClassDescription::addParam(const std::string& paramName)204 {205 std::list<LoadParamDescription*>::iterator it = this->paramList.begin();206 while (it != this->paramList.end())207 {208 if ((*it)->paramName == paramName)209 {210 return NULL;211 }212 it++;213 }214 102 215 LoadParamDescription* newParam = new LoadParamDescription(paramName);216 217 this->paramList.push_back(newParam);218 return newParam;219 }220 221 /**222 * prints out all loadable Classes, and their parameters223 * @param fileName prints the output to a File224 * @todo implement it225 */226 void LoadClassDescription::printAll(const std::string& fileName)227 {228 PRINT(3)("===============================================================\n");229 PRINT(3)(" Listing all the Loadable Options (loaded since Game started).\n\n");230 if (LoadClassDescription::classList != NULL)231 {232 std::list<LoadClassDescription*>::iterator classDesc = LoadClassDescription::classList->begin();233 while (classDesc != LoadClassDescription::classList->end())234 {235 PRINT(3)("<%s>\n", (*classDesc)->className.c_str());236 std::list<LoadParamDescription*>::iterator param = (*classDesc)->paramList.begin();237 while (param != (*classDesc)->paramList.end())238 {239 (*param)->print();240 param++;241 }242 PRINT(3)("</%s>\n\n", (*classDesc)->className.c_str());243 classDesc++;244 }245 }246 else247 PRINT(3)("no Classes defined so far\n");248 PRINT(3)("===============================================================\n");249 }250 251 /**252 * searches for classes, which beginn with classNameBegin253 * @param classNameBegin the beginning string of a Class254 * @return a NEW char-array with ClassNames. The LIST should be deleted afterwards,255 * !! The strings MUST NOT be deleted !!256 */257 std::list<std::string> LoadClassDescription::searchClassWithShort(const std::string& classNameBegin)258 {259 /// FIXME260 // NOT USED261 /* unsigned int searchLength = strlen(classNameBegin);262 std::list<const std::string&> retVal;263 264 tIterator<LoadClassDescription>* iterator = LoadClassDescription::classList->getIterator();265 LoadClassDescription* enumClassDesc = iterator->firstElement();266 while (enumClassDesc)267 {268 if (strlen(enumClassDesc->className)>searchLength+1 &&269 !strncasecmp(enumClassDesc->className, classNameBegin, searchLength))270 {271 retVal->add(enumClassDesc->className);272 }273 enumClassDesc = iterator->nextElement();274 }275 delete iterator;276 277 return retVal;*/278 std::list<std::string> a;279 return a;280 } -
trunk/src/lib/util/loading/load_param_description.h
r7221 r9869 15 15 16 16 /*! 17 * @file load_param .h17 * @file load_param_description.h 18 18 * A Class and macro-functions, that makes our lives easy to load-in parameters 19 19 */ … … 22 22 #define _LOAD_PARAM_DESCRIPTION_H 23 23 24 #include "base_object.h"25 #include < list>24 #include <vector> 25 #include <string> 26 26 27 27 // Forward Declaration // … … 34 34 class LoadParamDescription 35 35 { 36 friend class LoadParam;37 friend class LoadClassDescription;38 36 public: 39 LoadParamDescription(const std::string& paramName); 40 ~LoadParamDescription(); 37 LoadParamDescription(const std::string& paramName = ""); 38 39 //! Compares a LoadParamDescription with a String. 40 bool operator==(const std::string& paramName) const { return this->_name == paramName; }; 41 //! Compares two LoadParamDescription 42 bool operator==(const LoadParamDescription& paramDescr) const { return this->_name == paramDescr._name; }; 43 //! Compares two LoadParamDescription with the less operator 44 bool operator<(const LoadParamDescription& paramDescr) const { return this->_name < paramDescr._name; }; 41 45 42 46 void setDescription(const std::string& descriptionText); 47 void setValues(unsigned int paramCount, 48 const MultiType* const defaultValues, 49 bool retVal = false); 50 43 51 /** @returns the descriptionString */ 44 const std::string& getDescription() { return this->description; };52 const std::string& description() { return this->_description; }; 45 53 46 void print( ) const;54 void print(FILE* stream = stdout, bool withComments = true) const; 47 55 48 56 private: 49 std::string paramName; //!< The name of the parameter. 50 int paramCount; //!< The count of parameters. 51 int* types; //!< What kind of parameters does this function take ?? 52 std::string description; //!< A longer description about this function. 53 char** defaultValues; //!< The 'Default Values'. @TODO MAKE THIS A MULTITYPE 54 }; 57 std::string _name; //!< The Name of the Parameter. 58 unsigned int _parameterCount; //!< The Count of parameters. 59 std::string _description; //!< A longer description about this function. 55 60 56 //! A class for descriptions of a loadable module 57 class LoadClassDescription 58 { 59 friend class CLoadParam; 60 public: 61 LoadClassDescription(const std::string& className); 62 ~LoadClassDescription(); 63 64 static LoadClassDescription* addClass(const std::string& className); 65 LoadParamDescription* addParam(const std::string& paramName); 66 67 static void deleteAllDescriptions(); 68 69 static void printAll(const std::string& fileName = ""); 70 static std::list<std::string> searchClassWithShort(const std::string& classNameBegin); 71 // static const LoadParamDescription* getClass(const std::string& className); 72 73 private: 74 static bool parametersDescription; //!< if parameter-description should be enabled. 75 static std::list<LoadClassDescription*>* classList; //!< a list, that stores all the loadable classes. (after one instance has been loaded) 76 std::string className; //!< name of the class 77 78 std::list<LoadParamDescription*> paramList; //!< List of parameters this class knows. 61 std::vector<std::string> _types; //!< A Vector of types of this Parameter. 62 std::vector<std::string> _defaultValues; //!< A Vector of defaultValues of this Parameter. 79 63 }; 80 64 -
trunk/src/lib/util/loading/resource.cc
r9406 r9869 14 14 */ 15 15 16 #define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOAD ING16 #define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOAD 17 17 18 18 #include "resource.h" 19 20 21 22 23 /** 24 * standard constructor 25 */ 26 Resource::Resource (const std::string& fileName) 19 #include "resource_manager.h" 20 21 #include "debug.h" 22 23 24 namespace Resources 27 25 { 28 // this->setClassID(CL_RESOURCE, "Resource"); 29 26 //! Define an ObjectList for the Resources 27 ObjectListDefinition(Resource); 28 29 30 /** 31 * @brief standard constructor 32 * @param type the Type this resource belongs to. 33 */ 34 Resource::Resource (Type* type) 35 : _pointer(NULL), _type(type) 36 { 37 this->registerObject(this, Resource::_objectList); 38 } 39 40 /** 41 * @brief standard deconstructor 42 */ 43 Resource::~Resource () 44 { 45 // delete what has to be deleted here 46 } 47 48 /** 49 * @brief Locates a File inside of the Resources Paths and returns the appended path. 50 * 51 * @param fileName the Name of the file to look for. 52 * @returns the Name of the File prepended with the PAth it is in, if found, empty String ("") otherwise. 53 * 54 * This Function searches in (ordered): 55 * 1. mainGlobalPath (from ResourceManger) 56 * 2. all of the global Paths (from ResourceManger) 57 * 3. all of the Resources Paths (from Resources::Type) 58 * 59 * in each of these directory, first "./" is searched, and afterwards all of the subDirs (from Resources::Type) are searched. 60 * 61 * @todo finish it!! 62 */ 63 std::string Resource::locateFile(const std::string& fileName) const 64 { 65 if ((ResourceManager::getInstance()->mainGlobalPath() + File(fileName)).exists() ) 66 return (ResourceManager::getInstance()->mainGlobalPath() + File(fileName)).name(); 67 68 std::string locatedFile; 69 locatedFile = locateFileInSubDir(ResourceManager::getInstance()->mainGlobalPath(), fileName); 70 if (!locatedFile.empty()) 71 { 72 return locatedFile; 73 } 74 75 if (File(fileName).exists()) 76 return fileName; 77 78 return (ResourceManager::getInstance()->mainGlobalPath() + File(fileName)).name(); 79 } 80 81 /** 82 * @brief tests in all the SubDirectories defined in Resource under Directory if the fileName exists. 83 * @param directory the directory to in what to search for all subdirectories for. 84 * @param fileName the Name of the File to query for 85 * @return true on success. 86 */ 87 std::string Resource::locateFileInSubDir(const Directory& directory, const std::string& fileName) const 88 { 89 std::vector<Directory>::const_iterator it; 90 for (it = this->_type->resourceSubPaths().begin(); it != this->_type->resourceSubPaths().end(); ++it) 91 { 92 Directory dir = directory + (*it); 93 File file = dir + File(fileName); 94 if ((dir+ File(fileName)).exists()) 95 return (dir+File(fileName)).name(); 96 } 97 return ""; 98 } 99 100 101 /** 102 * @param loadString the Identifier of the Resource. 103 * @returns a Store-Pointer to the Resource if found, NULL otherwise 104 */ 105 StorePointer* Resource::acquireResource(const std::string& loadString) 106 { 107 //const Type* const type = _resourceTypes[this->_type->id()]; 108 109 for (unsigned int i = 0; i < _type->storedResources().size(); ++i) 110 { 111 if (_type->storedResources()[i]->loadString() == loadString) 112 return _type->storedResources()[i]; 113 } 114 115 return NULL; 116 } 117 118 /** 119 * @brief registers a StorePointer to a Resource's Type. 120 * @param pointer the StorePointer to register. 121 */ 122 void Resource::addResource(StorePointer* pointer) 123 { 124 assert(pointer != NULL); 125 this->_type->addResource(pointer); 126 } 127 128 129 130 131 132 133 /////////////////// 134 //// KEEPLEVEL //// 135 /////////////////// 136 137 //! Constructs a default KeepLevel as Set in the ResourceManager via setDefaultKeepLevel. 138 KeepLevel::KeepLevel() 139 { 140 this->_keepLevel = ResourceManager::getInstance()->defaultKeepLevel().keepLevel(); 141 } 142 /** 143 * @param keepLevel the level to set. 144 */ 145 KeepLevel::KeepLevel(unsigned int keepLevel) 146 { 147 _keepLevel = keepLevel; 148 } 149 150 /** 151 * @brief constructor of a KeepLevel. 152 * @param keepLevelName the Name of the KeepLevel. Must be one Name of the defined Names in the ResourceManager. 153 * 154 * @note the Name is transformed into an Integer for fast interpretation. 155 */ 156 KeepLevel::KeepLevel(const std::string& keepLevelName) 157 { 158 this->_keepLevel = ResourceManager::getInstance()->getKeepLevelID(keepLevelName); 159 } 160 161 /** 162 * @returns the name of the KeepLevel. 163 */ 164 const std::string& KeepLevel::name() const 165 { 166 return ResourceManager::getInstance()->getKeepLevelName(this->_keepLevel); 167 } 168 169 170 171 /////////////////////// 172 //// STORE POINTER //// 173 /////////////////////// 174 /** 175 * @brief allocates a StorePointer. 176 * @param loadString An identifier String that is unique between all resources of this type. 177 * @param keepLevel the KeepLevel at wich to keep this resource. 178 */ 179 StorePointer::StorePointer(const std::string& loadString, const KeepLevel& keeplevel) 180 : _loadString(loadString), _keepLevel(keeplevel) 181 { 182 PRINTF(4)("Acquired a Resource with LoadString '%s' and KeepLevel '%s'\n", _loadString.c_str(), _keepLevel.name().c_str()); 183 } 184 185 StorePointer::~StorePointer() 186 { 187 PRINTF(4)("Deleting Stored Resource '%s' from KeepLevel '%s'\n", _loadString.c_str(), _keepLevel.name().c_str()); 188 }; 189 190 191 192 ////////////// 193 //// TYPE //// 194 ////////////// 195 /** 196 * @brief allocates a Type. 197 * @param typeName the Name of the Type to be stored in this Container. 198 */ 199 Type::Type(const std::string& typeName) 200 : _typeName(typeName) 201 { 202 ResourceManager::getInstance()->registerType(this); 203 PRINTF(4)("Created ResourceType '%s'\n", typeName.c_str()); 204 } 205 206 //! Destructs a Type. 207 Type::~Type() 208 { 209 ResourceManager::getInstance()->unregisterType(this); 210 } 211 212 /** 213 * @brief adds a Resource to this Resource's type. 214 * @param resource the Resource to add. 215 */ 216 void Type::addResource(StorePointer* resource) 217 { 218 this->_storedResources.push_back(resource); 219 } 220 221 /** 222 * @brief adds a Path to the Type's resource-paths. 223 * @param path the path-name to add. 224 */ 225 bool Type::addResourcePath(const std::string& path) 226 { 227 std::vector<Directory>::const_iterator it; 228 for (it = this->_resourcePaths.begin(); it != this->_resourcePaths.end(); ++it) 229 if ((*it) == path) 230 return false; 231 this->_resourcePaths.push_back(path); 232 return true; 233 234 } 235 236 /** 237 * @brief Adds a SubPath to the Type's resource-subpaths. 238 * @param subPath the subpath to add. 239 */ 240 bool Type::addResourceSubPath(const std::string& subPath) 241 { 242 std::vector<Directory>::const_iterator it; 243 for (it = this->_resourceSubPaths.begin(); it != this->_resourceSubPaths.end(); ++it) 244 if ((*it) == subPath) 245 return false; 246 this->_resourceSubPaths.push_back(subPath); 247 return true; 248 } 249 250 /** 251 * @brief Unloads all Resources below a certain Level. 252 * @param keepLevel the KeepLevel at what to remove the Resources from. 253 */ 254 void Type::unloadAllBelowKeepLevel(const Resources::KeepLevel& keepLevel) 255 { 256 std::vector<Resources::StorePointer*>::iterator it, it2; 257 bool finished = false; 258 259 while (!finished) 260 { 261 finished = true; 262 for (it = this->_storedResources.begin(); it != this->_storedResources.end();++it) 263 if((*it)->keepLevel() < keepLevel && (*it)->last()) 264 { 265 delete (*it); 266 this->_storedResources.erase(it); 267 finished = false; 268 break; 269 } 270 } 271 } 272 273 /** 274 * @brief print out some nice Debug information in a beatifully designed style 275 */ 276 void Type::debug() const 277 { 278 PRINT(0)(" ResourceType '%s' stores %d Resources\n", this->_typeName.c_str(), this->_storedResources.size()); 279 PRINT(0)(" Paths:\n"); 280 for (unsigned int i = 0; i < this->_resourcePaths.size(); ++i) 281 PRINT(0)(" %s\n", this->_resourcePaths[i].name().c_str()); 282 PRINT(0)(" Sub-Paths:"); 283 for (unsigned int i = 0; i < this->_resourceSubPaths.size(); ++i) 284 PRINT(0)(" '%s'", this->_resourceSubPaths[i].name().c_str()); 285 PRINT(0)("\n"); 286 287 PRINT(0)(" Loaded Resources:\n"); 288 std::vector<Resources::StorePointer*>::const_iterator it; 289 for (it = this->_storedResources.begin(); it != this->_storedResources.end(); ++it) 290 PRINT(0)(" '%s' : KeepLevel '%s'\n", (*it)->loadString().c_str(), (*it)->keepLevel().name().c_str()); 291 } 30 292 } 31 32 /**33 * standard deconstructor34 */35 Resource::~Resource ()36 {37 // delete what has to be deleted here38 } -
trunk/src/lib/util/loading/resource.h
r7195 r9869 8 8 9 9 #include "base_object.h" 10 #include "multi_type.h"11 10 #include <string> 11 #include <vector> 12 #include <set> 12 13 13 // FORWARD DECLARATION 14 #include "filesys/directory.h" 15 16 //! A Namespace Resources and ResourceHandling is defined in. 17 namespace Resources 18 { 19 //! The KeepLevel handles the unloading of Resources. 20 /** 21 * Allocating a Resource also appends a KeepLevel to the Resource. 22 * When the Resource is not used anymore it is decided on the grounds of the KeepLevel, 23 * if the Resource should be deleted. (e.g. at the end of a Level, Campaign, or something like this). 24 */ 25 class KeepLevel 26 { 27 public: 28 KeepLevel(); 29 KeepLevel(unsigned int keepLevel); 30 KeepLevel(const std::string& keepLevelName); 31 32 //! Compare equality 33 inline bool operator==(const KeepLevel& keepLevel) const { return this->_keepLevel == keepLevel._keepLevel; }; 34 //! Compares inequality 35 inline bool operator!=(const KeepLevel& keepLevel) const { return this->_keepLevel != keepLevel._keepLevel; }; 36 //! Compares less/equal than 37 inline bool operator<=(const KeepLevel& keepLevel) const { return this->_keepLevel <= keepLevel._keepLevel; }; 38 //! Compares less than 39 inline bool operator<(const KeepLevel& keepLevel) const { return this->_keepLevel < keepLevel._keepLevel; }; 40 41 /** @returns the KeepLevel as a number */ 42 inline unsigned int keepLevel() const { return _keepLevel; }; 43 const std::string& name() const; 44 private: 45 unsigned int _keepLevel; //!< The KeepLevel a Resource is in. 46 }; 47 48 49 /////////////////// 50 // STORE POINTER // 51 /////////////////// 52 //! Stores a Resource-Pointer, the LoadString and it's keepLevel. 53 class StorePointer 54 { 55 public: 56 //! Virtual Destructor, that removes the Stored information-pointer. 57 virtual ~StorePointer(); 58 59 /** @returns the LoadString this resource was loaded with */ 60 const std::string& loadString() const { return _loadString; }; 61 /** @returns the KeepLevel of this resource */ 62 const Resources::KeepLevel& keepLevel() const { return _keepLevel; }; 63 64 virtual bool last() const = 0; 65 66 protected: 67 StorePointer(const std::string& loadString, const Resources::KeepLevel& keeplevel); 68 69 private: 70 StorePointer(const StorePointer&) : _keepLevel(0) {}; 71 72 private: 73 std::string _loadString; //!< An identifier, to match when loading a File. 74 Resources::KeepLevel _keepLevel; //!< The Priority of this resource. (can only be increased, so none else will delete this) 75 }; 14 76 15 77 16 78 17 //! An enumerator for different (UN)LOAD-types. 18 /** 19 * RP_NO: will be unloaded on request 20 * RP_LEVEL: will be unloaded at the end of a Level 21 * RP_CAMPAIGN: will be unloaded at the end of a Campaign 22 * RP_GAME: will be unloaded at the end of the whole Game (when closing orxonox) 23 */ 24 typedef enum ResourcePriority 25 { 26 RP_NO = 0, 27 RP_LEVEL = 1, 28 RP_CAMPAIGN = 2, 29 RP_GAME = 3 30 }; 79 /////////////////// 80 // RESOURCE TYPE // 81 /////////////////// 82 //! A Type of Resources. 83 /** 84 * The Type is used to store the Pointers to already loaded Resources, 85 * and also to store type-specific properties. 86 * These are the Loading Paths, the subpaths and so on. 87 */ 88 class Type 89 { 90 public: 91 virtual ~Type(); 92 /** @returns true if the names match @param typeName the Name to compare. @brief compare the Type with a Name */ 93 bool operator==(const std::string& typeName) const { return this->_typeName == typeName; }; 94 95 //////////////////// 96 //// EXTENSIONS //// 97 void addExtension(const std::string& extension); 98 99 /////////////// 100 //// PATHS //// 101 bool addResourcePath(const std::string& path); 102 bool addResourceSubPath(const std::string& subPath); 103 104 /// Retrieve Functions 105 /** @returns the name of the stored Class this Type loads Resources for */ 106 const std::string& storedClassName() const { return _typeName; }; 107 /** @returns the ID of the Type != ClassID */ 108 /** @returns the type-specific paths this Resource searches in. */ 109 const std::vector<Directory>& resourcePaths() const { return _resourcePaths; }; 110 /** @returns the Type specific SubPaths this Resource Searches in @see std::vector<std::string> _resourceSubPaths */ 111 const std::vector<Directory>& resourceSubPaths() const { return _resourceSubPaths; }; 112 /** @returns the Pointers to the Stored resources. @note do not use this, for more than some lookup */ 113 const std::vector<Resources::StorePointer*>& storedResources() const { return _storedResources; }; 114 115 /////////////////////////////// 116 //// LOADING AND UNLOADING //// 117 virtual void createFromString(const std::string& loadString, const KeepLevel& keepLevel = KeepLevel()) = 0; 118 void unloadAllBelowKeepLevel(const Resources::KeepLevel& keepLevel); 119 120 /////////////////// 121 //// INTERNALS //// 122 void addResource(Resources::StorePointer* resource); 123 124 /////////////// 125 //// DEBUG //// 126 void debug() const; 127 128 protected: 129 Type(const std::string& typeName); 130 131 private: 132 Type(const Type& type) {}; 133 private: 134 const std::string _typeName; //!< Name of the Type. (Name of the Resource this loads.) 135 std::vector<Directory> _resourcePaths; //!< The Paths to search for files in this type 136 std::vector<Directory> _resourceSubPaths; //!< The subpaths that will be searched under all the _resourcePaths. 137 std::vector<std::string> _fileExtensions; //!< File Extensions, this Resource supports. 138 139 std::vector<Resources::StorePointer*> _storedResources; //!< An array of all the stored Resources. 140 }; 141 142 /** 143 * @brief A Type Definition Class for any Object that is resourceable. 144 * 145 * This Class's main reason of Existence is, that resources can be dynamically 146 * created over a loadString. For this the Type of Resource is required, and the Resource must 147 * itself support the 'void createFromString(const std::string&)' function. 148 */ 149 template<class T> class tType : public Type 150 { 151 public: 152 /** Create the ResourceType @see Type(const std::string&) */ 153 tType(const std::string& typeName) : Type(typeName) {}; 154 /** @param loadString the String to load a Resource with @brief tries to create a Resource of Type T with a loadString */ 155 virtual void createFromString(const std::string& loadString, const KeepLevel& keepLevel = KeepLevel()) { T::createFromString(loadString, keepLevel); } 156 }; 31 157 32 158 33 159 34 //! A Resource is an Object, that can be loaded from Disk 35 /** 36 * 37 */ 38 class Resource : virtual public BaseObject { 160 ///////////////////// 161 // RESOURCE ITSELF // 162 ///////////////////// 163 //! A Resource is an Object, that can be loaded from Disk 164 /** 165 * The Resource Hanldes the location and stores pointers to data that can be retrieved. 166 */ 167 class Resource : virtual public BaseObject 168 { 169 ObjectListDeclaration(Resource); 39 170 40 public:41 Resource(const std::string& fileName);42 virtual ~Resource();171 public: 172 Resource(Resources::Type* type); 173 virtual ~Resource(); 43 174 44 virtual bool load(std::string& fileName, const MultiType& param1, const MultiType& param2); 45 virtual bool reload(); 46 virtual bool unload(); 175 /** @brief reloads the underlying resource */ 176 virtual bool reload() { return false; }; 177 /** @brief unloads the underlying Resource */ 178 virtual bool unload() { return false; }; 47 179 48 private: 49 std::string fileName; 180 std::string locateFile(const std::string& fileName) const; 50 181 51 unsigned int referenceCount; //!< How many times this Resource has been loaded.52 /// TODO REMOVE THIS: ResourceType type; //!< ResourceType of this Resource. 53 ResourcePriority prio; //!< The Priority of this resource. (can only be increased, so noone else will delete this)182 protected: 183 Resources::StorePointer* acquireResource(const std::string& loadString); 184 void addResource(Resources::StorePointer* pointer); 54 185 55 MultiType param[3]; //!< The Parameters given to this Resource. 56 }; 186 private: 187 std::string locateFileInSubDir(const Directory& directory, const std::string& fileName) const; 188 189 private: 190 Resources::StorePointer* _pointer; //!< Virtual Pointer to the ResourceData. 191 Resources::Type* _type; //!< Type of the Resource. 192 }; 193 } 57 194 58 195 #endif /* _RESOURCE_H */ -
trunk/src/lib/util/loading/resource_manager.cc
r9406 r9869 16 16 #define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOAD 17 17 18 #include "util/loading/resource_manager.h" 19 #include "substring.h" 18 #include "resource_manager.h" 20 19 #include "debug.h" 21 20 22 21 #include <algorithm> 23 #include <assert.h> 24 25 // different resource Types 26 #ifndef NO_MODEL 27 #include "objModel.h" 28 #include "primitive_model.h" 29 #include "md2/md2Model.h" 30 #include "md3/md3_data.h" 31 #include "md3/md3_animation_cfg.h" 32 #endif /* NO_MODEL */ 33 #ifndef NO_TEXTURES 34 #include "texture.h" 35 #endif /* NO_TEXTURES */ 36 #ifndef NO_TEXT 37 #include "font.h" 38 #endif /* NO_TEXT */ 39 #ifndef NO_AUDIO 40 #include "sound_buffer.h" 41 #include "ogg_player.h" 42 #endif /* NO_AUDIO */ 43 #ifndef NO_SHADERS 44 #include "shader.h" 45 #endif /* NO_SHADERS */ 46 47 // File Handling Includes 48 #include <sys/types.h> 49 #include <sys/stat.h> 50 #include <unistd.h> 51 52 53 54 /** 55 * @brief standard constructor 56 */ 57 ResourceManager::ResourceManager () 22 #include <cassert> 23 24 25 namespace Resources 58 26 { 59 this->setClassID(CL_RESOURCE_MANAGER, "ResourceManager"); 60 this->setName("ResourceManager"); 61 62 this->dataDir = "./"; 63 this->tryDataDir("./data"); 27 /// Definition of the ResourceManager's ObjectList. 28 ObjectListDefinition(ResourceManager); 29 //! Singleton Reference to the ResourceManager 30 ResourceManager* ResourceManager::_singletonRef = NULL; 31 32 33 /** 34 * @brief standard constructor 35 */ 36 ResourceManager::ResourceManager () 37 : _defaultKeepLevel(0) 38 { 39 this->registerObject(this, ResourceManager::_objectList); 40 this->setName("ResourceManager"); 41 this->_mainGlobalPath = Directory("./"); 42 } 43 44 45 /** 46 * @brief standard destructor 47 */ 48 ResourceManager::~ResourceManager () 49 { 50 this->unloadAllBelowKeepLevel(this->_keepLevelNames.size()); 51 ResourceManager::_singletonRef = NULL; 52 } 53 54 /** 55 * @brief Registers a new Type to the ResourceManager. 56 * @param type the Type to register. 57 */ 58 void ResourceManager::registerType(Resources::Type* type) 59 { 60 this->_resourceTypes.push_back(type); 61 PRINTF(5)("ResourceType '%s' added\n", type->storedClassName().c_str()); 62 } 63 64 /** 65 * @brief Unregisters a new Type to the ResourceManager. 66 * @param type the Type to unregister. 67 */ 68 void ResourceManager::unregisterType(Resources::Type* type) 69 { 70 std::vector<Resources::Type*>::iterator it = std::find (this->_resourceTypes.begin(), this->_resourceTypes.end(), type); 71 if (it != this->_resourceTypes.end()) 72 { 73 this->_resourceTypes.erase(it); 74 PRINTF(5)("ResourceType '%s' removed\n", type->storedClassName().c_str()); 75 } 76 } 77 78 /** 79 * @brief Sets the main Global path (the main path Resources are searched for) 80 * @param directory the directory to set. 81 * @see Resource::locateFile 82 */ 83 void ResourceManager::setMainGlobalPath(const Directory& directory) 84 { 85 this->_mainGlobalPath = directory; 86 this->_mainGlobalPath.open(); 87 } 88 89 /** 90 * @brief add a Global search path. (global paths besided the main path.) 91 * @param directory a directory to add. 92 */ 93 void ResourceManager::addGlobalPath(const Directory& directory) 94 { 95 std::vector<Directory>::const_iterator it = std::find(this->_globalPaths.begin(), this->_globalPaths.end(), directory); 96 if (it == this->_globalPaths.end()) 97 this->_globalPaths.push_back(directory); 98 } 99 100 /** 101 * @brief add a ResourcePath to a Type's Paths. 102 * @param resourceName the Type's name of Resource to add the path to. 103 * @param pathName pathName the Name of the path to add. 104 * @return true on success. (if a path was added (no duplicate, and resourceName existed). 105 */ 106 bool ResourceManager::addResourcePath(const std::string& resourceName, const std::string& pathName) 107 { 108 std::vector<Resources::Type*>::iterator it; 109 for (it = this->_resourceTypes.begin(); it != this->_resourceTypes.end(); ++it) 110 if (*(*it) == resourceName) 111 return (*it)->addResourcePath(pathName); 112 PRINTF(2)("ResourcePath %s could not be added to the ResourceType %s\n", pathName.c_str(), resourceName.c_str()); 113 return false; 114 } 115 116 /** 117 * @brief add a ResourcePath to a Type's SubPaths. 118 * @param resourceName the Type's name of Resource to add the subpath to. 119 * @param pathName pathName the Name of the path to add. 120 * @return true on success. (if a path was added (no duplicate, and resourceName existed). 121 */ 122 bool ResourceManager::addResourceSubPath(const std::string& resourceName, const std::string& pathName) 123 { 124 std::vector<Resources::Type*>::iterator it; 125 for (it = this->_resourceTypes.begin(); it != this->_resourceTypes.end(); ++it) 126 if (*(*it) == resourceName) 127 return (*it)->addResourceSubPath(pathName); 128 PRINTF(2)("ResourceSubPath %s could not be added to the ResourceType %s\n", pathName.c_str(), resourceName.c_str()); 129 return false; 130 } 131 132 /** 133 * @brief checks wether a File is inside of the MainPath. 134 * @param fileInside the file to check 135 * @return true if the file is inside. 136 */ 137 bool ResourceManager::checkFileInMainPath(const File& fileInside) 138 { 139 return (this->_mainGlobalPath + fileInside).exists(); 140 } 141 142 /** 143 * @brief prepends the fileName by the MainGlobalPath (same as mainGlobalPath + '/' + fileName). 144 * @param fileName The FileName to prepend 145 * @returns the prepended file-name 146 */ 147 std::string ResourceManager::prependAbsoluteMainPath(const std::string& fileName) 148 { 149 return (this->_mainGlobalPath + File(fileName)).name(); 150 } 151 152 /** 153 * @brief add a KeepLevelName (this function just counts upwards). 154 * @param keepLevelName the Name of the KeepLevel to set. 155 * @returns the Level the Name was set to. 156 */ 157 unsigned int ResourceManager::addKeepLevelName(const std::string& keepLevelName) 158 { 159 this->_keepLevelNames.push_back(keepLevelName); 160 return _keepLevelNames.size()-1; 161 } 162 163 /** 164 * @param keepLevelName the Name of the KeepLevel. 165 * @returns the ID of the KeepLevel named keepLevelName 166 */ 167 unsigned int ResourceManager::getKeepLevelID(const std::string& keepLevelName) const 168 { 169 for (unsigned int i = 0; i < this->_keepLevelNames.size(); ++i) 170 if (this->_keepLevelNames[i] == keepLevelName) 171 return i; 172 173 PRINTF(2)("KeepLevel '%s' not found. Using 0 instead\n", keepLevelName.c_str()); 174 return 0; 175 } 176 177 /** 178 * @param keepLevelID the ID to check. 179 * @return the name of the KeepLevel. 180 */ 181 const std::string& ResourceManager::getKeepLevelName(unsigned int keepLevelID) const 182 { 183 assert(keepLevelID < this->_keepLevelNames.size()); 184 return this->_keepLevelNames[keepLevelID]; 185 } 186 187 188 /** 189 * @brief loads a Resource from a TypeName and a loadString. 190 * @param resourceTypeName The Name of the Type to what to load a Resource from. 191 * @param loadString the loadString to load in the Type. 192 */ 193 void ResourceManager::loadFromLoadString(const std::string& resourceTypeName, const std::string& loadString, const KeepLevel& keepLevel) 194 { 195 std::vector<Resources::Type*>::const_iterator it; 196 for (it = this->_resourceTypes.begin(); it != this->_resourceTypes.end(); ++it) 197 { 198 if (*(*it) == resourceTypeName) 199 { 200 (*it)->createFromString(loadString, keepLevel); 201 /// TODO check if the resource was allocated!! 202 return ; 203 } 204 } 205 return ; 206 } 207 208 /** 209 * @brief unloads all Resources below a certain threshhold. 210 * @param keepLevel the KeepLevel below which to erase. 211 * 212 * @not Resources will only be erased, if th keepLevel is below, and the resources are not 213 * referenced anymore. 214 */ 215 void ResourceManager::unloadAllBelowKeepLevel(const Resources::KeepLevel& keepLevel) 216 { 217 std::vector<Resources::Type*>::const_iterator it; 218 for (it = this->_resourceTypes.begin(); it != this->_resourceTypes.end(); ++it) 219 { 220 (*it)->unloadAllBelowKeepLevel(keepLevel); 221 } 222 } 223 224 225 /** 226 * @brief outputs debug information about the ResourceManager 227 */ 228 void ResourceManager::debug() const 229 { 230 PRINT(0)("/==RM================================\\\n"); 231 PRINT(0)("| RESOURCE-MANAGER DEBUG INFORMATION |\n"); 232 PRINT(0)("\\====================================/\n"); 233 PRINT(0)(" MainGlobal search path is %s\n", this->_mainGlobalPath.name().c_str()); 234 if(!this->_globalPaths.empty()) 235 { 236 PRINT(0)(" Additional Global search Paths are: "); 237 for (unsigned int i = 0; i < this->_globalPaths.size(); ++i) 238 PRINT(0)("'%s' ", this->_globalPaths[i].name().c_str()); 239 PRINT(0)("\n"); 240 } 241 PRINT(0)(" Listing %d Types: \n", this->_resourceTypes.size()); 242 std::vector<Resources::Type*>::const_iterator it; 243 for (it = this->_resourceTypes.begin(); it != this->_resourceTypes.end(); ++it) 244 { 245 (*it)->debug(); 246 if (it != --this->_resourceTypes.end()) 247 PRINT(0)(" ------------------------------------\n "); 248 } 249 250 PRINT(0)("KeepLevels are: "); 251 for (unsigned int i = 0; i < this->_keepLevelNames.size(); ++i) 252 PRINT(0)("%d:'%s' ", i, this->_keepLevelNames[i].c_str()); 253 PRINT(0)("\n"); 254 PRINT(0)("=================================RM==/\n"); 255 } 64 256 } 65 66 //! Singleton Reference to the ResourceManager67 ResourceManager* ResourceManager::singletonRef = NULL;68 69 /**70 * @brief standard destructor71 */72 ResourceManager::~ResourceManager ()73 {74 // deleting the Resources-List75 this->unloadAllByPriority(RP_GAME);76 77 if (!this->resourceList.empty())78 PRINTF(1)("Not removed all Resources, since there are still %d resources registered\n", this->resourceList.size());79 80 ResourceManager::singletonRef = NULL;81 }82 83 /**84 * @brief sets the data main directory85 * @param dataDir the DataDirectory.86 */87 bool ResourceManager::setDataDir(const std::string& dataDir)88 {89 File dataDirectory(dataDir);90 if (dataDirectory.isDirectory())91 {92 this->dataDir = dataDirectory.name();93 94 if (dataDir[dataDir.size()-1] != '/' && dataDir[dataDir.size()-1] != '\\')95 {96 this->dataDir += '/';97 }98 return true;99 }100 else101 {102 PRINTF(1)("%s is not a Directory, and can not be the Data Directory, leaving as %s \n", dataDir.c_str(), this->dataDir.c_str());103 return false;104 }105 }106 107 /**108 * @brief sets the data main directory109 * @param dataDir the DataDirectory.110 *111 * this is essentially the same as setDataDir, but it ommits the error-message112 */113 bool ResourceManager::tryDataDir(const std::string& dataDir)114 {115 File dataDirectory(dataDir);116 if (dataDirectory.isDirectory())117 {118 this->dataDir = dataDirectory.name();119 120 if (dataDir[dataDir.size()-1] != '/' && dataDir[dataDir.size()-1] != '\\')121 {122 this->dataDir += '/';123 }124 return true;125 }126 return false;127 }128 129 130 /**131 * @brief checks for the DataDirectory, by looking if132 * @param fileInside is iniside of the given directory.133 */134 bool ResourceManager::verifyDataDir(const std::string& fileInside)135 {136 File dataDirectory(this->dataDir);137 if (!dataDirectory.isDirectory())138 {139 PRINTF(1)("'%s' is not a directory\n", this->dataDir.c_str());140 return false;141 }142 143 File testFile(this->dataDir + fileInside);144 return testFile.isFile();145 }146 147 #ifndef NO_TEXTURES148 /**149 * @brief adds a new Path for Images150 * @param imageDir The path to insert151 * @returns true, if the Path was well and injected (or already existent within the list)152 false otherwise153 */154 bool ResourceManager::addImageDir(const std::string& imageDir)155 {156 std::string newDir = imageDir;157 if (imageDir[imageDir.size()-1] != '/' && imageDir[imageDir.size()-1] != '\\')158 {159 newDir += '/';160 }161 // check if the param is a Directory162 if (File(newDir).isDirectory())163 {164 // check if the Directory has been added before165 std::vector<std::string>::const_iterator imageDir;166 for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)167 {168 if (*imageDir == newDir)169 {170 PRINTF(3)("Path %s already loaded\n", newDir.c_str());171 return true;172 }173 }174 // adding the directory to the List175 this->imageDirs.push_back(newDir);176 return true;177 }178 else179 {180 PRINTF(1)("%s is not a Directory, and can not be added to the Paths of Images\n", newDir.c_str());181 return false;182 }183 }184 #endif /* NO_TEXTURES */185 186 /**187 * @brief loads resources188 * @param fileName: The fileName of the resource to load189 * @param prio: The ResourcePriority of this resource (will only be increased)190 * @param param0: an additional option to parse (see the constuctors for more help)191 * @param param1: an additional option to parse (see the constuctors for more help)192 * @param param2: an additional option to parse (see the constuctors for more help)193 * @returns a pointer to a desired Resource.194 */195 BaseObject* ResourceManager::load(const std::string& fileName, ResourcePriority prio,196 const MultiType& param0, const MultiType& param1, const MultiType& param2)197 {198 ResourceType tmpType;199 #ifndef NO_MODEL200 #define __IF_OK201 if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".obj", 4))202 tmpType = OBJ;203 else if (!strncmp(fileName.c_str()+(fileName.size()-4), ".md2", 4))204 tmpType = MD2;205 else if (!strncmp(fileName.c_str()+(fileName.size()-4), ".md3", 4))206 tmpType = MD3;207 else if (!strncmp(fileName.c_str()+(fileName.size()-4), ".cfg", 4))208 tmpType = MD3_CONFIG;209 else if (!strcasecmp(fileName.c_str(), "cube") ||210 !strcasecmp(fileName.c_str(), "sphere") ||211 !strcasecmp(fileName.c_str(), "plane") ||212 !strcasecmp(fileName.c_str(), "cylinder") ||213 !strcasecmp(fileName.c_str(), "cone"))214 tmpType = PRIM;215 #endif /* NO_MODEL */216 #ifndef NO_AUDIO217 #ifdef __IF_OK218 else219 #endif220 #define __IF_OK221 if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".wav", 4))222 tmpType = WAV;223 else if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".mp3", 4))224 tmpType = MP3;225 else if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".ogg", 4))226 tmpType = OGG;227 #endif /* NO_AUDIO */228 #ifndef NO_TEXT229 #ifdef __IF_OK230 else231 #endif232 #define __IF_OK233 if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".ttf", 4))234 tmpType = TTF;235 #endif /* NO_TEXT */236 #ifndef NO_SHADERS237 #ifdef __IF_OK238 else239 #endif240 #define __IF_OK241 if (!strncasecmp(fileName.c_str()+(fileName.size()-5), ".vert", 5))242 tmpType = SHADER;243 #endif /* NO_SHADERS */244 #ifndef NO_TEXTURES245 #ifdef __IF_OK246 else247 #else248 if249 #endif250 tmpType = IMAGE;251 #endif /* NO_TEXTURES */252 #undef __IF_OK253 return this->load(fileName, tmpType, prio, param0, param1, param2);254 }255 256 /**257 * @brief caches a Resource258 *259 * @see load;260 *261 * @brief returns true if ok, false otherwise.262 * This function loads a Resource without applying it to an Object.263 * This is for loading purposes, e.g, when the user is loading a Resource264 * during the initialisation instead of at Runtime.265 */266 bool ResourceManager::cache(const std::string& fileName, ResourceType type, ResourcePriority prio,267 const MultiType& param0, const MultiType& param1, const MultiType& param2)268 {269 // searching if the resource was loaded before.270 Resource* tmpResource;271 // check if we already loaded this Resource272 tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);273 // otherwise load it274 if (tmpResource == NULL)275 tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);276 // return cached pointer.277 if (tmpResource != NULL) // if the resource was loaded before.278 {279 if(tmpResource->prio < prio)280 tmpResource->prio = prio;281 return true;282 }283 else284 return false;285 }286 287 /**288 * tells the ResourceManager to generate a Copy of the Resource.289 * @brief resourcePointer: The Pointer to the resource to copy290 * @returns the Resource pointed to resourcePointer.291 */292 BaseObject* ResourceManager::copy(BaseObject* resourcePointer)293 {294 Resource* tmp = locateResourceByPointer(resourcePointer);295 if (tmp!=NULL)296 {297 tmp->count++;298 return tmp->pointer;299 }300 else301 return NULL;302 }303 304 305 /**306 * @brief loads resources307 * @param fileName: The fileName of the resource to load308 * @param type: The Type of Resource to load.309 * @param prio: The ResourcePriority of this resource (will only be increased)310 * @param param0: an additional option to parse (see the constuctors for more help)311 * @param param1: an additional option to parse (see the constuctors for more help)312 * @param param2: an additional option to parse (see the constuctors for more help)313 * @returns a pointer to a desired Resource.314 */315 BaseObject* ResourceManager::load(const std::string& fileName, ResourceType type, ResourcePriority prio,316 const MultiType& param0, const MultiType& param1, const MultiType& param2)317 {318 319 // searching if the resource was loaded before.320 Resource* tmpResource;321 // check if we already loaded this Resource322 tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);323 // otherwise load it324 if (tmpResource == NULL)325 {326 tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);327 }328 // return cached pointer.329 if (tmpResource != NULL) // if the resource was loaded before.330 {331 tmpResource->count++;332 if(tmpResource->prio < prio)333 tmpResource->prio = prio;334 335 return tmpResource->pointer;336 }337 else338 return NULL;339 }340 341 342 /**343 * @brief loads resources for internal purposes344 * @param fileName: The fileName of the resource to load345 * @param type: The Type of Resource to load.346 * @param prio: The ResourcePriority of this resource (will only be increased)347 * @param param0: an additional option to parse (see the constuctors for more help)348 * @param param1: an additional option to parse (see the constuctors for more help)349 * @param param2: an additional option to parse (see the constuctors for more help)350 * @returns a pointer to a desired Resource.351 */352 Resource* ResourceManager::loadResource(const std::string& fileName, ResourceType type, ResourcePriority prio,353 const MultiType& param0, const MultiType& param1, const MultiType& param2)354 {355 // Setting up the new Resource356 Resource* tmpResource = new Resource;357 tmpResource->count = 0;358 tmpResource->type = type;359 tmpResource->prio = prio;360 tmpResource->pointer = NULL;361 tmpResource->name = fileName;362 363 // creating the full name. (directoryName + FileName)364 std::string fullName = ResourceManager::getFullName(fileName);365 // Checking for the type of resource \see ResourceType366 switch(type)367 {368 #ifndef NO_MODEL369 case OBJ:370 if (param0.getType() != MT_NULL)371 tmpResource->param[0] = param0;372 else373 tmpResource->param[0] = 1.0f;374 375 if(File(fullName).isFile())376 tmpResource->pointer = new OBJModel(fullName, tmpResource->param[0].getFloat());377 else378 {379 PRINTF(2)("File %s in %s does not exist. Loading a cube-Model instead\n", fileName.c_str(), dataDir.c_str());380 tmpResource->pointer = ResourceManager::load("cube", PRIM, prio, tmpResource->param[0].getFloat());381 }382 break;383 case PRIM:384 if (param0 != MT_NULL)385 tmpResource->param[0] = param0;386 else387 tmpResource->param[0] = 1.0f;388 389 if (tmpResource->name == "cube")390 tmpResource->pointer = new PrimitiveModel(PRIM_CUBE, tmpResource->param[0].getFloat());391 else if (tmpResource->name == "sphere")392 tmpResource->pointer = new PrimitiveModel(PRIM_SPHERE, tmpResource->param[0].getFloat());393 else if (tmpResource->name == "plane")394 tmpResource->pointer = new PrimitiveModel(PRIM_PLANE, tmpResource->param[0].getFloat());395 else if (tmpResource->name == "cylinder")396 tmpResource->pointer = new PrimitiveModel(PRIM_CYLINDER, tmpResource->param[0].getFloat());397 else if (tmpResource->name == "cone")398 tmpResource->pointer = new PrimitiveModel(PRIM_CONE, tmpResource->param[0].getFloat());399 break;400 case MD2:401 if(File(fullName).isFile())402 {403 tmpResource->param[0] = param0;404 tmpResource->param[1] = param1;405 tmpResource->pointer = new MD2Data(fullName, tmpResource->param[0].getCString(), tmpResource->param[1].getFloat());406 }407 break;408 case MD3:409 if(File(fullName).isFile())410 {411 tmpResource->param[0] = param0;412 tmpResource->param[1] = param1;413 tmpResource->pointer = new md3::MD3Data(fullName, tmpResource->param[0].getCString(), tmpResource->param[1].getFloat());414 }415 break;416 case MD3_CONFIG:417 if(File(fullName).isFile())418 {419 tmpResource->param[0] = param0;420 tmpResource->param[1] = param1;421 tmpResource->pointer = new md3::MD3AnimationCfg(fullName);422 }423 break;424 #endif /* NO_MODEL */425 #ifndef NO_TEXT426 case TTF:427 if (param0 != MT_NULL)428 {429 assert(param0.getInt() >= 0);430 tmpResource->param[0] = param0;431 }432 else433 tmpResource->param[0] = FONT_DEFAULT_RENDER_SIZE;434 435 if(File(fullName).isFile())436 tmpResource->pointer = new Font(fullName, (unsigned int) tmpResource->param[0].getInt());437 else438 PRINTF(2)("%s does not exist in %s. Not loading Font\n", fileName.c_str(), this->dataDir.c_str());439 break;440 #endif /* NO_TEXT */441 #ifndef NO_AUDIO442 case WAV:443 if(File(fullName).isFile())444 tmpResource->pointer = new OrxSound::SoundBuffer(fullName);445 break;446 case OGG:447 if (File(fullName).isFile())448 tmpResource->pointer = new OrxSound::OggPlayer(fullName);449 break;450 #endif /* NO_AUDIO */451 #ifndef NO_TEXTURES452 case IMAGE:453 if (param0 != MT_NULL)454 tmpResource->param[0] = param0;455 else456 tmpResource->param[0] = GL_TEXTURE_2D;457 if(File(fullName).isFile())458 {459 PRINTF(4)("Image %s resides to %s\n", fileName.c_str(), fullName.c_str());460 tmpResource->pointer = new Texture(fullName, tmpResource->param[0].getInt());461 }462 else463 {464 std::vector<std::string>::iterator imageDir;465 for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)466 {467 std::string imgName = *imageDir + fileName;468 if(File(imgName).isFile())469 {470 PRINTF(4)("Image %s resides to %s\n", fileName.c_str(), imgName.c_str());471 tmpResource->pointer = new Texture(imgName, tmpResource->param[0].getInt());472 break;473 }474 }475 }476 if(!tmpResource)477 PRINTF(2)("!!Image %s not Found!!\n", fileName.c_str());478 break;479 #endif /* NO_TEXTURES */480 #ifndef NO_SHADERS481 case SHADER:482 if(File(fullName).isFile())483 {484 if (param0 != MT_NULL)485 {486 MultiType param = param0; /// HACK487 std::string secFullName = ResourceManager::getFullName(param.getCString());488 if (File(secFullName).isFile())489 {490 tmpResource->param[0] = secFullName;491 tmpResource->pointer = new Shader(fullName, secFullName);492 }493 }494 else495 {496 tmpResource->param[0] = param0;497 tmpResource->pointer = new Shader(fullName, "");498 }499 }500 break;501 #endif /* NO_SHADERS */502 default:503 tmpResource->pointer = NULL;504 PRINTF(1)("No type found for %s.\n !!This should not happen unless the Type is not supported yet. JUST DO IT!!\n", tmpResource->name.c_str());505 break;506 }507 if (tmpResource->pointer != NULL)508 this->resourceList.push_back(tmpResource);509 510 if (tmpResource->pointer != NULL)511 return tmpResource;512 else513 {514 PRINTF(2)("Resource %s could not be loaded\n", fileName.c_str());515 delete tmpResource;516 return NULL;517 }518 }519 520 /**521 * @brief unloads a Resource522 * @param pointer: The pointer to free523 * @param prio: the PriorityLevel to unload this resource524 * @returns true if successful (pointer found, and deleted), false otherwise525 */526 bool ResourceManager::unload(BaseObject* pointer, ResourcePriority prio)527 {528 if (pointer == NULL)529 return false;530 // if pointer is existent. and only one resource of this type exists.531 Resource* tmpResource = this->locateResourceByPointer(pointer);532 if (tmpResource != NULL)533 return unload(tmpResource, prio);534 else535 {536 PRINTF(2)("Resource not Found %p\n", pointer);537 return false;538 }539 }540 541 /**542 * @brief unloads a Resource543 * @param resource: The resource to unloade544 * @param prio the PriorityLevel to unload this resource545 * @returns true on success, false otherwise.546 */547 bool ResourceManager::unload(Resource* resource, ResourcePriority prio)548 {549 if (resource == NULL)550 return false;551 if (resource->count > 0)552 resource->count--;553 554 if (resource->prio <= prio)555 {556 if (resource->count == 0)557 {558 delete resource->pointer;559 // deleting the List Entry:560 PRINTF(4)("Resource %s safely removed.\n", resource->name.c_str());561 std::vector<Resource*>::iterator resourceIT = std::find(this->resourceList.begin(), this->resourceList.end(), resource);562 this->resourceList.erase(resourceIT);563 delete resource;564 }565 else566 PRINTF(4)("Resource %s not removed, because there are still %d References to it.\n", resource->name.c_str(), resource->count);567 }568 else569 PRINTF(4)("not deleting resource %s because DeleteLevel to high\n", resource->name.c_str());570 return true;571 }572 573 574 /**575 * @brief unloads all alocated Memory of Resources with a pririty lower than prio576 * @param prio The priority to delete577 */578 bool ResourceManager::unloadAllByPriority(ResourcePriority prio)579 {580 bool removedAll = true;581 unsigned int removeCount;582 for (unsigned int round = 0; round < 3; round++)583 {584 int index = this->resourceList.size() - 1;585 removeCount = 0;586 while (index >= 0)587 {588 if (this->resourceList[index]->prio <= prio)589 {590 if (this->resourceList[index]->count == 0)591 unload(this->resourceList[index], prio);592 else593 {594 if (round == 3)595 {596 PRINTF(2)("unable to unload %s because there are still %d references to it\n",597 this->resourceList[index]->name.c_str(), this->resourceList[index]->count);598 removedAll = false;599 }600 removeCount++;601 }602 }603 index--;604 }605 if (removeCount == 0) break;606 }607 return removedAll;608 }609 610 611 /**612 * @brief Searches for a Resource by some information613 * @param fileName: The name to look for614 * @param type the Type of resource to locate.615 * @param param0: an additional option to parse (see the constuctors for more help)616 * @param param1: an additional option to parse (see the constuctors for more help)617 * @param param2: an additional option to parse (see the constuctors for more help)618 * @returns a Pointer to the Resource if found, NULL otherwise.619 */620 Resource* ResourceManager::locateResourceByInfo(const std::string& fileName, ResourceType type,621 const MultiType& param0, const MultiType& param1, const MultiType& param2) const622 {623 std::vector<Resource*>::const_iterator resource;624 for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)625 {626 if ((*resource)->type == type && fileName == (*resource)->name)627 {628 bool match = false;629 switch (type)630 {631 #ifndef NO_MODEL632 case PRIM:633 case OBJ:634 if (param0 == MT_NULL)635 {636 if ((*resource)->param[0] == 1.0f)637 match = true;638 }639 else if ((*resource)->param[0] == param0.getFloat())640 match = true;641 break;642 case MD2:643 if (param0 == MT_NULL && ((*resource)->param[0] == "") && param1 == MT_NULL && ((*resource)->param[0] == 1.0f))644 match = true;645 else if ((*resource)->param[0] == ((MultiType)param0).getString() && (*resource)->param[1] == ((MultiType)param1).getFloat())646 match = true;647 break;648 case MD3:649 if (param0 == MT_NULL && ((*resource)->param[0] == "") && param1 == MT_NULL && ((*resource)->param[0] == 1.0f))650 match = true;651 else if ((*resource)->param[0] == ((MultiType)param0).getString() && (*resource)->param[1] == ((MultiType)param1).getFloat())652 match = true;653 break;654 case MD3_CONFIG:655 if (param0 == MT_NULL && ((*resource)->param[0] == ""))656 match = true;657 else if ((*resource)->param[0] == ((MultiType)param0).getString())658 match = true;659 break;660 661 #endif /* NO_MODEL */662 #ifndef NO_TEXT663 case TTF:664 if (param0 == MT_NULL)665 {666 if ((*resource)->param[0] == FONT_DEFAULT_RENDER_SIZE)667 match = true;668 }669 else if ((*resource)->param[0] == param0.getInt())670 match = true;671 break;672 #endif /* NO_TEXT */673 #ifndef NO_SHADERS674 case SHADER:675 if (param0 == MT_NULL)676 {677 if ((*resource)->param[0] == "")678 match = true;679 }680 else if ((*resource)->param[0] == ((MultiType)param0).getString())681 match = true;682 break;683 #endif /* NO_SHADERS */684 #ifndef NO_TEXTURES685 case IMAGE:686 if (param0 == MT_NULL)687 {688 if ((*resource)->param[0] == GL_TEXTURE_2D)689 match = true;690 }691 else if ((*resource)->param[0] == param0.getInt())692 match = true;693 break;694 #endif /* NO_TEXTURES */695 default:696 match = true;697 break;698 }699 if (match)700 {701 return (*resource);702 }703 }704 }705 return NULL;706 }707 708 /**709 * @brief Searches for a Resource by Pointer710 * @param pointer the Pointer to search for711 * @returns a Pointer to the Resource if found, NULL otherwise.712 */713 Resource* ResourceManager::locateResourceByPointer(const void* pointer) const714 {715 // Resource* enumRes = resourceList->enumerate();716 std::vector<Resource*>::const_iterator resource;717 for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)718 if (pointer == (*resource)->pointer)719 return (*resource);720 return NULL;721 }722 723 std::string ResourceManager::toResourcableString(unsigned int i)724 {725 /* int len = strlen(ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));726 len += this->resourceList[i]->name.size();727 if (this->resourceList[i]->param[0].getCString()) len += strlen(this->resourceList[i]->param[0].getCString()) +1;728 if (this->resourceList[i]->param[1].getCString()) len += strlen(this->resourceList[i]->param[1].getCString()) +1;729 if (this->resourceList[i]->param[2].getCString()) len += strlen(this->resourceList[i]->param[2].getCString()) +1;730 len += 10;731 std::string tmp = new char[len];732 tmp[0] = '\0';733 strcat(tmp, ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));734 strcat(tmp,",");735 strcat (tmp, this->resourceList[i]->name);736 if (this->resourceList[i]->param[0].getCString() && this->resourceList[i]->param[0].getCString() != '\0')737 {738 strcat(tmp,",");739 strcat( tmp, this->resourceList[i]->param[0].getCString());740 }741 if (this->resourceList[i]->param[1].getCString() && this->resourceList[i]->param[1].getCString() != '\0')742 {743 strcat(tmp,",");744 strcat( tmp, this->resourceList[i]->param[1].getCString());745 }746 if (this->resourceList[i]->param[2].getCString() && this->resourceList[i]->param[2].getCString() != '\0')747 {748 strcat(tmp,",");749 strcat( tmp, this->resourceList[i]->param[2].getCString());750 }751 return tmp;*/752 return "";753 }754 755 /**756 * @brief caches a Resource from a ResourceableString created with the toResourcableString-function757 * @param resourceableString the String to cache the resource from.758 */759 bool ResourceManager::fromResourceableString(const std::string& resourceableString)760 {761 /* SubString splits(resourceableString, ',');762 splits.debug();763 if (splits.getCount() == 2)764 this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),765 RP_LEVEL);766 else if (splits.getCount() == 3)767 return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),768 RP_LEVEL, splits[2]);769 else if (splits.getCount() == 4)770 return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),771 RP_LEVEL, splits[2], splits[3]);772 else if (splits.getCount() == 5)773 return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),774 RP_LEVEL, splits[2], splits[3], splits[4]);*/775 return false;776 }777 778 779 /**780 * @param fileName the Name of the File to check781 * @returns The full name of the file, including the DataDir, and NULL if the file does not exist782 * !!IMPORTANT: this has to be deleted from the outside!!783 */784 std::string ResourceManager::getFullName(const std::string& fileName)785 {786 if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())787 return "";788 789 std::string retName = ResourceManager::getInstance()->getDataDir() +fileName;790 if (File(retName).isFile() || File(retName).isDirectory())791 return retName;792 else793 return "";794 }795 796 797 /**798 * @brief checks wether a file is in the DataDir.799 * @param fileName the File to check if it is in the Data-Dir structure.800 * @returns true if the file exists, false otherwise801 */802 bool ResourceManager::isInDataDir(const std::string& fileName)803 {804 if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())805 return false;806 807 bool retVal = false;808 std::string checkFile = ResourceManager::getInstance()->getDataDir() + fileName;809 810 if (File(checkFile).exists())811 retVal = true;812 else813 retVal = false;814 return retVal;815 }816 817 818 /**819 * @brief outputs debug information about the ResourceManager820 */821 void ResourceManager::debug() const822 {823 PRINT(0)("=RM===================================\n");824 PRINT(0)("= RESOURCE-MANAGER DEBUG INFORMATION =\n");825 PRINT(0)("======================================\n");826 // if it is not initialized827 PRINT(0)(" Reference is: %p\n", ResourceManager::singletonRef);828 PRINT(0)(" Data-Directory is: %s\n", this->dataDir.c_str());829 PRINT(0)(" List of Image-Directories: ");830 std::vector<std::string>::const_iterator imageDir;831 for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)832 PRINT(0)("%s ", (*imageDir).c_str());833 PRINT(0)("\n");834 835 PRINT(0)("List of all stored Resources:\n");836 std::vector<Resource*>::const_iterator resource;837 for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)838 839 {840 PRINT(0)("-----------------------------------------\n");841 PRINT(0)("Name: %s; References: %d; Type: %s ", (*resource)->name.c_str(), (*resource)->count, ResourceManager::ResourceTypeToChar((*resource)->type));842 843 PRINT(0)("gets deleted at ");844 switch((*resource)->prio)845 {846 default:847 case RP_NO:848 PRINT(0)("first posibility (0)\n");849 break;850 case RP_LEVEL:851 PRINT(0)("the end of the Level (1)\n");852 break;853 case RP_CAMPAIGN:854 PRINT(0)("the end of the campaign (2)\n");855 break;856 case RP_GAME:857 PRINT(0)("when leaving the game (3)\n");858 break;859 }860 }861 862 863 864 PRINT(0)("==================================RM==\n");865 }866 867 868 /**869 * @brief converts a ResourceType into the corresponding String870 * @param type the ResourceType to translate871 * @returns the converted String.872 */873 const char* ResourceManager::ResourceTypeToChar(ResourceType type)874 {875 return ResourceManager::resourceNames[type];876 }877 878 /**879 * @brief converts a String into a ResourceType (good for loading)880 * @param resourceType the name of the Type881 * @returns the Number of the Type, or 0 (defautl) if not found.882 */883 ResourceType ResourceManager::stringToResourceType(const std::string& resourceType)884 {885 for (unsigned int i = 0; i < RESOURCE_TYPE_SIZE; i++)886 if (resourceType == ResourceManager::resourceNames[i])887 return (ResourceType)i;888 return (ResourceType)0;889 }890 891 /**892 * The Names of the ResourceTypes893 */894 const char* ResourceManager::resourceNames[] =895 {896 #ifndef NO_MODEL897 "ObjectModel",898 "PrimitiveModel",899 "MD2-Data",900 "MD3-Data",901 "MD3-Config"902 #endif903 #ifndef NO_TEXT904 "Font",905 #endif906 #ifndef NO_AUDIO907 "Wav",908 "mp3",909 "ogg",910 #endif911 #ifndef NO_TEXTURES912 "Texture",913 #endif914 #ifndef NO_SHADERS915 "Shader",916 #endif917 918 }; -
trunk/src/lib/util/loading/resource_manager.h
r8724 r9869 1 1 /*! 2 2 * @file resource_manager.h 3 * The Resource Manager checks if a file/resource is loaded. 4 5 If a file/resource was already loaded the resourceManager will 6 return a void pointer to the desired resource. 7 Otherwise it will instruct the coresponding resource-loader to load, 8 and receive a pointer to it. 9 10 it is possible to compile the resource Manager without some modules by 11 just adding the compile flag -D.... 12 (NO_MODEL) 13 (NO_AUDIO) 14 (NO_TEXT) 15 (NO_TEXTURES) 16 (NO_SHADERS) 17 */ 3 */ 18 4 19 5 #ifndef _RESOURCE_MANAGER_H 20 6 #define _RESOURCE_MANAGER_H 21 7 22 #include " base_object.h"8 #include "resource.h" 23 9 #include "filesys/file.h" 10 #include "filesys/directory.h" 24 11 25 #include "multi_type.h" 26 #include <vector> 12 namespace Resources 13 { 27 14 28 //! An eumerator for different fileTypes the resourceManager supports 29 typedef enum ResourceType 30 { 31 #ifndef NO_MODEL 32 OBJ, //!< loading .obj file 33 PRIM, //!< loading primitive model 34 MD2, //!< loading md2-file 35 MD3, //!< loading md3-file 36 MD3_CONFIG, //!< the md3 config file 37 #endif /* NO_MODEL */ 38 #ifndef NO_TEXT 39 TTF, //!< loading a TrueTypeFont 40 #endif /* NO_TEXT */ 41 #ifndef NO_AUDIO 42 WAV, //!< loading wav 43 MP3, //!< loading mp3 44 OGG, //!< loading ogg 45 #endif /* NO_AUDIO */ 46 #ifndef NO_TEXTURES 47 IMAGE, //!< loading an image 48 #endif /* NO_TEXTURES */ 49 #ifndef NO_SHADERS 50 SHADER, //!< openGL-shader program 51 #endif /* NO_SHADERS */ 52 RESOURCE_TYPE_SIZE 53 }; 15 class ResourceManager : public BaseObject 16 { 17 ObjectListDeclaration(ResourceManager); 18 public: 19 /////////////////////// 20 //// INSTANZIATION //// 21 /** @returns a Pointer to the only object of this Class */ 22 inline static ResourceManager* getInstance() { if (!_singletonRef) _singletonRef = new ResourceManager(); return _singletonRef; }; 23 /** @brief deletes the Instance if it exists. */ 24 inline static void deleteInstance() { if (_singletonRef) delete _singletonRef; }; 54 25 55 //! An enumerator for different UNLOAD-types. 56 /** 57 RP_NO: will be unloaded on request 58 RP_LEVEL: will be unloaded at the end of a Level 59 RP_CAMPAIGN: will be unloaded at the end of a Campaign 60 RP_GAME: will be unloaded at the end of the whole Game (when closing orxonox) 61 */ 62 typedef enum ResourcePriority 63 { 64 RP_NO = 0, 65 RP_LEVEL = 1, 66 RP_CAMPAIGN = 2, 67 RP_GAME = 4 68 }; 26 //////////////////////// 27 //// RESOURCE PATHS //// 28 void setMainGlobalPath(const Directory& directory); 29 void addGlobalPath(const Directory& directory); 69 30 70 //! A Struct that keeps track about a resource its name its Type, and so on 71 struct Resource 72 { 73 BaseObject* pointer; //!< Pointer to the Resource. 74 unsigned int count; //!< How many times this Resource has been loaded. 31 bool addResourcePath(const std::string& resourceName, const std::string& pathName); 32 bool addResourceSubPath(const std::string& resourceName, const std::string& pathName); 33 void registerType(Resources::Type* type); 34 void unregisterType(Resources::Type* type); 75 35 76 std::string name; //!< Name of the Resource. 77 ResourceType type; //!< ResourceType of this Resource. 78 ResourcePriority prio; //!< The Priority of this resource. (This will only be increased) 36 /** @returns the main global search Path */ 37 const Directory& mainGlobalPath() const { return _mainGlobalPath; }; 38 /** @returns all global paths without mainGlobalPath */ 39 const std::vector<Directory>& globalPaths() const { return _globalPaths; }; 79 40 80 MultiType param[3]; //!< The Parameters given to this Resource. 81 }; 41 //////////////////// 42 //// KEEPLEVELS //// 43 unsigned int addKeepLevelName(const std::string& keepLevelName); 44 unsigned int getKeepLevelID(const std::string& keepLevelName) const; 45 const std::string& getKeepLevelName(unsigned int keepLevelID) const; 46 void setDefaultKeepLevel(const KeepLevel& keepLevel) { this->_defaultKeepLevel = keepLevel; }; 47 const KeepLevel& defaultKeepLevel() const { return this->_defaultKeepLevel; }; 82 48 49 ////////////////////////// 50 //// GENERAL QUERIES //// 51 /** @returns the Types of Resources */ 52 const std::vector<Resources::Type*> resourceTypes() const { return _resourceTypes; }; 83 53 84 //! The ResourceManager is a class, that decides if a file/resource should be loaded 85 /** 86 * If a file/resource was already loaded the resourceManager will 87 * return a pointer to the desired resource. 88 * Otherwise it will instruct the corresponding resource-loader to load, 89 * and receive the pointer to it. 90 * 91 * It does it by looking, if a desired file has already been loaded. 92 * There is also the possibility to check for some variables 93 */ 94 class ResourceManager : public BaseObject 95 { 96 public: 97 virtual ~ResourceManager(); 98 /** @returns a Pointer to the only object of this Class */ 99 inline static ResourceManager* getInstance() { if (!singletonRef) singletonRef = new ResourceManager(); return singletonRef; }; 54 bool checkFileInMainPath(const File& fileInside); 55 std::string prependAbsoluteMainPath(const std::string& fileName); 100 56 101 bool setDataDir(const std::string& dataDir); 102 /** @returns the Name of the data directory */ 103 inline const std::string& getDataDir() const { return this->dataDir; }; 57 //////////////////////////////////////// 58 //// RESOURCE LOADING AND UNLOADING //// 59 void loadFromLoadString(const std::string& resourceTypeName, const std::string& loadString, const KeepLevel& keepLevel = KeepLevel()); 60 void loadFromLoadStringHACK(const std::string& resourceTypeName, const std::string& loadString) { this->loadFromLoadString(resourceTypeName, loadString); }; 104 61 62 void unloadAllBelowKeepLevel(const Resources::KeepLevel& keepLevel); 63 void unloadAllBelowKeepLevelINT(unsigned int level) { unloadAllBelowKeepLevel(level); }; 105 64 106 bool tryDataDir(const std::string& dataDir);107 bool verifyDataDir(const std::string& fileInside);108 bool addImageDir(const std::string& imageDir);65 /////////////// 66 //// DEBUG //// 67 void debug() const; 109 68 110 bool cache(const std::string& fileName, ResourceType type, ResourcePriority prio = RP_NO,111 const MultiType& param0 = MultiType(), const MultiType& param1 = MultiType(), const MultiType& param2 = MultiType());112 BaseObject* copy(BaseObject* resourcePointer);69 private: 70 ResourceManager(); 71 virtual ~ResourceManager(); 113 72 114 BaseObject* load(const std::string& fileName, ResourcePriority prio = RP_NO, 115 const MultiType& param0 = MultiType(), const MultiType& param1 = MultiType(), const MultiType& param2 = MultiType()); 116 BaseObject* load(const std::string& fileName, ResourceType type, ResourcePriority prio = RP_NO, 117 const MultiType& param0 = MultiType(), const MultiType& param1 = MultiType(), const MultiType& param2 = MultiType()); 118 bool unload(BaseObject* pointer, ResourcePriority prio = RP_NO); 119 bool unload(Resource* resource, ResourcePriority = RP_NO); 120 bool unloadAllByPriority(ResourcePriority prio); 73 private: 74 static ResourceManager* _singletonRef; //!< singleton Reference 121 75 122 Resource* locateResourceByInfo(const std::string& fileName, ResourceType type, 123 const MultiType& param0 = MultiType(), const MultiType& param1 = MultiType(), const MultiType& param2 = MultiType()) const; 124 Resource* locateResourceByPointer(const void* pointer) const; 76 Directory _mainGlobalPath; //!< The main include directory (default at "./") 77 std::vector<Directory> _globalPaths; //!< Additional Global include directories. 125 78 126 std::string toResourcableString(unsigned int i); 127 bool fromResourceableString(const std::string& resourceableString); 128 /** @returns the Count of Resources the ResourceManager handles */ 129 unsigned int resourceCount() const { return this->resourceList.size(); } 79 std::vector<Resources::Type*> _resourceTypes; //!< A Vector of all the stored ResourceTypes @see Resources::Type 130 80 131 void debug() const; 81 std::vector<std::string> _keepLevelNames; //!< Names of KeepLevels @see Resources::KeepLevel 82 KeepLevel _defaultKeepLevel; //!< The default KeepLevel. 83 }; 132 84 133 134 // utility functions for handling files in and around the data-directory 135 static std::string getFullName(const std::string& fileName); 136 static bool isInDataDir(const std::string& fileName); 137 138 static const char* ResourceTypeToChar(ResourceType type); 139 static ResourceType stringToResourceType(const std::string& resourceType); 140 141 private: 142 ResourceManager(); 143 Resource* loadResource(const std::string& fileName, ResourceType type, ResourcePriority prio, 144 const MultiType& param0, const MultiType& param1, const MultiType& param2); 145 146 private: 147 static ResourceManager* singletonRef; //!< singleton Reference 148 149 std::string dataDir; //!< The Data Directory, where all relevant Data is stored. 150 std::vector<std::string> imageDirs; //!< A list of directories in which images are stored. 151 152 std::vector<Resource*> resourceList; //!< The List of Resources, that has already been loaded. 153 154 static const char* resourceNames[RESOURCE_TYPE_SIZE]; 155 }; 85 } 156 86 157 87 #endif /* _RESOURCE_MANAGER_H */ -
trunk/src/lib/util/multi_type.cc
r9406 r9869 33 33 { 34 34 default: 35 36 35 this->value.Float = 0.0f; 36 break; 37 37 case MT_BOOL: 38 39 38 this->value.Bool = false; 39 break; 40 40 case MT_INT: 41 42 41 this->value.Int = 0; 42 break; 43 43 case MT_FLOAT: 44 45 44 this->value.Float = 0.0f; 45 break; 46 46 case MT_CHAR: 47 48 47 this->value.Char = '\0'; 48 break; 49 49 case MT_STRING: 50 51 50 this->storedString = ""; 51 break; 52 52 } 53 53 } … … 142 142 { 143 143 case MT_NULL: 144 144 return true; 145 145 case MT_BOOL: 146 146 return (this->value.Bool == mt.value.Bool); 147 147 case MT_INT: 148 148 return (this->value.Int == mt.value.Int); 149 149 case MT_CHAR: 150 150 return (this->value.Char == mt.value.Char); 151 151 case MT_FLOAT: 152 152 return (this->value.Float == mt.value.Float); 153 153 case MT_STRING: 154 154 return (this->storedString == mt.storedString); 155 155 default: 156 156 return false; 157 157 } 158 158 } … … 171 171 { 172 172 case MT_BOOL: 173 174 173 this->setBool(this->getBool()); 174 break; 175 175 case MT_INT: 176 177 176 this->setInt(this->getInt()); 177 break; 178 178 case MT_FLOAT: 179 180 179 this->setFloat(this->getFloat()); 180 break; 181 181 case MT_CHAR: 182 183 182 this->setChar(this->getChar()); 183 break; 184 184 case MT_STRING: 185 186 185 this->setString(this->getString()); 186 break; 187 187 default: 188 188 this->type = type; 189 189 } 190 190 } … … 195 195 * 196 196 * This is a pure Value copy. The current type will be preserved. 197 *198 * @TODO speedup199 197 */ 200 198 void MultiType::setValueOf(const MultiType& mt) … … 257 255 } 258 256 257 /** 258 * @brief stores any value to the string. 259 * @note this Value can be grabbed by using the getStoredString function. 260 */ 261 void MultiType::storeString() 262 { 263 if (!(this->type & MT_STRING)) 264 this->storedString = this->getString(); 265 } 259 266 260 267 /************************** … … 275 282 else if (this->type & MT_STRING) return (this->storedString == "true" || 276 283 this->storedString == "TRUE" || 277 this->storedString != "0"); // ! @TODO make this better...284 this->storedString != "0"); // TODO make this better... 278 285 279 286 return false; … … 381 388 * @brief returns a Constant string (actually this is slower than getString() 382 389 * @returns a constant string of the stored version's one. 383 * @note this could lead to a inconsistency of data 390 * @note this could lead to a inconsistency of data AND IS HIGHLY NON_THREAD_SAFE! 391 * PLEASE THINK ABOUT USING THE getStoredString function in conjunction with storeString(). 384 392 */ 385 393 const std::string& MultiType::getConstString() const 386 394 { 387 388 395 MultiType::constString = this->getString(); 389 396 return MultiType::constString; 390 397 } 391 398 399 /** 400 * @brief returns the currently stored string. 401 * @returns the Stored string. 402 * @note Storing a string works as follows: \\ 403 * MultiType a(3); // Creates a MultiType of Type int with value 3 \\ 404 * a.storeString(); // Stores the String in the internal structure. \\ 405 * std::string name = a.getStoredString(); 406 * 407 * This would be the same as 408 * name = a.getString(); 409 * but with much more const'ness. 410 */ 411 const std::string& MultiType::getStoredString() const 412 { 413 MultiType::constString = this->getString(); 414 return MultiType::constString; 415 } 392 416 393 417 /** … … 433 457 { 434 458 case MT_BOOL: 435 436 459 this->setBool(false); 460 break; 437 461 case MT_INT: 438 439 462 this->setInt(0); 463 break; 440 464 case MT_FLOAT: 441 442 465 this->setFloat(0.0f); 466 break; 443 467 case MT_CHAR: 444 445 468 this->setChar('\0'); 469 break; 446 470 case MT_STRING: 447 448 471 this->setString(""); 472 break; 449 473 default: 450 474 #ifdef DEBUG 451 475 PRINTF(2)("Unknown Type not reseting\n"); 452 476 #endif 453 477 break; 454 478 } 455 479 } … … 465 489 { 466 490 case MT_BOOL: 467 491 return MultiType::typeNames[1]; 468 492 case MT_INT: 469 493 return MultiType::typeNames[2]; 470 494 case MT_FLOAT: 471 495 return MultiType::typeNames[3]; 472 496 case MT_CHAR: 473 497 return MultiType::typeNames[4]; 474 498 case MT_STRING: 475 499 return MultiType::typeNames[5]; 476 500 default: 477 501 return MultiType::typeNames[0]; 478 502 } 479 503 } -
trunk/src/lib/util/multi_type.h
r8035 r9869 17 17 MT_BOOL = 1, //!< A bool Value. 18 18 MT_INT = 2, //!< An int Value. 19 MT_UINT = 2, 20 MT_LONG = 2, 19 MT_UINT = 2, //!< A insigned int Value. 20 MT_LONG = 2, //!< A long Value 21 21 MT_FLOAT = 4, //!< A float Value. 22 22 MT_CHAR = 8, //!< A single char. … … 44 44 45 45 MultiType& operator=(const MultiType& mt); 46 /** @param value the value to set (here a bool) @returns the MultiType where this the bool is stored */ 46 47 MultiType& operator=(bool value) { this->setBool(value); return *this; }; 48 /** @param value the value to set (here an int) @returns the MultiType where this the int is stored */ 47 49 MultiType& operator=(int value) { this->setInt(value); return *this; }; 50 /** @param value the value to set (here an int) @returns the MultiType where this the float is stored */ 48 51 MultiType& operator=(float value) { this->setFloat(value); return *this; }; 52 /** @param value the value to set (here a char) @returns the MultiType where this the char is stored */ 49 53 MultiType& operator=(char value) { this->setChar(value); return *this; }; 54 /** @param value the value to set (here a string) @returns the MultiType where this the string is stored */ 50 55 MultiType& operator=(const std::string& value) { this->setString(value); return *this; }; 51 56 52 57 bool operator==(const MultiType& mt) const; 58 /** @param value the value to compare this MultiType against @returns true if comparison was io */ 53 59 bool operator==(bool value) const { return (this->getBool() == value); }; 60 /** @param value the value to compare this MultiType against @returns true if comparison was io */ 54 61 bool operator==(int value) const { return (this->getInt() == value); }; 62 /** @param value the value to compare this MultiType against @returns true if comparison was io */ 55 63 bool operator==(float value) const { return (this->getFloat() == value); }; 64 /** @param value the value to compare this MultiType against @returns true if comparison was io */ 56 65 bool operator==(char value) const { return (this->getChar() == value); }; 66 /** @param value the value to compare this MultiType against @returns true if comparison was io */ 57 67 bool operator==(const std::string& value) const { return (this->getString() == value); }; 68 /** @param type the Type to compare this MultiType against @returns true if the types matched */ 58 69 bool operator==(MT_Type type) const { return (this->type == type); } 70 /** @param type the type to compare this MultiType against @returns true if the types do not match */ 59 71 bool operator!=(MT_Type type) const { return (this->type != type); } 60 72 … … 68 80 69 81 // for your convenience. 82 /** @param value the value to set. Here a bool */ 70 83 inline void setValue(bool value) { this->setBool(value); }; 84 /** @param value the value to set. Here an int */ 71 85 inline void setValue(int value) { this->setInt(value); }; 86 /** @param value the value to set. Here a float */ 72 87 inline void setValue(float value) { this->setFloat(value); }; 88 /** @param value the value to set. Here a char */ 73 89 inline void setValue(char value) { this->setChar(value); }; 90 /** @param value the value to set. Here a char array (string) */ 74 91 inline void setValue(const char* value) { this->setString(value); }; 92 /** @param value the value to set. Here a string */ 75 93 inline void setValue(const std::string& value) { this->setString(value); }; 76 94 void setValueOf(const MultiType& mt); … … 79 97 inline MT_Type getType() const { return this->type; }; 80 98 99 void storeString(); 81 100 82 101 /* RETRIEVING FUNCTIONS */ … … 88 107 std::string getString() const; 89 108 const std::string& getConstString() const; 109 const std::string& getStoredString() const; 90 110 91 111 void reset(); -
trunk/src/lib/util/sigslot/signal.h
r9406 r9869 96 96 { 97 97 public: 98 virtual ~_connection_base0() {}; 98 99 virtual has_slots<mt_policy>* getdest() const = 0; 99 100 virtual void emit() = 0; … … 106 107 { 107 108 public: 109 virtual ~_connection_base1() {}; 108 110 virtual has_slots<mt_policy>* getdest() const = 0; 109 111 virtual void emit(arg1_type) = 0; … … 116 118 { 117 119 public: 120 virtual ~_connection_base2() {}; 118 121 virtual has_slots<mt_policy>* getdest() const = 0; 119 122 virtual void emit(arg1_type, arg2_type) = 0; … … 126 129 { 127 130 public: 131 virtual ~_connection_base3() {}; 128 132 virtual has_slots<mt_policy>* getdest() const = 0; 129 133 virtual void emit(arg1_type, arg2_type, arg3_type) = 0; … … 136 140 { 137 141 public: 142 virtual ~_connection_base4() {}; 138 143 virtual has_slots<mt_policy>* getdest() const = 0; 139 144 virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type) = 0; … … 147 152 { 148 153 public: 154 virtual ~_connection_base5() {}; 149 155 virtual has_slots<mt_policy>* getdest() const = 0; 150 156 virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, … … 161 167 { 162 168 public: 169 virtual ~_connection_base6() {}; 163 170 virtual has_slots<mt_policy>* getdest() const = 0; 164 171 virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, … … 175 182 { 176 183 public: 184 virtual ~_connection_base7() {}; 177 185 virtual has_slots<mt_policy>* getdest() const = 0; 178 186 virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, … … 189 197 { 190 198 public: 199 virtual ~_connection_base8() {}; 191 200 virtual has_slots<mt_policy>* getdest() const = 0; 192 201 virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, -
trunk/src/lib/util/substring.cc
r9406 r9869 51 51 * @param delimiters multiple set of characters at what to split. (delimiters) 52 52 * @param delimiterNeighbours neighbours of the delimiters, that will be erased only when near a delimiter. 53 * @param emptyEntries If empty entries should be allewed or removed. 53 54 * @param escapeChar The Escape Character that overrides splitters commends and so on... 54 55 * @param safemode_char within these characters splitting won't happen … … 109 110 /** @brief Helper that gets you a String consisting of all WhiteSpaces and the Comma */ 110 111 const std::string SubString::WhiteSpacesWithComma = " \n\t,"; 112 /** An Empty SubString */ 113 const SubString SubString::NullSubString = SubString(); 111 114 112 115 /** … … 145 148 * @brief comparator. 146 149 * @param subString the SubString to compare against this one. 150 * @param length how many entries to compare. (from 0 to length) 147 151 * @returns true if the Stored Strings match 148 152 */ … … 273 277 * @brief splits line into tokens and stores them in ret. 274 278 * @param ret the Array, where the Splitted strings will be stored in 275 * @param offsets an Array of Offsets, here the distance from the inputstring276 279 * to the beginning of the current token is stored 277 280 * @param line the inputLine to split 278 281 * @param delimiters a String of Delimiters (here the input will be splitted) 279 * @param delimiterNeighbour Naighbours to the Delimitter, that will be removed if they are to the left or the right of a Delimiter.282 * @param delimiterNeighbours Naighbours to the Delimitter, that will be removed if they are to the left or the right of a Delimiter. 280 283 * @param emptyEntries: if empty Strings are added to the List of Strings. 281 284 * @param escape_char: Escape carater (escapes splitters) -
trunk/src/lib/util/substring.h
r9406 r9869 33 33 { 34 34 public: 35 //! An enumerator for the State the Parser is in 35 36 typedef enum { 36 SL_NORMAL, 37 SL_ESCAPE, 38 SL_SAFEMODE, 39 SL_SAFEESCAPE, 40 SL_COMMENT, 37 SL_NORMAL, //!< Normal state 38 SL_ESCAPE, //!< After an escape character 39 SL_SAFEMODE, //!< In safe mode (between "" mostly). 40 SL_SAFEESCAPE, //!< In safe mode with the internal escape character, that escapes even the savemode character. 41 SL_COMMENT, //!< In Comment mode. 41 42 } SPLIT_LINE_STATE; 42 43 … … 48 49 const std::string& delimiters, const std::string& delimiterNeighbours = "", bool emptyEntries=false, 49 50 char escapeChar ='\\', char safemode_char = '"', char comment_char = '\0'); 51 SubString(unsigned int argc, const char** argv); 50 52 /** @brief create a Substring as a copy of another one. @param subString the SubString to copy. */ 51 SubString(unsigned int argc, const char** argv);52 53 SubString(const SubString& subString) { *this = subString; }; 53 54 SubString(const SubString& subString, unsigned int subSetBegin); … … 110 111 static const std::string WhiteSpaces; 111 112 static const std::string WhiteSpacesWithComma; 113 static const SubString NullSubString; 112 114 113 115 private:
Note: See TracChangeset
for help on using the changeset viewer.