Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed issue: Class(T) may not be allowed in StaticallyInitializedIdentifier::load() because T may not yet be initialized.
now the inheritance is resolved in Identifier::finishInitialization()

  • Property svn:eol-style set to native
File size: 19.6 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            struct InheritsFrom //! helper class to manually define inheritance
115            {
116                virtual ~InheritsFrom() {}
117                virtual Identifier* getParent() const = 0;
118            };
119
120        public:
121            Identifier(const std::string& name, Factory* factory, bool bLoadable);
122            Identifier(const Identifier& identifier); // don't copy
123            virtual ~Identifier();
124
125            /// Returns the name of the class the Identifier belongs to.
126            inline const std::string& getName() const { return this->name_; }
127
128            /// Returns the type_info of the class as it is returned by typeid(T)
129            virtual const std::type_info& getTypeInfo() = 0;
130
131            /// Returns the network ID to identify a class through the network.
132            inline uint32_t getNetworkID() const { return this->networkID_; }
133            void setNetworkID(uint32_t id);
134
135            /// Returns the unique ID of the class.
136            ORX_FORCEINLINE unsigned int getClassID() const { return this->classID_; }
137
138            /// Returns true if the Identifier has a Factory.
139            inline bool hasFactory() const { return (this->factory_ != 0); }
140
141            Identifiable* fabricate(Context* context);
142
143            /// Returns true if the class can be loaded through XML.
144            inline bool isLoadable() const { return this->bLoadable_; }
145
146            /// Returns true if child classes should inherit virtually from this class.
147            inline bool isVirtualBase() const { return this->bIsVirtualBase_; }
148            /// Defines if child classes should inherit virtually from this class.
149            inline void setVirtualBase(bool bIsVirtualBase) { this->bIsVirtualBase_ = bIsVirtualBase; }
150
151            /// Returns true if the Identifier was completely initialized.
152            inline bool isInitialized() const { return this->bInitialized_; }
153
154
155            /////////////////////////////
156            ////// Class Hierarchy //////
157            /////////////////////////////
158            Identifier& inheritsFrom(InheritsFrom* directParent);
159
160            void initializeParents(const std::list<const Identifier*>& initializationTrace);
161            void finishInitialization();
162            void reset();
163
164            bool isA(const Identifier* identifier) const;
165            bool isExactlyA(const Identifier* identifier) const;
166            bool isChildOf(const Identifier* identifier) const;
167            bool isDirectChildOf(const Identifier* identifier) const;
168            bool isParentOf(const Identifier* identifier) const;
169            bool isDirectParentOf(const Identifier* identifier) const;
170
171            /// Returns the direct parents of the class the Identifier belongs to.
172            inline const std::list<const Identifier*>& getDirectParents() const { return this->directParents_; }
173            /// Returns the parents of the class the Identifier belongs to.
174            inline const std::list<const Identifier*>& getParents() const { return this->parents_; }
175
176            /// Returns the direct children the class the Identifier belongs to.
177            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
178            /// Returns the children of the class the Identifier belongs to.
179            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
180
181
182            /////////////////////////
183            ///// Config Values /////
184            /////////////////////////
185            virtual void updateConfigValues(bool updateChildren = true) const = 0;
186
187            /// Returns true if this class has at least one config value.
188            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
189
190            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
191            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
192
193
194            ///////////////////
195            ///// XMLPort /////
196            ///////////////////
197            /// Returns the map that stores all XMLPort params.
198            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
199            /// Returns a const_iterator to the beginning of the map that stores all XMLPort params.
200            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
201            /// Returns a const_iterator to the end of the map that stores all XMLPort params.
202            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
203
204            /// Returns the map that stores all XMLPort objects.
205            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
206            /// Returns a const_iterator to the beginning of the map that stores all XMLPort objects.
207            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
208            /// Returns a const_iterator to the end of the map that stores all XMLPort objects.
209            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
210
211            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
212            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
213
214            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
215            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
216
217            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const = 0;
218
219            static bool initConfigValues_s; // TODO: this is a hack - remove it as soon as possible
220
221        protected:
222            virtual void createSuperFunctionCaller() const = 0;
223
224        private:
225            void verifyIdentifierTrace() const;
226            void addIfNotExists(std::list<const Identifier*>& list, const Identifier* identifierToAdd) const;
227
228            std::list<const InheritsFrom*> manualDirectParents_;            //!< Manually defined direct parents
229            std::list<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to (sorted by their order of initialization)
230            std::list<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to (sorted by their order of initialization)
231
232            std::set<const Identifier*> directChildren_;                   //!< The direct children of the class the Identifier belongs to
233            std::set<const Identifier*> children_;                         //!< The children of the class the Identifier belongs to
234
235            bool bInitialized_;                                            //!< Is true if the Identifier was completely initialized
236            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
237            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.
238            std::string name_;                                             //!< The name of the class the Identifier belongs to
239            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
240            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
241            unsigned int classID_;                                         //!< Uniquely identifies a class (might not be the same as the networkID_)
242
243            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
244            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
245
246            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
247            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
248    };
249
250    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
251
252
253    // ###############################
254    // ###     ClassIdentifier     ###
255    // ###############################
256    /**
257        @brief The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
258
259        ClassIdentifier is a Singleton, which means that only one ClassIdentifier for a given type T exists.
260        This makes it possible to store information about a class, sharing them with all
261        objects of that class without defining static variables in every class.
262
263        To be really sure that not more than exactly one object exists (even with libraries),
264        ClassIdentifiers are stored in a static map in Identifier.
265    */
266    template <class T>
267    class ClassIdentifier : public Identifier
268    {
269        BOOST_STATIC_ASSERT((boost::is_base_of<Identifiable, T>::value));
270
271        #ifndef DOXYGEN_SHOULD_SKIP_THIS
272          #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
273          #include "Super.h"
274        #endif
275
276        public:
277            ClassIdentifier(const std::string& name, Factory* factory, bool bLoadable) : Identifier(name, factory, bLoadable)
278            {
279                OrxVerify(ClassIdentifier<T>::classIdentifier_s == NULL, "Assertion failed in ClassIdentifier of type " << typeid(T).name());
280                ClassIdentifier<T>::classIdentifier_s = this;
281
282                SuperFunctionInitialization<0, T>::initialize(this);
283            }
284            ~ClassIdentifier()
285            {
286                SuperFunctionDestruction<0, T>::destroy(this);
287            }
288
289            bool initializeObject(T* object);
290
291            void setConfigValues(T* object, Configurable*) const;
292            void setConfigValues(T* object, Identifiable*) const;
293
294            void addObjectToList(T* object, Listable*);
295            void addObjectToList(T* object, Identifiable*);
296
297            virtual void updateConfigValues(bool updateChildren = true) const;
298
299            virtual const std::type_info& getTypeInfo()
300                { return typeid(T); }
301
302            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const
303                { return dynamic_cast<T*>(object) != 0; }
304
305            static ClassIdentifier<T>* getIdentifier();
306
307        private:
308            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
309
310            void updateConfigValues(bool updateChildren, Listable*) const;
311            void updateConfigValues(bool updateChildren, Identifiable*) const;
312
313            static WeakPtr<ClassIdentifier<T> > classIdentifier_s;
314    };
315
316    template <class T>
317    WeakPtr<ClassIdentifier<T> > ClassIdentifier<T>::classIdentifier_s;
318
319    /**
320        @brief Returns the only instance of this class.
321        @return The unique Identifier
322    */
323    template <class T>
324    /*static*/ inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
325    {
326        if (ClassIdentifier<T>::classIdentifier_s == NULL)
327            ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*) IdentifierManager::getInstance().getIdentifierByTypeInfo(typeid(T));
328
329        OrxVerify(ClassIdentifier<T>::classIdentifier_s != NULL, "Did you forget to register the class of type " << typeid(T).name() << "?");
330        return ClassIdentifier<T>::classIdentifier_s;
331    }
332
333    /**
334        @brief Adds an object of the given type to the ObjectList.
335        @param object The object to add
336    */
337    template <class T>
338    bool ClassIdentifier<T>::initializeObject(T* object)
339    {
340        orxout(verbose, context::object_list) << "Register Object: " << this->getName() << endl;
341
342        object->identifier_ = this;
343        if (IdentifierManager::getInstance().isCreatingHierarchy())
344        {
345            IdentifierManager::getInstance().createdObject(object);
346
347            if (Identifier::initConfigValues_s)
348                this->setConfigValues(object, object);
349
350            return true;
351        }
352        else
353        {
354            this->addObjectToList(object, object);
355
356            // Add pointer of type T to the map in the Identifiable instance that enables "dynamic_casts"
357            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
358            return false;
359        }
360    }
361
362    /**
363     * @brief Only configures the object if is a @ref Configurable
364     */
365    template <class T>
366    void ClassIdentifier<T>::setConfigValues(T* object, Configurable*) const
367    {
368        object->setConfigValues();
369    }
370
371    template <class T>
372    void ClassIdentifier<T>::setConfigValues(T*, Identifiable*) const
373    {
374        // no action
375    }
376
377    /**
378     * @brief Only adds the object to the object list if is a @ref Listable
379     */
380    template <class T>
381    void ClassIdentifier<T>::addObjectToList(T* object, Listable* listable)
382    {
383        if (listable->getContext())
384            listable->getContext()->addObject(object);
385    }
386
387    template <class T>
388    void ClassIdentifier<T>::addObjectToList(T*, Identifiable*)
389    {
390        // no action
391    }
392
393    /**
394        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
395    */
396    template <class T>
397    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
398    {
399        this->updateConfigValues(updateChildren, static_cast<T*>(NULL));
400    }
401
402    template <class T>
403    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Listable*) const
404    {
405        if (!this->hasConfigValues())
406            return;
407
408        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
409            this->setConfigValues(*it, *it);
410
411        if (updateChildren)
412            for (std::set<const Identifier*>::const_iterator it = this->getChildren().begin(); it != this->getChildren().end(); ++it)
413                (*it)->updateConfigValues(false);
414    }
415
416    template <class T>
417    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Identifiable*) const
418    {
419        // no action
420    }
421
422
423    // ###############################
424    // ###      orxonox_cast       ###
425    // ###############################
426    /**
427    @brief
428        Casts on object of type Identifiable to any derived type that is
429        registered in the class hierarchy.
430    @return
431        Returns NULL if the cast is not possible
432    @note
433        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
434        a class forgot to register its objects.
435        Also note that the function is implemented differently for GCC/MSVC.
436    */
437    template <class T, class U>
438    ORX_FORCEINLINE T orxonox_cast(U* source)
439    {
440#ifdef ORXONOX_COMPILER_MSVC
441        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
442        if (source != NULL)
443            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
444        else
445            return NULL;
446#else
447        return dynamic_cast<T>(source);
448#endif
449    }
450}
451
452#endif /* _Identifier_H__ */
Note: See TracBrowser for help on using the repository browser.