Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/class/Identifier.h @ 10467

Last change on this file since 10467 was 10467, checked in by landauf, 9 years ago

trying to fix compiler error on buildserver

  • Property svn:eol-style set to native
File size: 19.2 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30    @defgroup Identifier Identifier
31    @ingroup Class
32*/
33
34/**
35    @file
36    @ingroup Class Identifier
37    @brief Declaration of Identifier, definition of ClassIdentifier<T>; used to identify the class of an object.
38
39    @anchor IdentifierExample
40
41    An Identifier "identifies" the class of an object. It contains different information about
42    the class: Its name and ID, a list of all instances of this class, a factory to create new
43    instances of this class, and more.
44
45    It also contains information about the inheritance of this class: It stores a list of the
46    Identifiers of all parent-classes as well as a list of all child-classes. These relationships
47    can be tested using functions like @c isA(), @c isChildOf(), @c isParentOf(), and more.
48
49    Every Identifier is in fact a ClassIdentifier<T> (where T is the class that is identified
50    by the Identifier), Identifier is just the common base-class.
51
52    Example:
53    @code
54    MyClass* object = new MyClass();                                            // create an instance of MyClass
55
56    object->getIdentifier()->getName();                                         // returns "MyClass"
57
58    Identifiable* other = object->getIdentifier()->fabricate(0);                // fabricates a new instance of MyClass
59
60
61    // test the class hierarchy
62    object->getIdentifier()->isA(Class(MyClass));                               // returns true
63    object->isA(Class(MyClass));                                                // returns true (short version)
64
65    object->isA(Class(BaseClass));                                              // returns true if MyClass is a child of BaseClass
66
67    Class(ChildClass)->isChildOf(object->getIdentifier());                      // returns true if ChildClass is a child of MyClass
68    @endcode
69*/
70
71#ifndef _Identifier_H__
72#define _Identifier_H__
73
74#include "core/CorePrereqs.h"
75
76#include <cassert>
77#include <map>
78#include <set>
79#include <string>
80#include <typeinfo>
81#include <loki/TypeTraits.h>
82#include <boost/static_assert.hpp>
83#include <boost/type_traits/is_base_of.hpp>
84
85#include "util/Output.h"
86#include "util/OrxAssert.h"
87#include "core/object/ObjectList.h"
88#include "core/object/Listable.h"
89#include "core/object/Context.h"
90#include "core/object/Destroyable.h"
91#include "core/object/WeakPtr.h"
92#include "IdentifierManager.h"
93#include "Super.h"
94
95namespace orxonox
96{
97    // ###############################
98    // ###       Identifier        ###
99    // ###############################
100    /**
101        @brief The Identifier is used to identify the class of an object and to store information about the class.
102
103        Each Identifier stores information about one class. The Identifier can then be used to identify
104        this class. On the other hand it's also possible to get the corresponding Identifier of a class,
105        for example by using the macro Class().
106
107        @see See @ref IdentifierExample "Identifier.h" for more information and some examples.
108
109        @note You can't directly create an Identifier, it's just the base-class of ClassIdentifier<T>.
110    */
111    class _CoreExport Identifier : public Destroyable
112    {
113        public:
114            Identifier(const std::string& name, Factory* factory, bool bLoadable);
115            Identifier(const Identifier& identifier); // don't copy
116            virtual ~Identifier();
117
118            /// Returns the name of the class the Identifier belongs to.
119            inline const std::string& getName() const { return this->name_; }
120
121            /// Returns the type_info of the class as it is returned by typeid(T)
122            virtual const std::type_info& getTypeInfo() = 0;
123
124            /// Returns the network ID to identify a class through the network.
125            inline uint32_t getNetworkID() const { return this->networkID_; }
126            void setNetworkID(uint32_t id);
127
128            /// Returns the unique ID of the class.
129            ORX_FORCEINLINE unsigned int getClassID() const { return this->classID_; }
130
131            /// Returns true if the Identifier has a Factory.
132            inline bool hasFactory() const { return (this->factory_ != 0); }
133
134            Identifiable* fabricate(Context* context);
135
136            /// Returns true if the class can be loaded through XML.
137            inline bool isLoadable() const { return this->bLoadable_; }
138
139            /// Returns true if child classes should inherit virtually from this class.
140            inline bool isVirtualBase() const { return this->bIsVirtualBase_; }
141            /// Defines if child classes should inherit virtually from this class.
142            inline void setVirtualBase(bool bIsVirtualBase) { this->bIsVirtualBase_ = bIsVirtualBase; }
143
144            /// Returns true if the Identifier was completely initialized.
145            inline bool isInitialized() const { return this->bInitialized_; }
146
147
148            /////////////////////////////
149            ////// Class Hierarchy //////
150            /////////////////////////////
151            Identifier& inheritsFrom(Identifier* directParent);
152
153            void initializeParents(const std::list<const Identifier*>& initializationTrace);
154            void finishInitialization();
155            void reset();
156
157            bool isA(const Identifier* identifier) const;
158            bool isExactlyA(const Identifier* identifier) const;
159            bool isChildOf(const Identifier* identifier) const;
160            bool isDirectChildOf(const Identifier* identifier) const;
161            bool isParentOf(const Identifier* identifier) const;
162            bool isDirectParentOf(const Identifier* identifier) const;
163
164            /// Returns the direct parents of the class the Identifier belongs to.
165            inline const std::list<const Identifier*>& getDirectParents() const { return this->directParents_; }
166            /// Returns the parents of the class the Identifier belongs to.
167            inline const std::list<const Identifier*>& getParents() const { return this->parents_; }
168
169            /// Returns the direct children the class the Identifier belongs to.
170            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
171            /// Returns the children of the class the Identifier belongs to.
172            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
173
174
175            /////////////////////////
176            ///// Config Values /////
177            /////////////////////////
178            virtual void updateConfigValues(bool updateChildren = true) const = 0;
179
180            /// Returns true if this class has at least one config value.
181            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
182
183            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
184            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
185
186
187            ///////////////////
188            ///// XMLPort /////
189            ///////////////////
190            /// Returns the map that stores all XMLPort params.
191            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
192            /// Returns a const_iterator to the beginning of the map that stores all XMLPort params.
193            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
194            /// Returns a const_iterator to the end of the map that stores all XMLPort params.
195            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
196
197            /// Returns the map that stores all XMLPort objects.
198            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
199            /// Returns a const_iterator to the beginning of the map that stores all XMLPort objects.
200            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
201            /// Returns a const_iterator to the end of the map that stores all XMLPort objects.
202            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
203
204            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
205            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
206
207            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
208            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
209
210            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const = 0;
211
212            static bool initConfigValues_s; // TODO: this is a hack - remove it as soon as possible
213
214        protected:
215            virtual void createSuperFunctionCaller() const = 0;
216
217        private:
218            void verifyIdentifierTrace() const;
219            void addIfNotExists(std::list<const Identifier*>& list, const Identifier* identifierToAdd) const;
220
221            std::list<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to (sorted by their order of initialization)
222            std::list<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to (sorted by their order of initialization)
223
224            std::set<const Identifier*> directChildren_;                   //!< The direct children of the class the Identifier belongs to
225            std::set<const Identifier*> children_;                         //!< The children of the class the Identifier belongs to
226
227            bool bInitialized_;                                            //!< Is true if the Identifier was completely initialized
228            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
229            bool bIsVirtualBase_;                                          //!< If true, it is recommended to inherit virtually from this class. This changes the order of initialization of child classes, thus this information is necessary to check the class hierarchy.
230            std::string name_;                                             //!< The name of the class the Identifier belongs to
231            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
232            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
233            const unsigned int classID_;                                   //!< Uniquely identifies a class (might not be the same as the networkID_)
234
235            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
236            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
237
238            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
239            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
240    };
241
242    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
243
244
245    // ###############################
246    // ###     ClassIdentifier     ###
247    // ###############################
248    /**
249        @brief The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
250
251        ClassIdentifier is a Singleton, which means that only one ClassIdentifier for a given type T exists.
252        This makes it possible to store information about a class, sharing them with all
253        objects of that class without defining static variables in every class.
254
255        To be really sure that not more than exactly one object exists (even with libraries),
256        ClassIdentifiers are stored in a static map in Identifier.
257    */
258    template <class T>
259    class ClassIdentifier : public Identifier
260    {
261        BOOST_STATIC_ASSERT((boost::is_base_of<Identifiable, T>::value));
262
263        #ifndef DOXYGEN_SHOULD_SKIP_THIS
264          #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
265          #include "Super.h"
266        #endif
267
268        public:
269            ClassIdentifier(const std::string& name, Factory* factory, bool bLoadable) : Identifier(name, factory, bLoadable)
270            {
271                OrxVerify(ClassIdentifier<T>::classIdentifier_s == NULL, "Assertion failed in ClassIdentifier of type " << typeid(T).name());
272                ClassIdentifier<T>::classIdentifier_s = this;
273
274                SuperFunctionInitialization<0, T>::initialize(this);
275            }
276            ~ClassIdentifier()
277            {
278                SuperFunctionDestruction<0, T>::destroy(this);
279            }
280
281            bool initializeObject(T* object);
282
283            void setConfigValues(T* object, Configurable*) const;
284            void setConfigValues(T* object, Identifiable*) const;
285
286            void addObjectToList(T* object, Listable*);
287            void addObjectToList(T* object, Identifiable*);
288
289            virtual void updateConfigValues(bool updateChildren = true) const;
290
291            virtual const std::type_info& getTypeInfo()
292                { return typeid(T); }
293
294            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const
295                { return dynamic_cast<T*>(object) != 0; }
296
297            static ClassIdentifier<T>* getIdentifier();
298
299        private:
300            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
301
302            void updateConfigValues(bool updateChildren, Listable*) const;
303            void updateConfigValues(bool updateChildren, Identifiable*) const;
304
305            static WeakPtr<ClassIdentifier<T> > classIdentifier_s;
306    };
307
308    template <class T>
309    WeakPtr<ClassIdentifier<T> > ClassIdentifier<T>::classIdentifier_s;
310
311    /**
312        @brief Returns the only instance of this class.
313        @return The unique Identifier
314    */
315    template <class T>
316    /*static*/ inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
317    {
318        if (ClassIdentifier<T>::classIdentifier_s == NULL)
319            ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*) IdentifierManager::getInstance().getIdentifierByTypeInfo(typeid(T));
320
321        OrxVerify(ClassIdentifier<T>::classIdentifier_s != NULL, "Did you forget to register the class of type " << typeid(T).name() << "?");
322        return ClassIdentifier<T>::classIdentifier_s;
323    }
324
325    /**
326        @brief Adds an object of the given type to the ObjectList.
327        @param object The object to add
328    */
329    template <class T>
330    bool ClassIdentifier<T>::initializeObject(T* object)
331    {
332        orxout(verbose, context::object_list) << "Register Object: " << this->getName() << endl;
333
334        object->identifier_ = this;
335        if (IdentifierManager::getInstance().isCreatingHierarchy())
336        {
337            IdentifierManager::getInstance().createdObject(object);
338
339            if (Identifier::initConfigValues_s)
340                this->setConfigValues(object, object);
341
342            return true;
343        }
344        else
345        {
346            this->addObjectToList(object, object);
347
348            // Add pointer of type T to the map in the Identifiable instance that enables "dynamic_casts"
349            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
350            return false;
351        }
352    }
353
354    /**
355     * @brief Only configures the object if is a @ref Configurable
356     */
357    template <class T>
358    void ClassIdentifier<T>::setConfigValues(T* object, Configurable*) const
359    {
360        object->setConfigValues();
361    }
362
363    template <class T>
364    void ClassIdentifier<T>::setConfigValues(T*, Identifiable*) const
365    {
366        // no action
367    }
368
369    /**
370     * @brief Only adds the object to the object list if is a @ref Listable
371     */
372    template <class T>
373    void ClassIdentifier<T>::addObjectToList(T* object, Listable* listable)
374    {
375        if (listable->getContext())
376            listable->getContext()->addObject(object);
377    }
378
379    template <class T>
380    void ClassIdentifier<T>::addObjectToList(T*, Identifiable*)
381    {
382        // no action
383    }
384
385    /**
386        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
387    */
388    template <class T>
389    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
390    {
391        this->updateConfigValues(updateChildren, static_cast<T*>(NULL));
392    }
393
394    template <class T>
395    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Listable*) const
396    {
397        if (!this->hasConfigValues())
398            return;
399
400        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
401            this->setConfigValues(*it, *it);
402
403        if (updateChildren)
404            for (std::set<const Identifier*>::const_iterator it = this->getChildren().begin(); it != this->getChildren().end(); ++it)
405                (*it)->updateConfigValues(false);
406    }
407
408    template <class T>
409    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Identifiable*) const
410    {
411        // no action
412    }
413
414
415    // ###############################
416    // ###      orxonox_cast       ###
417    // ###############################
418    /**
419    @brief
420        Casts on object of type Identifiable to any derived type that is
421        registered in the class hierarchy.
422    @return
423        Returns NULL if the cast is not possible
424    @note
425        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
426        a class forgot to register its objects.
427        Also note that the function is implemented differently for GCC/MSVC.
428    */
429    template <class T, class U>
430    ORX_FORCEINLINE T orxonox_cast(U* source)
431    {
432#ifdef ORXONOX_COMPILER_MSVC
433        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
434        if (source != NULL)
435            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
436        else
437            return NULL;
438#else
439        return dynamic_cast<T>(source);
440#endif
441    }
442}
443
444#endif /* _Identifier_H__ */
Note: See TracBrowser for help on using the repository browser.