Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core6/src/libraries/core/class/Identifier.h @ 9643

Last change on this file since 9643 was 9643, checked in by landauf, 11 years ago

bugfix

  • Property svn:eol-style set to native
File size: 21.3 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
83#include "util/Output.h"
84#include "core/object/ObjectList.h"
85#include "core/object/Listable.h"
86#include "core/object/Context.h"
87#include "IdentifierManager.h"
88#include "Super.h"
89
90namespace orxonox
91{
92    // ###############################
93    // ###       Identifier        ###
94    // ###############################
95    /**
96        @brief The Identifier is used to identify the class of an object and to store information about the class.
97
98        Each Identifier stores information about one class. The Identifier can then be used to identify
99        this class. On the other hand it's also possible to get the corresponding Identifier of a class,
100        for example by using the macro Class().
101
102        @see See @ref IdentifierExample "Identifier.h" for more information and some examples.
103
104        @note You can't directly create an Identifier, it's just the base-class of ClassIdentifier<T>.
105    */
106    class _CoreExport Identifier
107    {
108        public:
109            Identifier();
110            Identifier(const Identifier& identifier); // don't copy
111            virtual ~Identifier();
112
113            /// Returns the name of the class the Identifier belongs to.
114            inline const std::string& getName() const { return this->name_; }
115            void setName(const std::string& name);
116
117            /// Returns the network ID to identify a class through the network.
118            inline uint32_t getNetworkID() const { return this->networkID_; }
119            void setNetworkID(uint32_t id);
120
121            /// Returns the unique ID of the class.
122            ORX_FORCEINLINE unsigned int getClassID() const { return this->classID_; }
123
124            /// Sets the Factory.
125            void setFactory(Factory* factory);
126            /// Returns true if the Identifier has a Factory.
127            inline bool hasFactory() const { return (this->factory_ != 0); }
128
129            Identifiable* fabricate(Context* context);
130
131            /// Returns true if the class can be loaded through XML.
132            inline bool isLoadable() const { return this->bLoadable_; }
133            /// Set the class to be loadable through XML or not.
134            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
135
136            bool isA(const Identifier* identifier) const;
137            bool isExactlyA(const Identifier* identifier) const;
138            bool isChildOf(const Identifier* identifier) const;
139            bool isDirectChildOf(const Identifier* identifier) const;
140            bool isParentOf(const Identifier* identifier) const;
141            bool isDirectParentOf(const Identifier* identifier) const;
142
143
144            /////////////////////////////
145            ////// Class Hierarchy //////
146            /////////////////////////////
147            /// Returns the parents of the class the Identifier belongs to.
148            inline const std::set<const Identifier*>& getParents() const { return this->parents_; }
149            /// Returns the begin-iterator of the parents-list.
150            inline std::set<const Identifier*>::const_iterator getParentsBegin() const { return this->parents_.begin(); }
151            /// Returns the end-iterator of the parents-list.
152            inline std::set<const Identifier*>::const_iterator getParentsEnd() const { return this->parents_.end(); }
153
154            /// Returns the children of the class the Identifier belongs to.
155            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
156            /// Returns the begin-iterator of the children-list.
157            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_.begin(); }
158            /// Returns the end-iterator of the children-list.
159            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_.end(); }
160
161            /// Returns the direct parents of the class the Identifier belongs to.
162            inline const std::set<const Identifier*>& getDirectParents() const { return this->directParents_; }
163            /// Returns the begin-iterator of the direct-parents-list.
164            inline std::set<const Identifier*>::const_iterator getDirectParentsBegin() const { return this->directParents_.begin(); }
165            /// Returns the end-iterator of the direct-parents-list.
166            inline std::set<const Identifier*>::const_iterator getDirectParentsEnd() const { return this->directParents_.end(); }
167
168            /// Returns the direct children the class the Identifier belongs to.
169            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
170            /// Returns the begin-iterator of the direct-children-list.
171            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_.begin(); }
172            /// Returns the end-iterator of the direct-children-list.
173            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_.end(); }
174
175
176            /////////////////////////
177            ///// Config Values /////
178            /////////////////////////
179            virtual void updateConfigValues(bool updateChildren = true) const = 0;
180
181            /// Returns true if this class has at least one config value.
182            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
183
184            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
185            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
186
187
188            ///////////////////
189            ///// XMLPort /////
190            ///////////////////
191            /// Returns the map that stores all XMLPort params.
192            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
193            /// Returns a const_iterator to the beginning of the map that stores all XMLPort params.
194            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
195            /// Returns a const_iterator to the end of the map that stores all XMLPort params.
196            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
197
198            /// Returns the map that stores all XMLPort objects.
199            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
200            /// Returns a const_iterator to the beginning of the map that stores all XMLPort objects.
201            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
202            /// Returns a const_iterator to the end of the map that stores all XMLPort objects.
203            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
204
205            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
206            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
207
208            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
209            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
210
211
212        protected:
213            virtual void createSuperFunctionCaller() const = 0;
214
215            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
216
217            /// Returns the children of the class the Identifier belongs to.
218            inline std::set<const Identifier*>& getChildrenIntern() const { return this->children_; }
219            /// Returns the direct children of the class the Identifier belongs to.
220            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return this->directChildren_; }
221
222        private:
223            void initialize(std::set<const Identifier*>* parents);
224
225            std::set<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to
226            mutable std::set<const Identifier*> children_;                 //!< The children of the class the Identifier belongs to
227
228            std::set<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to
229            mutable std::set<const Identifier*> directChildren_;           //!< The direct children of the class the Identifier belongs to
230
231            bool bCreatedOneObject_;                                       //!< True if at least one object of the given type was created (used to determine the need of storing the parents)
232            bool bSetName_;                                                //!< True if the name is set
233            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
234            std::string name_;                                             //!< The name of the class the Identifier belongs to
235            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
236            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
237            const unsigned int classID_;                                   //!< Uniquely identifies a class (might not be the same as the networkID_)
238
239            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
240            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
241
242            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
243            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
244    };
245
246    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
247
248
249    // ###############################
250    // ###     ClassIdentifier     ###
251    // ###############################
252    /**
253        @brief The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
254
255        ClassIdentifier is a Singleton, which means that only one ClassIdentifier for a given type T exists.
256        This makes it possible to store information about a class, sharing them with all
257        objects of that class without defining static variables in every class.
258
259        To be really sure that not more than exactly one object exists (even with libraries),
260        ClassIdentifiers are stored in a static map in Identifier.
261    */
262    template <class T>
263    class ClassIdentifier : public Identifier
264    {
265        #ifndef DOXYGEN_SHOULD_SKIP_THIS
266          #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
267          #include "Super.h"
268        #endif
269
270        public:
271            static ClassIdentifier<T>* getIdentifier();
272            static ClassIdentifier<T>* getIdentifier(const std::string& name);
273
274            bool initialiseObject(T* object, const std::string& className, bool bRootClass);
275
276            void setConfigValues(T* object, Configurable*) const;
277            void setConfigValues(T* object, Identifiable*) const;
278
279            void addObjectToList(T* object, Listable*);
280            void addObjectToList(T* object, Identifiable*);
281
282            void updateConfigValues(bool updateChildren = true) const;
283
284        private:
285            static void initialiseIdentifier();
286            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
287            ClassIdentifier()
288            {
289                SuperFunctionInitialization<0, T>::initialize(this);
290            }
291            ~ClassIdentifier()
292            {
293                SuperFunctionDestruction<0, T>::destroy(this);
294                if (classIdentifier_s == this)
295                    classIdentifier_s = 0;
296            }
297
298            void updateConfigValues(bool updateChildren, Listable*) const;
299            void updateConfigValues(bool updateChildren, Identifiable*) const;
300
301            static ClassIdentifier<T>* classIdentifier_s;
302    };
303
304    template <class T>
305    ClassIdentifier<T>* ClassIdentifier<T>::classIdentifier_s = 0;
306
307    /**
308        @brief Returns the only instance of this class.
309        @return The unique Identifier
310    */
311    template <class T>
312    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
313    {
314        // check if the Identifier already exists
315        if (!ClassIdentifier<T>::classIdentifier_s)
316            ClassIdentifier<T>::initialiseIdentifier();
317
318        return ClassIdentifier<T>::classIdentifier_s;
319    }
320
321    /**
322        @brief Does the same as getIdentifier() but sets the name if this wasn't done yet.
323        @param name The name of this Identifier
324        @return The Identifier
325    */
326    template <class T>
327    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier(const std::string& name)
328    {
329        ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
330        identifier->setName(name);
331        return identifier;
332    }
333
334    /**
335        @brief Assigns the static field for the identifier singleton.
336    */
337    template <class T>
338    void ClassIdentifier<T>::initialiseIdentifier()
339    {
340        // Get the name of the class
341        std::string name = typeid(T).name();
342
343        // create a new identifier anyway. Will be deleted in Identifier::getIdentifier if not used.
344        ClassIdentifier<T>* proposal = new ClassIdentifier<T>();
345
346        // Get the entry from the map
347        ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*)IdentifierManager::getInstance().getIdentifierSingleton(name, proposal);
348
349        if (ClassIdentifier<T>::classIdentifier_s == proposal)
350        {
351            orxout(verbose, context::identifier) << "Requested Identifier for " << name << " was not yet existing and got created." << endl;
352        }
353        else
354        {
355            orxout(verbose, context::identifier) << "Requested Identifier for " << name << " was already existing and got assigned." << endl;
356        }
357    }
358
359    /**
360        @brief Adds an object of the given type to the ObjectList.
361        @param object The object to add
362        @param className The name of the class T
363        @param bRootClass True if this is a root class (i.e. it inherits directly from OrxonoxClass)
364    */
365    template <class T>
366    bool ClassIdentifier<T>::initialiseObject(T* object, const std::string& className, bool bRootClass)
367    {
368        if (bRootClass)
369            orxout(verbose, context::object_list) << "Register Root-Object: " << className << endl;
370        else
371            orxout(verbose, context::object_list) << "Register Object: " << className << endl;
372
373        object->identifier_ = this;
374        if (IdentifierManager::getInstance().isCreatingHierarchy())
375        {
376            if (bRootClass && !object->parents_)
377                object->parents_ = new std::set<const Identifier*>();
378
379            if (object->parents_)
380            {
381                this->initializeClassHierarchy(object->parents_, bRootClass);
382                object->parents_->insert(object->parents_->end(), this);
383            }
384
385            this->setConfigValues(object, object);
386            return true;
387        }
388        else
389        {
390            this->addObjectToList(object, object);
391
392            // Add pointer of type T to the map in the Identifiable instance that enables "dynamic_casts"
393            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
394            return false;
395        }
396    }
397
398    /**
399     * @brief Only configures the object if is a @ref Configurable
400     */
401    template <class T>
402    void ClassIdentifier<T>::setConfigValues(T* object, Configurable*) const
403    {
404        object->setConfigValues();
405    }
406
407    template <class T>
408    void ClassIdentifier<T>::setConfigValues(T*, Identifiable*) const
409    {
410        // no action
411    }
412
413    /**
414     * @brief Only adds the object to the object list if is a @ref Listable
415     */
416    template <class T>
417    void ClassIdentifier<T>::addObjectToList(T* object, Listable* listable)
418    {
419        listable->getContext()->addObject(object);
420    }
421
422    template <class T>
423    void ClassIdentifier<T>::addObjectToList(T*, Identifiable*)
424    {
425        // no action
426    }
427
428    /**
429        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
430    */
431    template <class T>
432    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
433    {
434        this->updateConfigValues(updateChildren, static_cast<T*>(NULL));
435    }
436
437    template <class T>
438    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Listable*) const
439    {
440        if (!this->hasConfigValues())
441            return;
442
443        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
444            this->setConfigValues(*it, *it);
445
446        if (updateChildren)
447            for (std::set<const Identifier*>::const_iterator it = this->getChildrenBegin(); it != this->getChildrenEnd(); ++it)
448                (*it)->updateConfigValues(false);
449    }
450
451    template <class T>
452    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Identifiable*) const
453    {
454        // no action
455    }
456
457
458    // ###############################
459    // ###      orxonox_cast       ###
460    // ###############################
461    /**
462    @brief
463        Casts on object of type Identifiable to any derived type that is
464        registered in the class hierarchy.
465    @return
466        Returns NULL if the cast is not possible
467    @note
468        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
469        a class forgot to register its objects.
470        Also note that the function is implemented differently for GCC/MSVC.
471    */
472    template <class T, class U>
473    ORX_FORCEINLINE T orxonox_cast(U* source)
474    {
475#ifdef ORXONOX_COMPILER_MSVC
476        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
477        if (source != NULL)
478            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
479        else
480            return NULL;
481#else
482        return dynamic_cast<T>(source);
483#endif
484    }
485}
486
487#endif /* _Identifier_H__ */
Note: See TracBrowser for help on using the repository browser.