Index: /code/branches/libraries2/src/libraries/core/ArgumentCompleter.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ArgumentCompleter.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ArgumentCompleter.h	(revision 5712)
@@ -0,0 +1,79 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ArgumentCompleter_H__
+#define _ArgumentCompleter_H__
+
+#include "CorePrereqs.h"
+#include "ArgumentCompletionListElement.h"
+
+namespace orxonox
+{
+    class _CoreExport ArgumentCompleter
+    {
+        public:
+            ArgumentCompleter(ArgumentCompletionList (*function) (void)) : paramCount_(0), function_0_(function) {}
+            ArgumentCompleter(ArgumentCompletionList (*function) (const std::string& param1)) : paramCount_(1), function_1_(function) {}
+            ArgumentCompleter(ArgumentCompletionList (*function) (const std::string& param1, const std::string& param2)) : paramCount_(2), function_2_(function) {}
+            ArgumentCompleter(ArgumentCompletionList (*function) (const std::string& param1, const std::string& param2, const std::string& param3)) : paramCount_(3), function_3_(function) {}
+            ArgumentCompleter(ArgumentCompletionList (*function) (const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4)) : paramCount_(4), function_4_(function) {}
+            ArgumentCompleter(ArgumentCompletionList (*function) (const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4, const std::string& param5)) : paramCount_(5), function_5_(function) {}
+
+            ArgumentCompletionList operator()(const std::string& param1 = "", const std::string& param2 = "", const std::string& param3 = "", const std::string& param4 = "", const std::string& param5 = "")
+            {
+                switch (this->paramCount_)
+                {
+                    case 0:
+                        return (*this->function_0_)();
+                    case 1:
+                        return (*this->function_1_)(param1);
+                    case 2:
+                        return (*this->function_2_)(param1, param2);
+                    case 3:
+                        return (*this->function_3_)(param1, param2, param3);
+                    case 4:
+                        return (*this->function_4_)(param1, param2, param3, param4);
+                    case 5:
+                        return (*this->function_5_)(param1, param2, param3, param4, param5);
+                    default:
+                        return ArgumentCompletionList();
+                }
+            }
+
+        private:
+            unsigned char paramCount_;
+            ArgumentCompletionList (*function_0_) (void);
+            ArgumentCompletionList (*function_1_) (const std::string& param1);
+            ArgumentCompletionList (*function_2_) (const std::string& param1, const std::string& param2);
+            ArgumentCompletionList (*function_3_) (const std::string& param1, const std::string& param2, const std::string& param3);
+            ArgumentCompletionList (*function_4_) (const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4);
+            ArgumentCompletionList (*function_5_) (const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4, const std::string& param5);
+    };
+}
+
+#endif /* _ArgumentCompleter_H__ */
Index: /code/branches/libraries2/src/libraries/core/ArgumentCompletionFunctions.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ArgumentCompletionFunctions.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ArgumentCompletionFunctions.cc	(revision 5712)
@@ -0,0 +1,150 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "ArgumentCompletionFunctions.h"
+
+#include <map>
+#include <boost/version.hpp>
+#include <boost/filesystem.hpp>
+
+#include "util/Convert.h"
+#include "util/StringUtils.h"
+#include "Identifier.h"
+#include "ConfigValueContainer.h"
+#include "TclThreadManager.h"
+
+// Boost 1.36 has some issues with deprecated functions that have been omitted
+#if (BOOST_VERSION == 103600)
+#  define BOOST_LEAF_FUNCTION filename
+#else
+#  define BOOST_LEAF_FUNCTION leaf
+#endif
+
+namespace orxonox
+{
+    namespace autocompletion
+    {
+        ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(fallback)()
+        {
+            return ArgumentCompletionList();
+        }
+
+        ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(files)(const std::string& fragment)
+        {
+            ArgumentCompletionList dirlist;
+            ArgumentCompletionList filelist;
+
+            try
+            {
+                boost::filesystem::path input(fragment);
+                boost::filesystem::path startdirectory(input.branch_path());
+
+                if (!boost::filesystem::exists(startdirectory))
+                {
+                    startdirectory = ".";
+                }
+#ifdef ORXONOX_PLATFORM_WINDOWS
+                else
+                {
+                    std::string dir = startdirectory.string();
+                    if (dir.size() > 0 && dir[dir.size() - 1] == ':')
+                        startdirectory = dir + '/';
+                }
+#endif
+
+                boost::filesystem::directory_iterator file(startdirectory);
+                boost::filesystem::directory_iterator end;
+
+                while (file != end)
+                {
+                    if (boost::filesystem::is_directory(*file))
+                        dirlist.push_back(ArgumentCompletionListElement((*file).string() + '/', getLowercase((*file).string()) + '/', (*file).BOOST_LEAF_FUNCTION() + '/'));
+                    else
+                        filelist.push_back(ArgumentCompletionListElement((*file).string(), getLowercase((*file).string()), (*file).BOOST_LEAF_FUNCTION()));
+                    ++file;
+                }
+            }
+            catch (...) {}
+
+            filelist.insert(filelist.begin(), dirlist.begin(), dirlist.end());
+            return filelist;
+        }
+
+        ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(configvalueclasses)()
+        {
+            ArgumentCompletionList classlist;
+
+            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
+                if ((*it).second->hasConfigValues())
+                    classlist.push_back(ArgumentCompletionListElement((*it).second->getName(), getLowercase((*it).first)));
+
+            return classlist;
+        }
+
+        ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(configvalues)(const std::string& fragment, const std::string& classname)
+        {
+            ArgumentCompletionList configvalues;
+            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getIdentifierMap().find(classname);
+
+            if (identifier != Identifier::getIdentifierMapEnd() && (*identifier).second->hasConfigValues())
+            {
+                for (std::map<std::string, ConfigValueContainer*>::const_iterator it = (*identifier).second->getConfigValueMapBegin(); it != (*identifier).second->getConfigValueMapEnd(); ++it)
+                    configvalues.push_back(ArgumentCompletionListElement((*it).second->getName(), getLowercase((*it).first)));
+            }
+
+            return configvalues;
+        }
+
+        ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(configvalue)(const std::string& fragment, const std::string& varname, const std::string& classname)
+        {
+            ArgumentCompletionList oldvalue;
+            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
+            if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+            {
+                std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
+                if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())
+                {
+                    std::string valuestring = (*variable).second->toString();
+                    oldvalue.push_back(ArgumentCompletionListElement(valuestring, getLowercase(valuestring), "Old value: " + valuestring));
+                }
+            }
+            return oldvalue;
+        }
+
+        ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(tclthreads)()
+        {
+            std::list<unsigned int> threadnumbers = TclThreadManager::getInstance().getThreadList();
+            ArgumentCompletionList threads;
+
+            for (std::list<unsigned int>::const_iterator it = threadnumbers.begin(); it != threadnumbers.end(); ++it)
+                threads.push_back(ArgumentCompletionListElement(multi_cast<std::string>(*it)));
+
+            return threads;
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ArgumentCompletionFunctions.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ArgumentCompletionFunctions.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ArgumentCompletionFunctions.h	(revision 5712)
@@ -0,0 +1,63 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ArgumentCompletionFunctions_H__
+#define _ArgumentCompletionFunctions_H__
+
+#include "CorePrereqs.h"
+#include "ArgumentCompleter.h"
+
+
+#define ARGUMENT_COMPLETION_FUNCTION_DECLARATION(functionname) \
+    _CoreExport ArgumentCompleter* functionname(); \
+    _CoreExport ArgumentCompletionList acf_##functionname
+
+#define ARGUMENT_COMPLETION_FUNCTION_IMPLEMENTATION(functionname) \
+    ArgumentCompleter* functionname() \
+    { \
+        static ArgumentCompleter completer = ArgumentCompleter(&acf_##functionname); \
+        return &completer; \
+    } \
+    \
+    ArgumentCompletionList acf_##functionname
+
+
+namespace orxonox
+{
+    namespace autocompletion
+    {
+        ARGUMENT_COMPLETION_FUNCTION_DECLARATION(fallback)();
+        ARGUMENT_COMPLETION_FUNCTION_DECLARATION(files)(const std::string& fragment);
+        ARGUMENT_COMPLETION_FUNCTION_DECLARATION(configvalueclasses)();
+        ARGUMENT_COMPLETION_FUNCTION_DECLARATION(configvalues)(const std::string& fragment, const std::string& classname);
+        ARGUMENT_COMPLETION_FUNCTION_DECLARATION(configvalue)(const std::string& fragment, const std::string& varname, const std::string& classname);
+        ARGUMENT_COMPLETION_FUNCTION_DECLARATION(tclthreads)();
+    }
+}
+
+#endif /* _ArgumentCompletionFunctions_H__ */
Index: /code/branches/libraries2/src/libraries/core/ArgumentCompletionListElement.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ArgumentCompletionListElement.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ArgumentCompletionListElement.h	(revision 5712)
@@ -0,0 +1,73 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ArgumentCompletionListElement_H__
+#define _ArgumentCompletionListElement_H__
+
+#include "CorePrereqs.h"
+
+#include <list>
+#include <string>
+
+namespace orxonox
+{
+    const int ACL_MODE_NORMAL    = 1;
+    const int ACL_MODE_LOWERCASE = 2;
+    const int ACL_MODE_DISPLAY   = 4;
+
+    typedef std::list<ArgumentCompletionListElement> ArgumentCompletionList;
+
+    class _CoreExport ArgumentCompletionListElement
+    {
+        public:
+            ArgumentCompletionListElement(const std::string& normalcase) : mode_(ACL_MODE_NORMAL), normalCase_(normalcase) {}
+            ArgumentCompletionListElement(const std::string& normalcase, const std::string& lowercase) : mode_(ACL_MODE_NORMAL | ACL_MODE_LOWERCASE), normalCase_(normalcase), lowerCase_(lowercase) {}
+            ArgumentCompletionListElement(const std::string& normalcase, const std::string& lowercase, const std::string& display) : mode_(ACL_MODE_NORMAL | ACL_MODE_LOWERCASE | ACL_MODE_DISPLAY), normalCase_(normalcase), lowerCase_(lowercase), display_(display) {}
+
+            const std::string& getString() const
+                { return this->normalCase_; }
+            const std::string& getComparable() const
+                { if (this->mode_ & ACL_MODE_LOWERCASE) { return this->lowerCase_; } else { return this->normalCase_; } }
+            const std::string& getDisplay() const
+                { if (this->mode_ & ACL_MODE_DISPLAY) { return this->display_; } else { return this->normalCase_; } }
+
+            bool lowercaseComparison() const
+                { return (this->mode_ & ACL_MODE_LOWERCASE); }
+
+            bool operator<(const ArgumentCompletionListElement& other) const
+                { return (this->getComparable() < other.getComparable()); }
+
+        private:
+            unsigned char mode_;
+            std::string normalCase_;
+            std::string lowerCase_;
+            std::string display_;
+    };
+}
+
+#endif /* _ArgumentCompletionListElement_H__ */
Index: /code/branches/libraries2/src/libraries/core/BaseObject.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/BaseObject.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/BaseObject.cc	(revision 5712)
@@ -0,0 +1,342 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the BaseObject class.
+*/
+
+#include "BaseObject.h"
+
+#include <tinyxml/tinyxml.h>
+
+#include "util/StringUtils.h"
+#include "CoreIncludes.h"
+#include "Event.h"
+#include "EventIncludes.h"
+#include "Functor.h"
+#include "Iterator.h"
+#include "Template.h"
+#include "XMLFile.h"
+#include "XMLNameListener.h"
+#include "XMLPort.h"
+
+namespace orxonox
+{
+    CreateFactory(BaseObject);
+
+    /**
+        @brief Constructor: Registers the object in the BaseObject-list.
+    */
+    BaseObject::BaseObject(BaseObject* creator) : bInitialized_(false)
+    {
+        RegisterRootObject(BaseObject);
+
+        this->bInitialized_ = true;
+
+        this->bActive_ = true;
+        this->bVisible_ = true;
+        this->oldGametype_ = 0;
+
+        this->lastLoadedXMLElement_ = 0;
+
+        this->functorSetMainState_ = 0;
+        this->functorGetMainState_ = 0;
+
+        this->setCreator(creator);
+        if (this->creator_)
+        {
+            this->setFile(this->creator_->getFile());
+            this->setNamespace(this->creator_->getNamespace());
+            this->setScene(this->creator_->getScene());
+            this->setGametype(this->creator_->getGametype());
+        }
+        else
+        {
+            this->file_ = 0;
+            this->namespace_ = 0;
+            this->scene_ = 0;
+            this->gametype_ = 0;
+        }
+    }
+
+    /**
+        @brief Destructor
+    */
+    BaseObject::~BaseObject()
+    {
+        if (this->isInitialized())
+        {
+            for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
+                (*it)->unregisterEventListener(this);
+
+            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
+                it->first->removeEvent(this);
+
+            if (this->functorSetMainState_)
+                delete this->functorSetMainState_;
+            if (this->functorGetMainState_)
+                delete this->functorGetMainState_;
+        }
+    }
+
+    /**
+        @brief XML loading and saving.
+        @param xmlelement The XML-element
+        @param loading Loading (true) or saving (false)
+        @return The XML-element
+    */
+    void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        XMLPortParam(BaseObject, "name", setXMLName, getName, xmlelement, mode);
+        XMLPortParam(BaseObject, "visible", setVisible, isVisible, xmlelement, mode);
+        XMLPortParam(BaseObject, "active", setActive, isActive, xmlelement, mode);
+        XMLPortParam(BaseObject, "mainstate", setMainStateName, getMainStateName, xmlelement, mode);
+
+        XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
+
+        Element* events = xmlelement.FirstChildElement("events", false);
+
+        if (events)
+        {
+            std::list<std::string> eventnames;
+
+            if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
+            {
+                for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
+                    eventnames.push_back(child->Value());
+            }
+            else if (mode == XMLPort::SaveObject)
+            {
+                for (std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->getIdentifier()->getXMLPortEventMapBegin(); it != this->getIdentifier()->getXMLPortEventMapEnd(); ++it)
+                    eventnames.push_back(it->first);
+            }
+
+            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
+            {
+                std::string sectionname = (*it);
+                ExecutorMember<BaseObject>* loadexecutor = createExecutor(createFunctor(&BaseObject::addEvent), std::string( "BaseObject" ) + "::" + "addEvent");
+                ExecutorMember<BaseObject>* saveexecutor = createExecutor(createFunctor(&BaseObject::getEvent), std::string( "BaseObject" ) + "::" + "getEvent");
+                loadexecutor->setDefaultValue(1, sectionname);
+
+                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = 0;
+                container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(this->getIdentifier()->getXMLPortEventContainer(sectionname));
+                if (!container)
+                {
+                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(sectionname, this->getIdentifier(), loadexecutor, saveexecutor, false, true);
+                    this->getIdentifier()->addXMLPortEventContainer(sectionname, container);
+                }
+                container->port(this, *events, mode);
+            }
+        }
+    }
+
+    /**
+        @brief Loads the name of the object through XML and calls all XMLNameListener.
+        @param name The name of the object
+    */
+    void BaseObject::setXMLName(const std::string& name)
+    {
+        this->setName(name);
+
+        for (ObjectList<XMLNameListener>::iterator it = ObjectList<XMLNameListener>::begin(); it != ObjectList<XMLNameListener>::end(); ++it)
+            it->loadedNewXMLName(this);
+    }
+
+    /**
+        @brief Returns the levelfile that loaded this object.
+        @return The levelfile
+    */
+    const std::string& BaseObject::getFilename() const
+    {
+        if (this->file_)
+            return this->file_->getFilename();
+        else
+            return BLANKSTRING;
+    }
+
+    /**
+        @brief Adds a Template to the object.
+        @param name The name of the Template
+    */
+    void BaseObject::addTemplate(const std::string& name)
+    {
+        Template* temp = Template::getTemplate(name);
+        if (temp)
+            this->addTemplate(temp);
+        else
+            COUT(1) << "Error: \"" << name << "\" is not a valid Template name (in class: " << this->getIdentifier()->getName() << ", name: " << this->getName() << ")." << std::endl;
+    }
+
+    /**
+        @brief Adds a Template to the object.
+        @param temp The Template
+    */
+    void BaseObject::addTemplate(Template* temp)
+    {
+        this->templates_.insert(temp);
+        temp->applyOn(this);
+    }
+
+    /**
+        @brief Returns the Template with the given index.
+        @param index The index
+    */
+    Template* BaseObject::getTemplate(unsigned int index) const
+    {
+        unsigned int i = 0;
+        for (std::set<Template*>::const_iterator it = this->templates_.begin(); it != this->templates_.end(); ++it)
+        {
+            if (i == index)
+                return (*it);
+            i++;
+        }
+        return 0;
+    }
+
+    void BaseObject::addEvent(BaseObject* event, const std::string& sectionname)
+    {
+        event->registerEventListener(this, sectionname);
+        this->events_.push_back(event);
+    }
+
+    void BaseObject::removeEvent(BaseObject* event)
+    {
+        this->events_.remove(event);
+    }
+
+    BaseObject* BaseObject::getEvent(unsigned int index) const
+    {
+        unsigned int i = 0;
+        for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
+        {
+            if (i == index)
+                return (*it);
+            ++i;
+        }
+        return 0;
+    }
+
+    void BaseObject::addEventContainer(const std::string& sectionname, EventContainer* container)
+    {
+        std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
+        if (it != this->eventContainers_.end())
+        {
+            COUT(2) << "Warning: Overwriting EventContainer in class " << this->getIdentifier()->getName() << "." << std::endl;
+            delete (it->second);
+        }
+
+        this->eventContainers_[sectionname] = container;
+    }
+
+    EventContainer* BaseObject::getEventContainer(const std::string& sectionname) const
+    {
+        std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
+        if (it != this->eventContainers_.end())
+            return ((*it).second);
+        else
+            return 0;
+    }
+
+    void BaseObject::fireEvent()
+    {
+        this->fireEvent(true);
+        this->fireEvent(false);
+    }
+
+    void BaseObject::fireEvent(bool activate)
+    {
+        this->fireEvent(activate, this);
+    }
+
+    void BaseObject::fireEvent(bool activate, BaseObject* originator)
+    {
+        Event event(activate, originator);
+
+        for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
+        {
+            event.sectionname_ = it->second;
+            it->first->processEvent(event);
+        }
+    }
+
+    void BaseObject::fireEvent(Event& event)
+    {
+        for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
+            it->first->processEvent(event);
+    }
+
+    void BaseObject::processEvent(Event& event)
+    {
+        ORXONOX_SET_EVENT(BaseObject, "activity", setActive, event);
+        ORXONOX_SET_EVENT(BaseObject, "visibility", setVisible, event);
+    }
+
+    void BaseObject::setMainStateName(const std::string& name)
+    {
+        if (this->mainStateName_ != name)
+        {
+            this->mainStateName_ = name;
+            if (this->functorSetMainState_)
+                delete this->functorSetMainState_;
+            if (this->functorGetMainState_)
+                delete this->functorGetMainState_;
+            this->changedMainState();
+            if (!this->functorSetMainState_)
+                COUT(2) << "Warning: \"" << name << "\" is not a valid MainState." << std::endl;
+        }
+    }
+
+    void BaseObject::setMainState(bool state)
+    {
+        if (this->functorSetMainState_)
+            (*this->functorSetMainState_)(state);
+        else
+            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
+    }
+
+    bool BaseObject::getMainState() const
+    {
+        if (this->functorGetMainState_)
+        {
+            (*this->functorGetMainState_)();
+            return this->functorGetMainState_->getReturnvalue();
+        }
+        else
+        {
+            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
+            return false;
+        }
+    }
+
+    void BaseObject::changedMainState()
+    {
+        SetMainState(BaseObject, "activity",   setActive,  isActive);
+        SetMainState(BaseObject, "visibility", setVisible, isVisible);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/BaseObject.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/BaseObject.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/BaseObject.h	(revision 5712)
@@ -0,0 +1,214 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the BaseObject class.
+
+    The BaseObject is the parent of all classes representing an instance in the game.
+*/
+
+#ifndef _BaseObject_H__
+#define _BaseObject_H__
+
+#define SetMainState(classname, statename, setfunction, getfunction) \
+    if (this->getMainStateName() == statename) \
+    { \
+        this->functorSetMainState_ = createFunctor(&classname::setfunction)->setObject(this); \
+        this->functorGetMainState_ = createFunctor(&classname::getfunction)->setObject(this); \
+    }
+
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <list>
+
+#include "util/mbool.h"
+#include "OrxonoxClass.h"
+#include "Super.h"
+
+namespace orxonox
+{
+    class Scene;
+    class Gametype;
+
+    //! The BaseObject is the parent of all classes representing an instance in the game.
+    class _CoreExport BaseObject : virtual public OrxonoxClass
+    {
+        template <class T> friend class XMLPortClassParamContainer;
+
+        public:
+            BaseObject(BaseObject* creator);
+            virtual ~BaseObject();
+            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+
+            /** @brief Returns if the object was initialized (passed the object registration). @return True was the object is initialized */
+            inline bool isInitialized() const { return this->bInitialized_; }
+
+            /** @brief Sets the name of the object. @param name The name */
+            inline void setName(const std::string& name) { this->oldName_ = this->name_; this->name_ = name; this->changedName(); }
+            /** @brief Returns the name of the object. */
+            inline const std::string& getName() const { return this->name_; }
+            /** @brief Returns the old name of the object. */
+            inline const std::string& getOldName() const { return this->oldName_; }
+            /** @brief This function gets called if the name of the object changes. */
+            virtual void changedName() {}
+
+            /** @brief Sets the state of the objects activity. @param bActive True = active */
+            inline void setActive(bool bActive)
+            {
+                if (this->bActive_ != bActive)
+                {
+                    this->bActive_ = bActive;
+                    this->changedActivity();
+                }
+            }
+            /** @brief Returns the state of the objects activity. @return The state of the activity */
+            inline const mbool& isActive() const { return this->bActive_; }
+            /** @brief This function gets called if the activity of the object changes. */
+            virtual void changedActivity() {}
+
+            /** @brief Sets the state of the objects visibility. @param bVisible True = visible */
+            inline void setVisible(bool bVisible)
+            {
+                if (this->bVisible_ != bVisible)
+                {
+                    this->bVisible_ = bVisible;
+                    this->changedVisibility();
+                }
+            }
+            /** @brief Returns the state of the objects visibility. @return The state of the visibility */
+            inline const mbool& isVisible() const { return this->bVisible_; }
+            /** @brief This function gets called if the visibility of the object changes. */
+            virtual void changedVisibility() {}
+
+            void setMainState(bool state);
+            bool getMainState() const;
+
+            void setMainStateName(const std::string& name);
+            inline const std::string& getMainStateName() const { return this->mainStateName_; }
+            virtual void changedMainState();
+
+            /** @brief Sets a pointer to the xml file that loaded this object. @param file The pointer to the XMLFile */
+            inline void setFile(const XMLFile* file) { this->file_ = file; }
+            /** @brief Returns a pointer to the XMLFile that loaded this object. @return The XMLFile */
+            inline const XMLFile* getFile() const { return this->file_; }
+            const std::string& getFilename() const;
+
+            void addTemplate(const std::string& name);
+            void addTemplate(Template* temp);
+            /** @brief Returns the set of all aplied templates. */
+            inline const std::set<Template*>& getTemplates() const
+                { return this->templates_; }
+
+            virtual inline void setNamespace(Namespace* ns) { this->namespace_ = ns; }
+            inline Namespace* getNamespace() const { return this->namespace_; }
+
+            inline void setCreator(BaseObject* creator) { this->creator_ = creator; }
+            inline BaseObject* getCreator() const { return this->creator_; }
+
+            inline void setScene(Scene* scene) { this->scene_ = scene; }
+            inline Scene* getScene() const { return this->scene_; }
+
+            inline void setGametype(Gametype* gametype)
+            {
+                if (gametype != this->gametype_)
+                {
+                    this->oldGametype_ = this->gametype_;
+                    this->gametype_ = gametype;
+                    this->changedGametype();
+                }
+            }
+            inline Gametype* getGametype() const { return this->gametype_; }
+            inline Gametype* getOldGametype() const { return this->oldGametype_; }
+            virtual void changedGametype() {}
+
+            void fireEvent();
+            void fireEvent(bool activate);
+            void fireEvent(bool activate, BaseObject* originator);
+            void fireEvent(Event& event);
+
+            virtual void processEvent(Event& event);
+
+            inline void registerEventListener(BaseObject* object, const std::string& sectionname)
+                { this->eventListeners_[object] = sectionname; }
+            inline void unregisterEventListener(BaseObject* object)
+                { this->eventListeners_.erase(object); }
+
+            void addEvent(BaseObject* event, const std::string& sectionname);
+            void removeEvent(BaseObject* event);
+            BaseObject* getEvent(unsigned int index) const;
+
+            void addEventContainer(const std::string& sectionname, EventContainer* container);
+            EventContainer* getEventContainer(const std::string& sectionname) const;
+
+            /** @brief Sets the indentation of the debug output in the Loader. @param indentation The indentation */
+            inline void setLoaderIndentation(const std::string& indentation) { this->loaderIndentation_ = indentation; }
+            /** @brief Returns the indentation of the debug output in the Loader. @return The indentation */
+            inline const std::string& getLoaderIndentation() const { return this->loaderIndentation_; }
+
+        protected:
+            std::string name_;                                 //!< The name of the object
+            std::string oldName_;                              //!< The old name of the object
+            mbool       bActive_;                              //!< True = the object is active
+            mbool       bVisible_;                             //!< True = the object is visible
+            std::string mainStateName_;
+            Functor*    functorSetMainState_;
+            Functor*    functorGetMainState_;
+
+        private:
+            void setXMLName(const std::string& name);
+            Template* getTemplate(unsigned int index) const;
+
+            bool                   bInitialized_;              //!< True if the object was initialized (passed the object registration)
+            const XMLFile*         file_;                      //!< The XMLFile that loaded this object
+            Element*               lastLoadedXMLElement_;      //!< Non 0 if the TinyXML attributes have already been copied to our own lowercase map
+            std::map<std::string, std::string> xmlAttributes_; //!< Lowercase XML attributes
+            std::string            loaderIndentation_;         //!< Indentation of the debug output in the Loader
+            Namespace*             namespace_;
+            BaseObject*            creator_;
+            Scene*                 scene_;
+            Gametype*              gametype_;
+            Gametype*              oldGametype_;
+            std::set<Template*>    templates_;
+            std::map<BaseObject*,  std::string> eventListeners_;
+            std::list<BaseObject*> events_;
+            std::map<std::string, EventContainer*> eventContainers_;
+    };
+
+    SUPER_FUNCTION(0, BaseObject, XMLPort, false);
+    SUPER_FUNCTION(2, BaseObject, changedActivity, false);
+    SUPER_FUNCTION(3, BaseObject, changedVisibility, false);
+    SUPER_FUNCTION(4, BaseObject, processEvent, false);
+    SUPER_FUNCTION(6, BaseObject, changedMainState, false);
+    SUPER_FUNCTION(9, BaseObject, changedName, false);
+    SUPER_FUNCTION(10, BaseObject, changedGametype, false);
+}
+
+#endif /* _BaseObject_H__ */
Index: /code/branches/libraries2/src/libraries/core/CMakeLists.txt
===================================================================
--- /code/branches/libraries2/src/libraries/core/CMakeLists.txt	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CMakeLists.txt	(revision 5712)
@@ -0,0 +1,104 @@
+ #
+ #             ORXONOX - the hottest 3D action shooter ever to exist
+ #                             > www.orxonox.net <
+ #
+ #        This program is free software; you can redistribute it and/or
+ #         modify it under the terms of the GNU General Public License
+ #        as published by the Free Software Foundation; either version 2
+ #            of the License, or (at your option) any later version.
+ #
+ #       This program is distributed in the hope that it will be useful,
+ #        but WITHOUT ANY WARRANTY; without even the implied warranty of
+ #        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ #                 GNU General Public License for more details.
+ #
+ #   You should have received a copy of the GNU General Public License along
+ #      with this program; if not, write to the Free Software Foundation,
+ #     Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ #
+
+SET_SOURCE_FILES(CORE_SRC_FILES
+  Clock.cc
+  ConfigFileManager.cc
+  ConfigValueContainer.cc
+  Core.cc
+  DynLib.cc
+  DynLibManager.cc
+  Event.cc
+  Game.cc
+  GameMode.cc
+  GameState.cc
+  GraphicsManager.cc
+  GUIManager.cc
+  Language.cc
+  LuaState.cc
+  MemoryArchive.cc
+  ObjectListBase.cc
+  OrxonoxClass.cc
+  Resource.cc
+  WindowEventListener.cc
+
+  # command
+  ArgumentCompletionFunctions.cc
+  CommandEvaluation.cc
+  CommandExecutor.cc
+  CommandLine.cc
+  ConsoleCommand.cc
+  ConsoleCommandCompilation.cc
+  Executor.cc
+
+  # hierarchy
+  Factory.cc
+  Identifier.cc
+  MetaObjectList.cc
+
+  # level
+  BaseObject.cc
+  ClassTreeMask.cc
+  Loader.cc
+  Namespace.cc
+  NamespaceNode.cc
+  Template.cc
+  XMLPort.cc
+  XMLNameListener.cc
+
+  # shell
+  IRC.cc
+  Shell.cc
+  TclBind.cc
+  TclThreadManager.cc
+  
+  # multithreading
+  Thread.cc
+  ThreadPool.cc
+)
+ADD_SUBDIRECTORY(input)
+
+ORXONOX_ADD_LIBRARY(core
+  FIND_HEADER_FILES
+  TOLUA_FILES
+    CommandExecutor.h
+    Loader.h
+    LuaState.h
+  DEFINE_SYMBOL
+    "CORE_SHARED_BUILD"
+  PCH_FILE
+    CorePrecompiledHeaders.h
+  LINK_LIBRARIES
+    ${OGRE_LIBRARY}
+    ${Boost_FILESYSTEM_LIBRARY}
+    ${Boost_SYSTEM_LIBRARY} # Filesystem dependency
+    ${Boost_THREAD_LIBRARY}
+    ${Boost_DATE_TIME_LIBRARY} # Thread dependency
+    ${CEGUI_LIBRARY}
+    ${CEGUILUA_LIBRARY}
+    ${LUA_LIBRARIES}
+    cpptcl_orxonox
+    ogreceguirenderer_orxonox
+    ois_orxonox
+    tinyxml++_orxonox
+    tolua++_orxonox
+    util
+  SOURCE_FILES
+    ${CORE_SRC_FILES}
+)
Index: /code/branches/libraries2/src/libraries/core/ClassFactory.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ClassFactory.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ClassFactory.h	(revision 5712)
@@ -0,0 +1,106 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition and implementation of the ClassFactory class
+
+    The ClassFactory is able to create new objects of a specific class.
+*/
+
+#ifndef _ClassFactory_H__
+#define _ClassFactory_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+
+#include "util/Debug.h"
+#include "Factory.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###      ClassFactory       ###
+    // ###############################
+    //! The ClassFactory is able to create new objects of a specific class.
+    template <class T>
+    class ClassFactory : public BaseFactory
+    {
+        public:
+            static bool create(const std::string& name, bool bLoadable = true);
+            BaseObject* fabricate(BaseObject* creator);
+
+        private:
+            ClassFactory() {}                               // Don't create
+            ClassFactory(const ClassFactory& factory) {}    // Don't copy
+            virtual ~ClassFactory() {}                      // Don't delete
+
+            static T* createNewObject(BaseObject* creator);
+    };
+
+    /**
+        @brief Adds the ClassFactory to the Identifier of the same type and the Identifier to the Factory.
+        @param name The name of the class
+        @param bLoadable True if the class can be loaded through XML
+        @return Always true (this is needed because the compiler only allows assignments before main())
+    */
+    template <class T>
+    bool ClassFactory<T>::create(const std::string& name, bool bLoadable)
+    {
+        COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
+        ClassIdentifier<T>::getIdentifier(name)->addFactory(new ClassFactory<T>);
+        ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
+        Factory::add(name, ClassIdentifier<T>::getIdentifier());
+
+        return true;
+    }
+
+    /**
+        @brief Creates and returns a new object of class T.
+        @return The new object
+    */
+    template <class T>
+    inline BaseObject* ClassFactory<T>::fabricate(BaseObject* creator)
+    {
+        return ClassFactory<T>::createNewObject(creator);
+    }
+
+    /**
+        @brief Creates and returns a new object of class T; this is a wrapper for the new operator.
+        @return The new object
+    */
+    template <class T>
+    inline T* ClassFactory<T>::createNewObject(BaseObject* creator)
+    {
+        return new T(creator);
+    }
+}
+
+#endif /* _ClassFactory_H__ */
Index: /code/branches/libraries2/src/libraries/core/ClassTreeMask.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ClassTreeMask.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ClassTreeMask.cc	(revision 5712)
@@ -0,0 +1,963 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the ClassTreeMask, ClassTreeMaskNode and ClassTreeMaskIterator classes.
+*/
+
+#include "ClassTreeMask.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###    ClassTreeMaskNode    ###
+    // ###############################
+    /**
+        @brief Constructor: Creates the node, sets the subclass and the rule.
+        @param subclass The subclass the rule refers to
+        @param bIncluded The rule: included (true) or excluded (false)
+    */
+    ClassTreeMaskNode::ClassTreeMaskNode(const Identifier* subclass, bool bIncluded)
+    {
+        this->subclass_ = subclass;
+        this->bIncluded_ = bIncluded;
+    }
+
+    /**
+        @brief Destructor: Deletes all subnodes.
+    */
+    ClassTreeMaskNode::~ClassTreeMaskNode()
+    {
+        // Go through the list of all subnodes and delete them
+        this->deleteAllSubnodes();
+    }
+
+    /**
+        @brief Sets the rule for the node to "included".
+        @param overwrite True = overwrite previously added rules for inheriting classes
+    */
+    void ClassTreeMaskNode::include(bool overwrite)
+    {
+        this->setIncluded(true, overwrite);
+    }
+
+    /**
+        @brief Sets the rule for the node to "excluded".
+        @param overwrite True = overwrite previously added rules for inheriting classes
+    */
+    void ClassTreeMaskNode::exclude(bool overwrite)
+    {
+        this->setIncluded(false, overwrite);
+    }
+
+    /**
+        @brief Sets the rule for the node to a given value and erases all following rules.
+        @param bIncluded The rule: included (true) or excluded (false)
+        @param overwrite True = overwrite previously added rules for inheriting classes
+    */
+    void ClassTreeMaskNode::setIncluded(bool bIncluded, bool overwrite)
+    {
+        if (overwrite)
+            this->deleteAllSubnodes();
+
+        this->bIncluded_ = bIncluded;
+    }
+
+    /**
+        @brief Adds a new subnode to the list of subnodes.
+        @param subnode The new subnode
+    */
+    void ClassTreeMaskNode::addSubnode(ClassTreeMaskNode* subnode)
+    {
+        this->subnodes_.insert(this->subnodes_.end(), subnode);
+    }
+
+    /**
+        @brief Deletes all subnodes of this node.
+    */
+    void ClassTreeMaskNode::deleteAllSubnodes()
+    {
+        // Go through the list of all subnodes and delete them
+        for (std::list<ClassTreeMaskNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); )
+            delete (*(it++));
+
+        // Clear the list
+        this->subnodes_.clear();
+    }
+
+
+    // ###############################
+    // ###  ClassTreeMaskIterator  ###
+    // ###############################
+    /**
+        @brief Constructor: Initializes the iterator by creating a helper-list with the root-node and putting it to the stack.
+        @param node The root-node
+    */
+    ClassTreeMaskIterator::ClassTreeMaskIterator(ClassTreeMaskNode* node)
+    {
+        // Create a list and put the root-note into it
+        std::list<ClassTreeMaskNode*>::iterator it = this->rootlist_.insert(this->rootlist_.end(), node);
+
+        // Put the iterator to the only element of the list and the corresponding end()-iterator on the stack
+        this->nodes_.push(std::pair<std::list<ClassTreeMaskNode*>::iterator, std::list<ClassTreeMaskNode*>::iterator>(it, this->rootlist_.end()));
+    }
+
+    /**
+        @brief Destructor: Does nothing.
+    */
+    ClassTreeMaskIterator::~ClassTreeMaskIterator()
+    {
+    }
+
+    /**
+        @brief Iterates through the rule-tree.
+        @return A reference to the iterator itself
+    */
+    const ClassTreeMaskIterator& ClassTreeMaskIterator::operator++()
+    {
+        // Check if the actual node has subnodes
+        if ((*this->nodes_.top().first)->subnodes_.begin() != (*this->nodes_.top().first)->subnodes_.end())
+        {
+            // Yes it has: Push an iterator, pointing at the first subnode, on the stack
+            this->nodes_.push(std::pair<std::list<ClassTreeMaskNode*>::iterator, std::list<ClassTreeMaskNode*>::iterator>((*this->nodes_.top().first)->subnodes_.begin(), (*this->nodes_.top().first)->subnodes_.end()));
+        }
+        else
+        {
+            // No subnodes, meaning we reached a leaf: Go to the next node
+            do
+            {
+                // Iterate one step in the current list
+                ++this->nodes_.top().first;
+
+                // Check if we reached the end of the list (the second item in the stored pair always represents the end)
+                if (this->nodes_.top().first == this->nodes_.top().second)
+                {
+                    // Yes we've reached the end: Pop the list-iterator from the stack
+                    this->nodes_.pop();
+
+                    // Continue with the loop, meaning: Try to iterate through the previous list
+                    continue;
+                }
+
+                // If we reached this point, we aren't yet at the end of the list: Leave the loop
+                break;
+            } while (!this->nodes_.empty()); // Stop looping if the stack is empty, meaning: We've iterated to the end
+        }
+
+        // Finally return a reference to the iterator itself
+        return *this;
+    }
+
+    /**
+        @brief Returns a pointer to the ClassTreeMaskNode whereon the iterator points.
+        @return The pointer to the node
+    */
+    ClassTreeMaskNode* ClassTreeMaskIterator::operator*() const
+    {
+        return (*this->nodes_.top().first);
+    }
+
+    /**
+        @brief Returns a pointer to the ClassTreeMaskNode whereon the iterator points.
+        @return The pointer to the node
+    */
+    ClassTreeMaskNode* ClassTreeMaskIterator::operator->() const
+    {
+        return (*this->nodes_.top().first);
+    }
+
+    /**
+        @brief Returns true if the stack is empty, meaning we've reached the end of the tree.
+        @return True if we've reached the end of the tree
+    */
+    ClassTreeMaskIterator::operator bool() const
+    {
+        return (!this->nodes_.empty());
+    }
+
+    /**
+        @brief Compares the current node with the given one and returns true if they match.
+        @param compare The node to compare with
+        @return The result of the comparison (true if they match)
+    */
+    bool ClassTreeMaskIterator::operator==(ClassTreeMaskNode* compare) const
+    {
+        if (!this->nodes_.empty())
+            return ((*this->nodes_.top().first) == compare);
+        else
+            return (compare == 0);
+    }
+
+    /**
+        @brief Compares the current node with the given one and returns true if they don't match.
+        @param compare The node to compare with
+        @return The result of the comparison (true if they don't match)
+    */
+    bool ClassTreeMaskIterator::operator!=(ClassTreeMaskNode* compare) const
+    {
+        if (!this->nodes_.empty())
+            return ((*this->nodes_.top().first) != compare);
+        else
+            return (compare != 0);
+    }
+
+
+    // ###############################
+    // ###      ClassTreeMask      ###
+    // ###############################
+    /**
+        @brief Constructor: Adds the root-node of the tree with the first rule ("include everything").
+    */
+    ClassTreeMask::ClassTreeMask()
+    {
+        this->root_ = new ClassTreeMaskNode(ClassIdentifier<BaseObject>::getIdentifier(), true);
+    }
+
+    /**
+        @brief Copyconstructor: Adds the root-node of the tree with the first rule ("include everything") and adds all rules from the other mask.
+        @param other The other mask
+    */
+    ClassTreeMask::ClassTreeMask(const ClassTreeMask& other)
+    {
+        this->root_ = new ClassTreeMaskNode(ClassIdentifier<BaseObject>::getIdentifier(), true);
+        for (ClassTreeMaskIterator it = other.root_; it; ++it)
+            this->add(it->getClass(), it->isIncluded(), false);
+    }
+
+    /**
+        @brief Destructor: Deletes the root node (which will delete all subnodes too).
+    */
+    ClassTreeMask::~ClassTreeMask()
+    {
+        delete this->root_;
+    }
+
+    /**
+        @brief Adds a new "include" rule for a given subclass to the mask.
+        @param subclass The subclass
+        @param overwrite True = overwrite previously added rules for inheriting classes
+        @param clean True = clean the tree after adding the new rule
+    */
+    void ClassTreeMask::include(const Identifier* subclass, bool overwrite, bool clean)
+    {
+        this->add(subclass, true, overwrite, clean);
+    }
+
+    /**
+        @brief Adds a new "exclude" rule for a given subclass to the mask.
+        @param subclass The subclass
+        @param overwrite True = overwrite previously added rules for inheriting classes
+        @param clean True = clean the tree after adding the new rule
+    */
+    void ClassTreeMask::exclude(const Identifier* subclass, bool overwrite, bool clean)
+    {
+        this->add(subclass, false, overwrite, clean);
+    }
+
+    /**
+        @brief Adds a new rule for a given subclass to the mask.
+        @param subclass The subclass
+        @param bInclude The rule: include (true) or exclude (false)
+        @param overwrite True = overwrite previously added rules for inheriting classes
+        @param clean True = clean the tree after adding the new rule
+    */
+    void ClassTreeMask::add(const Identifier* subclass, bool bInclude, bool overwrite, bool clean)
+    {
+        // Check if the given subclass is a child of our root-class
+        if (subclass->isA(this->root_->getClass()))
+        {
+            // Yes it is: Just add the rule to the three
+            this->add(this->root_, subclass, bInclude, overwrite);
+        }
+        else
+        {
+            // No it's not: Search for classes inheriting from the given class and add the rules for them
+            for (std::set<const Identifier*>::const_iterator it = subclass->getDirectChildrenBegin(); it != subclass->getDirectChildrenEnd(); ++it)
+                if ((*it)->isA(this->root_->getClass()))
+                    if (overwrite || (!this->nodeExists(*it))) // If we don't want to overwrite, only add nodes that don't already exist
+                        this->add(this->root_, *it, bInclude, overwrite);
+        }
+
+        // Clean the rule-tree
+        if (clean)
+            this->clean();
+    }
+
+    /**
+        @brief Adds a new rule for a given subclass to a node of the internal rule-tree (recursive function).
+        @param node The node
+        @param subclass The subclass
+        @param bInclude The rule: include (true) or exclude (false)
+        @param overwrite True = overwrite previously added rules for inheriting classes
+    */
+    void ClassTreeMask::add(ClassTreeMaskNode* node, const Identifier* subclass, bool bInclude, bool overwrite)
+    {
+        // Check if the current node contains exactly the subclass we want to add
+        if (subclass == node->getClass())
+        {
+            // We're at the right place, just change the mask and return
+            node->setIncluded(bInclude, overwrite);
+            return;
+        }
+        else if (subclass->isA(node->getClass()))
+        {
+            // Search for an already existing node, containing the subclass we want to add
+            for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); ++it)
+            {
+                if (subclass->isA((*it)->getClass()))
+                {
+                    // We've found an existing node -> delegate the work with a recursive function-call and return
+                    this->add(*it, subclass, bInclude, overwrite);
+                    return;
+                }
+            }
+
+            // There is no existing node satisfying our needs -> we create a new node
+            ClassTreeMaskNode* newnode = new ClassTreeMaskNode(subclass, bInclude);
+
+            // Search for nodes that should actually be subnodes of our new node and erase them
+            for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); )
+            {
+                if ((*it)->getClass()->isChildOf(subclass))
+                {
+                    // We've found a subnode: add it to the new node and erase it from the current node
+                    if (!overwrite)
+                        newnode->addSubnode(*it);
+                    else
+                        delete (*it);
+
+                    node->subnodes_.erase(it++);
+                }
+                else
+                {
+                    ++it;
+                }
+            }
+
+            // Finally add the new node as a subnode to the current node
+            node->addSubnode(newnode);
+        }
+    }
+
+    /**
+        @brief Adds a new "include" rule for a single subclass. The new rule doesn't change the mask for inheriting classes.
+        @param subclass The subclass
+        @param clean True = clean the tree after adding the new rule
+    */
+    void ClassTreeMask::includeSingle(const Identifier* subclass, bool clean)
+    {
+        this->addSingle(subclass, true, clean);
+    }
+
+    /**
+        @brief Adds a new "exclude" rule for a single subclass. The new rule doesn't change the mask for inheriting classes.
+        @param subclass The subclass
+        @param clean True = clean the tree after adding the new rule
+    */
+    void ClassTreeMask::excludeSingle(const Identifier* subclass, bool clean)
+    {
+        this->addSingle(subclass, false, clean);
+    }
+
+    /**
+        @brief Adds a new rule for a single subclass. The new rule doesn't change the mask for inheriting classes.
+        @param bInclude The rule: include (true) or exclude (false)
+        @param subclass The subclass
+        @param clean True = clean the tree after adding the new rule
+    */
+    void ClassTreeMask::addSingle(const Identifier* subclass, bool bInclude, bool clean)
+    {
+        for (std::set<const Identifier*>::const_iterator it = subclass->getDirectChildrenBegin(); it != subclass->getDirectChildrenEnd(); ++it)
+            this->add(*it, this->isIncluded(*it), false, false);
+
+        this->add(subclass, bInclude, false, clean);
+    }
+
+    /**
+        @brief Resets the mask to "include everything".
+    */
+    void ClassTreeMask::reset()
+    {
+        delete this->root_;
+        this->root_ = new ClassTreeMaskNode(ClassIdentifier<BaseObject>::getIdentifier(), true);
+    }
+
+    /**
+        @brief Tells if a given subclass is included or not.
+        @param subclass The subclass
+        @return Included (true) or excluded (false)
+    */
+    bool ClassTreeMask::isIncluded(const Identifier* subclass) const
+    {
+        return this->isIncluded(this->root_, subclass);
+    }
+
+    /**
+        @brief Tells if a given subclass of a node in the rule-tree is included or not (recursive function).
+        @param node The node
+        @param subclass The subclass
+        @return Included (true) or excluded (false)
+    */
+    bool ClassTreeMask::isIncluded(ClassTreeMaskNode* node, const Identifier* subclass) const
+    {
+        // Check if the searched subclass is of the same type as the class in the current node or a derivative
+        if (subclass->isA(node->getClass()))
+        {
+            // Check for the special case
+            if (subclass == node->getClass())
+                return node->isIncluded();
+
+            // Go through the list of subnodes and look for a node containing the searched subclass and delegate the request by a recursive function-call.
+            for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); ++it)
+                if (subclass->isA((*it)->getClass()))
+                    return isIncluded(*it, subclass);
+
+            // There is no subnode containing our class -> the rule of the current node takes in effect
+            return node->isIncluded();
+        }
+        else
+        {
+            // The class is not included in the mask: return false
+            return false;
+        }
+    }
+
+    /**
+        @brief Tells if a given subclass is excluded or not.
+        @param subclass The subclass
+        @return The inverted rule: Excluded (true) or included (false)
+    */
+    bool ClassTreeMask::isExcluded(const Identifier* subclass) const
+    {
+        return (!this->isIncluded(subclass));
+    }
+
+    /**
+        @brief Removes all unneeded rules that don't change the information of the mask.
+    */
+    void ClassTreeMask::clean()
+    {
+        this->clean(this->root_);
+    }
+
+    /**
+        @brief Removes all unneded rules that don't change the information of a node of a mask (recursive function).
+        @param node The node
+    */
+    void ClassTreeMask::clean(ClassTreeMaskNode* node)
+    {
+        // Iterate through all subnodes of the given node
+        for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); )
+        {
+            // Recursive function-call: Clean the subnode
+            this->clean(*it);
+
+            // Now check if the subnode contains the same rule as the current node
+            if ((*it)->isIncluded() == node->isIncluded())
+            {
+                // It does: Move all subnodes of the redundant subnode to the current node
+                node->subnodes_.insert(node->subnodes_.end(), (*it)->subnodes_.begin(), (*it)->subnodes_.end());
+                (*it)->subnodes_.clear();
+
+                // Remove the redundant subnode from the current node
+                node->subnodes_.erase(it++);
+            }
+            else
+            {
+                // The subnode is necessary: Move on to the next subnode
+                ++it;
+            }
+        }
+    }
+
+    /**
+        @brief Checks if a node for the given subclass exists.
+        @param subclass The Identifier of the subclass
+        @return True = the node exists
+    */
+    bool ClassTreeMask::nodeExists(const Identifier* subclass)
+    {
+        for (ClassTreeMaskIterator it = this->root_; it; ++it)
+            if ((*it)->getClass() == subclass)
+                return true;
+
+        return false;
+    }
+
+    /**
+        @brief Assignment operator: Adds all rules of the other mask.
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator=(const ClassTreeMask& other)
+    {
+        // Make a copy to avoid troubles with self-assignments (like A = A).
+        ClassTreeMask temp(other);
+
+        // Removes all current rules
+        this->reset();
+
+        // Copy all rules from the other mask
+        for (ClassTreeMaskIterator it = temp.root_; it; ++it)
+            this->add(it->getClass(), it->isIncluded(), false, false);
+
+        // Return a reference to the mask itself
+        return (*this);
+    }
+
+    /**
+        @brief Compares the mask with another mask and returns true if they represent the same logic.
+        @param other The other mask
+        @return True if both masks represent the same logic
+    */
+    bool ClassTreeMask::operator==(const ClassTreeMask& other) const
+    {
+        ClassTreeMask temp1 = other;
+        ClassTreeMask temp2 = (*this);
+
+        temp1.clean();
+        temp2.clean();
+
+        ClassTreeMaskIterator it1 = temp1.root_;
+        ClassTreeMaskIterator it2 = temp2.root_;
+
+        for ( ; it1 && it2; ++it1, ++it2)
+            if (it1->getClass() != it2->getClass())
+                return false;
+
+        return true;
+    }
+
+    /**
+        @brief Compares the mask with another mask and returns true if they represent different logics.
+        @param other The other mask
+        @return True if the masks represent different logics
+    */
+    bool ClassTreeMask::operator!=(const ClassTreeMask& other) const
+    {
+        return (!((*this) == other));
+    }
+
+    /**
+        @brief Prefix operator + does nothing.
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator+() const
+    {
+        return (*this);
+    }
+
+    /**
+        @brief Prefix operator - inverts the mask.
+        @return The inverted mask
+    */
+    ClassTreeMask ClassTreeMask::operator-() const
+    {
+        return (!(*this));
+    }
+
+    /**
+        @brief Adds two masks in the sense of a union (all classes that are included in at least one of the masks will be included in the resulting mask too).
+        @param other The mask to unite with
+        @return The union
+    */
+    ClassTreeMask ClassTreeMask::operator+(const ClassTreeMask& other) const
+    {
+        // Create a new mask
+        ClassTreeMask newmask;
+
+        // Add all nodes from the first mask, calculate the rule with the or-operation
+        for (ClassTreeMaskIterator it = this->root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, this->isIncluded(subclass) or other.isIncluded(subclass), false, false);
+        }
+
+        // Add all nodes from the second mask, calculate the rule with the or-operation
+        for (ClassTreeMaskIterator it = other.root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, this->isIncluded(subclass) or other.isIncluded(subclass), false, false);
+        }
+
+        // Drop all redundant rules
+        newmask.clean();
+
+        // Return the new mask
+        return newmask;
+    }
+
+    /**
+        @brief Intersects two masks (only classes that are included in both masks will be included in the resulting mask too).
+        @param other The mask to intersect with
+        @return The intersection
+    */
+    ClassTreeMask ClassTreeMask::operator*(const ClassTreeMask& other) const
+    {
+        // Create a new mask
+        ClassTreeMask newmask;
+
+        // Add all nodes from the first mask, calculate the rule with the and-operation
+        for (ClassTreeMaskIterator it = this->root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, this->isIncluded(subclass) and other.isIncluded(subclass), false, false);
+        }
+
+        // Add all nodes from the second mask, calculate the rule with the and-operation
+        for (ClassTreeMaskIterator it = other.root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, this->isIncluded(subclass) and other.isIncluded(subclass), false, false);
+        }
+
+        // Drop all redundant rules
+        newmask.clean();
+
+        // Return the new mask
+        return newmask;
+    }
+
+    /**
+        @brief Removes all elements of the second mask from the first mask (all classes that are included in the first mask stay included, except those that are included in the second mask too).
+        @param other The mask to subtract.
+        @return The difference
+    */
+    ClassTreeMask ClassTreeMask::operator-(const ClassTreeMask& other) const
+    {
+        return ((*this) * (!other));
+    }
+
+    /**
+        @brief Inverts the mask (all included classes are now excluded and vice versa).
+        @return The complement
+    */
+    ClassTreeMask ClassTreeMask::operator!() const
+    {
+        // Create a new mask
+        ClassTreeMask newmask;
+
+        // Add all nodes from the other mask, inverting the rules
+        for (ClassTreeMaskIterator it = this->root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, !this->isIncluded(subclass), false, false);
+        }
+
+        // Return the new mask
+        return newmask;
+    }
+
+    /**
+        @brief Unites this mask with another mask.
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator+=(const ClassTreeMask& other)
+    {
+        (*this) = (*this) + other;
+        return (*this);
+    }
+
+    /**
+        @brief Intersects this mask with another mask.
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator*=(const ClassTreeMask& other)
+    {
+        (*this) = (*this) * other;
+        return (*this);
+    }
+
+    /**
+        @brief Subtracts another mask from this mask.
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator-=(const ClassTreeMask& other)
+    {
+        (*this) = (*this) - other;
+        return (*this);
+    }
+
+    /**
+        @brief Intersects two masks (only classes that are included in both masks will be included in the resulting mask too).
+        @param other The mask to intersect with
+        @return The intersection
+    */
+    ClassTreeMask ClassTreeMask::operator&(const ClassTreeMask& other) const
+    {
+        return ((*this) * other);
+    }
+
+    /**
+        @brief Adds two masks in the sense of a union (all classes that are included in at least one of the masks will be included in the resulting mask too).
+        @param other The mask to unite with
+        @return The union
+    */
+    ClassTreeMask ClassTreeMask::operator|(const ClassTreeMask& other) const
+    {
+        return ((*this) + other);
+    }
+
+    /**
+        @brief Joins two masks in the sense of a xor (exclusivity) operation (all classes that are included in exactly one of the masks, but not in both, will be included in the resulting mask too).
+        @param other The mask to join with
+        @return The result
+    */
+    ClassTreeMask ClassTreeMask::operator^(const ClassTreeMask& other) const
+    {
+        // Create a new mask
+        ClassTreeMask newmask;
+
+        // Add all nodes from the first mask, calculate the rule with the xor-operation
+        for (ClassTreeMaskIterator it = this->root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, this->isIncluded(subclass) xor other.isIncluded(subclass), false, false);
+        }
+
+        // Add all nodes from the second mask, calculate the rule with the xor-operation
+        for (ClassTreeMaskIterator it = other.root_; it; ++it)
+        {
+            const Identifier* subclass = it->getClass();
+            newmask.add(subclass, this->isIncluded(subclass) xor other.isIncluded(subclass), false, false);
+        }
+
+        // Drop all redundant rules
+        newmask.clean();
+
+        // Return the new mask
+        return newmask;
+    }
+
+    /**
+        @brief Inverts the mask (all included classes are now excluded and vice versa).
+        @return The complement
+    */
+    ClassTreeMask ClassTreeMask::operator~() const
+    {
+        return (!(*this));
+    }
+
+    /**
+        @brief Intersects this mask with another mask (and-operation)
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator&=(const ClassTreeMask& other)
+    {
+        (*this) = (*this) & other;
+        return (*this);
+    }
+
+    /**
+        @brief Unites this mask with another mask (or-operation).
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator|=(const ClassTreeMask& other)
+    {
+        (*this) = (*this) | other;
+        return (*this);
+    }
+
+    /**
+        @brief Joins this mask with another mask with a xor-operation.
+        @param other The other mask
+        @return A reference to the mask itself
+    */
+    const ClassTreeMask& ClassTreeMask::operator^=(const ClassTreeMask& other)
+    {
+        (*this) = (*this) ^ other;
+        return (*this);
+    }
+
+    /**
+        @brief Converts the content of a mask into a human readable string and puts it on the ostream.
+        @param out The ostream
+        @param mask The mask
+        @return A reference to the ostream
+    */
+    std::ostream& operator<<(std::ostream& out, const ClassTreeMask& mask)
+    {
+        // Iterate through all rules
+        for (ClassTreeMaskIterator it = mask.root_; it; ++it)
+        {
+            // Calculate the prefix: + means included, - means excluded
+            if (it->isIncluded())
+                out << "+";
+            else
+                out << "-";
+
+            // Put the name of the corresponding class on the stream
+            out << it->getClass()->getName() << " ";
+        }
+
+        return out;
+    }
+
+
+    // ###################################
+    // ### ClassTreeMaskObjectIterator ###
+    // ###################################
+    /**
+        @brief Initializes the iterator from a given ClassTreeMask.
+        @param mask The mask
+    */
+    const ClassTreeMaskObjectIterator& ClassTreeMaskObjectIterator::operator=(const ClassTreeMask& mask)
+    {
+        // Clear everything, use a cleaned copy of the mask
+        this->subclasses_.clear();
+        ClassTreeMask temp = mask;
+        temp.clean();
+
+        // Create the subclass-list by going through the mask-tree, starting with the root-node
+        this->create(temp.root_);
+
+        // Move the subclass-iterator to the beginning of the subclass-list
+        this->subclassIterator_ = this->subclasses_.begin();
+
+        // If there is a first subclass, move the object-iterator to the first object of this class. Else go to the end
+        if (this->subclassIterator_ != this->subclasses_.end())
+            this->objectIterator_ = (*this->subclassIterator_).first->getObjects()->begin();
+        else
+            this->objectIterator_ = ObjectList<BaseObject>::end();
+
+        // Check if the iterator points on a valid object. If not, go to the next object by calling ++
+        if (!this->objectIterator_ || ((*this->subclassIterator_).second && !this->objectIterator_->isExactlyA((*this->subclassIterator_).first)))
+            this->operator++();
+
+        return (*this);
+    }
+
+    /**
+        @brief Iterate to the next object (if any).
+        @return The iterator itself
+    */
+    const ClassTreeMaskObjectIterator& ClassTreeMaskObjectIterator::operator++()
+    {
+        if (this->objectIterator_)
+        {
+            // The iterator points on a valid object, therefore we also have a valid subclass-iterator at the moment
+            do
+            {
+                // Go to the next object
+                ++this->objectIterator_;
+
+                while (!this->objectIterator_)
+                {
+                    // We reached the end of the current objectlist - go to the next class
+                    ++this->subclassIterator_;
+
+                    // Check if there really is a next class. If yes, move the object-iterator to the first object
+                    if (this->subclassIterator_ != this->subclasses_.end())
+                        this->objectIterator_ = (*this->subclassIterator_).first->getObjects()->begin();
+                    else
+                        return (*this);
+                }
+
+            // Repeat this until we reach a valid object or the end
+            } while ((*this->subclassIterator_).second && !this->objectIterator_->isExactlyA((*this->subclassIterator_).first));
+        }
+        return (*this);
+    }
+
+    /**
+        @brief Recursive function to create the Iterators subclass-list by going through the node-tree of the mask.
+        @param node The current node
+    */
+    void ClassTreeMaskObjectIterator::create(ClassTreeMaskNode* node)
+    {
+        // Add the class of this node to the list, if the class is included
+        if (node->isIncluded())
+        {
+            // If there are some subnodes, the bool is "true", meaning we have to check for the exact clss when iterating
+            if (node->hasSubnodes())
+                this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(node->getClass(), true));
+            else
+                this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(node->getClass(), false));
+        }
+
+        // Now check if the node has subnodes
+        if (node->hasSubnodes())
+        {
+            // Get all _direct_ children of the nodes class
+            std::set<const Identifier*> directChildren = node->getClass()->getDirectChildren();
+
+            // Iterate through all subnodes
+            for (std::list<ClassTreeMaskNode*>::iterator it1 = node->subnodes_.begin(); it1 != node->subnodes_.end(); ++it1)
+            {
+                // Recursive call to this function with the subnode
+                this->create(*it1);
+
+                // Only execute the following code if the current node is included, meaning some of the subnodes might be included too
+                if (node->isIncluded())
+                {
+                    scanChildren: // This is a label for goto
+
+                    // Iterate through all direct children
+                    for (std::set<const Identifier*>::iterator it2 = directChildren.begin(); it2 != directChildren.end(); ++it2)
+                    {
+                        // Check if the subnode (it1) is a child of the directChild (it2)
+                        if ((*it1)->getClass()->isA(*it2))
+                        {
+                            // Yes it is - remove the directChild (it2) from the list, because it will already be handled by a recursive call to the create() function
+                            directChildren.erase(it2);
+
+                            // Check if the removed directChild was exactly the subnode
+                            if (!(*it1)->getClass()->isExactlyA(*it2))
+                            {
+                                // No, it wasn't exactly the subnode - therefore there are some classes between
+
+                                // Add the previously removed directChild (it2) to the subclass-list
+                                this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(*it2, true));
+
+                                // Insert all directChildren of the directChild
+                                directChildren.insert((*it2)->getDirectChildrenBegin(), (*it2)->getDirectChildrenEnd());
+
+                                // Restart the scan with the expanded set of directChildren
+                                goto scanChildren;
+                            }
+                            break;
+                        }
+                    }
+                }
+            }
+
+            // Now add all directChildren which don't have subnodes on their own to the subclass-list
+            // The bool is "false", meaning they have no subnodes and therefore need no further checks
+            if (node->isIncluded())
+                for (std::set<const Identifier*>::iterator it = directChildren.begin(); it != directChildren.end(); ++it)
+                    this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(*it, false));
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ClassTreeMask.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ClassTreeMask.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ClassTreeMask.h	(revision 5712)
@@ -0,0 +1,286 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the ClassTreeMask, ClassTreeMaskNode and ClassTreeMaskIterator classes.
+
+    ClassTreeMask is a class to define a mask of the class-tree beginning with BaseObject.
+    You can include or exclude classes by calling the corresponding functions with the
+    Identifier of the class.
+
+    You can work with a ClassTreeMask in the sense of the set-theory, meaning that you can create
+    unions, intersections, complements and differences by using overloaded operators.
+
+
+
+    The ClassTreeMask is internally represented by a tree. The nodes in the tree are
+    ClassTreeMaskNodes, containing the rule (included or excluded) for this class and all
+    subclasses and a list of all subnodes. To minimize the size, the tree contains only
+    nodes changing the mask. By adding new rules, the tree gets reordered dynamically.
+
+    Adding a new rule overwrites all rules assigned to inherited classes. Use overwrite = false
+    if you don't like this feature. Useless rules that don't change the information of the mask
+    aren't saved in the internal tree. Use clean = false if you wan't to save them.
+
+    With overwrite = false and clean = false it doesn't matter in which way you create the mask.
+    You can manually drop useless rules from the tree by calling clean().
+
+
+
+    Because of the complicated shape of the internal tree, there is an iterator to iterate
+    through all ClassTreeMaskNodes of a mask. It starts with the BaseObject and moves on to
+    the first subclass until it reaches a leaf of the tree. Then the iterator moves one step
+    back and iterates to the second subclass. If there are no more subclasses, it steps another
+    step back, and so on.
+
+    Example: A and B are children of BaseObject, A1 and A2 are children of A, B1 and B2 are children of B.
+    The ClassTreeMaskIterator would move trough the tree in the following order:
+    BaseObject, A, A1, A2, B, B1, B2.
+
+    Note that the iterator doesn't move trough the whole class-tree, but only through the
+    internal tree of the mask, containing the minimal needed set of nodes to describe the mask.
+*/
+
+#ifndef _ClassTreeMask_H__
+#define _ClassTreeMask_H__
+
+#include "CorePrereqs.h"
+
+#include <list>
+#include <stack>
+#include "BaseObject.h"
+#include "Iterator.h"
+
+namespace orxonox
+{
+    // ###################################
+    // ###      ClassTreeMaskNode      ###
+    // ###################################
+    //! The ClassTreeMaskNode is a node in the internal tree of the ClassTreeMask, containing the rules of the mask.
+    /**
+        The ClassTreeMaskNode is used to store the rule (included or excluded) for a given
+        class (described by the corresponding Identifier). The nodes are used in the internal
+        tree of ClassTreeMask. To build a tree, they store a list of all subnodes.
+    */
+    class _CoreExport ClassTreeMaskNode
+    {
+        friend class ClassTreeMask;
+        friend class ClassTreeMaskIterator;
+        friend class ClassTreeMaskObjectIterator;
+
+        public:
+            ClassTreeMaskNode(const Identifier* subclass, bool bIncluded = true);
+            ~ClassTreeMaskNode();
+
+            void include(bool overwrite = true);
+            void exclude(bool overwrite = true);
+            void setIncluded(bool bIncluded, bool overwrite = true);
+
+            void addSubnode(ClassTreeMaskNode* subnode);
+
+            /** @brief Tells if the rule is "included" or not. @return The rule: true = included, false = excluded */
+            inline bool isIncluded() const { return this->bIncluded_; }
+            /** @brief Tells if the rule is "excluded" or not. @return The inverted rule: true = excluded, false = included */
+            inline bool isExcluded() const { return (!this->bIncluded_); }
+
+            /** @brief Returns the Identifier of the class the rule refers to. @return The Identifier representing the class */
+            inline const Identifier* getClass() const { return this->subclass_; }
+
+            /** @brief Returns true if the Node has some subnodes. */
+            inline bool hasSubnodes() const { return !this->subnodes_.empty(); }
+
+        private:
+            void deleteAllSubnodes();
+
+            const Identifier* subclass_;                //!< The Identifier of the subclass the rule refers to
+            bool bIncluded_;                            //!< The rule: included or excluded
+            std::list<ClassTreeMaskNode*> subnodes_;    //!< A list containing all subnodes in the tree
+    };
+
+
+    // ###################################
+    // ###    ClassTreeMaskIterator    ###
+    // ###################################
+    //! The ClassTreeMaskIterator moves through all ClassTreeMaskNodes of the internal tree of a ClassTreeMask, containing the rules.
+    /**
+        Because of the complicated shape of the internal rule-tree of ClassTreeMask, an
+        iterator is used to move through all nodes of the tree. It starts with the BaseObject
+        and moves on to the first subclass until it reaches a leaf of the tree. Then the
+        iterator moves one step back and iterates to the second subclass. If there are no more
+        subclasses, it steps another step back, and so on.
+    */
+    class _CoreExport ClassTreeMaskIterator
+    {
+        public:
+            ClassTreeMaskIterator(ClassTreeMaskNode* node);
+            ~ClassTreeMaskIterator();
+
+            const ClassTreeMaskIterator& operator++();
+            ClassTreeMaskNode* operator*() const;
+            ClassTreeMaskNode* operator->() const;
+            operator bool() const;
+            bool operator==(ClassTreeMaskNode* compare) const;
+            bool operator!=(ClassTreeMaskNode* compare) const;
+
+        private:
+            std::stack<std::pair<std::list<ClassTreeMaskNode*>::iterator, std::list<ClassTreeMaskNode*>::iterator> > nodes_;    //!< A stack to store list-iterators
+            std::list<ClassTreeMaskNode*> rootlist_;                                                                            //!< A list for internal use (it only stores the root-node)
+    };
+
+
+    // ###################################
+    // ###        ClassTreeMask        ###
+    // ###################################
+    //! The ClassTreeMask is a set of rules, containing the information for each class whether it's included or not.
+    /**
+        With a ClassTreeMask, you can include or exclude subtrees of the class-tree, starting
+        with a given subclass, described by the corresponding Identifier. To minimize the size
+        of the mask, the mask saves only relevant rules. But you can manually add rules that
+        don't change the information of the mask by using clean = false. If you want to drop
+        useless rules, call the clean() function.
+    */
+    class _CoreExport ClassTreeMask
+    {
+        friend class ClassTreeMaskObjectIterator;
+
+        public:
+            ClassTreeMask();
+            ClassTreeMask(const ClassTreeMask& other);
+            ~ClassTreeMask();
+
+            void include(const Identifier* subclass, bool overwrite = true, bool clean = true);
+            void exclude(const Identifier* subclass, bool overwrite = true, bool clean = true);
+            void add(const Identifier* subclass, bool bInclude, bool overwrite = true, bool clean = true);
+
+            void includeSingle(const Identifier* subclass, bool clean = true);
+            void excludeSingle(const Identifier* subclass, bool clean = true);
+            void addSingle(const Identifier* subclass, bool bInclude, bool clean = true);
+
+            void reset();
+            void clean();
+
+            bool isIncluded(const Identifier* subclass) const;
+            bool isExcluded(const Identifier* subclass) const;
+
+            /** @brief Begin of the ClassTreeMaskObjectIterator. */
+            inline const ClassTreeMask& begin() const { return (*this); }
+            /** @brief End of the ClassTreeMaskObjectIterator. */
+            inline BaseObject*          end()   const { return 0; }
+
+            const ClassTreeMask& operator=(const ClassTreeMask& other);
+
+            bool operator==(const ClassTreeMask& other) const;
+            bool operator!=(const ClassTreeMask& other) const;
+
+            const ClassTreeMask& operator+() const;
+            ClassTreeMask operator-() const;
+
+            ClassTreeMask operator+(const ClassTreeMask& other) const;
+            ClassTreeMask operator*(const ClassTreeMask& other) const;
+            ClassTreeMask operator-(const ClassTreeMask& other) const;
+            ClassTreeMask operator!() const;
+
+            const ClassTreeMask& operator+=(const ClassTreeMask& other);
+            const ClassTreeMask& operator*=(const ClassTreeMask& other);
+            const ClassTreeMask& operator-=(const ClassTreeMask& other);
+
+            ClassTreeMask operator&(const ClassTreeMask& other) const;
+            ClassTreeMask operator|(const ClassTreeMask& other) const;
+            ClassTreeMask operator^(const ClassTreeMask& other) const;
+            ClassTreeMask operator~() const;
+
+            const ClassTreeMask& operator&=(const ClassTreeMask& other);
+            const ClassTreeMask& operator|=(const ClassTreeMask& other);
+            const ClassTreeMask& operator^=(const ClassTreeMask& other);
+
+            friend std::ostream& operator<<(std::ostream& out, const ClassTreeMask& mask);
+
+        private:
+            void add(ClassTreeMaskNode* node, const Identifier* subclass, bool bInclude, bool overwrite = true);
+            bool isIncluded(ClassTreeMaskNode* node, const Identifier* subclass) const;
+            void clean(ClassTreeMaskNode* node);
+            bool nodeExists(const Identifier* subclass);
+
+            ClassTreeMaskNode* root_;   //!< The root-node of the internal rule-tree, usually BaseObject
+    };
+
+
+    // ###################################
+    // ### ClassTreeMaskObjectIterator ###
+    // ###################################
+    //! The ClassTreeMaskObjectIterator iterates through all objects of all classes, included by a ClassTreeMask.
+    /**
+        The ClassTreeMaskObjectIterator iterates through all objects of all classes,
+        included by a ClassTreeMask. This is done the following way:
+
+        ClassTreeMask mask;
+        for (ClassTreeMaskObjectIterator it = mask.begin(); it != mask.end(); ++it)
+            it->doSomething();
+
+        Note: The ClassTreeMaskObjectIterator handles all objects as BaseObjects. If
+              you want to use another class, you should use a dynamic_cast.
+
+        Performance of ClassTreeMaskObjectIterator is good as long as you don't exclude
+        subclasses of included classes. Of course you can still exlucde subclasses, but
+        if this is done more often, we need a new implementation using a second ObjectList
+        in the Identifier, containing all objects of exactly one class.
+    */
+    class _CoreExport ClassTreeMaskObjectIterator
+    {
+        public:
+            /** @brief Defaultconstructor: Does nothing. */
+            inline ClassTreeMaskObjectIterator() {}
+            /** @brief Constructor: Initializes the iterator from a given ClassTreeMask. @param mask The mask */
+            inline ClassTreeMaskObjectIterator(const ClassTreeMask& mask) { (*this) = mask; }
+
+            const ClassTreeMaskObjectIterator& operator=(const ClassTreeMask& mask);
+
+            const ClassTreeMaskObjectIterator& operator++();
+
+            /** @brief Returns true if the ClassTreeMaskObjectIterator points at the given object. @param pointer The pointer of the object */
+            inline bool operator==(BaseObject* pointer) const { return ((*this->objectIterator_) == pointer); }
+            /** @brief Returns true if the ClassTreeMaskObjectIterator doesn't point at the given object. @param pointer The pointer of the object */
+            inline bool operator!=(BaseObject* pointer) const { return ((*this->objectIterator_) != pointer); }
+            /** @brief Returns true if the ClassTreeMaskObjectIterator hasn't already reached the end. */
+            inline operator bool() const { return (this->objectIterator_); }
+            /** @brief Returns the object the ClassTreeMaskObjectIterator currently points at. */
+            inline BaseObject* operator*() const { return (*this->objectIterator_); }
+            /** @brief Returns the object the ClassTreeMaskObjectIterator currently points at. */
+            inline BaseObject* operator->() const { return (*this->objectIterator_); }
+
+        private:
+            void create(ClassTreeMaskNode* node);
+
+            std::list<std::pair<const Identifier*, bool> >           subclasses_;       //!< A list of all Identifiers through which objects the iterator should iterate
+            std::list<std::pair<const Identifier*, bool> >::iterator subclassIterator_; //!< The current class of the iterator
+            Iterator<BaseObject>                                     objectIterator_;   //!< The current object of the iterator
+    };
+}
+
+#endif /* _ClassTreeMask_H__ */
Index: /code/branches/libraries2/src/libraries/core/Clock.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Clock.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Clock.cc	(revision 5712)
@@ -0,0 +1,78 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief
+*/
+
+#include "Clock.h"
+#include <OgreTimer.h>
+
+namespace orxonox
+{
+    Clock::Clock()
+        : timer_(new Ogre::Timer())
+        , storedTime_(0)
+        , tickTime_(0)
+        , tickDt_(0)
+        , tickDtFloat_(0.0f)
+        , lastTimersTime_(0)
+    {
+    }
+
+    Clock::~Clock()
+    {
+        delete timer_;
+    }
+    
+    void Clock::capture()
+    {
+        unsigned long timersTime = timer_->getMicroseconds();
+        tickTime_ = storedTime_ + timersTime;
+        tickDt_ = timersTime - lastTimersTime_;
+        tickDtFloat_ = static_cast<float>(tickDt_) / 1000000.0f;
+
+        if (timersTime > 0xFFFFFFFF/4)
+        {
+            // Ogre timer will overflow at 2^32 microseconds if unsigned long is 32 bit
+            storedTime_ += timersTime;
+            lastTimersTime_ = 0;
+            timer_->reset();
+        }
+        else
+        {
+            lastTimersTime_ = timersTime;
+        }
+    }
+
+    unsigned long long Clock::getRealMicroseconds() const
+    {
+        return this->timer_->getMicroseconds() + this->storedTime_;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Clock.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Clock.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Clock.h	(revision 5712)
@@ -0,0 +1,67 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Clock_H__
+#define _Clock_H__
+
+#include "CorePrereqs.h"
+#include "util/OgreForwardRefs.h"
+
+namespace orxonox
+{
+    class _CoreExport Clock
+    {
+    public:
+        Clock();
+        ~Clock();
+
+        void capture();
+
+        unsigned long long getMicroseconds()   const { return tickTime_; }
+        unsigned long long getMilliseconds()   const { return tickTime_ / 1000; }
+        unsigned long      getSeconds()        const { return static_cast<long> (tickTime_ / 1000000); }
+        float              getSecondsPrecise() const { return static_cast<float>(tickTime_ / 1000000.0f); }
+
+        float              getDeltaTime()      const { return tickDtFloat_; }
+        long               getDeltaTimeMicroseconds() const { return tickDt_; }
+
+        unsigned long long getRealMicroseconds() const;
+
+    private:
+        Clock(const Clock& instance);
+
+        Ogre::Timer*       timer_;
+        unsigned long long storedTime_;
+        unsigned long long tickTime_;
+        long               tickDt_;
+        float              tickDtFloat_;
+        unsigned long      lastTimersTime_;
+    };
+}
+
+#endif /* _Clock_H__ */
Index: /code/branches/libraries2/src/libraries/core/CommandEvaluation.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/CommandEvaluation.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CommandEvaluation.cc	(revision 5712)
@@ -0,0 +1,313 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "CommandEvaluation.h"
+
+#include "util/Debug.h"
+#include "util/StringUtils.h"
+#include "ConsoleCommand.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    CommandEvaluation::CommandEvaluation()
+    {
+        this->initialize("");
+        this->state_ = CommandState::Uninitialized;
+    }
+
+    void CommandEvaluation::initialize(const std::string& command)
+    {
+        this->bNewCommand_ = true;
+        this->bCommandChanged_ = false;
+        this->originalCommand_ = command;
+        this->command_ = command;
+        this->commandTokens_.split(command, " ", SubString::WhiteSpaces, false, '\\', false, '"', false, '(', ')', false, '\0');
+
+        this->additionalParameter_ = "";
+
+        this->bEvaluatedParams_ = false;
+
+        this->listOfPossibleIdentifiers_.clear();
+        this->listOfPossibleFunctions_.clear();
+        this->listOfPossibleArguments_.clear();
+
+        this->functionclass_ = 0;
+        this->function_ = 0;
+        this->possibleArgument_ = "";
+        this->argument_ = "";
+
+        this->errorMessage_ = "";
+        this->state_ = CommandState::Empty;
+    }
+
+    bool CommandEvaluation::isValid() const
+    {
+        return (this->function_);
+    }
+
+    bool CommandEvaluation::execute() const
+    {
+        if (!this->isValid())
+            return false;
+
+        if (this->bEvaluatedParams_ && this->function_)
+        {
+            COUT(6) << "CE_execute (evaluation): " << this->function_->getName() << " " << this->param_[0] << " " << this->param_[1] << " " << this->param_[2] << " " << this->param_[3] << " " << this->param_[4] << std::endl;
+            (*this->function_)(this->param_[0], this->param_[1], this->param_[2], this->param_[3], this->param_[4]);
+            return true;
+        }
+
+        if (!this->bCommandChanged_ || nocaseCmp(removeTrailingWhitespaces(this->command_), removeTrailingWhitespaces(this->originalCommand_)) == 0)
+        {
+            COUT(4) << "CE_execute: " << this->command_ << "\n";
+
+            unsigned int startindex = this->getStartindex();
+            if (this->commandTokens_.size() > startindex)
+                return this->function_->parse(removeSlashes(this->commandTokens_.subSet(startindex).join() + this->getAdditionalParameter()));
+            else
+                return this->function_->parse(removeSlashes(this->additionalParameter_));
+        }
+
+        return false;
+    }
+
+    std::string CommandEvaluation::complete()
+    {
+        if (!this->bNewCommand_)
+        {
+            switch (this->state_)
+            {
+                case CommandState::Uninitialized:
+                    break;
+                case CommandState::Empty:
+                    break;
+                case CommandState::ShortcutOrIdentifier:
+                    if (this->function_)
+                    {
+                        if (this->function_->getParamCount() == 0)
+                            return (this->command_ = this->function_->getName());
+                        else
+                            return (this->command_ = this->function_->getName() + " ");
+                    }
+                    else if (this->functionclass_)
+                        return (this->command_ = this->functionclass_->getName() + " ");
+                    break;
+                case CommandState::Function:
+                    if (this->function_)
+                    {
+                        if (this->function_->getParamCount() == 0)
+                            return (this->command_ = this->functionclass_->getName() + " " + this->function_->getName());
+                        else
+                            return (this->command_ = this->functionclass_->getName() + " " + this->function_->getName() + " ");
+                    }
+                    break;
+                case CommandState::ParamPreparation:
+                case CommandState::Params:
+                {
+                    if (this->argument_ == "" && this->possibleArgument_ == "")
+                        break;
+
+                    unsigned int maxIndex = this->commandTokens_.size();
+                    if (this->command_[this->command_.size() - 1] != ' ')
+                        maxIndex -= 1;
+                    std::string whitespace = "";
+
+                    if (this->possibleArgument_ != "")
+                    {
+                        this->argument_ = this->possibleArgument_;
+                        if (this->function_->getParamCount() > (maxIndex + 1 - this->getStartindex()))
+                            whitespace = " ";
+                    }
+
+                    return (this->command_ = this->commandTokens_.subSet(0, maxIndex).join() + " " + this->argument_ + whitespace);
+                    break;
+                }
+                case CommandState::Finished:
+                    break;
+                case CommandState::Error:
+                    break;
+            }
+        }
+        this->bNewCommand_ = false;
+        return this->command_;
+    }
+
+    std::string CommandEvaluation::hint() const
+    {
+        switch (this->state_)
+        {
+            case CommandState::Uninitialized:
+                break;
+            case CommandState::Empty:
+            case CommandState::ShortcutOrIdentifier:
+                if (this->listOfPossibleFunctions_.size() == 0)
+                    return CommandEvaluation::dump(this->listOfPossibleIdentifiers_);
+                else if (this->listOfPossibleIdentifiers_.size() == 0)
+                    return CommandEvaluation::dump(this->listOfPossibleFunctions_);
+                else
+                    return (CommandEvaluation::dump(this->listOfPossibleFunctions_) + "\n" + CommandEvaluation::dump(this->listOfPossibleIdentifiers_));
+                break;
+            case CommandState::Function:
+                return CommandEvaluation::dump(this->listOfPossibleFunctions_);
+                break;
+            case CommandState::ParamPreparation:
+            case CommandState::Params:
+                if (this->listOfPossibleArguments_.size() > 0)
+                    return CommandEvaluation::dump(this->listOfPossibleArguments_);
+                else
+                    return CommandEvaluation::dump(this->function_);
+            case CommandState::Finished:
+                if (this->function_)
+                    return CommandEvaluation::dump(this->function_);
+                break;
+            case CommandState::Error:
+                return this->errorMessage_;
+                break;
+        }
+
+        return "";
+    }
+
+    void CommandEvaluation::evaluateParams()
+    {
+        this->bEvaluatedParams_ = false;
+
+        for (unsigned int i = 0; i < MAX_FUNCTOR_ARGUMENTS; i++)
+            this->param_[i] = MT_Type::Null;
+
+        if (!this->isValid())
+            return;
+
+        unsigned int startindex = this->getStartindex();
+
+        if (this->commandTokens_.size() <= startindex)
+        {
+            if (this->function_->evaluate(this->getAdditionalParameter(), this->param_, " "))
+                this->bEvaluatedParams_ = true;
+        }
+        else if (this->commandTokens_.size() > startindex)
+        {
+            if (this->function_->evaluate(this->commandTokens_.subSet(startindex).join() + this->getAdditionalParameter(), this->param_, " "))
+                this->bEvaluatedParams_ = true;
+        }
+    }
+
+    void CommandEvaluation::setEvaluatedParameter(unsigned int index, MultiType param)
+    {
+        if (index < MAX_FUNCTOR_ARGUMENTS)
+            this->param_[index] = param;
+    }
+
+    MultiType CommandEvaluation::getEvaluatedParameter(unsigned int index) const
+    {
+        if (index < MAX_FUNCTOR_ARGUMENTS)
+            return this->param_[index];
+
+        return MT_Type::Null;
+    }
+
+    bool CommandEvaluation::hasReturnvalue() const
+    {
+        if (this->function_)
+            return this->function_->hasReturnvalue();
+
+        return MT_Type::Null;
+    }
+
+    MultiType CommandEvaluation::getReturnvalue() const
+    {
+        if (this->function_)
+            return this->function_->getReturnvalue();
+
+        return MultiType();
+    }
+
+
+    unsigned int CommandEvaluation::getStartindex() const
+    {
+        if (this->functionclass_ && this->function_)
+            return 2;
+        else if (this->function_)
+            return 1;
+        else
+            return 0;
+    }
+
+    std::string CommandEvaluation::dump(const std::list<std::pair<const std::string*, const std::string*> >& list)
+    {
+        std::string output = "";
+        for (std::list<std::pair<const std::string*, const std::string*> >::const_iterator it = list.begin(); it != list.end(); ++it)
+        {
+            if (it != list.begin())
+                output += " ";
+
+            output += *(*it).second;
+        }
+        return output;
+    }
+
+    std::string CommandEvaluation::dump(const ArgumentCompletionList& list)
+    {
+        std::string output = "";
+        for (ArgumentCompletionList::const_iterator it = list.begin(); it != list.end(); ++it)
+        {
+            if (it != list.begin())
+                output += " ";
+
+            output += (*it).getDisplay();
+        }
+        return output;
+    }
+
+    std::string CommandEvaluation::dump(const ConsoleCommand* command)
+    {
+        std::string output = command->getName();
+        if (command->getParamCount() > 0)
+            output += ": ";
+
+        for (unsigned int i = 0; i < command->getParamCount(); i++)
+        {
+            if (i != 0)
+                output += " ";
+
+            if (command->defaultValueSet(i))
+                output += "[";
+            else
+                output += "{";
+
+            output += command->getTypenameParam(i);
+
+            if (command->defaultValueSet(i))
+                output += "=" + command->getDefaultValue(i).getString() + "]";
+            else
+                output += "}";
+        }
+        return output;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/CommandEvaluation.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/CommandEvaluation.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CommandEvaluation.h	(revision 5712)
@@ -0,0 +1,124 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _CommandEvaluation_H__
+#define _CommandEvaluation_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include <list>
+
+#include "ArgumentCompletionListElement.h"
+#include "util/SubString.h"
+#include "util/MultiType.h"
+
+namespace orxonox
+{
+    namespace CommandState
+    {
+        enum Value
+        {
+            Uninitialized,
+            Empty,
+            ShortcutOrIdentifier,
+            Function,
+            ParamPreparation,
+            Params,
+            Finished,
+            Error
+        };
+    }
+
+    class _CoreExport CommandEvaluation
+    {
+        friend class CommandExecutor;
+
+        public:
+            CommandEvaluation();
+
+            void initialize(const std::string& command);
+
+            bool execute() const;
+            std::string complete();
+            std::string hint() const;
+            void evaluateParams();
+
+            bool isValid() const;
+
+            inline ConsoleCommand* getConsoleCommand() const
+                { return this->function_; }
+            inline const std::string& getOriginalCommand() const
+                { return this->originalCommand_; }
+            inline const std::string& getCommand() const
+                { return this->command_; }
+
+            inline void setAdditionalParameter(const std::string& param)
+                { this->additionalParameter_ = param; this->bEvaluatedParams_ = false; }
+            inline std::string getAdditionalParameter() const
+                { return (this->additionalParameter_ != "") ? (" " + this->additionalParameter_) : ""; }
+
+            void setEvaluatedParameter(unsigned int index, MultiType param);
+            MultiType getEvaluatedParameter(unsigned int index) const;
+
+            bool hasReturnvalue() const;
+            MultiType getReturnvalue() const;
+
+        private:
+            unsigned int getStartindex() const;
+            static std::string dump(const std::list<std::pair<const std::string*, const std::string*> >& list);
+            static std::string dump(const ArgumentCompletionList& list);
+            static std::string dump(const ConsoleCommand* command);
+
+
+            bool bNewCommand_;
+            bool bCommandChanged_;
+
+            std::string originalCommand_;
+            std::string command_;
+            SubString commandTokens_;
+            std::string additionalParameter_;
+
+            std::list<std::pair<const std::string*, const std::string*> > listOfPossibleIdentifiers_;
+            std::list<std::pair<const std::string*, const std::string*> > listOfPossibleFunctions_;
+            ArgumentCompletionList listOfPossibleArguments_;
+
+            Identifier* functionclass_;
+            ConsoleCommand* function_;
+            std::string possibleArgument_;
+            std::string argument_;
+
+            std::string errorMessage_;
+            CommandState::Value state_;
+
+            bool bEvaluatedParams_;
+            MultiType param_[5];
+    };
+}
+
+#endif /* _CommandEvaluation_H__ */
Index: /code/branches/libraries2/src/libraries/core/CommandExecutor.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/CommandExecutor.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CommandExecutor.cc	(revision 5712)
@@ -0,0 +1,672 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "CommandExecutor.h"
+
+#include "util/Debug.h"
+#include "util/StringUtils.h"
+#include "ConsoleCommand.h"
+#include "Identifier.h"
+#include "Language.h"
+#include "TclBind.h"
+
+namespace orxonox
+{
+    CommandExecutor& CommandExecutor::getInstance()
+    {
+        static CommandExecutor instance;
+        return instance;
+    }
+
+    CommandEvaluation& CommandExecutor::getEvaluation()
+    {
+        return CommandExecutor::getInstance().evaluation_;
+    }
+
+    const CommandEvaluation& CommandExecutor::getLastEvaluation()
+    {
+        return CommandExecutor::getInstance().evaluation_;
+    }
+
+    ConsoleCommand& CommandExecutor::addConsoleCommandShortcut(ConsoleCommand* command, bool bDeleteAtExit)
+    {
+        std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_.find(command->getName());
+        if (it != CommandExecutor::getInstance().consoleCommandShortcuts_.end())
+        {
+            COUT(2) << "Warning: Overwriting console-command shortcut with name " << command->getName() << "." << std::endl;
+        }
+
+        // Make sure we can also delete the external ConsoleCommands that don't belong to an Identifier
+        if (command && bDeleteAtExit)
+        {
+            CommandExecutor::getInstance().consoleCommandExternals_.insert(command);
+        }
+
+        CommandExecutor::getInstance().consoleCommandShortcuts_[command->getName()] = command;
+        CommandExecutor::getInstance().consoleCommandShortcuts_LC_[getLowercase(command->getName())] = command;
+        return (*command);
+    }
+
+    /**
+        @brief Returns the executor of a console command shortcut with given name.
+        @brief name The name of the requested console command shortcut
+        @return The executor of the requested console command shortcut
+    */
+    ConsoleCommand* CommandExecutor::getConsoleCommandShortcut(const std::string& name)
+    {
+        std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_.find(name);
+        if (it != CommandExecutor::getInstance().consoleCommandShortcuts_.end())
+            return (*it).second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns the executor of a console command shortcut with given name in lowercase.
+        @brief name The name of the requested console command shortcut in lowercase
+        @return The executor of the requested console command shortcut
+    */
+    ConsoleCommand* CommandExecutor::getLowercaseConsoleCommandShortcut(const std::string& name)
+    {
+        std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_LC_.find(name);
+        if (it != CommandExecutor::getInstance().consoleCommandShortcuts_LC_.end())
+            return (*it).second;
+        else
+            return 0;
+    }
+
+    bool CommandExecutor::execute(const std::string& command, bool useTcl)
+    {
+        if (useTcl)
+            return TclBind::eval(command);
+
+        CommandExecutor::parseIfNeeded(command);
+        return CommandExecutor::getEvaluation().execute();
+    }
+
+    MultiType CommandExecutor::getReturnValue()
+    {
+        return CommandExecutor::getEvaluation().getReturnvalue();
+    }
+
+    std::string CommandExecutor::getReturnValueString()
+    {
+        return CommandExecutor::getEvaluation().getReturnvalue().getString();
+    }
+
+    std::string CommandExecutor::complete(const std::string& command)
+    {
+        CommandExecutor::parseIfNeeded(command);
+        return CommandExecutor::getEvaluation().complete();
+    }
+
+    std::string CommandExecutor::hint(const std::string& command)
+    {
+        CommandExecutor::parseIfNeeded(command);
+        return CommandExecutor::getEvaluation().hint();
+    }
+
+    CommandEvaluation CommandExecutor::evaluate(const std::string& command)
+    {
+        CommandExecutor::parse(command);
+        CommandExecutor::getEvaluation().evaluateParams();
+        return CommandExecutor::getEvaluation();
+    }
+
+    void CommandExecutor::parseIfNeeded(const std::string& command)
+    {
+        if (CommandExecutor::getEvaluation().state_ == CommandState::Uninitialized)
+        {
+            CommandExecutor::parse(command);
+        }
+        else if (CommandExecutor::getEvaluation().originalCommand_ != command)
+        {
+            if (CommandExecutor::getEvaluation().command_ == command)
+            {
+                CommandExecutor::parse(command);
+                CommandExecutor::getEvaluation().bNewCommand_ = false;
+            }
+            else
+            {
+                CommandExecutor::parse(command);
+            }
+        }
+    }
+
+    void CommandExecutor::parse(const std::string& command, bool bInitialize)
+    {
+        if (bInitialize)
+            CommandExecutor::getEvaluation().initialize(command);
+
+        CommandExecutor::getEvaluation().commandTokens_.split(command, " ", SubString::WhiteSpaces, false, '\\', false, '"', false, '(', ')', false, '\0');
+        CommandExecutor::getEvaluation().command_ = command;
+
+        switch (CommandExecutor::getEvaluation().state_)
+        {
+            case CommandState::Uninitialized:
+            {
+                // Impossible
+                break;
+            }
+            case CommandState::Empty:
+            {
+                if (CommandExecutor::argumentsGiven() == 0)
+                {
+                    CommandExecutor::createListOfPossibleFunctions("");
+                    CommandExecutor::createListOfPossibleIdentifiers("");
+                    break;
+                }
+                else
+                {
+                    CommandExecutor::getEvaluation().state_ = CommandState::ShortcutOrIdentifier;
+                    // Move on to next case
+                }
+            }
+            case CommandState::ShortcutOrIdentifier:
+            {
+                if (CommandExecutor::argumentsGiven() > 1)
+                {
+                    // There's a finished first argument - check if it's a shortcut or a classname
+                    CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(0));
+                    CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(CommandExecutor::getArgument(0));
+
+                    if (CommandExecutor::getEvaluation().function_)
+                    {
+                        // It's a shortcut
+                        CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                        CommandExecutor::getEvaluation().functionclass_ = 0;
+                        // Move on to next case
+                    }
+                    else if (CommandExecutor::getEvaluation().functionclass_)
+                    {
+                        // It's a functionname
+                        CommandExecutor::getEvaluation().state_ = CommandState::Function;
+                        CommandExecutor::getEvaluation().function_ = 0;
+                        // Move on to next case
+                    }
+                    else
+                    {
+                        // The first argument is bad
+                        CommandExecutor::getEvaluation().state_ = CommandState::Error;
+                        AddLanguageEntry("commandexecutorunknownfirstargument", "is not a shortcut nor a classname");
+                        CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getArgument(0) + " " + GetLocalisation("commandexecutorunknownfirstargument") + ".";
+                        return;
+                    }
+                }
+                else
+                {
+                    // There's no finished first argument - search possible shortcuts or classnames
+                    CommandExecutor::createListOfPossibleFunctions(CommandExecutor::getArgument(0));
+                    CommandExecutor::createListOfPossibleIdentifiers(CommandExecutor::getArgument(0));
+
+                    unsigned int num_functions = CommandExecutor::getEvaluation().listOfPossibleFunctions_.size();
+                    unsigned int num_identifiers = CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.size();
+
+                    if (num_functions == 1 && num_identifiers == 0)
+                    {
+                        // It's a shortcut
+                        std::string functionname = *(*CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()).first;
+                        CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(functionname);
+                        if (getLowercase(functionname) != getLowercase(CommandExecutor::getArgument(0)))
+                        {
+                            // Unfinished shortcut
+                            CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                        }
+                        CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                        CommandExecutor::getEvaluation().functionclass_ = 0;
+                        CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().function_->getName();
+                        if (CommandExecutor::getEvaluation().function_->getParamCount() > 0)
+                        {
+                            CommandExecutor::getEvaluation().command_ += " ";
+                            CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                        }
+                        // Move on to next case
+                    }
+                    else if (num_identifiers == 1 && num_functions == 0)
+                    {
+                        // It's a classname
+                        std::string classname = *(*CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.begin()).first;
+                        CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(classname);
+                        if (getLowercase(classname) != getLowercase(CommandExecutor::getArgument(0)))
+                        {
+                            // Unfinished classname
+                            CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                        }
+                        CommandExecutor::getEvaluation().state_ = CommandState::Function;
+                        CommandExecutor::getEvaluation().function_ = 0;
+                        CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " ";
+                        // Move on to next case
+                    }
+                    else if (num_identifiers == 0 && num_functions == 0)
+                    {
+                        // No possibilities
+                        CommandExecutor::getEvaluation().state_ = CommandState::Error;
+                        AddLanguageEntry("commandexecutorunknownfirstargumentstart", "There is no command or classname starting with");
+                        CommandExecutor::getEvaluation().errorMessage_ = "Error: " + GetLocalisation("commandexecutorunknownfirstargumentstart") + " " + CommandExecutor::getArgument(0) + ".";
+                        return;
+                    }
+                    else
+                    {
+                        // There are several possiblilities
+                        std::list<std::pair<const std::string*, const std::string*> > temp;
+                        temp.insert(temp.end(), CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin(), CommandExecutor::getEvaluation().listOfPossibleFunctions_.end());
+                        temp.insert(temp.end(), CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.begin(), CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.end());
+                        CommandExecutor::getEvaluation().command_ = CommandExecutor::getCommonBegin(temp);
+                        CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(0));
+                        CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(CommandExecutor::getArgument(0));
+                        CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                        return;
+                    }
+                }
+            }
+            case CommandState::Function:
+            {
+                if (CommandExecutor::getEvaluation().functionclass_)
+                {
+                    // There is a classname - search for the commandname
+                    if (CommandExecutor::argumentsGiven() > 2)
+                    {
+                        // There is a finished second argument - check if it's a commandname
+                        CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_);
+
+                        if (CommandExecutor::getEvaluation().function_)
+                        {
+                            // It's a function
+                            CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                            // Move on to next case
+                        }
+                        else
+                        {
+                            // The second argument is bad
+                            CommandExecutor::getEvaluation().state_ = CommandState::Error;
+                            AddLanguageEntry("commandexecutorunknownsecondargument", "is not a function of");
+                            CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getArgument(1) + " " + GetLocalisation("commandexecutorunknownsecondargument") + " " + CommandExecutor::getEvaluation().functionclass_->getName() + ".";
+                            return;
+                        }
+                    }
+                    else
+                    {
+                        // There is no finished second argument - search for possibilities
+                        CommandExecutor::createListOfPossibleFunctions(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_);
+                        unsigned int num_functions = CommandExecutor::getEvaluation().listOfPossibleFunctions_.size();
+
+                        if (num_functions == 1)
+                        {
+                            // It's a function
+                            std::string functionname = *(*CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()).first;
+                            CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(functionname, CommandExecutor::getEvaluation().functionclass_);
+                            if (getLowercase(functionname) != getLowercase(CommandExecutor::getArgument(1)))
+                            {
+                                // Unfinished function
+                                CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                            }
+                            CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                            CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " " + CommandExecutor::getEvaluation().function_->getName();
+                            if (CommandExecutor::getEvaluation().function_->getParamCount() > 0)
+                            {
+                                CommandExecutor::getEvaluation().command_ += " ";
+                                CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                            }
+                            // Move on to next case
+                        }
+                        else if (num_functions == 0)
+                        {
+                            // No possibilities
+                            CommandExecutor::getEvaluation().state_ = CommandState::Error;
+                            AddLanguageEntry("commandexecutorunknownsecondargumentstart", "has no function starting with");
+                            CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getEvaluation().functionclass_->getName() + " " + GetLocalisation("commandexecutorunknownsecondargumentstart") + " " + CommandExecutor::getArgument(1) + ".";
+                            return;
+                        }
+                        else
+                        {
+                            // There are several possibilities
+                            CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " " + CommandExecutor::getCommonBegin(CommandExecutor::getEvaluation().listOfPossibleFunctions_);
+                            CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_);
+                            CommandExecutor::getEvaluation().bCommandChanged_ = true;
+                            return;
+                        }
+                    }
+                }
+                else
+                {
+                    // There is no classname - move on to CommandState::ParamPreparation
+                }
+            }
+            case CommandState::ParamPreparation:
+            {
+                if (CommandExecutor::getEvaluation().function_->getParamCount() == 0 || CommandExecutor::enoughArgumentsGiven(CommandExecutor::getEvaluation().function_))
+                {
+                    CommandExecutor::getEvaluation().state_ = CommandState::Finished;
+                    return;
+                }
+                else
+                {
+                    unsigned int argumentNumber = CommandExecutor::argumentsGiven() - 2;
+                    if (CommandExecutor::getEvaluation().functionclass_)
+                        argumentNumber -= 1;
+
+                    CommandExecutor::createListOfPossibleArguments(CommandExecutor::getLastArgument(), CommandExecutor::getEvaluation().function_, argumentNumber);
+                    CommandExecutor::getEvaluation().state_ = CommandState::Params;
+
+                    if (CommandExecutor::getEvaluation().bCommandChanged_)
+                    {
+                        // Don't do more than one change
+                        return;
+                    }
+                }
+            }
+            case CommandState::Params:
+            {
+                if (CommandExecutor::getEvaluation().listOfPossibleArguments_.size() == 1)
+                {
+                    // There is exactly one possible argument
+                    CommandExecutor::getEvaluation().argument_ = (*CommandExecutor::getEvaluation().listOfPossibleArguments_.begin()).getString();
+                    CommandExecutor::getEvaluation().possibleArgument_ = (*CommandExecutor::getEvaluation().listOfPossibleArguments_.begin()).getString();
+                    CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                    return;
+                }
+                else if (CommandExecutor::getEvaluation().listOfPossibleArguments_.size() == 0)
+                {
+                    // The user tries something new - we let him do
+                    CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                    CommandExecutor::getEvaluation().argument_ = CommandExecutor::getLastArgument();
+                    return;
+                }
+                else
+                {
+                    // There are several possibilities
+                    unsigned int argumentNumber = CommandExecutor::argumentsGiven();
+                    if (argumentNumber > 0)
+                        --argumentNumber;
+                    if (CommandExecutor::getEvaluation().functionclass_ && argumentNumber > 0)
+                        --argumentNumber;
+
+                    CommandExecutor::getEvaluation().argument_ = CommandExecutor::getCommonBegin(CommandExecutor::getEvaluation().listOfPossibleArguments_);
+                    CommandExecutor::getEvaluation().possibleArgument_ = CommandExecutor::getPossibleArgument(CommandExecutor::getLastArgument(), CommandExecutor::getEvaluation().function_, argumentNumber);
+                    CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation;
+                    return;
+                }
+            }
+            case CommandState::Finished:
+            {
+                // Nothing more to do
+                break;
+            }
+            case CommandState::Error:
+            {
+                // Bad, very bad
+                break;
+            }
+        }
+    }
+
+    unsigned int CommandExecutor::argumentsFinished()
+    {
+        unsigned int argumentsGiven = CommandExecutor::argumentsGiven();
+        if (argumentsGiven > 0)
+            return argumentsGiven - 1;
+        else
+            return 0;
+    }
+
+    unsigned int CommandExecutor::argumentsGiven()
+    {
+        if (CommandExecutor::getEvaluation().command_.size() > 0 && CommandExecutor::getEvaluation().command_[CommandExecutor::getEvaluation().command_.size() - 1] == ' ')
+            return CommandExecutor::getEvaluation().commandTokens_.size() + 1;
+        else
+            return CommandExecutor::getEvaluation().commandTokens_.size();
+    }
+
+    bool CommandExecutor::enoughArgumentsGiven(ConsoleCommand* command)
+    {
+        if (CommandExecutor::getEvaluation().functionclass_)
+            return (CommandExecutor::argumentsGiven() > (2 + command->getParamCount()));
+        else
+            return (CommandExecutor::argumentsGiven() > (1 + command->getParamCount()));
+    }
+
+    std::string CommandExecutor::getArgument(unsigned int index)
+    {
+        if (index < (CommandExecutor::getEvaluation().commandTokens_.size()))
+            return CommandExecutor::getEvaluation().commandTokens_[index];
+        else
+            return "";
+    }
+
+    std::string CommandExecutor::getLastArgument()
+    {
+        return CommandExecutor::getArgument(CommandExecutor::argumentsGiven() - 1);
+    }
+
+    void CommandExecutor::createListOfPossibleIdentifiers(const std::string& fragment)
+    {
+        CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.clear();
+        std::string lowercase = getLowercase(fragment);
+        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMapBegin(); it != Identifier::getLowercaseIdentifierMapEnd(); ++it)
+            if ((*it).second->hasConsoleCommands())
+                if ((*it).first.find(lowercase) == 0 || fragment == "")
+                    CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second->getName()));
+    }
+
+    void CommandExecutor::createListOfPossibleFunctions(const std::string& fragment, Identifier* identifier)
+    {
+        CommandExecutor::getEvaluation().listOfPossibleFunctions_.clear();
+        std::string lowercase = getLowercase(fragment);
+        if (!identifier)
+        {
+            for (std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getLowercaseConsoleCommandShortcutMapBegin(); it != CommandExecutor::getLowercaseConsoleCommandShortcutMapEnd(); ++it)
+                if ((*it).first.find(lowercase) == 0 || fragment == "")
+                    CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second->getName()));
+        }
+        else
+        {
+            for (std::map<std::string, ConsoleCommand*>::const_iterator it = identifier->getLowercaseConsoleCommandMapBegin(); it != identifier->getLowercaseConsoleCommandMapEnd(); ++it)
+                if ((*it).first.find(lowercase) == 0 || fragment == "")
+                    CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second->getName()));
+        }
+    }
+
+    void CommandExecutor::createListOfPossibleArguments(const std::string& fragment, ConsoleCommand* command, unsigned int param)
+    {
+        CommandExecutor::createArgumentCompletionList(command, param);
+
+        CommandExecutor::getEvaluation().listOfPossibleArguments_.clear();
+        std::string lowercase = getLowercase(fragment);
+        for (ArgumentCompletionList::const_iterator it = command->getArgumentCompletionListBegin(); it != command->getArgumentCompletionListEnd(); ++it)
+        {
+            if ((*it).lowercaseComparison())
+            {
+                if ((*it).getComparable().find(lowercase) == 0 || fragment == "")
+                    CommandExecutor::getEvaluation().listOfPossibleArguments_.push_back(*it);
+            }
+            else
+            {
+                if ((*it).getComparable().find(fragment) == 0 || fragment == "")
+                    CommandExecutor::getEvaluation().listOfPossibleArguments_.push_back(*it);
+            }
+        }
+    }
+
+    Identifier* CommandExecutor::getPossibleIdentifier(const std::string& name)
+    {
+        std::string lowercase = getLowercase(name);
+        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMap().find(lowercase);
+        if ((it != Identifier::getLowercaseIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
+            return (*it).second;
+
+        return 0;
+    }
+
+    ConsoleCommand* CommandExecutor::getPossibleCommand(const std::string& name, Identifier* identifier)
+    {
+        std::string lowercase = getLowercase(name);
+        if (!identifier)
+        {
+            std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getLowercaseConsoleCommandShortcutMap().find(lowercase);
+            if (it != CommandExecutor::getLowercaseConsoleCommandShortcutMapEnd())
+                return (*it).second;
+        }
+        else
+        {
+            std::map<std::string, ConsoleCommand*>::const_iterator it = identifier->getLowercaseConsoleCommandMap().find(lowercase);
+            if (it != identifier->getLowercaseConsoleCommandMapEnd())
+                return (*it).second;
+        }
+        return 0;
+    }
+
+    std::string CommandExecutor::getPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param)
+    {
+        CommandExecutor::createArgumentCompletionList(command, param);
+
+        std::string lowercase = getLowercase(name);
+        for (ArgumentCompletionList::const_iterator it = command->getArgumentCompletionListBegin(); it != command->getArgumentCompletionListEnd(); ++it)
+        {
+            if ((*it).lowercaseComparison())
+            {
+                if ((*it).getComparable() == lowercase)
+                    return (*it).getString();
+            }
+            else
+            {
+                if ((*it).getComparable() == name)
+                    return (*it).getString();
+            }
+        }
+
+        return "";
+    }
+
+    void CommandExecutor::createArgumentCompletionList(ConsoleCommand* command, unsigned int param)
+    {
+        std::string params[5];
+
+        unsigned int index = 0;
+        unsigned int lowestIndex = 1 + (CommandExecutor::getEvaluation().functionclass_ != 0);
+
+        for (unsigned int i = CommandExecutor::argumentsGiven() - 1; i >= lowestIndex; --i)
+        {
+            params[index] = CommandExecutor::getArgument(i);
+            ++index;
+            if (index >= 5)
+                break;
+        }
+
+        command->createArgumentCompletionList(param, params[0], params[1], params[2], params[3], params[4]);
+    }
+
+    std::string CommandExecutor::getCommonBegin(const std::list<std::pair<const std::string*, const std::string*> >& list)
+    {
+        if (list.size() == 0)
+        {
+            return "";
+        }
+        else if (list.size() == 1)
+        {
+            return ((*(*list.begin()).first) + " ");
+        }
+        else
+        {
+            std::string output = "";
+            for (unsigned int i = 0; true; i++)
+            {
+                char temp = 0;
+                for (std::list<std::pair<const std::string*, const std::string*> >::const_iterator it = list.begin(); it != list.end(); ++it)
+                {
+                    if ((*(*it).first).size() > i)
+                    {
+                        if (it == list.begin())
+                        {
+                            temp = (*(*it).first)[i];
+                        }
+                        else
+                        {
+                            if (temp != (*(*it).first)[i])
+                                return output;
+                        }
+                    }
+                    else
+                    {
+                        return output;
+                    }
+                }
+                output += temp;
+            }
+            return output;
+        }
+    }
+
+    std::string CommandExecutor::getCommonBegin(const ArgumentCompletionList& list)
+    {
+        if (list.size() == 0)
+        {
+            return "";
+        }
+        else if (list.size() == 1)
+        {
+            return ((*list.begin()).getComparable() + " ");
+        }
+        else
+        {
+            std::string output = "";
+            for (unsigned int i = 0; true; i++)
+            {
+                char temp = 0;
+                for (ArgumentCompletionList::const_iterator it = list.begin(); it != list.end(); ++it)
+                {
+                    std::string argument = (*it).getComparable();
+                    if (argument.size() > i)
+                    {
+                        if (it == list.begin())
+                        {
+                            temp = argument[i];
+                        }
+                        else
+                        {
+                            if (temp != argument[i])
+                                return output;
+                        }
+                    }
+                    else
+                    {
+                        return output;
+                    }
+                }
+                output += temp;
+            }
+            return output;
+        }
+    }
+
+    void CommandExecutor::destroyExternalCommands()
+    {
+        for (std::set<ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandExternals_.begin();
+            it != CommandExecutor::getInstance().consoleCommandExternals_.end(); ++it)
+            delete *it;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/CommandExecutor.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/CommandExecutor.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CommandExecutor.h	(revision 5712)
@@ -0,0 +1,114 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _CommandExecutor_H__
+#define _CommandExecutor_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <set>
+#include <string>
+
+#include "util/MultiType.h"
+#include "CommandEvaluation.h"
+
+// tolua_begin
+namespace orxonox
+{
+    class _CoreExport CommandExecutor
+    {
+// tolua_end
+        public:
+            static bool execute(const std::string& command, bool useTcl = true); // tolua_export
+            static MultiType getReturnValue();
+            static std::string getReturnValueString(); // tolua_export
+
+            static std::string complete(const std::string& command);
+            static std::string hint(const std::string& command);
+
+            static CommandEvaluation evaluate(const std::string& command);
+            static const CommandEvaluation& getLastEvaluation();
+
+            static ConsoleCommand& addConsoleCommandShortcut(ConsoleCommand* command, bool bDeleteAtExit = false);
+            static ConsoleCommand* getConsoleCommandShortcut(const std::string& name);
+            static ConsoleCommand* getLowercaseConsoleCommandShortcut(const std::string& name);
+
+            /** @brief Returns the map that stores all console commands. @return The const_iterator */
+            static inline const std::map<std::string, ConsoleCommand*>& getConsoleCommandShortcutMap() { return CommandExecutor::getInstance().consoleCommandShortcuts_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all console commands. @return The const_iterator */
+            static inline std::map<std::string, ConsoleCommand*>::const_iterator getConsoleCommandShortcutMapBegin() { return CommandExecutor::getInstance().consoleCommandShortcuts_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all console commands. @return The const_iterator */
+            static inline std::map<std::string, ConsoleCommand*>::const_iterator getConsoleCommandShortcutMapEnd() { return CommandExecutor::getInstance().consoleCommandShortcuts_.end(); }
+
+            /** @brief Returns the map that stores all console commands with their names in lowercase. @return The const_iterator */
+            static inline const std::map<std::string, ConsoleCommand*>& getLowercaseConsoleCommandShortcutMap() { return CommandExecutor::getInstance().consoleCommandShortcuts_LC_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all console commands with their names in lowercase. @return The const_iterator */
+            static inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandShortcutMapBegin() { return CommandExecutor::getInstance().consoleCommandShortcuts_LC_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all console commands with their names in lowercase. @return The const_iterator */
+            static inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandShortcutMapEnd() { return CommandExecutor::getInstance().consoleCommandShortcuts_LC_.end(); }
+
+            static void destroyExternalCommands();
+
+        private:
+            CommandExecutor() {}
+            CommandExecutor(const CommandExecutor& other);
+            ~CommandExecutor() {}
+
+            static CommandExecutor& getInstance();
+            static CommandEvaluation& getEvaluation();
+
+            static void parseIfNeeded(const std::string& command);
+            static void parse(const std::string& command, bool bInitialize = true);
+
+            static unsigned int argumentsFinished();
+            static unsigned int argumentsGiven();
+            static bool enoughArgumentsGiven(ConsoleCommand* command);
+            static std::string getArgument(unsigned int index);
+            static std::string getLastArgument();
+
+            static void createListOfPossibleIdentifiers(const std::string& fragment);
+            static void createListOfPossibleFunctions(const std::string& fragment, Identifier* identifier = 0);
+            static void createListOfPossibleArguments(const std::string& fragment, ConsoleCommand* command, unsigned int param);
+
+            static Identifier* getPossibleIdentifier(const std::string& name);
+            static ConsoleCommand* getPossibleCommand(const std::string& name, Identifier* identifier = 0);
+            static std::string getPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param);
+
+            static void createArgumentCompletionList(ConsoleCommand* command, unsigned int param);
+            static std::string getCommonBegin(const std::list<std::pair<const std::string*, const std::string*> >& list);
+            static std::string getCommonBegin(const ArgumentCompletionList& list);
+
+            CommandEvaluation evaluation_;
+            std::map<std::string, ConsoleCommand*> consoleCommandShortcuts_;
+            std::map<std::string, ConsoleCommand*> consoleCommandShortcuts_LC_;
+            std::set<ConsoleCommand*>              consoleCommandExternals_;
+    }; // tolua_export
+} // tolua_export
+
+#endif /* _CommandExecutor_H__ */
Index: /code/branches/libraries2/src/libraries/core/CommandLine.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/CommandLine.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CommandLine.cc	(revision 5712)
@@ -0,0 +1,378 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "CommandLine.h"
+
+#include <algorithm>
+#include <sstream>
+#include <boost/filesystem.hpp>
+
+#include "util/Convert.h"
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/StringUtils.h"
+#include "util/SubString.h"
+#include "Core.h"
+
+namespace orxonox
+{
+    SetCommandLineOnlyArgument(optionsFile, "start.ini").shortcut("o");
+
+    /**
+    @brief
+        Parses a value string for a command line argument.
+        It simply uses convertValue(Output, Input) to do that.
+        Bools are treated specially. That is necessary
+        so that you can have simple command line switches.
+    */
+    void CommandLineArgument::parse(const std::string& value, bool bParsingFile)
+    {
+        if (bParsingFile && this->bCommandLineOnly_)
+            ThrowException(Argument, "Command line argument '" + getName() + "' is not allowed in files.");
+        if (value_.getType() == MT_Type::Bool)
+        {
+            // simulate command line switch
+            bool temp;
+            if (convertValue(&temp, value))
+            {
+                this->bHasDefaultValue_ = false;
+                this->value_ = temp;
+            }
+            else if (value == "")
+            {
+                this->bHasDefaultValue_ = false;
+                this->value_ = true;
+            }
+            else
+                ThrowException(Argument, "Could not read command line argument '" + getName() + "'.");
+        }
+        else
+        {
+            if (!value_.setValue(value))
+            {
+                value_.setValue(defaultValue_);
+                ThrowException(Argument, "Could not read command line argument '" + getName() + "'.");
+            }
+            else
+                this->bHasDefaultValue_ = false;
+        }
+    }
+
+
+    /**
+    @brief
+        Destructor destroys all CommandLineArguments with it.
+    */
+    CommandLine::~CommandLine()
+    {
+        CommandLine::destroyAllArguments();
+    }
+
+    /**
+    @brief
+        Returns a unique instance (Meyers Singleton).
+    */
+    CommandLine& CommandLine::_getInstance()
+    {
+        static CommandLine instance;
+        return instance;
+    }
+
+    /**
+    @brief
+        Destroys all command line arguments. This should be called at the end
+        of main. Do not use before that.
+    */
+    void CommandLine::destroyAllArguments()
+    {
+        for (std::map<std::string, CommandLineArgument*>::const_iterator it = _getInstance().cmdLineArgs_.begin();
+            it != _getInstance().cmdLineArgs_.end(); ++it)
+            delete it->second;
+        _getInstance().cmdLineArgs_.clear();
+    }
+
+    /**
+    @brief
+        Reads the command line parses the values of each argument.
+        It is then stored in the corresponding CommandLineArgument.
+    @note
+        The reason that you have to provide the string to be parsed as
+        space separted list is because of argc and argv. If you only have
+        a whole string, simply use getAllStrings() of SubString.
+    @param arguments
+        Vector of space separated strings.
+    */
+    void CommandLine::_parse(const std::vector<std::string>& arguments, bool bParsingFile)
+    {
+        try
+        {
+            // why this? See bFirstTimeParse_ declaration.
+            if (bFirstTimeParse_)
+            {
+                // first shove all the shortcuts in a map
+                for (std::map<std::string, CommandLineArgument*>::const_iterator it = cmdLineArgs_.begin();
+                    it != cmdLineArgs_.end(); ++it)
+                {
+                    OrxAssert(cmdLineArgsShortcut_.find(it->second->getShortcut()) == cmdLineArgsShortcut_.end(),
+                        "Cannot have two command line shortcut with the same name.");
+                    if (it->second->getShortcut() != "")
+                        cmdLineArgsShortcut_[it->second->getShortcut()] = it->second;
+                }
+                bFirstTimeParse_ = false;
+            }
+
+            std::string name;
+            std::string shortcut;
+            std::string value;
+            for (unsigned int i = 0; i < arguments.size(); ++i)
+            {
+                if (arguments[i].size() != 0)
+                {
+                    // sure not ""
+                    if (arguments[i][0] == '-')
+                    {
+                        // start with "-"
+                        if (arguments[i].size() == 1)
+                        {
+                            // argument[i] is "-", probably a minus sign
+                            value += "- ";
+                        }
+                        else if (arguments[i][1] <= 57 && arguments[i][1] >= 48)
+                        {
+                            // negative number as a value
+                            value += arguments[i] + " ";
+                        }
+                        else
+                        {
+                            // can be shortcut or full name argument
+
+                            // save old data first
+                            value = removeTrailingWhitespaces(value);
+                            if (name != "")
+                            {
+                                checkFullArgument(name, value, bParsingFile);
+                                name = "";
+                                assert(shortcut == "");
+                            }
+                            else if (shortcut != "")
+                            {
+                                checkShortcut(shortcut, value, bParsingFile);
+                                shortcut = "";
+                                assert(name == "");
+                            }
+
+                            if (arguments[i][1] == '-')
+                            {
+                                // full name argument with "--name"
+                                name = arguments[i].substr(2);
+                            }
+                            else
+                            {
+                                // shortcut with "-s"
+                                shortcut = arguments[i].substr(1);
+                            }
+
+                            // reset value string
+                            value = "";
+                        }
+                    }
+                    else
+                    {
+                        // value string
+
+                        if (name == "" && shortcut == "")
+                        {
+                            ThrowException(Argument, "Expected \"-\" or \"-\" in command line arguments.\n");
+                        }
+
+                        // Concatenate strings as long as there's no new argument by "-" or "--"
+                        value += arguments[i] + ' ';
+                    }
+                }
+            }
+
+            // parse last argument
+            value = removeTrailingWhitespaces(value);
+            if (name != "")
+            {
+                checkFullArgument(name, value, bParsingFile);
+                assert(shortcut == "");
+            }
+            else if (shortcut != "")
+            {
+                checkShortcut(shortcut, value, bParsingFile);
+                assert(name == "");
+            }
+        }
+        catch (const ArgumentException& ex)
+        {
+            COUT(0) << "Could not parse command line (including additional files): " << ex.what() << std::endl;
+            COUT(0) << CommandLine::getUsageInformation() << std::endl;
+            throw GeneralException("");
+        }
+    }
+
+    /**
+    @brief
+        Parses an argument based on its full name.
+    @param name
+        Full name of the argument
+    @param value
+        String containing the value
+    */
+    void CommandLine::checkFullArgument(const std::string& name, const std::string& value, bool bParsingFile)
+    {
+        std::map<std::string, CommandLineArgument*>::const_iterator it = cmdLineArgs_.find(name);
+        if (it == cmdLineArgs_.end())
+            ThrowException(Argument, "Command line argument '" + name + "' does not exist.");
+
+        it->second->parse(value, bParsingFile);
+    }
+
+    /**
+    @brief
+        Parses an argument based on its shortcut.
+    @param shortcut
+        Shotcut to the argument
+    @param value
+        String containing the value
+    */
+    void CommandLine::checkShortcut(const std::string& shortcut, const std::string& value, bool bParsingFile)
+    {
+        std::map<std::string, CommandLineArgument*>::const_iterator it = cmdLineArgsShortcut_.find(shortcut);
+        if (it == cmdLineArgsShortcut_.end())
+            ThrowException(Argument, "Command line shortcut '" + shortcut + "' does not exist.");
+
+        it->second->parse(value, bParsingFile);
+    }
+
+    std::string CommandLine::getUsageInformation()
+    {
+        CommandLine& inst = _getInstance();
+        std::ostringstream infoStr;
+
+        // determine maximum name size
+        size_t maxNameSize = 0;
+        for (std::map<std::string, CommandLineArgument*>::const_iterator it = inst.cmdLineArgs_.begin();
+            it != inst.cmdLineArgs_.end(); ++it)
+        {
+            maxNameSize = std::max(it->second->getName().size(), maxNameSize);
+        }
+
+        infoStr << "Usage: orxonox [options]" << std::endl;
+        infoStr << "Available options:" << std::endl;
+
+        for (std::map<std::string, CommandLineArgument*>::const_iterator it = inst.cmdLineArgs_.begin();
+            it != inst.cmdLineArgs_.end(); ++it)
+        {
+            if (it->second->getShortcut() != "")
+                infoStr << " [-" << it->second->getShortcut() << "] ";
+            else
+                infoStr << "      ";
+            infoStr << "--" << it->second->getName() << " ";
+            if (it->second->getValue().getType() != MT_Type::Bool)
+                infoStr << "ARG ";
+            else
+                infoStr << "    ";
+            // fill with the necessary amount of blanks
+            infoStr << std::string(maxNameSize - it->second->getName().size(), ' ');
+            infoStr << ": " << it->second->getInformation();
+            infoStr << std::endl;
+        }
+        return infoStr.str();
+    }
+
+    /**
+    @brief
+        Retrieves a CommandLineArgument.
+        The method throws an exception if 'name' was not found or the value could not be converted.
+    @note
+        You shold of course not call this method before the command line has been parsed.
+    */
+    const CommandLineArgument* CommandLine::getArgument(const std::string& name)
+    {
+        std::map<std::string, CommandLineArgument*>::const_iterator it = _getInstance().cmdLineArgs_.find(name);
+        if (it == _getInstance().cmdLineArgs_.end())
+        {
+            ThrowException(Argument, "Could find command line argument '" + name + "'.");
+        }
+        else
+        {
+            return it->second;
+        }
+    }
+
+    /**
+    @brief
+        Parses only the command line for CommandLineArguments.
+    */
+    void CommandLine::_parseCommandLine(const std::string& cmdLine)
+    {
+        std::vector<std::string> args;
+        SubString tokens(cmdLine, " ", " ", false, '\\', true, '"', true, '(', ')', false);
+        for (unsigned i = 0; i < tokens.size(); ++i)
+            args.push_back(tokens[i]);
+        this->_parse(args, false);
+    }
+
+    /**
+    @brief
+        Parses start.ini (or the file specified with --optionsFile) for CommandLineArguments.
+    */
+    void CommandLine::_parseFile()
+    {
+        std::string filename = CommandLine::getValue("optionsFile").getString();
+        boost::filesystem::path filepath(Core::getConfigPath() / filename);
+
+        // look for additional arguments in given file or start.ini as default
+        // They will not overwrite the arguments given directly
+        std::ifstream file;
+        file.open(filepath.string().c_str());
+        std::vector<std::string> args;
+        if (file)
+        {
+            while (!file.eof())
+            {
+                std::string line;
+                std::getline(file, line);
+                line = removeTrailingWhitespaces(line);
+                //if (!(line[0] == '#' || line[0] == '%'))
+                //{
+                SubString tokens(line, " ", " ", false, '\\', true, '"', true, '(', ')', false, '#');
+                for (unsigned i = 0; i < tokens.size(); ++i)
+                    if (tokens[i][0] != '#')
+                        args.push_back(tokens[i]);
+                //args.insert(args.end(), tokens.getAllStrings().begin(), tokens.getAllStrings().end());
+                //}
+            }
+            file.close();
+        }
+
+        _parse(args, true);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/CommandLine.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/CommandLine.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CommandLine.h	(revision 5712)
@@ -0,0 +1,223 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _CommandLine_H__
+#define _CommandLine_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include "util/OrxAssert.h"
+#include "util/MultiType.h"
+
+#define SetCommandLineArgument(name, defaultValue) \
+    orxonox::CommandLineArgument& CmdArgumentDummyBoolVar##name \
+    = orxonox::CommandLine::addArgument(#name, defaultValue, false)
+#define SetCommandLineOnlyArgument(name, defaultValue) \
+    orxonox::CommandLineArgument& CmdArgumentDummyBoolVar##name \
+    = orxonox::CommandLine::addArgument(#name, defaultValue, true)
+#define SetCommandLineSwitch(name) \
+    orxonox::CommandLineArgument& CmdArgumentDummyBoolVar##name \
+    = orxonox::CommandLine::addArgument(#name, false, false)
+#define SetCommandLineOnlySwitch(name) \
+    orxonox::CommandLineArgument& CmdArgumentDummyBoolVar##name \
+    = orxonox::CommandLine::addArgument(#name, false, true)
+
+
+namespace orxonox
+{
+    /**
+    @brief
+        Container class for a command line argument of any type supported by MultiType.
+
+        Whenever you want to have an option specified by a command line switch,
+        you need to first define it with SetCommandLineArgument(name, defaultValue).
+        It is then added to a map and possibly changed when the command line is being parsed.
+        If the option was not given, you can detect this by asking hasDefaultValue().
+
+        There is a possibility to define a short cut so you can write "-p 20" instead of "--port 20".
+        Note the difference between "-" and "--"!
+        Also, there is no restriction to the number of strings you add after --name.
+        So "--startVector (2, 4, 5)" is perfectly legal.
+
+        Retrieving an argument is possible with the getCommandLineArgument function of the
+        CommandLine class. It is a Singleton, but the public interface is static.
+    */
+    class _CoreExport CommandLineArgument
+    {
+        friend class CommandLine;
+
+    public:
+        //! Tells whether the value has been changed by the command line.
+        bool hasDefaultValue() const { return bHasDefaultValue_; }
+        //! Returns the name of the argument.
+        const std::string& getName() const { return name_; }
+
+        //! Returns the shortcut (example: "-p 22" for "--port 22") of the argument.
+        //! Evaluates to "" if there is none.
+        const std::string& getShortcut() const { return shortcut_; }
+        //! Sets the shortcut for the argument
+        CommandLineArgument& shortcut(const std::string& shortcut)
+        { this->shortcut_ = shortcut; return *this; }
+
+        //! Returns the usage information
+        const std::string& getInformation() const { return this->usageInformation_; }
+        //! Sets the option information when displaying orxonox usage.
+        CommandLineArgument& information(const std::string& usage)
+        { this->usageInformation_ = usage; return *this; }
+
+        //! Returns the actual value of the argument. Can be equal to default value.
+        MultiType getValue() const { return value_; }
+        //! Returns the given default value as type T.
+        MultiType getDefaultValue() const { return defaultValue_; }
+
+    private:
+        //! Constructor initialises both value_ and defaultValue_ with defaultValue.
+        CommandLineArgument(const std::string& name, const MultiType& defaultValue, bool bCommandLineOnly)
+            : bHasDefaultValue_(true)
+            , name_(name)
+            , value_(defaultValue)
+            , defaultValue_(defaultValue)
+            , bCommandLineOnly_(bCommandLineOnly)
+        { }
+
+        //! Undefined copy constructor
+        CommandLineArgument(const CommandLineArgument& instance);
+        ~CommandLineArgument() { }
+
+        //! Parses the value string of a command line argument.
+        void parse(const std::string& value, bool bParsingFile);
+
+        //! Tells whether the value has been changed by the command line.
+        bool bHasDefaultValue_;
+
+    private:
+        std::string name_;             //!< Name of the argument
+        std::string shortcut_;         //!< Shortcut of the argument. @see getShortcut().
+        std::string usageInformation_; //!< Tells about the usage of this parameter
+
+        MultiType   value_;            //!< The actual value
+        MultiType   defaultValue_;     //!< Default value. Should not be changed.
+        bool        bCommandLineOnly_; //!< Whether you cannot specify the value in a text file
+    };
+
+
+    /**
+    @brief
+        Global interface to command line options.
+        Allows to add and retrieve command line arguments. Also does the parsing.
+    @note
+        Internally it is a Singleton, but the public interface is static.
+    @see
+        CommandLineArgument
+    */
+    class _CoreExport CommandLine
+    {
+    public:
+
+        //! Parse redirection to internal member method.
+        static void parseCommandLine(const std::string& cmdLine) { _getInstance()._parseCommandLine(cmdLine); }
+        static void parseFile() { _getInstance()._parseFile(); }
+
+        static std::string getUsageInformation();
+
+        static const CommandLineArgument* getArgument(const std::string& name);
+        //! Writes the argument value in the given parameter.
+        template <class T>
+        static void getValue(const std::string& name, T* value)
+        { *value = (T)(getArgument(name)->getValue()); }
+        static MultiType getValue(const std::string& name)
+        { return getArgument(name)->getValue(); }
+        template <class T>
+        static CommandLineArgument& addArgument(const std::string& name, T defaultValue, bool bCommandLineOnly);
+
+        static bool existsArgument(const std::string& name)
+        {
+            std::map<std::string, CommandLineArgument*>::const_iterator it = _getInstance().cmdLineArgs_.find(name);
+            return !(it == _getInstance().cmdLineArgs_.end());
+        }
+
+        static void destroyAllArguments();
+
+    private:
+        //! Constructor initialises bFirstTimeParse_ with true.
+        CommandLine() : bFirstTimeParse_(true) { }
+        //! Undefined copy constructor
+        CommandLine(const CommandLine& instance);
+        ~CommandLine();
+
+        static CommandLine& _getInstance();
+
+        void _parseCommandLine(const std::string& cmdLine);
+        void _parseFile();
+        void _parse(const std::vector<std::string>& arguments, bool bParsingFile);
+        void checkFullArgument(const std::string& name, const std::string& value, bool bParsingFile);
+        void checkShortcut(const std::string& shortcut, const std::string& value, bool bParsingFile);
+
+        /**
+            Tells whether we parsed for the first time. The CommmandLineArguments are added before main().
+            So when we call parse() the first time, we need to create a map with all shortcuts since these
+            get added after addCommandLineArgument().
+        */
+        bool bFirstTimeParse_;
+
+        //! Holds all pointers to the arguments and serves as a search map by name.
+        std::map<std::string, CommandLineArgument*> cmdLineArgs_;
+        //! Search map by shortcut for the arguments.
+        std::map<std::string, CommandLineArgument*> cmdLineArgsShortcut_;
+    };
+
+    template <>
+    inline void CommandLine::getValue<std::string>(const std::string& name, std::string* value)
+    {
+        *value = getArgument(name)->getValue().getString();
+    }
+
+    /**
+    @brief
+        Adds a new CommandLineArgument to the internal map.
+        Note that only such arguments are actually valid.
+    @param name
+        Name of the argument. Shortcut can be added later.
+    @param defaultValue
+        Default value that is used when argument was not given.
+    */
+    template <class T>
+    CommandLineArgument& CommandLine::addArgument(const std::string& name, T defaultValue, bool bCommandLineOnly)
+    {
+        OrxAssert(!_getInstance().existsArgument(name),
+            "Cannot add a command line argument with name '" + name + "' twice.");
+        OrxAssert(MultiType(defaultValue).getType() != MT_Type::Bool || MultiType(defaultValue).getBool() != true,
+               "Boolean command line arguments with positive default values are not supported." << std::endl
+            << "Please use SetCommandLineSwitch and adjust your argument: " << name);
+
+        return *(_getInstance().cmdLineArgs_[name] = new CommandLineArgument(name, defaultValue, bCommandLineOnly));
+    }
+}
+
+#endif /* _CommandLine_H__ */
Index: /code/branches/libraries2/src/libraries/core/ConfigFileManager.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConfigFileManager.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConfigFileManager.cc	(revision 5712)
@@ -0,0 +1,573 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "ConfigFileManager.h"
+
+#include <boost/filesystem.hpp>
+
+#include "util/Convert.h"
+#include "util/Math.h"
+#include "util/StringUtils.h"
+#include "ConsoleCommand.h"
+#include "ConfigValueContainer.h"
+#include "Core.h"
+
+namespace orxonox
+{
+    SetConsoleCommandShortcutExtern(config).argumentCompleter(0, autocompletion::configvalueclasses()).argumentCompleter(1, autocompletion::configvalues()).argumentCompleter(2, autocompletion::configvalue());
+    SetConsoleCommandShortcutExtern(tconfig).argumentCompleter(0, autocompletion::configvalueclasses()).argumentCompleter(1, autocompletion::configvalues()).argumentCompleter(2, autocompletion::configvalue());
+    SetConsoleCommandShortcutExtern(reloadConfig);
+    SetConsoleCommandShortcutExtern(cleanConfig);
+    SetConsoleCommandShortcutExtern(loadSettings).argumentCompleter(0, autocompletion::files());
+
+    bool config(const std::string& classname, const std::string& varname, const std::string& value)
+    {
+        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
+        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+        {
+            std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
+            if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())
+                return (*variable).second->set(value);
+        }
+        return false;
+    }
+
+    bool tconfig(const std::string& classname, const std::string& varname, const std::string& value)
+    {
+        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
+        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+        {
+            std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
+            if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())
+                return (*variable).second->tset(value);
+        }
+        return false;
+    }
+
+    void reloadConfig()
+    {
+        ConfigFileManager::getInstance().load();
+    }
+
+    void cleanConfig()
+    {
+        ConfigFileManager::getInstance().clean(false);
+    }
+
+    void loadSettings(const std::string& filename)
+    {
+        ConfigFileManager::getInstance().setFilename(ConfigFileType::Settings, filename);
+    }
+
+    //////////////////////////
+    // ConfigFileEntryValue //
+    //////////////////////////
+
+    void ConfigFileEntryValue::setValue(const std::string& value)
+    {
+        if (!this->bString_)
+            this->value_ = value;
+        else
+            this->value_ = "\"" + addSlashes(stripEnclosingQuotes(value)) + "\"";
+    }
+
+    std::string ConfigFileEntryValue::getValue() const
+    {
+        if (!this->bString_)
+            return this->value_;
+        else
+            return removeSlashes(stripEnclosingQuotes(this->value_));
+    }
+
+    std::string ConfigFileEntryValue::getFileEntry() const
+    {
+        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
+            return (this->name_ + "=" + this->value_);
+        else
+            return (this->name_ + "=" + this->value_ + " " + this->additionalComment_);
+    }
+
+
+    ////////////////////////////////
+    // ConfigFileEntryVectorValue //
+    ////////////////////////////////
+    std::string ConfigFileEntryVectorValue::getFileEntry() const
+    {
+        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
+            return (this->name_ + "[" + multi_cast<std::string>(this->index_) + "]" + "=" + this->value_);
+        else
+            return (this->name_ + "[" + multi_cast<std::string>(this->index_) + "]=" + this->value_ + " " + this->additionalComment_);
+    }
+
+
+    ///////////////////////
+    // ConfigFileSection //
+    ///////////////////////
+    ConfigFileSection::~ConfigFileSection()
+    {
+        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
+            delete (*(it++));
+    }
+
+    void ConfigFileSection::deleteVectorEntries(const std::string& name, unsigned int startindex)
+    {
+        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
+        {
+            if (((*it)->getName() == name) && ((*it)->getIndex() >= startindex))
+            {
+                delete (*it);
+                this->entries_.erase(it++);
+            }
+            else
+            {
+                ++it;
+            }
+        }
+    }
+
+    unsigned int ConfigFileSection::getVectorSize(const std::string& name)
+    {
+        unsigned int size = 0;
+        for (std::list<ConfigFileEntry*>::const_iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
+            if ((*it)->getName() == name)
+                if ((*it)->getIndex() > size)
+                    size = (*it)->getIndex();
+        if (size == 0)
+            return 0;
+        else
+            return (size + 1);
+    }
+
+    std::string ConfigFileSection::getFileEntry() const
+    {
+        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
+            return ("[" + this->name_ + "]");
+        else
+            return ("[" + this->name_ + "] " + this->additionalComment_);
+    }
+
+    std::list<ConfigFileEntry*>::iterator ConfigFileSection::getEntryIterator(const std::string& name, const std::string& fallback, bool bString)
+    {
+        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
+        {
+            if ((*it)->getName() == name)
+            {
+                (*it)->setString(bString);
+                return it;
+            }
+        }
+
+        this->bUpdated_ = true;
+
+        return this->entries_.insert(this->entries_.end(), static_cast<ConfigFileEntry*>(new ConfigFileEntryValue(name, fallback, bString)));
+    }
+
+    std::list<ConfigFileEntry*>::iterator ConfigFileSection::getEntryIterator(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
+    {
+        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
+        {
+            if (((*it)->getName() == name) && ((*it)->getIndex() == index))
+            {
+                (*it)->setString(bString);
+                return it;
+            }
+        }
+
+        this->bUpdated_ = true;
+
+        if (index == 0)
+            return this->entries_.insert(this->entries_.end(), static_cast<ConfigFileEntry*>(new ConfigFileEntryVectorValue(name, index, fallback, bString)));
+        else
+            return this->entries_.insert(++this->getEntryIterator(name, index - 1, "", bString), static_cast<ConfigFileEntry*>(new ConfigFileEntryVectorValue(name, index, fallback, bString)));
+    }
+
+
+    ////////////////
+    // ConfigFile //
+    ////////////////
+    ConfigFile::~ConfigFile()
+    {
+        this->clear();
+    }
+
+    void ConfigFile::load(bool bCreateIfNotExisting)
+    {
+        // Be sure we start from new in the memory
+        this->clear();
+
+        // Get default file if necessary and available
+        boost::filesystem::path filepath(Core::getConfigPath() / this->filename_);
+        if (!boost::filesystem::exists(filepath))
+        {
+            // Try to get default one from the data folder
+            boost::filesystem::path defaultFilepath(Core::getDataPath() / "defaultConfig" / this->filename_);
+            if (boost::filesystem::exists(defaultFilepath))
+            {
+                COUT(3) << "Copied " << this->filename_ << " from the defaultConfig folder." << std::endl;
+                boost::filesystem::copy_file(defaultFilepath, filepath);
+            }
+        }
+
+        // Open the file
+        std::ifstream file;
+        file.open(filepath.string().c_str(), std::fstream::in);
+        if (file.is_open())
+        {
+            ConfigFileSection* newsection = 0;
+
+            while (file.good() && !file.eof())
+            {
+                std::string line;
+                std::getline(file, line);
+
+                std::string temp = getStripped(line);
+                if (!isEmpty(temp) && !isComment(temp))
+                {
+                    size_t   pos1 = temp.find('[');
+                    if (pos1 == 0) pos1 = line.find('['); else pos1 = std::string::npos;
+                    size_t   pos2 = line.find(']');
+
+                    if (pos1 != std::string::npos && pos2 != std::string::npos && pos2 > pos1 + 1)
+                    {
+                        // New section
+                        std::string comment = line.substr(pos2 + 1);
+                        if (isComment(comment))
+                            newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1), comment);
+                        else
+                            newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1));
+                        this->sections_.insert(this->sections_.end(), newsection);
+                        continue;
+                    }
+                }
+
+                if (newsection != 0)
+                {
+                    if (isComment(line))
+                    {
+                        // New comment
+                        newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryComment(removeTrailingWhitespaces(line)));
+                        continue;
+                    }
+                    else
+                    {
+                        size_t pos1 = line.find('=');
+
+                        if (pos1 != std::string::npos && pos1 > 0)
+                        {
+                            // New entry
+                            size_t pos2 = line.find('[');
+                            size_t pos3 = line.find(']');
+                            size_t commentposition = getNextCommentPosition(line, pos1 + 1);
+                            while (isBetweenQuotes(line, commentposition))
+                            {
+                                commentposition = getNextCommentPosition(line, commentposition + 1);
+                            }
+                            std::string value = "", comment = "";
+                            if (commentposition == std::string::npos)
+                            {
+                                value = removeTrailingWhitespaces(line.substr(pos1 + 1));
+                            }
+                            else
+                            {
+                                value = removeTrailingWhitespaces(line.substr(pos1 + 1, commentposition - pos1 - 1));
+                                comment = removeTrailingWhitespaces(line.substr(commentposition));
+                            }
+
+                            if (pos2 != std::string::npos && pos3 != std::string::npos && pos3 > pos2 + 1)
+                            {
+                                // There might be an array index
+                                unsigned int index = 0;
+                                if (convertValue(&index, line.substr(pos2 + 1, pos3 - pos2 - 1)))
+                                {
+                                    // New array
+                                    std::list<ConfigFileEntry*>::iterator it = newsection->getEntryIterator(getStripped(line.substr(0, pos2)), index, value, false);
+                                    (*it)->setValue(value);
+                                    (*it)->setComment(comment);
+                                    continue;
+                                }
+                            }
+
+                            // New value
+                            newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryValue(getStripped(line.substr(0, pos1)), value, false, comment));
+                            continue;
+                        }
+                    }
+                }
+            }
+
+            file.close();
+
+            COUT(3) << "Loaded config file \"" << this->filename_ << "\"." << std::endl;
+
+            // Save the file in case something changed (like stripped whitespaces)
+            this->save();
+
+            // Update all ConfigValueContainers
+            this->updateConfigValues();
+        } // end file.is_open()
+    }
+
+    void ConfigFile::save() const
+    {
+        std::ofstream file;
+        file.open((Core::getConfigPathString() + filename_).c_str(), std::fstream::out);
+        file.setf(std::ios::fixed, std::ios::floatfield);
+        file.precision(6);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "An error occurred in ConfigFileManager.cc:" << std::endl;
+            COUT(1) << "Error: Couldn't open config-file \"" << this->filename_ << "\"." << std::endl;
+            return;
+        }
+
+        for (std::list<ConfigFileSection*>::const_iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
+        {
+            file << (*it)->getFileEntry() << std::endl;
+
+            for (std::list<ConfigFileEntry*>::const_iterator it_entries = (*it)->getEntriesBegin(); it_entries != (*it)->getEntriesEnd(); ++it_entries)
+            {
+                file << (*it_entries)->getFileEntry() << std::endl;
+            }
+
+            file << std::endl;
+        }
+
+        file.close();
+
+        COUT(4) << "Saved config file \"" << this->filename_ << "\"." << std::endl;
+    }
+
+    void ConfigFile::saveAs(const std::string& filename)
+    {
+        std::string temp = this->filename_;
+        this->filename_ = filename;
+        this->save();
+        this->filename_ = temp;
+    }
+
+    void ConfigFile::clean(bool bCleanComments)
+    {
+        for (std::list<ConfigFileSection*>::iterator it1 = this->sections_.begin(); it1 != this->sections_.end(); )
+        {
+            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getIdentifierMap().find((*it1)->getName());
+            if (it2 != Identifier::getIdentifierMapEnd() && (*it2).second->hasConfigValues())
+            {
+                // The section exists, delete comment
+                if (bCleanComments)
+                    (*it1)->setComment("");
+                for (std::list<ConfigFileEntry*>::iterator it3 = (*it1)->entries_.begin(); it3 != (*it1)->entries_.end(); )
+                {
+                    std::map<std::string, ConfigValueContainer*>::const_iterator it4 = (*it2).second->getConfigValueMap().find((*it3)->getName());
+                    if (it4 != (*it2).second->getConfigValueMapEnd())
+                    {
+                        // The config-value exists, delete comment
+                        if (bCleanComments)
+                            (*it3)->setComment("");
+                        ++it3;
+                    }
+                    else
+                    {
+                        // The config-value doesn't exist
+                        delete (*it3);
+                        (*it1)->entries_.erase(it3++);
+                    }
+                }
+                ++it1;
+            }
+            else
+            {
+                // The section doesn't exist
+                delete (*it1);
+                this->sections_.erase(it1++);
+            }
+        }
+
+        // Save the file
+        this->save();
+    }
+
+    void ConfigFile::clear()
+    {
+        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); )
+            delete (*(it++));
+        this->sections_.clear();
+    }
+
+    ConfigFileSection* ConfigFile::getSection(const std::string& section)
+    {
+        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
+            if ((*it)->getName() == section)
+                return (*it);
+
+        this->bUpdated_ = true;
+
+        return (*this->sections_.insert(this->sections_.end(), new ConfigFileSection(section)));
+    }
+
+    void ConfigFile::saveIfUpdated()
+    {
+        bool sectionsUpdated = false;
+
+        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
+        {
+            if ((*it)->bUpdated_)
+            {
+                sectionsUpdated = true;
+                (*it)->bUpdated_ = false;
+            }
+        }
+
+        if (this->bUpdated_ || sectionsUpdated)
+        {
+            this->bUpdated_ = false;
+            this->save();
+        }
+    }
+
+    void ConfigFile::updateConfigValues()
+    {
+        if (this->type_ == ConfigFileType::Settings)
+        {
+            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
+            {
+                if (it->second->hasConfigValues())
+                {
+                    for (std::map<std::string, ConfigValueContainer*>::const_iterator it2 = (*it).second->getConfigValueMapBegin(); it2 != (*it).second->getConfigValueMapEnd(); ++it2)
+                        it2->second->update();
+
+                    it->second->updateConfigValues();
+                }
+            }
+        }
+    }
+
+
+    ///////////////////////
+    // ConfigFileManager //
+    ///////////////////////
+
+    ConfigFileManager* ConfigFileManager::singletonPtr_s = 0;
+
+    std::string ConfigFileManager::DEFAULT_CONFIG_FILE = "default.ini";
+
+    ConfigFileManager::ConfigFileManager()
+         : mininmalFreeType_(ConfigFileType::numberOfReservedTypes)
+    {
+    }
+
+    ConfigFileManager::~ConfigFileManager()
+    {
+        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); )
+            delete (it++)->second;
+    }
+
+    void ConfigFileManager::setFilename(ConfigFileType type, const std::string& filename)
+    {
+        std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.find(type);
+        if (it != this->configFiles_.end())
+        {
+            assert(it->second);
+            delete it->second;
+        }
+        this->configFiles_[type] = new ConfigFile(filename, type);
+        this->load(type);
+    }
+
+    void ConfigFileManager::load()
+    {
+        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
+            it->second->load();
+    }
+
+    void ConfigFileManager::save()
+    {
+        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
+            it->second->save();
+    }
+
+    void ConfigFileManager::clean(bool bCleanComments)
+    {
+        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
+            this->clean(it->first, bCleanComments);
+    }
+
+    void ConfigFileManager::load(ConfigFileType type)
+    {
+        this->getFile(type)->load();
+    }
+
+    void ConfigFileManager::save(ConfigFileType type)
+    {
+        this->getFile(type)->save();
+    }
+
+    void ConfigFileManager::saveAs(ConfigFileType type, const std::string& saveFilename)
+    {
+        this->getFile(type)->saveAs(saveFilename);
+    }
+
+    void ConfigFileManager::clean(ConfigFileType type, bool bCleanComments)
+    {
+        this->getFile(type)->clean(bCleanComments);
+    }
+
+    void ConfigFileManager::updateConfigValues()
+    {
+        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
+            it->second->updateConfigValues();
+    }
+
+    void ConfigFileManager::updateConfigValues(ConfigFileType type)
+    {
+        this->getFile(type)->updateConfigValues();
+    }
+
+    const std::string& ConfigFileManager::getFilename(ConfigFileType type)
+    {
+        std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.find(type);
+        if (it != this->configFiles_.end())
+            return it->second->getFilename();
+        else
+            return BLANKSTRING;
+    }
+
+    ConfigFile* ConfigFileManager::getFile(ConfigFileType type)
+    {
+        std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.find(type);
+        if (it != this->configFiles_.end())
+            return it->second;
+        else
+        {
+            COUT(1) << "ConfigFileManager: Can't find a config file for type with ID " << static_cast<int>(type) << std::endl;
+            COUT(1) << "Using " << DEFAULT_CONFIG_FILE << " file." << std::endl;
+            this->setFilename(type, DEFAULT_CONFIG_FILE);
+            return getFile(type);
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ConfigFileManager.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConfigFileManager.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConfigFileManager.h	(revision 5712)
@@ -0,0 +1,323 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ConfigFileManager_H__
+#define _ConfigFileManager_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <string>
+#include <list>
+#include <map>
+
+#include "util/OrxEnum.h"
+#include "util/Singleton.h"
+
+namespace orxonox
+{
+    // Use int as config file type to have an arbitrary number of files
+    struct ConfigFileType : OrxEnum<ConfigFileType>
+    {
+        OrxEnumConstructors(ConfigFileType);
+
+        static const int NoType              = 0;
+        static const int Settings            = 1;
+        static const int JoyStickCalibration = 2;
+
+        static const int numberOfReservedTypes = 1024;
+    };
+
+    bool config(const std::string& classname, const std::string& varname, const std::string& value);
+    bool tconfig(const std::string& classname, const std::string& varname, const std::string& value);
+    void reloadConfig();
+    void saveConfig();
+    void cleanConfig();
+    void loadSettings(const std::string& filename);
+
+
+    /////////////////////
+    // ConfigFileEntry //
+    /////////////////////
+    class _CoreExport ConfigFileEntry
+    {
+        public:
+            virtual ~ConfigFileEntry() {};
+            virtual void setValue(const std::string& value) = 0;
+            virtual std::string getValue() const = 0;
+            virtual const std::string& getName() const = 0;
+            virtual void setComment(const std::string& comment) = 0;
+            virtual unsigned int getIndex() const { return 0; }
+            virtual void setString(bool bString) = 0;
+            virtual std::string getFileEntry() const = 0;
+    };
+
+
+    //////////////////////////
+    // ConfigFileEntryValue //
+    //////////////////////////
+    class _CoreExport ConfigFileEntryValue : public ConfigFileEntry
+    {
+        public:
+            inline ConfigFileEntryValue(const std::string& name, const std::string& value = "", bool bString = false, const std::string& additionalComment = "") : name_(name), value_(value), bString_(bString), additionalComment_(additionalComment) {}
+            inline virtual ~ConfigFileEntryValue() {}
+
+            inline virtual const std::string& getName() const
+                { return this->name_; }
+
+            inline virtual void setComment(const std::string& comment)
+                { this->additionalComment_ = comment; }
+
+            virtual void setValue(const std::string& value);
+            virtual std::string getValue() const;
+
+            inline bool isString() const
+                { return this->bString_; }
+            inline void setString(bool bString)
+                { this->bString_ = bString; }
+
+            virtual std::string getFileEntry() const;
+
+        protected:
+            std::string name_;
+            std::string value_;
+            bool bString_;
+            std::string additionalComment_;
+    };
+
+
+    ///////////////////////////////
+    // ConfigFileEntryVectorValue //
+    ///////////////////////////////
+    class _CoreExport ConfigFileEntryVectorValue : public ConfigFileEntryValue
+    {
+        public:
+            inline ConfigFileEntryVectorValue(const std::string& name, unsigned int index, const std::string& value = "", bool bString = false, const std::string& additionalComment = "") : ConfigFileEntryValue(name, value, bString, additionalComment), index_(index) {}
+            inline virtual ~ConfigFileEntryVectorValue() {}
+
+            inline virtual unsigned int getIndex() const
+                { return this->index_; }
+
+            virtual std::string getFileEntry() const;
+
+        private:
+            unsigned int index_;
+    };
+
+
+    ////////////////////////////
+    // ConfigFileEntryComment //
+    ////////////////////////////
+    class _CoreExport ConfigFileEntryComment : public ConfigFileEntry
+    {
+        public:
+            inline ConfigFileEntryComment(const std::string& comment) : comment_(comment) {}
+            inline virtual ~ConfigFileEntryComment() {}
+
+            inline virtual const std::string& getName() const
+                { return this->comment_; }
+
+            inline virtual void setComment(const std::string& comment)
+                { this->comment_ = comment; }
+
+            inline virtual void setValue(const std::string& value)
+                {}
+            inline virtual std::string getValue() const
+                { return this->comment_; }
+
+            inline void setString(bool bString) {}
+
+            inline virtual std::string getFileEntry() const
+                { return this->comment_; }
+
+        private:
+            std::string comment_;
+    };
+
+
+    ///////////////////////
+    // ConfigFileSection //
+    ///////////////////////
+    class _CoreExport ConfigFileSection
+    {
+        friend class ConfigFile;
+
+        public:
+            inline ConfigFileSection(const std::string& name, const std::string& additionalComment = "") : name_(name), additionalComment_(additionalComment), bUpdated_(false) {}
+            ~ConfigFileSection();
+
+            inline const std::string& getName() const
+                { return this->name_; }
+
+            inline void setComment(const std::string& comment)
+                { this->additionalComment_ = comment; }
+
+            inline void setValue(const std::string& name, const std::string& value, bool bString)
+                { this->getEntry(name, value, bString)->setValue(value); }
+            inline std::string getValue(const std::string& name, const std::string& fallback, bool bString)
+                { return this->getEntry(name, fallback, bString)->getValue(); }
+
+            inline void setValue(const std::string& name, unsigned int index, const std::string& value, bool bString)
+                { this->getEntry(name, index, value, bString)->setValue(value); }
+            inline std::string getValue(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
+                { return this->getEntry(name, index, fallback, bString)->getValue(); }
+
+            void deleteVectorEntries(const std::string& name, unsigned int startindex = 0);
+            unsigned int getVectorSize(const std::string& name);
+
+            std::string getFileEntry() const;
+
+        private:
+            std::list<ConfigFileEntry*>& getEntries()
+                { return this->entries_; }
+            std::list<ConfigFileEntry*>::const_iterator getEntriesBegin() const
+                { return this->entries_.begin(); }
+            std::list<ConfigFileEntry*>::const_iterator getEntriesEnd() const
+                { return this->entries_.end(); }
+
+            std::list<ConfigFileEntry*>::iterator getEntryIterator(const std::string& name, const std::string& fallback, bool bString);
+            std::list<ConfigFileEntry*>::iterator getEntryIterator(const std::string& name, unsigned int index, const std::string& fallback, bool bString);
+
+            inline ConfigFileEntry* getEntry(const std::string& name, const std::string& fallback, bool bString)
+                { return (*this->getEntryIterator(name, fallback, bString)); }
+            inline ConfigFileEntry* getEntry(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
+                { return (*this->getEntryIterator(name, index, fallback, bString)); }
+
+            std::string name_;
+            std::string additionalComment_;
+            std::list<ConfigFileEntry*> entries_;
+            bool bUpdated_;
+    };
+
+
+    ////////////////
+    // ConfigFile //
+    ////////////////
+    class _CoreExport ConfigFile
+    {
+        public:
+            inline ConfigFile(const std::string& filename, ConfigFileType type)
+                : filename_(filename)
+                , type_(type)
+                , bUpdated_(false)
+            { }
+            ~ConfigFile();
+
+            void load(bool bCreateIfNotExisting = true);
+            void save() const;
+            void saveAs(const std::string& filename);
+            void clean(bool bCleanComments = false);
+            void clear();
+
+            const std::string& getFilename() { return this->filename_; }
+
+            inline void setValue(const std::string& section, const std::string& name, const std::string& value, bool bString)
+                { this->getSection(section)->setValue(name, value, bString); this->save(); }
+            inline std::string getValue(const std::string& section, const std::string& name, const std::string& fallback, bool bString)
+                { std::string output = this->getSection(section)->getValue(name, fallback, bString); this->saveIfUpdated(); return output; }
+
+            inline void setValue(const std::string& section, const std::string& name, unsigned int index, const std::string& value, bool bString)
+                { this->getSection(section)->setValue(name, index, value, bString); this->save(); }
+            inline std::string getValue(const std::string& section, const std::string& name, unsigned int index, const std::string& fallback, bool bString)
+                { std::string output = this->getSection(section)->getValue(name, index, fallback, bString); this->saveIfUpdated(); return output; }
+
+            inline void deleteVectorEntries(const std::string& section, const std::string& name, unsigned int startindex = 0)
+                { this->getSection(section)->deleteVectorEntries(name, startindex); }
+            inline unsigned int getVectorSize(const std::string& section, const std::string& name)
+                { return this->getSection(section)->getVectorSize(name); }
+
+            void updateConfigValues();
+
+        private:
+            ConfigFileSection* getSection(const std::string& section);
+            void saveIfUpdated();
+
+            std::string filename_;
+            ConfigFileType type_;
+            std::list<ConfigFileSection*> sections_;
+            bool bUpdated_;
+    };
+
+
+    ///////////////////////
+    // ConfigFileManager //
+    ///////////////////////
+    class _CoreExport ConfigFileManager : public Singleton<ConfigFileManager>
+    {
+        friend class Singleton<ConfigFileManager>;
+        public:
+            ConfigFileManager();
+            ~ConfigFileManager();
+
+            void load();
+            void save();
+            void clean(bool bCleanComments = false);
+
+            void setFilename(ConfigFileType type, const std::string& filename);
+            const std::string& getFilename(ConfigFileType type);
+
+            ConfigFileType getNewConfigFileType() { return mininmalFreeType_++; }
+
+            void load(ConfigFileType type);
+            void save(ConfigFileType type);
+            void saveAs(ConfigFileType type, const std::string& saveFilename);
+            void clean(ConfigFileType type, bool bCleanComments = false);
+
+            inline void setValue(ConfigFileType type, const std::string& section, const std::string& name, const std::string& value, bool bString)
+                { this->getFile(type)->setValue(section, name, value, bString); }
+            inline std::string getValue(ConfigFileType type, const std::string& section, const std::string& name, const std::string& fallback, bool bString)
+                { return this->getFile(type)->getValue(section, name, fallback, bString); }
+
+            inline void setValue(ConfigFileType type, const std::string& section, const std::string& name, unsigned int index, const std::string& value, bool bString)
+                { this->getFile(type)->setValue(section, name, index, value, bString); }
+            inline std::string getValue(ConfigFileType type, const std::string& section, const std::string& name, unsigned int index, const std::string& fallback, bool bString)
+                { return this->getFile(type)->getValue(section, name, index, fallback, bString); }
+
+            inline void deleteVectorEntries(ConfigFileType type, const std::string& section, const std::string& name, unsigned int startindex = 0)
+                { this->getFile(type)->deleteVectorEntries(section, name, startindex); }
+            inline unsigned int getVectorSize(ConfigFileType type, const std::string& section, const std::string& name)
+                { return this->getFile(type)->getVectorSize(section, name); }
+
+            void updateConfigValues();
+            void updateConfigValues(ConfigFileType type);
+
+            static std::string DEFAULT_CONFIG_FILE;
+
+        private:
+            ConfigFileManager(const ConfigFileManager&);
+
+            ConfigFile* getFile(ConfigFileType type);
+
+            std::map<ConfigFileType, ConfigFile*> configFiles_;
+            unsigned int mininmalFreeType_;
+
+            static ConfigFileManager* singletonPtr_s;
+    };
+}
+
+#endif /* _ConfigFileManager_H__ */
Index: /code/branches/libraries2/src/libraries/core/ConfigValueContainer.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConfigValueContainer.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConfigValueContainer.cc	(revision 5712)
@@ -0,0 +1,344 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the ConfigValueContainer class.
+*/
+
+#include "ConfigValueContainer.h"
+
+#include "util/Convert.h"
+#include "util/SubString.h"
+#include "Language.h"
+
+namespace orxonox
+{
+    const unsigned int MAX_VECTOR_INDEX  = 255; // to avoid up to 4*10^9 vector entries in the config file after accidentally using a wrong argument
+
+    /**
+        @brief Initializes the ConfigValueContainer with defaultvalues.
+    */
+    void ConfigValueContainer::init(ConfigFileType type, Identifier* identifier, const std::string& sectionname, const std::string& varname)
+    {
+        this->type_ = type;
+        this->identifier_ = identifier;
+        this->sectionname_ = sectionname;
+        this->varname_ = varname;
+        this->callback_ = 0;
+        this->bContainerIsNew_ = true;
+        this->bDoInitialCallback_ = false;
+        this->bAddedDescription_ = false;
+    }
+
+    /**
+        @brief Does some special initialization for single config-values.
+    */
+    void ConfigValueContainer::initValue(const MultiType& defvalue)
+    {
+        this->value_ = defvalue;
+        this->bIsVector_ = false;
+
+        this->defvalueString_ = this->value_.getString();
+        this->update();
+    }
+
+    /**
+        @brief Does some special initialization for vector config-values.
+    */
+    void ConfigValueContainer::initVector()
+    {
+        this->bIsVector_ = true;
+
+        for (unsigned int i = 0; i < this->valueVector_.size(); i++)
+        {
+            ConfigFileManager::getInstance().getValue(this->type_, this->sectionname_, this->varname_, i, this->valueVector_[i], this->value_.isType(MT_Type::String));
+            this->defvalueStringVector_.push_back(this->valueVector_[i]);
+        }
+
+        this->update();
+    }
+
+    /**
+        @brief Destructor: Deletes the callback object if necessary.
+    */
+    ConfigValueContainer::~ConfigValueContainer()
+    {
+        if (this->callback_)
+            delete this->callback_;
+    }
+
+    /**
+        @brief Assigns a new value to the config-value of all objects and writes the change into the config-file.
+        @param input The new value
+        @return True if the new value was successfully assigned
+    */
+    bool ConfigValueContainer::set(const MultiType& input)
+    {
+        if (this->bIsVector_)
+        {
+            return this->callFunctionWithIndex(&ConfigValueContainer::set, input);
+        }
+        else
+        {
+            if (this->tset(input))
+            {
+                ConfigFileManager::getInstance().setValue(this->type_, this->sectionname_, this->varname_, input, this->value_.isType(MT_Type::String));
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+        @brief Assigns a new value to the config-value of all objects and writes the change into the config-file.
+        @param index The index in the vector
+        @param input The new value
+        @return True if the new value was successfully assigned
+    */
+    bool ConfigValueContainer::set(unsigned int index, const MultiType& input)
+    {
+        if (this->bIsVector_)
+        {
+            if (this->tset(index, input))
+            {
+                ConfigFileManager::getInstance().setValue(this->type_, this->sectionname_, this->varname_, index, input, this->value_.isType(MT_Type::String));
+                return true;
+            }
+        }
+        else
+        {
+            COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
+        }
+        return false;
+    }
+
+    /**
+        @brief Assigns a new value to the config-value of all objects, but doesn't change the config-file (t stands for temporary).
+        @param input The new value. If bIsVector_ then write "index value"
+        @return True if the new value was successfully assigned
+    */
+    bool ConfigValueContainer::tset(const MultiType& input)
+    {
+        if (this->bIsVector_)
+        {
+            return this->callFunctionWithIndex(&ConfigValueContainer::tset, input);
+            return false;
+        }
+        else
+        {
+            this->value_ = input;
+
+            if (this->identifier_)
+                this->identifier_->updateConfigValues();
+
+            return true;
+        }
+    }
+
+    /**
+        @brief Assigns a new value to the config-value of all objects, but doesn't change the config-file (t stands for temporary).
+        @param index The index in the vector
+        @param input The new value
+        @return True if the new value was successfully assigned
+    */
+    bool ConfigValueContainer::tset(unsigned int index, const MultiType& input)
+    {
+        if (this->bIsVector_)
+        {
+            if (index > MAX_VECTOR_INDEX)
+            {
+                COUT(1) << "Error: Index " << index << " is too large." << std::endl;
+                return false;
+            }
+
+            if (index >= this->valueVector_.size())
+            {
+                for (unsigned int i = this->valueVector_.size(); i <= index; i++)
+                {
+                    this->valueVector_.push_back(MultiType());
+                }
+            }
+
+            this->valueVector_[index] = input;
+
+            if (this->identifier_)
+                this->identifier_->updateConfigValues();
+
+            return true;
+        }
+        else
+        {
+            COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
+            return false;
+        }
+    }
+
+    /**
+        @brief Adds a new entry to the end of the vector.
+        @param input The new entry
+        @return True if the new entry was successfully added
+    */
+    bool ConfigValueContainer::add(const MultiType& input)
+    {
+        if (this->bIsVector_)
+            return this->set(this->valueVector_.size(), input);
+
+        COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
+        return false;
+    }
+
+    /**
+        @brief Removes an existing entry from the vector.
+        @param index The index of the entry
+        @return True if the entry was removed
+    */
+    bool ConfigValueContainer::remove(unsigned int index)
+    {
+        if (this->bIsVector_)
+        {
+            if (index < this->valueVector_.size())
+            {
+                // Erase the entry from the vector, change (shift) all entries beginning with index in the config file, remove the last entry from the file
+                this->valueVector_.erase(this->valueVector_.begin() + index);
+                for (unsigned int i = index; i < this->valueVector_.size(); i++)
+                    ConfigFileManager::getInstance().setValue(this->type_, this->sectionname_, this->varname_, i, this->valueVector_[i], this->value_.isType(MT_Type::String));
+                ConfigFileManager::getInstance().deleteVectorEntries(this->type_, this->sectionname_, this->varname_, this->valueVector_.size());
+
+                return true;
+            }
+            COUT(1) << "Error: Invalid vector-index." << std::endl;
+        }
+
+        COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
+        return false;
+    }
+
+    /**
+        @brief Sets the value of the variable back to the default value and resets the config-file entry.
+    */
+    bool ConfigValueContainer::reset()
+    {
+        if (!this->bIsVector_)
+            return this->set(this->defvalueString_);
+        else
+        {
+            bool success = true;
+            for (unsigned int i = 0; i < this->defvalueStringVector_.size(); i++)
+                if (!this->set(i, this->defvalueStringVector_[i]))
+                    success = false;
+            ConfigFileManager::getInstance().deleteVectorEntries(this->type_, this->sectionname_, this->varname_, this->defvalueStringVector_.size());
+            return success;
+        }
+    }
+
+    /**
+        @brief Retrieves the configured value from the currently loaded config-file.
+    */
+    void ConfigValueContainer::update()
+    {
+        if (!this->bIsVector_)
+            this->value_ = ConfigFileManager::getInstance().getValue(this->type_, this->sectionname_, this->varname_, this->defvalueString_, this->value_.isType(MT_Type::String));
+        else
+        {
+            this->valueVector_.clear();
+            unsigned int vectorSize = ConfigFileManager::getInstance().getVectorSize(this->type_, this->sectionname_, this->varname_);
+            for (unsigned int i = 0; i < vectorSize; i++)
+            {
+                if (i < this->defvalueStringVector_.size())
+                {
+                    this->value_ = ConfigFileManager::getInstance().getValue(this->type_, this->sectionname_, this->varname_, i, this->defvalueStringVector_[i], this->value_.isType(MT_Type::String));
+                }
+                else
+                {
+                    this->value_ = ConfigFileManager::getInstance().getValue(this->type_, this->sectionname_, this->varname_, i, MultiType(), this->value_.isType(MT_Type::String));
+                }
+
+                this->valueVector_.push_back(this->value_);
+            }
+        }
+    }
+
+    /**
+        @brief Calls the given function with parsed index and the parsed argument from the input string.
+        @param function The function to call
+        @param input The input string
+        @return The returnvalue of the functioncall
+    */
+    bool ConfigValueContainer::callFunctionWithIndex(bool (ConfigValueContainer::* function) (unsigned int, const MultiType&), const std::string& input)
+    {
+        SubString token(input, " ", SubString::WhiteSpaces, true, '\\', false, '"', false, '(', ')', false, '\0');
+        int index = -1;
+        bool success = false;
+
+        if (token.size() > 0)
+            success = convertValue(&index, token[0]);
+
+        if (!success || index < 0 || index > (signed int)MAX_VECTOR_INDEX)
+        {
+            if (!success)
+            {
+                COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is a vector." << std::endl;
+            }
+            else
+            {
+                COUT(1) << "Error: Invalid vector-index." << std::endl;
+            }
+            return false;
+        }
+
+        if (token.size() >= 2)
+            return (this->*function)(index, token.subSet(1).join());
+        else
+            return (this->*function)(index, "");
+    }
+
+    /**
+        @brief Adds a description to the config-value.
+        @param description The description
+    */
+    ConfigValueContainer& ConfigValueContainer::description(const std::string& description)
+    {
+        if (!this->bAddedDescription_)
+        {
+            this->description_ = std::string("ConfigValueDescription::" + this->sectionname_ + "::" + this->varname_);
+            AddLanguageEntry(this->description_, description);
+            this->bAddedDescription_ = true;
+        }
+        return (*this);
+    }
+
+    /**
+        @brief Returns the description of the config-value.
+        @return The description
+    */
+    const std::string& ConfigValueContainer::getDescription() const
+    {
+        return GetLocalisation(this->description_);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ConfigValueContainer.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConfigValueContainer.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConfigValueContainer.h	(revision 5712)
@@ -0,0 +1,301 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the ConfigValueContainer class.
+
+    The ConfigValueContainer class contains all needed information about a configurable variable:
+     - the name of the variable
+     - the name of the class the variable belongs to
+     - the default value
+     - the user-specified value
+     - a pointer to the entry in the config-file
+
+    This is needed to assign the configured values to all newly created objects.
+*/
+
+#ifndef _ConfigValueContainer_H__
+#define _ConfigValueContainer_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include <vector>
+
+#include "util/MultiType.h"
+#include "ConfigFileManager.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    class ConfigValueCallbackBase
+    {
+        public:
+            virtual void call(void* object) = 0;
+            inline virtual ~ConfigValueCallbackBase() {}
+    };
+
+    template <class T>
+    class ConfigValueCallback: public ConfigValueCallbackBase
+    {
+        public:
+            inline ConfigValueCallback(void (T::*function) (void)) : function_(function) {}
+            inline virtual ~ConfigValueCallback() {}
+            inline virtual void call(void* object)
+            {
+                if (!Identifier::isCreatingHierarchy())
+                    (static_cast<T*>(object)->*this->function_)();
+            }
+
+        private:
+            void (T::*function_) (void);
+    };
+
+
+    //! The ConfigValuecontainer contains all needed information about a configurable variable.
+    /**
+        The ConfigValueContainer class contains all needed information about a configurable variable:
+         - the name of the variable
+         - the name of the class the variable belongs to
+         - the default value
+         - the user-specified value
+         - a pointer to the entry in the config-file
+
+        This is needed to assign the configured values to all newly created objects.
+
+        The container searches for the entry in the config file.
+        If there is an entry, it parses the specified value and assigns it to the variable of the right type.
+        If there is no entry, it adds the entry with the default-value to the section of the variables class.
+        If there is no section, the section and the entry are added to the end of the config-file.
+    */
+    class _CoreExport ConfigValueContainer
+    {
+        public:
+            /**
+                @brief Constructor: Converts the default-value to a string, checks the config-file for a changed value, sets the intern value variable.
+                @param type The type of the corresponding config-file
+                @param identifier The identifier of the class the variable belongs to
+                @param sectionname Name of the section the configValue should be put in.
+                @param varname The name of the variable
+                @param defvalue The default-value
+                @param value Only needed do determine the right type.
+            */
+            template <class D, class V>
+            ConfigValueContainer(ConfigFileType type, Identifier* identifier, const std::string& sectionname, const std::string& varname, const D& defvalue, const V& value)
+            {
+                this->init(type, identifier, sectionname, varname);
+                this->initValue(static_cast<V>(defvalue));
+            }
+
+            /**
+                @brief Constructor: Converts the default-value to a string, checks the config-file for a changed value, sets the intern value variable.
+                @param type The type of the corresponding config-file
+                @param identifier The identifier of the class the variable belongs to
+                @param varname The name of the variable
+                @param defvalue The default-value
+            */
+            template <class V>
+            ConfigValueContainer(ConfigFileType type, Identifier* identifier, const std::string& sectionname, const std::string& varname, const std::vector<V>& defvalue)
+            {
+                this->init(type, identifier, sectionname, varname);
+
+                this->value_ = V();
+                for (unsigned int i = 0; i < defvalue.size(); i++)
+                    this->valueVector_.push_back(MultiType(defvalue[i]));
+
+                this->initVector();
+            }
+
+            ~ConfigValueContainer();
+
+            /**
+                @brief Returns the configured value.
+                @param value A pointer to the variable to store the value.
+                @param object The object calling this function
+                @return The ConfigValueContainer
+            */
+            template <typename T, class C>
+            ConfigValueContainer& getValue(T* value, C* object)
+            {
+                if ((this->callback_ && object) || this->bContainerIsNew_)
+                {
+                    if (this->bContainerIsNew_)
+                        this->bContainerIsNew_ = false;
+
+                    T temp = *value;
+                    this->value_.getValue(value);
+                    if ((*value) != temp)
+                    {
+                        if (this->callback_ && object)
+                            this->callback_->call(object);
+                        else
+                            this->bDoInitialCallback_ = true;
+                    }
+                }
+                else
+                {
+                    this->value_.getValue(value);
+                }
+                return *this;
+            }
+
+            /**
+                @brief Returns the configured vector.
+                @param value A pointer to the vector to store the values.
+                @param object The object calling this function
+                @return The ConfigValueContainer
+            */
+            template <typename T, class C>
+            ConfigValueContainer& getValue(std::vector<T>* value, C* object)
+            {
+                if ((this->callback_ && object) || this->bContainerIsNew_)
+                {
+                    if (this->bContainerIsNew_)
+                        this->bContainerIsNew_ = false;
+
+                    std::vector<T> temp = *value;
+                    value->clear();
+                    for (unsigned int i = 0; i < this->valueVector_.size(); ++i)
+                        value->push_back(this->valueVector_[i]);
+
+                    if (value->size() != temp.size())
+                    {
+                        if (this->callback_ && object)
+                            this->callback_->call(object);
+                        else
+                            this->bDoInitialCallback_ = true;
+                    }
+                    else
+                    {
+                        for (unsigned int i = 0; i < value->size(); ++i)
+                        {
+                            if ((*value)[i] != temp[i])
+                            {
+                                if (this->callback_ && object)
+                                    this->callback_->call(object);
+                                else
+                                    this->bDoInitialCallback_ = true;
+                                break;
+                            }
+                        }
+                    }
+                }
+                else
+                {
+                    value->clear();
+                    for (unsigned int i = 0; i < this->valueVector_.size(); ++i)
+                        value->push_back(this->valueVector_[i]);
+                }
+                return *this;
+            }
+
+            /** @brief Returns the name of this container. */
+            inline const std::string& getName() const
+                { return this->varname_; }
+            /** @brief Retuns the name of the section this config value is in. */
+            inline const std::string& getSectionName() const
+                { return this->sectionname_; }
+            /** @brief Returns true if this config-value is a vector */
+            inline bool isVector() const
+                { return this->bIsVector_; }
+            /** @brief Returns the vectors size (or zero if it's not a vector). */
+            inline unsigned int getVectorSize() const
+                { return this->valueVector_.size(); }
+
+            ConfigValueContainer& description(const std::string& description);
+            const std::string& getDescription() const;
+
+            /**
+                @brief Adds a callback function, that gets called after getValue() if the newly assigned value differs from the old value of the variable.
+                @param object The object to call the function
+                @param function The callback function
+            */
+            template <class T>
+            inline ConfigValueContainer& callback(T* object, void (T::*function) (void))
+            {
+                if (!this->callback_)
+                {
+                    this->callback_ = new ConfigValueCallback<T>(function);
+
+                    if (this->bDoInitialCallback_)
+                    {
+                        this->bDoInitialCallback_ = false;
+                        this->callback_->call(object);
+                    }
+                }
+
+                return (*this);
+            }
+
+            bool set(const MultiType& input);
+            bool tset(const MultiType& input);
+
+            bool set(unsigned int index, const MultiType& input);
+            bool tset(unsigned int index, const MultiType& input);
+            bool add(const MultiType& input);
+            bool remove(unsigned int index);
+
+            bool reset();
+            void update();
+
+            /** @brief Converts the config-value to a string. @return The string */
+            inline std::string toString() const
+                { return this->value_; }
+            /** @brief Returns the typename of the assigned config-value. @return The typename */
+            inline std::string getTypename() const
+                { return this->value_.getTypename(); }
+
+        private:
+            void init(ConfigFileType type, Identifier* identifier, const std::string& sectionname, const std::string& varname);
+            void initValue(const MultiType& defvalue);
+            void initVector();
+            bool callFunctionWithIndex(bool (ConfigValueContainer::* function) (unsigned int, const MultiType&), const std::string& input);
+
+            bool                       bIsVector_;                  //!< True if the container contains a std::vector
+
+            ConfigFileType             type_;                       //!< The type of the corresponding config-file
+            Identifier*                identifier_;                 //!< The identifier of the class
+            std::string                sectionname_;                //!< The name of the class the variable belongs to
+            std::string                varname_;                    //!< The name of the variable
+            std::string                defvalueString_;             //!< The string of the default-value
+            std::vector<std::string>   defvalueStringVector_;       //!< A vector, containg the strings of the default-values in case we're storing a vector
+
+            MultiType                  value_;                      //!< The value
+            std::vector<MultiType>     valueVector_;                //!< A vector, containg the values in case we're storing a vector
+
+            bool                       bAddedDescription_;          //!< True if a description was added
+            LanguageEntryLabel         description_;                //!< The description
+            ConfigValueCallbackBase*   callback_;                   //!< A callback function to call after getValue if the value changed
+
+            bool                       bContainerIsNew_;            //!< True if it's the first time getValue() gets called
+            bool                       bDoInitialCallback_;         //!< True if the callback should be called as soon as it gets created
+    };
+}
+
+#endif /* _ConfigValueContainer_H__ */
Index: /code/branches/libraries2/src/libraries/core/ConfigValueIncludes.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConfigValueIncludes.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConfigValueIncludes.h	(revision 5712)
@@ -0,0 +1,114 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of macros for config-values.
+*/
+
+#ifndef _ConfigValueIncludes_H__
+#define _ConfigValueIncludes_H__
+
+#include "CorePrereqs.h"
+
+#include "Identifier.h"
+#include "ConfigValueContainer.h"
+#include "ConfigFileManager.h"
+
+
+/**
+    @brief Assigns the value, defined in the config-file, to the variable (or the default-value, if there is no entry in the file).
+    @param varname The name of the variable
+    @param defvalue The default-value of the variable
+*/
+#define SetConfigValueGeneric(type, varname, defvalue) \
+    static orxonox::Identifier* identifier##varname = this->getIdentifier(); \
+    orxonox::ConfigValueContainer* container##varname = identifier##varname->getConfigValueContainer(#varname); \
+    if (!container##varname) \
+    { \
+        container##varname = new orxonox::ConfigValueContainer(type, identifier##varname, identifier##varname->getName(), #varname, defvalue, varname); \
+        identifier##varname->addConfigValueContainer(#varname, container##varname); \
+    } \
+    container##varname->getValue(&varname, this)
+
+#define SetConfigValue(varname, defvalue) SetConfigValueGeneric(ConfigFileType::Settings, varname, defvalue)
+
+
+/**
+    @brief Assigns the vector-values, defined in the config-file, to the vector (or the default-value, if there are no entries in the file).
+    @param varname The name of the std::vector
+    @param defvalue The default-value
+*/
+#define SetConfigValueVectorGeneric(type, varname, defvalue) \
+    static orxonox::Identifier* identifier##varname = this->getIdentifier(); \
+    orxonox::ConfigValueContainer* container##varname = identifier##varname->getConfigValueContainer(#varname); \
+    if (!container##varname) \
+    { \
+        container##varname = new orxonox::ConfigValueContainer(type, identifier##varname, identifier##varname->getName(), #varname, defvalue); \
+        identifier##varname->addConfigValueContainer(#varname, container##varname); \
+    } \
+    container##varname->getValue(&varname, this)
+
+#define SetConfigValueVector(varname, defvalue) SetConfigValueVectorGeneric(ConfigFileType::Settings, varname, defvalue)
+
+
+/**
+    @brief Sets the variable and the config-file entry back to the previously defined default-value.
+    @param varname The name of the variable
+*/
+#define ResetConfigValue(varname) \
+    orxonox::ConfigValueContainer* container##varname##reset = this->getIdentifier()->getConfigValueContainer(#varname); \
+    if (container##varname##reset) \
+    { \
+        container##varname##reset->reset(); \
+        container##varname##reset->getValue(&varname, this); \
+    } \
+    else \
+    { \
+        COUT(2) << "Warning: Couldn't reset config-value '" << #varname << "', corresponding container doesn't exist." << std::endl; \
+    }
+
+
+/**
+    @brief Modifies a config-value by using a modifier and some arguments.
+    @param varname The name of the config-value
+    @param modifier The name of the modifier: set, tset, add, remove, reset, update
+*/
+#define ModifyConfigValue(varname, modifier, ...) \
+    orxonox::ConfigValueContainer* container##varname##modify##modifier = this->getIdentifier()->getConfigValueContainer(#varname); \
+    if (container##varname##modify##modifier) \
+    { \
+        container##varname##modify##modifier->modifier(__VA_ARGS__); \
+        container##varname##modify##modifier->getValue(&varname, this); \
+    } \
+    else \
+    { \
+        COUT(2) << "Warning: Couln't modify config-value '" << #varname << "', corresponding container doesn't exist." << std::endl; \
+    }
+
+#endif /* _ConfigValueIncludes_H__ */
Index: /code/branches/libraries2/src/libraries/core/ConsoleCommand.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConsoleCommand.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConsoleCommand.cc	(revision 5712)
@@ -0,0 +1,72 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "ConsoleCommand.h"
+
+namespace orxonox
+{
+    ConsoleCommand::ConsoleCommand(Functor* functor, const std::string& name) : Executor(functor, name)
+    {
+        this->accessLevel_ = AccessLevel::None;
+        this->argumentCompleter_[0] = 0;
+        this->argumentCompleter_[1] = 0;
+        this->argumentCompleter_[2] = 0;
+        this->argumentCompleter_[3] = 0;
+        this->argumentCompleter_[4] = 0;
+
+        this->keybindMode_ = KeybindMode::OnPress;
+        this->inputConfiguredParam_ = -1;
+    }
+
+    ConsoleCommand& ConsoleCommand::argumentCompleter(unsigned int param, ArgumentCompleter* completer)
+    {
+        if (param < 5)
+            this->argumentCompleter_[param] = completer;
+        else
+        {
+            COUT(2) << "Warning: Couldn't add autocompletion-function for param " << param << ": index out of bound." << std::endl;
+        }
+        return (*this);
+    }
+
+    ArgumentCompleter* ConsoleCommand::getArgumentCompleter(unsigned int param) const
+    {
+        if (param < 5)
+            return this->argumentCompleter_[param];
+        else
+            return 0;
+    }
+
+    void ConsoleCommand::createArgumentCompletionList(unsigned int param, const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4, const std::string& param5)
+    {
+        if (param < 5 && this->argumentCompleter_[param])
+            this->argumentList_ = (*this->argumentCompleter_[param])(param1, param2, param3, param4, param5);
+        else
+            this->argumentList_.clear();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ConsoleCommand.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConsoleCommand.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConsoleCommand.h	(revision 5712)
@@ -0,0 +1,157 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ConsoleCommand_H__
+#define _ConsoleCommand_H__
+
+#include "CorePrereqs.h"
+
+#include <boost/preprocessor/cat.hpp>
+
+#include "ArgumentCompletionFunctions.h"
+#include "CommandExecutor.h"
+#include "Executor.h"
+#include "Identifier.h"
+
+
+#define SetConsoleCommand(classname, function, bCreateShortcut) \
+    SetConsoleCommandGeneric(classname, function, #function, bCreateShortcut)
+#define SetConsoleCommandAlias(classname, function, name, bCreateShortcut) \
+    SetConsoleCommandGeneric(classname, function, name, bCreateShortcut)
+
+#define SetConsoleCommandGeneric(classname, function, name, bCreateShortcut) \
+    orxonox::ConsoleCommand& BOOST_PP_CAT(classname##function##consolecommand__, __LINE__) = orxonox::ClassIdentifier<classname>::getIdentifier(#classname)->addConsoleCommand(orxonox::createConsoleCommand(orxonox::createFunctor(&classname::function), name), bCreateShortcut)
+
+
+#define SetConsoleCommandShortcut(classname, function) \
+    SetConsoleCommandShortcutAliasGeneric(classname, function, #function)
+#define SetConsoleCommandShortcutAlias(classname, function, name) \
+    SetConsoleCommandShortcutAliasGeneric(classname, function, name)
+#define SetConsoleCommandShortcutAliasGeneric(classname, function, name) \
+    SetConsoleCommandShortcutGeneric(BOOST_PP_CAT(function##consolecommand__, __LINE__), orxonox::createConsoleCommand(orxonox::createFunctor(&classname::function), name))
+
+#define SetConsoleCommandShortcutExtern(function) \
+    SetConsoleCommandShortcutExternAliasGeneric(function, #function)
+#define SetConsoleCommandShortcutExternAlias(function, name) \
+    SetConsoleCommandShortcutExternAliasGeneric(function, name)
+#define SetConsoleCommandShortcutExternAliasGeneric(function, name) \
+    SetConsoleCommandShortcutGeneric(BOOST_PP_CAT(function##consolecommand__, __LINE__), orxonox::createConsoleCommand(orxonox::createFunctor(&function), name))
+
+#define SetConsoleCommandShortcutGeneric(fakevariable, command) \
+    orxonox::ConsoleCommand& fakevariable = orxonox::CommandExecutor::addConsoleCommandShortcut(command, true)
+
+
+namespace orxonox
+{
+    namespace AccessLevel
+    {
+        enum Value
+        {
+            None,
+            User,
+            Admin,
+            Offline,
+            Debug,
+            Disabled
+        };
+    }
+
+    class _CoreExport ConsoleCommand : public Executor
+    {
+        public:
+            ConsoleCommand(Functor* functor, const std::string& name = "");
+
+            inline ConsoleCommand& description(const std::string& description)
+                { this->Executor::setDescription(description); return (*this); }
+            inline ConsoleCommand& descriptionParam(int param, const std::string& description)
+                { this->Executor::setDescriptionParam(param, description); return (*this); }
+            inline ConsoleCommand& descriptionReturnvalue(const std::string& description)
+                { this->Executor::setDescriptionReturnvalue(description); return (*this); }
+            inline ConsoleCommand& defaultValues(const MultiType& param1)
+                { this->Executor::setDefaultValues(param1); return (*this); }
+            inline ConsoleCommand& defaultValues(const MultiType& param1, const MultiType& param2)
+                { this->Executor::setDefaultValues(param1, param2); return (*this); }
+            inline ConsoleCommand& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3)
+                { this->Executor::setDefaultValues(param1, param2, param3); return (*this); }
+            inline ConsoleCommand& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4)
+                { this->Executor::setDefaultValues(param1, param2, param3, param4); return (*this); }
+            inline ConsoleCommand& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5)
+                { this->Executor::setDefaultValues(param1, param2, param3, param4, param5); return (*this); }
+            inline ConsoleCommand& defaultValue(unsigned int index, const MultiType& param)
+                { this->Executor::setDefaultValue(index, param); return (*this); }
+
+            inline ConsoleCommand& accessLevel(AccessLevel::Value level)
+                { this->accessLevel_ = level; return (*this); }
+            inline AccessLevel::Value getAccessLevel() const
+                { return this->accessLevel_; }
+
+            ConsoleCommand& argumentCompleter(unsigned int param, ArgumentCompleter* completer);
+            ArgumentCompleter* getArgumentCompleter(unsigned int param) const;
+
+            void createArgumentCompletionList(unsigned int param, const std::string& param1 = "", const std::string& param2 = "", const std::string& param3 = "", const std::string& param4 = "", const std::string& param5 = "");
+            const ArgumentCompletionList& getArgumentCompletionList() const
+                { return this->argumentList_; }
+            ArgumentCompletionList::const_iterator getArgumentCompletionListBegin() const
+                { return this->argumentList_.begin(); }
+            ArgumentCompletionList::const_iterator getArgumentCompletionListEnd() const
+                { return this->argumentList_.end(); }
+
+            inline ConsoleCommand& setAsInputCommand()
+            {
+                this->keybindMode(KeybindMode::OnHold);
+                this->defaultValue(0, Vector2(0.0f, 0.0f));
+                this->inputConfiguredParam(0);
+                return *this;
+            }
+
+            inline ConsoleCommand& keybindMode(KeybindMode::Value mode)
+                { this->keybindMode_ = mode; return *this; }
+            inline KeybindMode::Value getKeybindMode() const
+                { return this->keybindMode_; }
+
+            inline ConsoleCommand& inputConfiguredParam(int index)
+                { this->inputConfiguredParam_ = index; return *this; }
+            inline int getInputConfiguredParam_() const
+                { return this->inputConfiguredParam_; }
+
+        private:
+            AccessLevel::Value accessLevel_;
+            ArgumentCompleter* argumentCompleter_[5];
+            ArgumentCompletionList argumentList_;
+
+            KeybindMode::Value keybindMode_;
+            int inputConfiguredParam_;
+    };
+
+    inline ConsoleCommand* createConsoleCommand(Functor* functor, const std::string& name = "")
+    {
+        return new ConsoleCommand(functor, name);
+    }
+}
+
+#endif /* _ConsoleCommand_H__ */
Index: /code/branches/libraries2/src/libraries/core/ConsoleCommandCompilation.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConsoleCommandCompilation.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConsoleCommandCompilation.cc	(revision 5712)
@@ -0,0 +1,180 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "ConsoleCommandCompilation.h"
+
+#include <fstream>
+#include <set>
+#include <string>
+
+#include "util/Debug.h"
+#include "util/ExprParser.h"
+#include "ConsoleCommand.h"
+
+namespace orxonox
+{
+    SetConsoleCommandShortcutExtern(source).argumentCompleter(0, autocompletion::files());
+    SetConsoleCommandShortcutExtern(echo);
+    SetConsoleCommandShortcutExtern(puts);
+
+    SetConsoleCommandShortcutExtern(read).argumentCompleter(0, autocompletion::files());
+    SetConsoleCommandShortcutExtern(append).argumentCompleter(0, autocompletion::files());
+    SetConsoleCommandShortcutExtern(write).argumentCompleter(0, autocompletion::files());
+
+    SetConsoleCommandShortcutExtern(calculate);
+
+    void source(const std::string& filename)
+    {
+        static std::set<std::string> executingFiles;
+
+        std::set<std::string>::const_iterator it = executingFiles.find(filename);
+        if (it != executingFiles.end())
+        {
+            COUT(1) << "Error: Recurring source command in \"" << filename << "\". Stopped execution." << std::endl;
+            return;
+        }
+
+        // Open the file
+        std::ifstream file;
+        file.open(filename.c_str(), std::fstream::in);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "Error: Couldn't open file \"" << filename << "\"." << std::endl;
+            return;
+        }
+
+        executingFiles.insert(filename);
+
+        // Iterate through the file and put the lines into the CommandExecutor
+        while (file.good() && !file.eof())
+        {
+            std::string line;
+            std::getline(file, line);
+            CommandExecutor::execute(line);
+        }
+
+        executingFiles.erase(filename);
+        file.close();
+    }
+
+    std::string echo(const std::string& text)
+    {
+        std::cout << text << std::endl;
+        return text;
+    }
+
+    void puts(bool newline, const std::string& text)
+    {
+        if (newline)
+        {
+            COUT(0) << stripEnclosingBraces(text) << std::endl;
+        }
+        else
+        {
+            COUT(0) << stripEnclosingBraces(text);
+        }
+    }
+
+    void write(const std::string& filename, const std::string& text)
+    {
+        std::ofstream file;
+        file.open(filename.c_str(), std::fstream::out);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "Error: Couldn't write to file \"" << filename << "\"." << std::endl;
+            return;
+        }
+
+        file << text << std::endl;
+        file.close();
+    }
+
+    void append(const std::string& filename, const std::string& text)
+    {
+        std::ofstream file;
+        file.open(filename.c_str(), std::fstream::app);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "Error: Couldn't append to file \"" << filename << "\"." << std::endl;
+            return;
+        }
+
+        file << text << std::endl;
+        file.close();
+    }
+
+    std::string read(const std::string& filename)
+    {
+        std::ifstream file;
+        file.open(filename.c_str(), std::fstream::in);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "Error: Couldn't read from file \"" << filename << "\"." << std::endl;
+            return "";
+        }
+
+        std::string output = "";
+        while (file.good() && !file.eof())
+        {
+            std::string line;
+            std::getline(file, line);
+            output += line;
+            output += "\n";
+        }
+
+        file.close();
+
+        return output;
+    }
+
+    float calculate(const std::string& calculation)
+    {
+        ExprParser expr(calculation);
+        if (expr.getSuccess())
+        {
+            if (expr.getResult() == 42.0)
+            {
+                COUT(3) << "Greetings from the restaurant at the end of the universe." << std::endl;
+            }
+            if (expr.getRemains() != "")
+            {
+                COUT(2) << "Warning: Expression could not be parsed to the end! Remains: '" << expr.getRemains() << "'" << std::endl;
+            }
+            return static_cast<float>(expr.getResult());
+        }
+        else
+        {
+            COUT(1) << "Error: Cannot calculate expression: Parse error." << std::endl;
+            return 0;
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ConsoleCommandCompilation.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ConsoleCommandCompilation.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ConsoleCommandCompilation.h	(revision 5712)
@@ -0,0 +1,47 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ConsoleCommandCompilation_H__
+#define _ConsoleCommandCompilation_H__
+
+#include "CorePrereqs.h"
+
+namespace orxonox
+{
+    _CoreExport void source(const std::string& filename);
+    _CoreExport std::string echo(const std::string& text);
+    _CoreExport void puts(bool newline, const std::string& test);
+
+    _CoreExport void write(const std::string& filename, const std::string& text);
+    _CoreExport void append(const std::string& filename, const std::string& text);
+    _CoreExport std::string read(const std::string& filename);
+
+    _CoreExport float calculate(const std::string& calculation);
+}
+
+#endif /* _ConsoleCommandCompilation_H__ */
Index: /code/branches/libraries2/src/libraries/core/Core.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Core.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Core.cc	(revision 5712)
@@ -0,0 +1,754 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the Core singleton with its global variables (avoids boost include)
+*/
+
+#include "Core.h"
+
+#include <cassert>
+#include <fstream>
+#include <cstdlib>
+#include <cstdio>
+#include <boost/version.hpp>
+#include <boost/filesystem.hpp>
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
+#  include <windows.h>
+#  undef min
+#  undef max
+#elif defined(ORXONOX_PLATFORM_APPLE)
+#  include <sys/param.h>
+#  include <mach-o/dyld.h>
+#else /* Linux */
+#  include <sys/types.h>
+#  include <unistd.h>
+#endif
+
+#include "SpecialConfig.h"
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/SignalHandler.h"
+#include "Clock.h"
+#include "CommandExecutor.h"
+#include "CommandLine.h"
+#include "ConfigFileManager.h"
+#include "ConfigValueIncludes.h"
+#include "CoreIncludes.h"
+#include "DynLibManager.h"
+#include "Factory.h"
+#include "GameMode.h"
+#include "GraphicsManager.h"
+#include "GUIManager.h"
+#include "Identifier.h"
+#include "Language.h"
+#include "LuaState.h"
+#include "Shell.h"
+#include "TclBind.h"
+#include "TclThreadManager.h"
+#include "input/InputManager.h"
+
+// Boost 1.36 has some issues with deprecated functions that have been omitted
+#if (BOOST_VERSION == 103600)
+#  define BOOST_LEAF_FUNCTION filename
+#else
+#  define BOOST_LEAF_FUNCTION leaf
+#endif
+
+namespace orxonox
+{
+    //! Static pointer to the singleton
+    Core* Core::singletonPtr_s  = 0;
+
+    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
+    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
+    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
+#ifdef ORXONOX_PLATFORM_WINDOWS
+    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)");
+#endif
+
+    /**
+    @brief
+        Helper class for the Core singleton: we cannot derive
+        Core from OrxonoxClass because we need to handle the Identifier
+        destruction in the Core destructor.
+    */
+    class CoreConfiguration : public OrxonoxClass
+    {
+    public:
+        CoreConfiguration()
+        {
+        }
+
+        void initialise()
+        {
+            RegisterRootObject(CoreConfiguration);
+            this->setConfigValues();
+
+            // External data directory only exists for dev runs
+            if (Core::isDevelopmentRun())
+            {
+                // Possible data path override by the command line
+                if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
+                    tsetExternalDataPath(CommandLine::getValue("externalDataPath"));
+            }
+        }
+
+        /**
+            @brief Function to collect the SetConfigValue-macro calls.
+        */
+        void setConfigValues()
+        {
+#ifdef NDEBUG
+            const unsigned int defaultLevelConsole = 1;
+            const unsigned int defaultLevelLogfile = 3;
+            const unsigned int defaultLevelShell   = 1;
+#else
+            const unsigned int defaultLevelConsole = 3;
+            const unsigned int defaultLevelLogfile = 4;
+            const unsigned int defaultLevelShell   = 3;
+#endif
+            SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
+                .description("The maximal level of debug output shown in the console")
+                .callback(this, &CoreConfiguration::debugLevelChanged);
+            SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
+                .description("The maximal level of debug output shown in the logfile")
+                .callback(this, &CoreConfiguration::debugLevelChanged);
+            SetConfigValue(softDebugLevelShell_, defaultLevelShell)
+                .description("The maximal level of debug output shown in the ingame shell")
+                .callback(this, &CoreConfiguration::debugLevelChanged);
+
+            SetConfigValue(language_, Language::getInstance().defaultLanguage_)
+                .description("The language of the ingame text")
+                .callback(this, &CoreConfiguration::languageChanged);
+            SetConfigValue(bInitializeRandomNumberGenerator_, true)
+                .description("If true, all random actions are different each time you start the game")
+                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
+        }
+
+        /**
+            @brief Callback function if the debug level has changed.
+        */
+        void debugLevelChanged()
+        {
+            // softDebugLevel_ is the maximum of the 3 variables
+            this->softDebugLevel_ = this->softDebugLevelConsole_;
+            if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
+                this->softDebugLevel_ = this->softDebugLevelLogfile_;
+            if (this->softDebugLevelShell_ > this->softDebugLevel_)
+                this->softDebugLevel_ = this->softDebugLevelShell_;
+
+            OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
+            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
+            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
+            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
+        }
+
+        /**
+            @brief Callback function if the language has changed.
+        */
+        void languageChanged()
+        {
+            // Read the translation file after the language was configured
+            Language::getInstance().readTranslatedLanguageFile();
+        }
+
+        /**
+            @brief Sets the language in the config-file back to the default.
+        */
+        void resetLanguage()
+        {
+            ResetConfigValue(language_);
+        }
+
+        /**
+        @brief
+            Temporary sets the data path
+        @param path
+            The new data path
+        */
+        void tsetExternalDataPath(const std::string& path)
+        {
+            dataPath_ = boost::filesystem::path(path);
+        }
+
+        void initializeRandomNumberGenerator()
+        {
+            static bool bInitialized = false;
+            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
+            {
+                srand(static_cast<unsigned int>(time(0)));
+                rand();
+                bInitialized = true;
+            }
+        }
+
+        int softDebugLevel_;                            //!< The debug level
+        int softDebugLevelConsole_;                     //!< The debug level for the console
+        int softDebugLevelLogfile_;                     //!< The debug level for the logfile
+        int softDebugLevelShell_;                       //!< The debug level for the ingame shell
+        std::string language_;                          //!< The language
+        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
+
+        //! Path to the parent directory of the ones above if program was installed with relativ pahts
+        boost::filesystem::path rootPath_;
+        boost::filesystem::path executablePath_;        //!< Path to the executable
+        boost::filesystem::path modulePath_;            //!< Path to the modules
+        boost::filesystem::path dataPath_;              //!< Path to the data file folder
+        boost::filesystem::path externalDataPath_;      //!< Path to the external data file folder
+        boost::filesystem::path configPath_;            //!< Path to the config file folder
+        boost::filesystem::path logPath_;               //!< Path to the log file folder
+    };
+
+
+    Core::Core(const std::string& cmdLine)
+        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
+        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
+        // Cleanup guard for external console commands that don't belong to an Identifier
+        , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
+        , configuration_(new CoreConfiguration()) // Don't yet create config values!
+        , bDevRun_(false)
+        , bGraphicsLoaded_(false)
+    {
+        // Set the hard coded fixed paths
+        this->setFixedPaths();
+
+        // Create a new dynamic library manager
+        this->dynLibManager_.reset(new DynLibManager());
+
+        // Load modules
+        try
+        {
+            // We search for helper files with the following extension
+            std::string moduleextension = specialConfig::moduleExtension;
+            size_t moduleextensionlength = moduleextension.size();
+
+            // Search in the directory of our executable
+            boost::filesystem::path searchpath = this->configuration_->modulePath_;
+
+            // Add that path to the PATH variable in case a module depends on another one
+            std::string pathVariable = getenv("PATH");
+            putenv(const_cast<char*>(("PATH=" + pathVariable + ";" + configuration_->modulePath_.string()).c_str()));
+
+            boost::filesystem::directory_iterator file(searchpath);
+            boost::filesystem::directory_iterator end;
+
+            // Iterate through all files
+            while (file != end)
+            {
+                std::string filename = file->BOOST_LEAF_FUNCTION();
+
+                // Check if the file ends with the exension in question
+                if (filename.size() > moduleextensionlength)
+                {
+                    if (filename.substr(filename.size() - moduleextensionlength) == moduleextension)
+                    {
+                        // We've found a helper file - now load the library with the same name
+                        std::string library = filename.substr(0, filename.size() - moduleextensionlength);
+                        boost::filesystem::path librarypath = searchpath / library;
+
+                        try
+                        {
+                            DynLibManager::getInstance().load(librarypath.string());
+                        }
+                        catch (const std::exception& e)
+                        {
+                            COUT(1) << "Couldn't load module \"" << librarypath.string() << "\": " << e.what() << std::endl;
+                        }
+                        catch (...)
+                        {
+                            COUT(1) << "Couldn't load module \"" << librarypath.string() << "\"" << std::endl;
+                        }
+                    }
+                }
+
+                ++file;
+            }
+        }
+        catch (const std::exception& e)
+        {
+            COUT(1) << "An error occurred while loading modules: " << e.what() << std::endl;
+        }
+        catch (...)
+        {
+            COUT(1) << "An error occurred while loading modules." << std::endl;
+        }
+
+        // Parse command line arguments AFTER the modules have been loaded (static code!)
+        CommandLine::parseCommandLine(cmdLine);
+
+        // Set configurable paths like log, config and media
+        this->setConfigurablePaths();
+
+        // create a signal handler (only active for linux)
+        // This call is placed as soon as possible, but after the directories are set
+        this->signalHandler_.reset(new SignalHandler());
+        this->signalHandler_->doCatch(configuration_->executablePath_.string(), Core::getLogPathString() + "orxonox_crash.log");
+
+        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
+        OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
+
+        // Parse additional options file now that we know its path
+        CommandLine::parseFile();
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
+        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
+        // the timer though).
+        int limitToCPU = CommandLine::getValue("limitToCPU");
+        if (limitToCPU > 0)
+            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
+#endif
+
+        // Manage ini files and set the default settings file (usually orxonox.ini)
+        this->configFileManager_.reset(new ConfigFileManager());
+        this->configFileManager_->setFilename(ConfigFileType::Settings,
+            CommandLine::getValue("settingsFile").getString());
+
+        // Required as well for the config values
+        this->languageInstance_.reset(new Language());
+
+        // creates the class hierarchy for all classes with factories
+        Factory::createClassHierarchy();
+
+        // Do this soon after the ConfigFileManager has been created to open up the
+        // possibility to configure everything below here
+        this->configuration_->initialise();
+
+        // Load OGRE excluding the renderer and the render window
+        this->graphicsManager_.reset(new GraphicsManager(false));
+
+        // initialise Tcl
+        this->tclBind_.reset(new TclBind(Core::getDataPathString()));
+        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
+
+        // create a shell
+        this->shell_.reset(new Shell());
+    }
+
+    /**
+    @brief
+        All destruction code is handled by scoped_ptrs and ScopeGuards.
+    */
+    Core::~Core()
+    {
+    }
+
+    void Core::loadGraphics()
+    {
+        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
+        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
+
+        // Upgrade OGRE to receive a render window
+        graphicsManager_->upgradeToGraphics();
+
+        // Calls the InputManager which sets up the input devices.
+        inputManager_.reset(new InputManager());
+
+        // load the CEGUI interface
+        guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
+            inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
+
+        unloader.Dismiss();
+
+        bGraphicsLoaded_ = true;
+    }
+
+    void Core::unloadGraphics()
+    {
+        this->guiManager_.reset();;
+        this->inputManager_.reset();;
+        this->graphicsManager_.reset();
+
+        // Load Ogre::Root again, but without the render system
+        try
+            { this->graphicsManager_.reset(new GraphicsManager(false)); }
+        catch (...)
+        {
+            COUT(0) << "An exception occurred during 'new GraphicsManager' while "
+                    << "another exception was being handled. This will lead to undefined behaviour!" << std::endl
+                    << "Terminating the program." << std::endl;
+            abort();
+        }
+
+        bGraphicsLoaded_ = false;
+    }
+
+    /**
+        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
+        @param device The device
+        @return The softDebugLevel
+    */
+    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
+    {
+        switch (device)
+        {
+        case OutputHandler::LD_All:
+            return Core::getInstance().configuration_->softDebugLevel_;
+        case OutputHandler::LD_Console:
+            return Core::getInstance().configuration_->softDebugLevelConsole_;
+        case OutputHandler::LD_Logfile:
+            return Core::getInstance().configuration_->softDebugLevelLogfile_;
+        case OutputHandler::LD_Shell:
+            return Core::getInstance().configuration_->softDebugLevelShell_;
+        default:
+            assert(0);
+            return 2;
+        }
+    }
+
+     /**
+        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
+        @param device The device
+        @param level The level
+    */
+    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
+    {
+        if (device == OutputHandler::LD_All)
+            Core::getInstance().configuration_->softDebugLevel_ = level;
+        else if (device == OutputHandler::LD_Console)
+            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
+        else if (device == OutputHandler::LD_Logfile)
+            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
+        else if (device == OutputHandler::LD_Shell)
+            Core::getInstance().configuration_->softDebugLevelShell_ = level;
+
+        OutputHandler::setSoftDebugLevel(device, level);
+    }
+
+    /**
+        @brief Returns the configured language.
+    */
+    /*static*/ const std::string& Core::getLanguage()
+    {
+        return Core::getInstance().configuration_->language_;
+    }
+
+    /**
+        @brief Sets the language in the config-file back to the default.
+    */
+    /*static*/ void Core::resetLanguage()
+    {
+        Core::getInstance().configuration_->resetLanguage();
+    }
+
+    /*static*/ void Core::tsetExternalDataPath(const std::string& path)
+    {
+        getInstance().configuration_->tsetExternalDataPath(path);
+    }
+
+    /*static*/ const boost::filesystem::path& Core::getDataPath()
+    {
+        return getInstance().configuration_->dataPath_;
+    }
+    /*static*/ std::string Core::getDataPathString()
+    {
+        return getInstance().configuration_->dataPath_.string() + '/';
+    }
+
+    /*static*/ const boost::filesystem::path& Core::getExternalDataPath()
+    {
+        return getInstance().configuration_->externalDataPath_;
+    }
+    /*static*/ std::string Core::getExternalDataPathString()
+    {
+        return getInstance().configuration_->externalDataPath_.string() + '/';
+    }
+
+    /*static*/ const boost::filesystem::path& Core::getConfigPath()
+    {
+        return getInstance().configuration_->configPath_;
+    }
+    /*static*/ std::string Core::getConfigPathString()
+    {
+        return getInstance().configuration_->configPath_.string() + '/';
+    }
+
+    /*static*/ const boost::filesystem::path& Core::getLogPath()
+    {
+        return getInstance().configuration_->logPath_;
+    }
+    /*static*/ std::string Core::getLogPathString()
+    {
+        return getInstance().configuration_->logPath_.string() + '/';
+    }
+
+    /*static*/ const boost::filesystem::path& Core::getRootPath()
+    {
+        return getInstance().configuration_->rootPath_;
+    }
+    /*static*/ std::string Core::getRootPathString()
+    {
+        return getInstance().configuration_->rootPath_.string() + '/';
+    }
+
+    /**
+    @note
+        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
+            (Object-oriented Graphics Rendering Engine)
+        For the latest info, see http://www.ogre3d.org/
+
+        Copyright (c) 2000-2008 Torus Knot Software Ltd
+
+        OGRE is licensed under the LGPL. For more info, see OGRE license.
+    */
+    void Core::setThreadAffinity(int limitToCPU)
+    {
+#ifdef ORXONOX_PLATFORM_WINDOWS
+
+        if (limitToCPU <= 0)
+            return;
+
+        unsigned int coreNr = limitToCPU - 1;
+        // Get the current process core mask
+        DWORD procMask;
+        DWORD sysMask;
+#  if _MSC_VER >= 1400 && defined (_M_X64)
+        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
+#  else
+        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
+#  endif
+
+        // If procMask is 0, consider there is only one core available
+        // (using 0 as procMask will cause an infinite loop below)
+        if (procMask == 0)
+            procMask = 1;
+
+        // if the core specified with coreNr is not available, take the lowest one
+        if (!(procMask & (1 << coreNr)))
+            coreNr = 0;
+
+        // Find the lowest core that this process uses and coreNr suggests
+        DWORD threadMask = 1;
+        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
+            threadMask <<= 1;
+
+        // Set affinity to the first core
+        SetThreadAffinityMask(GetCurrentThread(), threadMask);
+#endif
+    }
+
+    /**
+    @brief
+        Retrievs the executable path and sets all hard coded fixed path (currently only the module path)
+        Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
+        If found it means that this is not an installed run, hence we
+        don't write the logs and config files to ~/.orxonox
+    @throw
+        GeneralException
+    */
+    void Core::setFixedPaths()
+    {
+        //////////////////////////
+        // FIND EXECUTABLE PATH //
+        //////////////////////////
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+        // get executable module
+        TCHAR buffer[1024];
+        if (GetModuleFileName(NULL, buffer, 1024) == 0)
+            ThrowException(General, "Could not retrieve executable path.");
+
+#elif defined(ORXONOX_PLATFORM_APPLE)
+        char buffer[1024];
+        unsigned long path_len = 1023;
+        if (_NSGetExecutablePath(buffer, &path_len))
+            ThrowException(General, "Could not retrieve executable path.");
+
+#else /* Linux */
+        /* written by Nicolai Haehnle <prefect_@gmx.net> */
+
+        /* Get our PID and build the name of the link in /proc */
+        char linkname[64]; /* /proc/<pid>/exe */
+        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
+        {
+            /* This should only happen on large word systems. I'm not sure
+               what the proper response is here.
+               Since it really is an assert-like condition, aborting the
+               program seems to be in order. */
+            assert(false);
+        }
+
+        /* Now read the symbolic link */
+        char buffer[1024];
+        int ret;
+        ret = readlink(linkname, buffer, 1024);
+        /* In case of an error, leave the handling up to the caller */
+        if (ret == -1)
+            ThrowException(General, "Could not retrieve executable path.");
+
+        /* Ensure proper NUL termination */
+        buffer[ret] = 0;
+#endif
+
+        configuration_->executablePath_ = boost::filesystem::path(buffer);
+#ifndef ORXONOX_PLATFORM_APPLE
+        configuration_->executablePath_ = configuration_->executablePath_.branch_path(); // remove executable name
+#endif
+
+        /////////////////////
+        // SET MODULE PATH //
+        /////////////////////
+
+        if (boost::filesystem::exists(configuration_->executablePath_ / "orxonox_dev_build.keep_me"))
+        {
+            COUT(1) << "Running from the build tree." << std::endl;
+            Core::bDevRun_ = true;
+            configuration_->modulePath_ = specialConfig::moduleDevDirectory;
+        }
+        else
+        {
+
+#ifdef INSTALL_COPYABLE // --> relative paths
+
+            // Also set the root path
+            boost::filesystem::path relativeExecutablePath(specialConfig::defaultRuntimePath);
+            configuration_->rootPath_ = configuration_->executablePath_;
+            while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
+                   && !configuration_->rootPath_.empty())
+                configuration_->rootPath_ = configuration_->rootPath_.branch_path();
+            if (configuration_->rootPath_.empty())
+                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
+
+            // Module path is fixed as well
+            configuration_->modulePath_ = configuration_->rootPath_ / specialConfig::defaultModulePath;
+
+#else
+
+            // There is no root path, so don't set it at all
+            // Module path is fixed as well
+            configuration_->modulePath_ = specialConfig::moduleInstallDirectory;
+
+#endif
+        }
+    }
+
+    /**
+    @brief
+        Sets config, log and media path and creates folders if necessary.
+    @throws
+        GeneralException
+    */
+    void Core::setConfigurablePaths()
+    {
+        if (Core::isDevelopmentRun())
+        {
+            configuration_->dataPath_  = specialConfig::dataDevDirectory;
+            configuration_->externalDataPath_ = specialConfig::externalDataDevDirectory;
+            configuration_->configPath_ = specialConfig::configDevDirectory;
+            configuration_->logPath_    = specialConfig::logDevDirectory;
+        }
+        else
+        {
+
+#ifdef INSTALL_COPYABLE // --> relative paths
+
+            // Using paths relative to the install prefix, complete them
+            configuration_->dataPath_   = configuration_->rootPath_ / specialConfig::defaultDataPath;
+            configuration_->configPath_ = configuration_->rootPath_ / specialConfig::defaultConfigPath;
+            configuration_->logPath_    = configuration_->rootPath_ / specialConfig::defaultLogPath;
+
+#else
+
+            configuration_->dataPath_  = specialConfig::dataInstallDirectory;
+
+            // Get user directory
+#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
+            char* userDataPathPtr(getenv("HOME"));
+#  else
+            char* userDataPathPtr(getenv("APPDATA"));
+#  endif
+            if (userDataPathPtr == NULL)
+                ThrowException(General, "Could not retrieve user data path.");
+            boost::filesystem::path userDataPath(userDataPathPtr);
+            userDataPath /= ".orxonox";
+
+            configuration_->configPath_ = userDataPath / specialConfig::defaultConfigPath;
+            configuration_->logPath_    = userDataPath / specialConfig::defaultLogPath;
+
+#endif
+
+        }
+
+        // Option to put all the config and log files in a separate folder
+        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
+        {
+            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
+            configuration_->configPath_ = configuration_->configPath_ / directory;
+            configuration_->logPath_    = configuration_->logPath_    / directory;
+        }
+
+        // Create directories to avoid problems when opening files in non existent folders.
+        std::vector<std::pair<boost::filesystem::path, std::string> > directories;
+        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->configPath_), "config"));
+        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->logPath_), "log"));
+
+        for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
+            it != directories.end(); ++it)
+        {
+            if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
+            {
+                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
+                                         Please remove " + it->first.string());
+            }
+            if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
+            {
+                COUT(4) << "Created " << it->second << " directory" << std::endl;
+            }
+        }
+    }
+
+    void Core::preUpdate(const Clock& time)
+    {
+        if (this->bGraphicsLoaded_)
+        {
+            // process input events
+            this->inputManager_->update(time);
+            // process gui events
+            this->guiManager_->update(time);
+        }
+        // process thread commands
+        this->tclThreadManager_->update(time);
+    }
+
+    void Core::postUpdate(const Clock& time)
+    {
+        if (this->bGraphicsLoaded_)
+        {
+            // Render (doesn't throw)
+            this->graphicsManager_->update(time);
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Core.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Core.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Core.h	(revision 5712)
@@ -0,0 +1,147 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Declaration of the Core class.
+@details
+    The Core class is a singleton, only used to configure some variables
+    in the core through the config-file.
+*/
+
+#ifndef _Core_H__
+#define _Core_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <boost/scoped_ptr.hpp>
+#include "util/OutputHandler.h"
+#include "util/ScopeGuard.h"
+#include "util/Singleton.h"
+
+namespace orxonox
+{
+    class CoreConfiguration;
+
+    /**
+    @brief
+        The Core class is a singleton used to configure the program basics.
+    @details
+        The class provides information about the data, config and log path.
+        It determines those by the use of platform specific functions.
+    @remark
+        You should only create this singleton once because it destroys the identifiers!
+    */
+    class _CoreExport Core : public Singleton<Core>
+    {
+        typedef Loki::ScopeGuardImpl0<void (*)()> SimpleScopeGuard;
+        friend class Singleton<Core>;
+        friend class Game;
+
+        public:
+            /**
+            @brief
+                Determines the executable path, checks for build directory runs, creates
+                the output directories and sets up the other core library singletons.
+            @throws
+                GeneralException
+            */
+            Core(const std::string& cmdLine);
+            ~Core();
+
+            void setConfigValues();
+
+            static int   getSoftDebugLevel(OutputHandler::OutputDevice device = OutputHandler::LD_All);
+            static void  setSoftDebugLevel(OutputHandler::OutputDevice device, int level);
+            static const std::string& getLanguage();
+            static void  resetLanguage();
+
+            static void tsetExternalDataPath(const std::string& path);
+            //! Returns the path to the data files as boost::filesystem::path
+            static const boost::filesystem::path& getDataPath();
+            //! Returns the path to the external data files as boost::filesystem::path
+            static const boost::filesystem::path& getExternalDataPath();
+            //! Returns the path to the config files as boost::filesystem::path
+            static const boost::filesystem::path& getConfigPath();
+            //! Returns the path to the log files as boost::filesystem::path
+            static const boost::filesystem::path& getLogPath();
+            //! Returns the path to the root folder as boost::filesystem::path
+            static const boost::filesystem::path& getRootPath();
+            //! Returns the path to the data files as std::string
+            static std::string getDataPathString();
+            //! Returns the path to the external data files as std::string
+            static std::string getExternalDataPathString();
+            //! Returns the path to the config files as std::string
+            static std::string getConfigPathString();
+            //! Returns the path to the log files as std::string
+            static std::string getLogPathString();
+            //! Returns the path to the root folder as std::string
+            static std::string getRootPathString();
+
+            static bool isDevelopmentRun() { return getInstance().bDevRun_; }
+
+        private:
+            Core(const Core&); //!< Don't use (undefined symbol)
+
+            void preUpdate(const Clock& time);
+            void postUpdate(const Clock& time);
+
+            void loadGraphics();
+            void unloadGraphics();
+
+            void setFixedPaths();
+            void setConfigurablePaths();
+            void setThreadAffinity(int limitToCPU);
+
+            // Mind the order for the destruction!
+            scoped_ptr<DynLibManager>     dynLibManager_;
+            scoped_ptr<SignalHandler>     signalHandler_;
+            SimpleScopeGuard              identifierDestroyer_;
+            SimpleScopeGuard              consoleCommandDestroyer_;
+            scoped_ptr<ConfigFileManager> configFileManager_;
+            scoped_ptr<Language>          languageInstance_;
+            scoped_ptr<CoreConfiguration> configuration_;
+            scoped_ptr<TclBind>           tclBind_;
+            scoped_ptr<TclThreadManager>  tclThreadManager_;
+            scoped_ptr<Shell>             shell_;
+            // graphical
+            scoped_ptr<GraphicsManager>   graphicsManager_;     //!< Interface to OGRE
+            scoped_ptr<InputManager>      inputManager_;        //!< Interface to OIS
+            scoped_ptr<GUIManager>        guiManager_;          //!< Interface to GUI
+
+            bool                          bDevRun_;             //!< True for runs in the build directory (not installed)
+            bool                          bGraphicsLoaded_;
+
+            static Core* singletonPtr_s;
+    };
+}
+
+#endif /* _Core_H__ */
Index: /code/branches/libraries2/src/libraries/core/CoreIncludes.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/CoreIncludes.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CoreIncludes.h	(revision 5712)
@@ -0,0 +1,120 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of macros for Identifier and Factory.
+
+    Every class needs the RegisterObject(class) macro in its constructor. If the class is an interface
+    or the BaseObject itself, it needs the macro RegisterRootObject(class) instead.
+
+    To allow the object being created through the factory, use the CreateFactory(class) macro outside
+    the of the class implementation, so it gets executed before main().
+*/
+
+#ifndef _CoreIncludes_H__
+#define _CoreIncludes_H__
+
+#include "CorePrereqs.h"
+
+#include "util/Debug.h"
+#include "Identifier.h"
+#include "Factory.h"
+#include "ClassFactory.h"
+#include "ObjectList.h"
+
+
+/**
+    @brief Intern macro, containing the common parts of RegisterObject and RegisterRootObject.
+    @param ClassName The name of the class
+    @param bRootClass True if the class is directly derived from OrxonoxClass
+*/
+#define InternRegisterObject(ClassName, bRootClass) \
+    if (ClassIdentifier<ClassName>::getIdentifier(#ClassName)->initialiseObject(this, #ClassName, bRootClass)) \
+        return; \
+    else \
+        ((void)0)
+
+/**
+    @brief RegisterObject - with and without debug output.
+    @param ClassName The name of the class
+*/
+#define RegisterObject(ClassName) \
+    InternRegisterObject(ClassName, false)
+
+/**
+    @brief RegisterRootObject - with and without debug output.
+    @param ClassName The name of the class
+*/
+#define RegisterRootObject(ClassName) \
+    InternRegisterObject(ClassName, true)
+
+/**
+    @brief Creates the entry in the Factory.
+    @param ClassName The name of the class
+*/
+#define CreateFactory(ClassName) \
+    bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, true)
+
+/**
+    @brief Creates the entry in the Factory for classes which should not be loaded through XML.
+    @param ClassName The name of the class
+*/
+#define CreateUnloadableFactory(ClassName) \
+    bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, false)
+
+/**
+    @brief Returns the Identifier of the given class.
+    @param ClassName The name of the class
+*/
+#define Class(ClassName) \
+    orxonox::ClassIdentifier<ClassName>::getIdentifier()
+
+
+namespace orxonox
+{
+    /**
+        @brief Returns the Identifier with a given name through the factory.
+        @param String The name of the class
+    */
+    inline Identifier* ClassByString(const std::string& name)
+    {
+        return Factory::getIdentifier(name);
+    }
+
+    /**
+        @brief Returns the Identifier with a given network ID through the factory.
+        @param networkID The network ID of the class
+    */
+    inline Identifier* ClassByID(uint32_t id)
+    {
+        return Factory::getIdentifier(id);
+    }
+}
+
+#endif /* _CoreIncludes_H__ */
Index: /code/branches/libraries2/src/libraries/core/CorePrecompiledHeaders.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/CorePrecompiledHeaders.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CorePrecompiledHeaders.h	(revision 5712)
@@ -0,0 +1,81 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Compilation of the most often used header files in the core library for MSVC
+*/
+
+#include "OrxonoxConfig.h"
+
+#include <cassert>
+#include <fstream>
+#include <iostream>
+#include <list>
+#include <locale>
+#include <map>
+#include <queue>
+#include <set>
+#include <sstream>
+#include <stack>
+#include <string>
+#include <vector>
+
+
+#ifdef ORXONOX_COMPILER_MSVC
+
+#include <OgreMath.h>
+#include <OgreVector2.h>
+#include <OgreVector3.h>
+#include <OgreVector4.h>
+#include <OgreQuaternion.h>
+#include <OgreColourValue.h>
+
+#include <boost/shared_ptr.hpp> // 12
+#include <boost/preprocessor/cat.hpp> // 12
+
+// Just in case some header included windows.h
+#undef min
+#undef max
+
+#endif /* ORXONOX_COMPILER_MSVC */
+
+
+#include "util/Debug.h"
+#include "util/Math.h"
+#include "util/MultiType.h"
+#include "util/SubString.h"
+
+
+#ifdef ORXONOX_COMPILER_MSVC
+
+// A change would trigger an 80% Core rebuild anyway
+#include "Identifier.h"
+
+#endif /*ORXONOX_COMPILER_MSVC */
Index: /code/branches/libraries2/src/libraries/core/CorePrereqs.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/CorePrereqs.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/CorePrereqs.h	(revision 5712)
@@ -0,0 +1,294 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+  @file
+  @brief Contains all the necessary forward declarations for all classes and structs.
+*/
+
+#ifndef _CorePrereqs_H__
+#define _CorePrereqs_H__
+
+#include "OrxonoxConfig.h"
+
+//-----------------------------------------------------------------------
+// Shared library settings
+//-----------------------------------------------------------------------
+#if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( CORE_STATIC_BUILD )
+#  ifdef CORE_SHARED_BUILD
+#    define _CoreExport __declspec(dllexport)
+#  else
+#    if defined( __MINGW32__ )
+#      define _CoreExport
+#    else
+#      define _CoreExport __declspec(dllimport)
+#    endif
+#  endif
+#elif defined ( ORXONOX_GCC_VISIBILITY )
+#  define _CoreExport  __attribute__ ((visibility("default")))
+#else
+#  define _CoreExport
+#endif
+
+
+//-----------------------------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------------------------
+namespace orxonox
+{
+    namespace XMLPort
+    {
+        enum Mode
+        {
+            LoadObject,
+            SaveObject,
+            ExpandObject
+        };
+    }
+
+    namespace KeybindMode
+    {
+        enum Value
+        {
+            OnPress,
+            OnHold,
+            OnRelease,
+            None
+        };
+    };
+
+    typedef std::string LanguageEntryLabel;
+
+    class ArgumentCompleter;
+    class ArgumentCompletionListElement;
+    class BaseFactory;
+    class BaseMetaObjectListElement;
+    class BaseObject;
+    template <class T>
+    class ClassFactory;
+    template <class T>
+    class ClassIdentifier;
+    class ClassTreeMask;
+    class ClassTreeMaskIterator;
+    class ClassTreeMaskNode;
+    class ClassTreeMaskObjectIterator;
+    class Clock;
+    class CommandEvaluation;
+    class CommandExecutor;
+    class CommandLine;
+    class CommandLineArgument;
+    class ConfigFile;
+    class ConfigFileEntry;
+    class ConfigFileEntryComment;
+    class ConfigFileEntryValue;
+    class ConfigFileManager;
+    class ConfigFileSection;
+    class ConfigValueContainer;
+    class ConsoleCommand;
+    class Core;
+    class DynLib;
+    class DynLibManager;
+    struct Event;
+    class EventContainer;
+    class Executor;
+    template <class T>
+    class ExecutorMember;
+    class ExecutorStatic;
+    class Factory;
+    class Functor;
+    template <class T>
+    class FunctorMember;
+    class FunctorStatic;
+    class GraphicsManager;
+    class GUIManager;
+    class Identifier;
+    class IRC;
+    template <class T>
+    class Iterator;
+    class IteratorBase;
+    class Language;
+    class LanguageEntry;
+    class Loader;
+    class LuaState;
+    class MemoryArchive;
+    class MemoryArchiveFactory;
+    class MetaObjectList;
+    class MetaObjectListElement;
+    class Namespace;
+    class NamespaceNode;
+    template <class T>
+    class ObjectList;
+    class ObjectListBase;
+    class ObjectListBaseElement;
+    template <class T>
+    class ObjectListElement;
+    template <class T>
+    class ObjectListIterator;
+    class OgreWindowEventListener;
+    class OrxonoxClass;
+    struct ResourceInfo;
+    class Shell;
+    class ShellListener;
+    template <class T>
+    class SubclassIdentifier;
+    class TclBind;
+    struct TclInterpreterBundle;
+    template <class T>
+    class TclThreadList;
+    class TclThreadManager;
+    class Template;
+    class WindowEventListener;
+    class XMLFile;
+    class XMLNameListener;
+    template <class T, class O>
+    class XMLPortClassObjectContainer;
+    template <class T>
+    class XMLPortClassParamContainer;
+    class XMLPortObjectContainer;
+    class XMLPortParamContainer;
+
+    // game states
+    class Game;
+    class GameState;
+    struct GameStateInfo;
+    struct GameStateTreeNode;
+
+    // input
+    class BaseCommand;
+    class BufferedParamCommand;
+    class Button;
+    class CalibratorCallback;
+    class HalfAxis;
+    class InputBuffer;
+    class InputDevice;
+    template <class Traits>
+    class InputDeviceTemplated;
+    class InputHandler;
+    class InputManager;
+    class InputState;
+    class JoyStick;
+    class Mouse;
+    class Keyboard;
+    class KeyBinder;
+    class KeyDetector;
+    class ParamCommand;
+    class SimpleCommand;
+
+
+    // multithreading
+    class Thread;
+    class ThreadPool;
+}
+
+// CppTcl
+namespace Tcl
+{
+    class interpreter;
+    class object;
+}
+
+// Boost
+namespace boost
+{
+    namespace filesystem
+    {
+        struct path_traits;
+        template <class String, class Traits> class basic_path;
+        typedef basic_path<std::string, path_traits> path;
+    }
+    class thread;
+    class mutex;
+    class shared_mutex;
+    class condition_variable;
+}
+
+// Ogre
+namespace Ogre
+{
+    class DataStream;
+    template <class T> class SharedPtr;
+    typedef SharedPtr<DataStream> DataStreamPtr;
+}
+namespace orxonox
+{
+    // Import the Ogre::DataStream
+    using Ogre::DataStream;
+    using Ogre::DataStreamPtr;
+}
+
+// CEGUI
+namespace CEGUI
+{
+    class DefaultLogger;
+    class Logger;
+    class LuaScriptModule;
+
+    class OgreCEGUIRenderer;
+    class OgreCEGUIResourceProvider;
+    class OgreCEGUITexture;
+}
+
+// Lua
+struct lua_State;
+
+// TinyXML and TinyXML++
+class TiXmlString;
+class TiXmlOutStream;
+class TiXmlNode;
+class TiXmlHandle;
+class TiXmlDocument;
+class TiXmlElement;
+class TiXmlComment;
+class TiXmlUnknown;
+class TiXmlAttribute;
+class TiXmlText;
+class TiXmlDeclaration;
+class TiXmlParsingData;
+namespace ticpp
+{
+    class Document;
+    class Element;
+    class Declaration;
+    class StylesheetReference;
+    class Text;
+    class Comment;
+    class Attribute;
+}
+namespace orxonox
+{
+    using ticpp::Document;
+    using ticpp::Element;
+    using ticpp::Declaration;
+    using ticpp::StylesheetReference;
+    using ticpp::Text;
+    using ticpp::Comment;
+    using ticpp::Attribute;
+}
+
+
+#endif /* _CorePrereqs_H__ */
Index: /code/branches/libraries2/src/libraries/core/DynLib.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/DynLib.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/DynLib.cc	(revision 5712)
@@ -0,0 +1,134 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
+
+#include "DynLib.h"
+
+#include "util/Exception.h"
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+#  define WIN32_LEAN_AND_MEAN
+#  ifndef NOMINMAX
+#    define NOMINMAX // required to stop windows.h messing up std::min
+#  endif
+#  include <windows.h>
+#endif
+
+#ifdef ORXONOX_PLATFORM_APPLE
+#   include "macPlugins.h"
+#endif
+
+namespace orxonox
+{
+    //-----------------------------------------------------------------------
+    DynLib::DynLib( const std::string& name )
+    {
+        mName = name;
+        m_hInst = NULL;
+    }
+
+    //-----------------------------------------------------------------------
+    DynLib::~DynLib()
+    {
+    }
+
+    //-----------------------------------------------------------------------
+    void DynLib::load()
+    {
+        // Log library load
+        COUT(2) << "Loading module " << mName << std::endl;
+
+		std::string name = mName;
+#ifdef ORXONOX_PLATFORM_LINUX
+        // dlopen() does not add .so to the filename, like windows does for .dll
+        if (name.substr(name.length() - 3, 3) != ".so")
+           name += ".so";
+#endif
+
+        m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
+
+        if( !m_hInst )
+            ThrowException(
+                General,
+                "Could not load dynamic library " + mName +
+                ".  System Error: " + dynlibError());
+    }
+
+    //-----------------------------------------------------------------------
+    void DynLib::unload()
+    {
+        // Log library unload
+        COUT(4) << "Unloading module " << mName << std::endl;
+
+        if( DYNLIB_UNLOAD( m_hInst ) )
+		{
+            ThrowException(
+                General,
+                "Could not unload dynamic library " + mName +
+                ".  System Error: " + dynlibError());
+		}
+
+    }
+
+    //-----------------------------------------------------------------------
+    void* DynLib::getSymbol( const std::string& strName ) const throw()
+    {
+        return (void*)DYNLIB_GETSYM( m_hInst, strName.c_str() );
+    }
+    //-----------------------------------------------------------------------
+    std::string DynLib::dynlibError( void )
+    {
+#if defined(ORXONOX_PLATFORM_WINDOWS)
+        LPVOID lpMsgBuf;
+        FormatMessage(
+            FORMAT_MESSAGE_ALLOCATE_BUFFER |
+            FORMAT_MESSAGE_FROM_SYSTEM |
+            FORMAT_MESSAGE_IGNORE_INSERTS,
+            NULL,
+            GetLastError(),
+            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+            (LPTSTR) &lpMsgBuf,
+            0,
+            NULL
+            );
+        std::string ret = (char*)lpMsgBuf;
+        // Free the buffer.
+        LocalFree( lpMsgBuf );
+        return ret;
+#elif defined(ORXONOX_PLATFORM_LINUX)
+        return std::string(dlerror());
+#elif defined(ORXONOX_PLATFORM_APPLE)
+        return std::string(mac_errorBundle());
+#else
+        return std::string("");
+#endif
+    }
+
+}
Index: /code/branches/libraries2/src/libraries/core/DynLib.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/DynLib.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/DynLib.h	(revision 5712)
@@ -0,0 +1,121 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
+
+#ifndef _Core_DynLib_H__
+#define _Core_DynLib_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+
+#if defined(ORXONOX_PLATFORM_WINDOWS)
+#    define DYNLIB_HANDLE hInstance
+#    define DYNLIB_LOAD( a ) LoadLibraryEx( a, NULL, LOAD_WITH_ALTERED_SEARCH_PATH )
+#    define DYNLIB_GETSYM( a, b ) GetProcAddress( a, b )
+#    define DYNLIB_UNLOAD( a ) !FreeLibrary( a )
+
+struct HINSTANCE__;
+typedef struct HINSTANCE__* hInstance;
+
+#elif defined(ORXONOX_PLATFORM_LINUX)
+#    define DYNLIB_HANDLE void*
+#    define DYNLIB_LOAD( a ) dlopen( a, RTLD_LAZY | RTLD_GLOBAL)
+#    define DYNLIB_GETSYM( a, b ) dlsym( a, b )
+#    define DYNLIB_UNLOAD( a ) dlclose( a )
+
+#elif defined(ORXONOX_PLATFORM_APPLE)
+#    define DYNLIB_HANDLE CFBundleRef
+#    define DYNLIB_LOAD( a ) mac_loadExeBundle( a )
+#    define DYNLIB_GETSYM( a, b ) mac_getBundleSym( a, b )
+#    define DYNLIB_UNLOAD( a ) mac_unloadExeBundle( a )
+#endif
+
+namespace orxonox
+{
+    /** Resource holding data about a dynamic library.
+        @remarks
+            This class holds the data required to get symbols from
+            libraries loaded at run-time (i.e. from DLL's for so's)
+        @author
+            Adrian Cearnãu (cearny@cearny.ro)
+        @since
+            27 January 2002
+        @see
+            Resource
+    */
+	class _CoreExport DynLib
+    {
+	protected:
+		std::string mName;
+        /// Gets the last loading error
+        std::string dynlibError(void);
+    public:
+        /** Default constructor - used by DynLibManager.
+            @warning
+                Do not call directly
+        */
+        DynLib( const std::string& name );
+
+        /** Default destructor.
+        */
+        ~DynLib();
+
+        /** Load the library
+        */
+        void load();
+        /** Unload the library
+        */
+        void unload();
+		/// Get the name of the library
+		const std::string& getName(void) const { return mName; }
+
+        /**
+            Returns the address of the given symbol from the loaded library.
+            @param
+                strName The name of the symbol to search for
+            @returns
+                If the function succeeds, the returned value is a handle to
+                the symbol.
+            @par
+                If the function fails, the returned value is <b>NULL</b>.
+
+        */
+        void* getSymbol( const std::string& strName ) const throw();
+
+    protected:
+
+        /// Handle to the loaded library.
+        DYNLIB_HANDLE m_hInst;
+    };
+
+}
+
+#endif /* _Core_DynLib_H__ */
Index: /code/branches/libraries2/src/libraries/core/DynLibManager.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/DynLibManager.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/DynLibManager.cc	(revision 5712)
@@ -0,0 +1,86 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
+
+#include "DynLibManager.h"
+
+#include "DynLib.h"
+
+namespace orxonox
+{
+    //-----------------------------------------------------------------------
+    //! Static pointer to the singleton
+    DynLibManager* DynLibManager::singletonPtr_s  = 0;
+
+    //-----------------------------------------------------------------------
+	DynLibManager::DynLibManager()
+	{
+	}
+	//-----------------------------------------------------------------------
+    DynLib* DynLibManager::load( const std::string& filename)
+    {
+		DynLibList::iterator i = mLibList.find(filename);
+		if (i != mLibList.end())
+		{
+			return i->second;
+		}
+		else
+		{
+	        DynLib* pLib = new DynLib(filename);
+			pLib->load();
+        	mLibList[filename] = pLib;
+	        return pLib;
+		}
+    }
+	//-----------------------------------------------------------------------
+	void DynLibManager::unload(DynLib* lib)
+	{
+		DynLibList::iterator i = mLibList.find(lib->getName());
+		if (i != mLibList.end())
+		{
+			mLibList.erase(i);
+		}
+		lib->unload();
+		delete lib;
+	}
+	//-----------------------------------------------------------------------
+    DynLibManager::~DynLibManager()
+    {
+        // Unload & delete resources in turn
+        for( DynLibList::iterator it = mLibList.begin(); it != mLibList.end(); ++it )
+        {
+            it->second->unload();
+            delete it->second;
+        }
+
+        // Empty the list
+        mLibList.clear();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/DynLibManager.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/DynLibManager.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/DynLibManager.h	(revision 5712)
@@ -0,0 +1,90 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
+
+#ifndef _Core_DynLibManager_H__
+#define _Core_DynLibManager_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <string>
+#include "util/Singleton.h"
+
+namespace orxonox
+{
+    /** Manager for Dynamic-loading Libraries.
+        @remarks
+            This manager keeps a track of all the open dynamic-loading
+            libraries, opens them and returns references to already-open
+            libraries.
+    */
+    class _CoreExport DynLibManager: public Singleton<DynLibManager>
+    {
+        friend class Singleton<DynLibManager>;
+
+        protected:
+            typedef std::map<std::string, DynLib*> DynLibList;
+            DynLibList mLibList;
+
+        public:
+            /** Default constructor.
+                @note
+                    <br>Should never be called as the singleton is automatically
+                    created during the creation of the Root object.
+                @see
+                    Root::Root
+            */
+            DynLibManager();
+
+            /** Default destructor.
+                @see
+                    Root::~Root
+            */
+            virtual ~DynLibManager();
+
+            /** Loads the passed library.
+                @param
+                    filename The name of the library. The extension can be omitted
+            */
+            DynLib* load(const std::string& filename);
+
+            /** Unloads the passed library.
+            @param
+            filename The name of the library. The extension can be omitted
+            */
+            void unload(DynLib* lib);
+
+        private:
+            static DynLibManager* singletonPtr_s;
+    };
+}
+
+#endif /* _Core_DynLibManager_H__ */
Index: /code/branches/libraries2/src/libraries/core/Event.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Event.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Event.cc	(revision 5712)
@@ -0,0 +1,79 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Event.h"
+
+#include "BaseObject.h"
+#include "Executor.h"
+
+namespace orxonox
+{
+    EventContainer::~EventContainer()
+    {
+        delete this->eventfunction_;
+    }
+
+    void EventContainer::process(BaseObject* object, const Event& event)
+    {
+        if (this->bActive_)
+        {
+            COUT(2) << "Warning: Detected Event loop in section \"" << this->eventname_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
+            return;
+        }
+
+        this->bActive_ = true;
+
+        if (this->eventname_ == event.sectionname_)
+        {
+            if (event.originator_->isA(this->subclass_))
+            {
+                if (event.activate_)
+                    ++this->activeEvents_;
+                else
+                {
+                    --this->activeEvents_;
+
+                    if (this->activeEvents_ < 0)
+                        this->activeEvents_ = 0;
+                }
+
+                if (this->eventfunction_->getParamCount() == 0 && event.activate_)
+                    (*this->eventfunction_)();
+                else if ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_))
+                {
+                    if (this->eventfunction_->getParamCount() == 1)
+                        (*this->eventfunction_)(this->activeEvents_);
+                    else if (this->eventfunction_->getParamCount() >= 2 && event.castedOriginator_)
+                        (*this->eventfunction_)(this->activeEvents_, event.castedOriginator_);
+                }
+            }
+        }
+
+        this->bActive_ = false;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Event.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Event.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Event.h	(revision 5712)
@@ -0,0 +1,65 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Event_H__
+#define _Event_H__
+
+#include "CorePrereqs.h"
+#include <string>
+
+namespace orxonox
+{
+    struct _CoreExport Event
+    {
+            Event(bool activate, BaseObject* originator) : activate_(activate), originator_(originator), castedOriginator_(0) {}
+
+            bool        activate_;
+            BaseObject* originator_;
+            void*       castedOriginator_;
+            std::string sectionname_;
+    };
+
+    class _CoreExport EventContainer
+    {
+        public:
+            EventContainer(const std::string& eventname, Executor* eventfunction, Identifier* subclass) : bActive_(false), eventname_(eventname), eventfunction_(eventfunction), subclass_(subclass), activeEvents_(0) {}
+            virtual ~EventContainer();
+
+            void process(BaseObject* object, const Event& event);
+
+        private:
+            bool bActive_;
+            std::string eventname_;
+            Executor* eventfunction_;
+            Identifier* subclass_;
+
+            int activeEvents_;
+    };
+}
+
+#endif /* _Event_H__ */
Index: /code/branches/libraries2/src/libraries/core/EventIncludes.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/EventIncludes.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/EventIncludes.h	(revision 5712)
@@ -0,0 +1,71 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _EventIncludes_H__
+#define _EventIncludes_H__
+
+#include "CorePrereqs.h"
+#include "Executor.h"
+
+#define ORXONOX_SET_EVENT(classname, eventname, functionname, event) \
+    ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject)
+
+#define ORXONOX_SET_EVENT_TEMPLATE(classname, eventname, functionname, event, ...) \
+    ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject, __VA_ARGS__)
+
+#define ORXONOX_SET_SUBCLASS_EVENT(classname, eventname, functionname, event, subclassname) \
+    ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname)
+
+#define ORXONOX_SET_SUBCLASS_EVENT_TEMPLATE(classname, eventname, functionname, event, subclassname, ...) \
+    ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname, __VA_ARGS__)
+
+#define ORXONOX_SET_EVENT_GENERIC(containername, classname, eventname, functionname, event, subclassname) \
+    orxonox::EventContainer* containername = this->getEventContainer(eventname); \
+    if (!containername) \
+    { \
+        ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
+        executor->setObject(this); \
+        containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
+        this->addEventContainer(eventname, containername); \
+    } \
+    event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
+    containername->process(this, event)
+
+#define ORXONOX_SET_EVENT_GENERIC_TEMPLATE(containername, classname, eventname, functionname, event, subclassname, ...) \
+    orxonox::EventContainer* containername = this->getEventContainer(eventname); \
+    if (!containername) \
+    { \
+        ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
+        executor->setObject(this); \
+        containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
+        this->addEventContainer(eventname, containername); \
+    } \
+    event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
+    containername->process(this, event)
+
+#endif /* _EventIncludes_H__ */
Index: /code/branches/libraries2/src/libraries/core/Executor.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Executor.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Executor.cc	(revision 5712)
@@ -0,0 +1,252 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ *   Inspiration: Executor by Benjamin Grauer
+ */
+
+#include "Executor.h"
+
+#include "util/Convert.h"
+#include "Language.h"
+
+namespace orxonox
+{
+    Executor::Executor(Functor* functor, const std::string& name)
+    {
+        this->functor_ = functor;
+        this->name_ = name;
+
+        this->bAddedDescription_ = false;
+        this->bAddedDescriptionReturnvalue_ = false;
+
+        this->bAddedDescriptionParam_[0] = false;
+        this->bAddedDescriptionParam_[1] = false;
+        this->bAddedDescriptionParam_[2] = false;
+        this->bAddedDescriptionParam_[3] = false;
+        this->bAddedDescriptionParam_[4] = false;
+
+        this->bAddedDefaultValue_[0] = false;
+        this->bAddedDefaultValue_[1] = false;
+        this->bAddedDefaultValue_[2] = false;
+        this->bAddedDefaultValue_[3] = false;
+        this->bAddedDefaultValue_[4] = false;
+    }
+
+    Executor::~Executor()
+    {
+        delete this->functor_;
+    }
+
+    bool Executor::parse(const std::string& params, const std::string& delimiter) const
+    {
+        EXECUTOR_PARSE(normal);
+    }
+
+    bool Executor::evaluate(const std::string& params, MultiType param[5], const std::string& delimiter) const
+    {
+        unsigned int paramCount = this->functor_->getParamCount();
+
+        if (paramCount == 1)
+        {
+            // only one param: check if there are params given, otherwise try to use default values
+            std::string temp = getStripped(params);
+            if ((temp != "") && (temp.size() != 0))
+            {
+                param[0] = params;
+                this->functor_->evaluateParam(0, param[0]);
+                return true;
+            }
+            else if (this->bAddedDefaultValue_[0])
+            {
+                param[0] = this->defaultValue_[0];
+                this->functor_->evaluateParam(0, param[0]);
+                return true;
+            }
+            return false;
+        }
+        else
+        {
+            // more than one param
+            SubString tokens(params, delimiter, SubString::WhiteSpaces, false, '\\', true, '"', true, '(', ')', true, '\0');
+
+            // if there are not enough params given, check if there are default values
+            for (unsigned int i = tokens.size(); i < this->functor_->getParamCount(); i++)
+                if (!this->bAddedDefaultValue_[i])
+                    return false;
+
+            // assign all given arguments to the multitypes
+            for (unsigned int i = 0; i < std::min(tokens.size(), MAX_FUNCTOR_ARGUMENTS); i++)
+                param[i] = tokens[i];
+
+            // fill the remaining multitypes with default values
+            for (unsigned int i = tokens.size(); i < std::min(paramCount, MAX_FUNCTOR_ARGUMENTS); i++)
+                param[i] = this->defaultValue_[i];
+
+            // evaluate the param types through the functor
+            for (unsigned int i = 0; i < std::min(paramCount, MAX_FUNCTOR_ARGUMENTS); i++)
+                this->functor_->evaluateParam(i, param[i]);
+
+            return true;
+        }
+    }
+
+    Executor& Executor::setDescription(const std::string& description)
+    {
+        if (!this->bAddedDescription_)
+        {
+            this->description_ = std::string("ExecutorDescription::" + this->name_ + "::function");
+            AddLanguageEntry(this->description_, description);
+            this->bAddedDescription_ = true;
+        }
+        return (*this);
+    }
+
+    const std::string& Executor::getDescription() const
+    {
+        return GetLocalisation(this->description_);
+    }
+
+    Executor& Executor::setDescriptionParam(unsigned int param, const std::string& description)
+    {
+        if (param < MAX_FUNCTOR_ARGUMENTS)
+        {
+            if (!this->bAddedDescriptionParam_[param])
+            {
+                std::string paramnumber;
+                if (!convertValue(&paramnumber, param))
+                    return (*this);
+
+                this->descriptionParam_[param] = std::string("ExecutorDescription::" + this->name_ + "::param" + paramnumber);
+                AddLanguageEntry(this->descriptionParam_[param], description);
+                this->bAddedDescriptionParam_[param] = true;
+            }
+        }
+        return (*this);
+    }
+
+    const std::string& Executor::getDescriptionParam(unsigned int param) const
+    {
+        if (param < MAX_FUNCTOR_ARGUMENTS)
+            return GetLocalisation(this->descriptionParam_[param]);
+
+        return this->descriptionParam_[0];
+    }
+
+    Executor& Executor::setDescriptionReturnvalue(const std::string& description)
+    {
+        if (!this->bAddedDescriptionReturnvalue_)
+        {
+            this->descriptionReturnvalue_ = std::string("ExecutorDescription::" + this->name_ + "::returnvalue");
+            AddLanguageEntry(this->descriptionReturnvalue_, description);
+            this->bAddedDescriptionReturnvalue_ = true;
+        }
+        return (*this);
+    }
+
+    const std::string& Executor::getDescriptionReturnvalue(int param) const
+    {
+        return GetLocalisation(this->descriptionReturnvalue_);
+    }
+
+    Executor& Executor::setDefaultValues(const MultiType& param1)
+    {
+        this->defaultValue_[0] = param1;
+        this->bAddedDefaultValue_[0] = true;
+
+        return (*this);
+    }
+
+    Executor& Executor::setDefaultValues(const MultiType& param1, const MultiType& param2)
+    {
+        this->defaultValue_[0] = param1;
+        this->bAddedDefaultValue_[0] = true;
+        this->defaultValue_[1] = param2;
+        this->bAddedDefaultValue_[1] = true;
+
+        return (*this);
+    }
+
+    Executor& Executor::setDefaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3)
+    {
+        this->defaultValue_[0] = param1;
+        this->bAddedDefaultValue_[0] = true;
+        this->defaultValue_[1] = param2;
+        this->bAddedDefaultValue_[1] = true;
+        this->defaultValue_[2] = param3;
+        this->bAddedDefaultValue_[2] = true;
+
+        return (*this);
+    }
+
+    Executor& Executor::setDefaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4)
+    {
+        this->defaultValue_[0] = param1;
+        this->bAddedDefaultValue_[0] = true;
+        this->defaultValue_[1] = param2;
+        this->bAddedDefaultValue_[1] = true;
+        this->defaultValue_[2] = param3;
+        this->bAddedDefaultValue_[2] = true;
+        this->defaultValue_[3] = param4;
+        this->bAddedDefaultValue_[3] = true;
+
+        return (*this);
+    }
+
+    Executor& Executor::setDefaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5)
+    {
+        this->defaultValue_[0] = param1;
+        this->bAddedDefaultValue_[0] = true;
+        this->defaultValue_[1] = param2;
+        this->bAddedDefaultValue_[1] = true;
+        this->defaultValue_[2] = param3;
+        this->bAddedDefaultValue_[2] = true;
+        this->defaultValue_[3] = param4;
+        this->bAddedDefaultValue_[3] = true;
+        this->defaultValue_[4] = param5;
+        this->bAddedDefaultValue_[4] = true;
+
+        return (*this);
+    }
+
+    Executor& Executor::setDefaultValue(unsigned int index, const MultiType& param)
+    {
+        if (index < MAX_FUNCTOR_ARGUMENTS)
+        {
+            this->defaultValue_[index] = param;
+            this->bAddedDefaultValue_[index] = true;
+        }
+        return (*this);
+    }
+
+    bool Executor::allDefaultValuesSet() const
+    {
+        for (unsigned int i = 0; i < this->functor_->getParamCount(); i++)
+            if (!this->bAddedDefaultValue_[i])
+                return false;
+
+        return true;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Executor.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Executor.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Executor.h	(revision 5712)
@@ -0,0 +1,312 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ *   Inspiration: Executor by Benjamin Grauer
+ */
+
+#ifndef _Executor_H__
+#define _Executor_H__
+
+#include "CorePrereqs.h"
+
+#include <algorithm>
+#include <string>
+
+#include "util/Debug.h"
+#include "util/Math.h"
+#include "util/StringUtils.h"
+#include "util/SubString.h"
+#include "Functor.h"
+
+
+#define EXECUTOR_PARSE_FUNCTORCALL(mode) EXECUTOR_PARSE_FUNCTORCALL##mode
+#define EXECUTOR_PARSE_FUNCTORCALLnormal (*this->functor_)
+#define EXECUTOR_PARSE_FUNCTORCALLobject (*((FunctorMember<T>*)this->functor_))
+
+#define EXECUTOR_PARSE_OBJECT(mode, comma) EXECUTOR_PARSE_OBJECT##mode##comma
+#define EXECUTOR_PARSE_OBJECTnormal0
+#define EXECUTOR_PARSE_OBJECTnormal1
+#define EXECUTOR_PARSE_OBJECTobject0 object
+#define EXECUTOR_PARSE_OBJECTobject1 object,
+
+#define EXECUTOR_PARSE(mode) \
+    unsigned int paramCount = this->functor_->getParamCount(); \
+    \
+    if (paramCount == 0) \
+    { \
+        COUT(5) << "Calling Executor " << this->name_ << " through parser without parameters." << std::endl; \
+        EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 0)); \
+    } \
+    else if (paramCount == 1) \
+    { \
+        std::string temp = getStripped(params); \
+        if ((temp != "") && (temp.size() != 0)) \
+        { \
+            COUT(5) << "Calling Executor " << this->name_ << " through parser with one parameter, using whole string: " << params << std::endl; \
+            EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 1) MultiType(params)); \
+        } \
+        else if (this->bAddedDefaultValue_[0]) \
+        { \
+            COUT(5) << "Calling Executor " << this->name_ << " through parser with one parameter, using default value: " << this->defaultValue_[0] << std::endl; \
+            EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 1) this->defaultValue_[0]); \
+        } \
+        else \
+        { \
+            COUT(2) << "Warning: Can't call executor " << this->name_ << " through parser: Not enough parameters or default values given (input: " << temp << ")." << std::endl; \
+            return false; \
+        } \
+    } \
+    else \
+    { \
+        SubString tokens(params, delimiter, SubString::WhiteSpaces, false, '\\', true, '"', true, '(', ')', true, '\0'); \
+        \
+        for (unsigned int i = tokens.size(); i < this->functor_->getParamCount(); i++) \
+        { \
+            if (!this->bAddedDefaultValue_[i]) \
+            { \
+                COUT(2) << "Warning: Can't call executor " << this->name_ << " through parser: Not enough parameters or default values given (input:" << params << ")." << std::endl; \
+                return false; \
+            } \
+        } \
+        \
+        MultiType param[MAX_FUNCTOR_ARGUMENTS]; \
+        COUT(5) << "Calling Executor " << this->name_ << " through parser with " << paramCount << " parameters, using " << tokens.size() << " tokens ("; \
+        for (unsigned int i = 0; i < tokens.size() && i < MAX_FUNCTOR_ARGUMENTS; i++) \
+        { \
+            param[i] = tokens[i]; \
+            if (i != 0) \
+            { \
+                COUT(5) << ", "; \
+            } \
+            COUT(5) << tokens[i]; \
+        } \
+        COUT(5) << ") and " << std::max(static_cast<int>(paramCount) - static_cast<int>(tokens.size()), 0) << " default values ("; \
+        for (unsigned int i = tokens.size(); i < paramCount; i++) \
+        { \
+            param[i] = this->defaultValue_[i]; \
+            if (i != 0) \
+            { \
+                COUT(5) << ", "; \
+            } \
+            COUT(5) << this->defaultValue_[i]; \
+        } \
+        COUT(5) << ")." << std::endl; \
+        \
+        if ((tokens.size() > paramCount) && (this->functor_->getTypenameParam(paramCount - 1) == "string")) \
+            param[paramCount - 1] = tokens.subSet(paramCount - 1).join(); \
+        \
+        switch(paramCount) \
+        { \
+            case 2: \
+                EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 1) param[0], param[1]); \
+                break; \
+            case 3: \
+                EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 1) param[0], param[1], param[2]); \
+                break; \
+            case 4: \
+                EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 1) param[0], param[1], param[2], param[3]); \
+                break; \
+            case 5: \
+                EXECUTOR_PARSE_FUNCTORCALL(mode)(EXECUTOR_PARSE_OBJECT(mode, 1) param[0], param[1], param[2], param[3], param[4]); \
+                break; \
+        } \
+    } \
+    \
+    return true
+
+namespace orxonox
+{
+    class _CoreExport Executor
+    {
+        public:
+            Executor(Functor* functor, const std::string& name = "");
+            virtual ~Executor();
+
+            inline void operator()() const
+                { (*this->functor_)(this->defaultValue_[0], this->defaultValue_[1], this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const MultiType& param1) const
+                { (*this->functor_)(param1, this->defaultValue_[1], this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const MultiType& param1, const MultiType& param2) const
+                { (*this->functor_)(param1, param2, this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const MultiType& param1, const MultiType& param2, const MultiType& param3) const
+                { (*this->functor_)(param1, param2, param3, this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4) const
+                { (*this->functor_)(param1, param2, param3, param4, this->defaultValue_[4]); }
+            inline void operator()(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5) const
+                { (*this->functor_)(param1, param2, param3, param4, param5); }
+
+            bool parse(const std::string& params, const std::string& delimiter = " ") const;
+
+            bool evaluate(const std::string& params, MultiType param[5], const std::string& delimiter = " ") const;
+
+            Executor& setDescription(const std::string& description);
+            const std::string& getDescription() const;
+
+            Executor& setDescriptionParam(unsigned int param, const std::string& description);
+            const std::string& getDescriptionParam(unsigned int param) const;
+
+            Executor& setDescriptionReturnvalue(const std::string& description);
+            const std::string& getDescriptionReturnvalue(int param) const;
+
+            inline Functor* getFunctor() const
+                { return this->functor_; }
+            inline unsigned int getParamCount() const
+                { return this->functor_->getParamCount(); }
+            inline bool hasReturnvalue() const
+                { return this->functor_->hasReturnvalue(); }
+            inline FunctionType::Value getType() const
+                { return this->functor_->getType(); }
+            inline const MultiType& getReturnvalue() const
+                { return this->functor_->getReturnvalue(); }
+            inline const std::string& getTypenameParam(unsigned int param) const
+                { return this->functor_->getTypenameParam(param); }
+            inline const std::string& getTypenameReturnvalue() const
+                { return this->functor_->getTypenameReturnvalue(); }
+
+            inline void setName(const std::string name)
+                { this->name_ = name; }
+            inline const std::string& getName() const
+                { return this->name_; }
+
+            Executor& setDefaultValues(const MultiType& param1);
+            Executor& setDefaultValues(const MultiType& param1, const MultiType& param2);
+            Executor& setDefaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3);
+            Executor& setDefaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4);
+            Executor& setDefaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5);
+            Executor& setDefaultValue(unsigned int index, const MultiType& param);
+
+            inline MultiType getDefaultValue(unsigned int index) const
+            {
+                if (index < MAX_FUNCTOR_ARGUMENTS)
+                    return this->defaultValue_[index];
+
+                return MT_Type::Null;
+            }
+
+            bool allDefaultValuesSet() const;
+            inline bool defaultValueSet(unsigned int index) const
+            {
+                if (index < MAX_FUNCTOR_ARGUMENTS)
+                    return this->bAddedDefaultValue_[index];
+
+                return false;
+            }
+
+        protected:
+            Functor* functor_;
+            std::string name_;
+            MultiType defaultValue_[MAX_FUNCTOR_ARGUMENTS];
+            bool bAddedDefaultValue_[MAX_FUNCTOR_ARGUMENTS];
+
+        private:
+            LanguageEntryLabel description_;
+            LanguageEntryLabel descriptionReturnvalue_;
+            LanguageEntryLabel descriptionParam_[MAX_FUNCTOR_ARGUMENTS];
+
+            bool bAddedDescription_;
+            bool bAddedDescriptionReturnvalue_;
+            bool bAddedDescriptionParam_[MAX_FUNCTOR_ARGUMENTS];
+    };
+
+    class _CoreExport ExecutorStatic : public Executor
+    {
+        public:
+            ExecutorStatic(FunctorStatic* functor, const std::string& name = "") : Executor(functor, name) {}
+            virtual ~ExecutorStatic() {}
+    };
+
+    template <class T>
+    class ExecutorMember : public Executor
+    {
+        public:
+            ExecutorMember(FunctorMember<T>* functor, const std::string& name = "") : Executor(functor, name) {}
+            virtual ~ExecutorMember() {}
+
+            using Executor::operator();
+
+            inline void operator()(T* object) const
+                { (*((FunctorMember<T>*)this->functor_))(object, this->defaultValue_[0], this->defaultValue_[1], this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(T* object, const MultiType& param1) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, this->defaultValue_[1], this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(T* object, const MultiType& param1, const MultiType& param2) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(T* object, const MultiType& param1, const MultiType& param2, const MultiType& param3) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, param3, this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(T* object, const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, param3, param4, this->defaultValue_[4]); }
+            inline void operator()(T* object, const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, param3, param4, param5); }
+
+
+            inline void operator()(const T* object) const
+                { (*((FunctorMember<T>*)this->functor_))(object, this->defaultValue_[0], this->defaultValue_[1], this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const T* object, const MultiType& param1) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, this->defaultValue_[1], this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const T* object, const MultiType& param1, const MultiType& param2) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, this->defaultValue_[2], this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const T* object, const MultiType& param1, const MultiType& param2, const MultiType& param3) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, param3, this->defaultValue_[3], this->defaultValue_[4]); }
+            inline void operator()(const T* object, const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, param3, param4, this->defaultValue_[4]); }
+            inline void operator()(const T* object, const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5) const
+                { (*((FunctorMember<T>*)this->functor_))(object, param1, param2, param3, param4, param5); }
+
+            inline void setObject(T* object) const
+                { ((FunctorMember<T>*)this->functor_)->setObject(object); }
+            inline void setObject(const T* object) const
+                { ((FunctorMember<T>*)this->functor_)->setObject(object); }
+
+            using Executor::parse;
+
+            bool parse(T* object, const std::string& params, const std::string& delimiter = " ") const
+            {
+                EXECUTOR_PARSE(object);
+            }
+
+            bool parse(const T* object, const std::string& params, const std::string& delimiter = " ") const
+            {
+                EXECUTOR_PARSE(object);
+            }
+    };
+
+    inline Executor* createExecutor(Functor* functor, const std::string& name = "")
+    {
+        return new Executor(functor, name);
+    }
+
+    template <class T>
+    inline ExecutorMember<T>* createExecutor(FunctorMember<T>* functor, const std::string& name = "")
+    {
+        return new ExecutorMember<T>(functor, name);
+    }
+
+    inline ExecutorStatic* createExecutor(FunctorStatic* functor, const std::string& name = "")
+    {
+        return new ExecutorStatic(functor, name);
+    }
+}
+
+#endif /* _Executor_H__ */
Index: /code/branches/libraries2/src/libraries/core/Factory.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Factory.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Factory.cc	(revision 5712)
@@ -0,0 +1,129 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the Factory class.
+*/
+
+#include "Factory.h"
+
+#include "util/Debug.h"
+#include "Identifier.h"
+#include "BaseObject.h"
+
+namespace orxonox
+{
+    /**
+        @brief Returns the Identifier with a given name.
+        @param name The name of the wanted Identifier
+        @return The Identifier
+    */
+    Identifier* Factory::getIdentifier(const std::string& name)
+    {
+        std::map<std::string, Identifier*>::const_iterator it = getFactoryPointer()->identifierStringMap_.find(name);
+        if (it != getFactoryPointer()->identifierStringMap_.end())
+            return it->second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns the Identifier with a given network ID.
+        @param id The network ID of the wanted Identifier
+        @return The Identifier
+    */
+    Identifier* Factory::getIdentifier(const uint32_t id)
+    {
+        std::map<uint32_t, Identifier*>::const_iterator it = getFactoryPointer()->identifierNetworkIDMap_.find(id);
+        if (it != getFactoryPointer()->identifierNetworkIDMap_.end())
+            return it->second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Adds a new Identifier to both maps.
+        @param name The name of the identifier
+        @param identifier The identifier to add
+    */
+    void Factory::add(const std::string& name, Identifier* identifier)
+    {
+        getFactoryPointer()->identifierStringMap_[name] = identifier;
+        getFactoryPointer()->identifierNetworkIDMap_[identifier->getNetworkID()] = identifier;
+    }
+
+    /**
+        @brief Removes the entry with the old network ID and adds a new one.
+        @param identifier The identifier to change
+        @param oldID The old networkID
+        @param newID The new networkID
+    */
+    void Factory::changeNetworkID(Identifier* identifier, const uint32_t oldID, const uint32_t newID)
+    {
+//        getFactoryPointer()->identifierNetworkIDMap_.erase(oldID);
+        getFactoryPointer()->identifierNetworkIDMap_[newID] = identifier;
+    }
+
+    /**
+        @brief Cleans the NetworkID map (needed on clients for correct initialization)
+    */
+    void Factory::cleanNetworkIDs()
+    {
+        getFactoryPointer()->identifierNetworkIDMap_.clear();
+    }
+
+    /**
+        @brief Creates the class-hierarchy by creating and destroying one object of each type.
+    */
+    void Factory::createClassHierarchy()
+    {
+        COUT(3) << "*** Factory: Create class-hierarchy" << std::endl;
+        std::map<std::string, Identifier*>::iterator it;
+        it = getFactoryPointer()->identifierStringMap_.begin();
+        (*getFactoryPointer()->identifierStringMap_.begin()).second->startCreatingHierarchy();
+        for (it = getFactoryPointer()->identifierStringMap_.begin(); it != getFactoryPointer()->identifierStringMap_.end(); ++it)
+        {
+            // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards.
+            BaseObject* temp = (*it).second->fabricate(0);
+            delete temp;
+        }
+        (*getFactoryPointer()->identifierStringMap_.begin()).second->stopCreatingHierarchy();
+        COUT(3) << "*** Factory: Finished class-hierarchy creation" << std::endl;
+    }
+
+    /**
+        @brief Ensures the Factory gets created in the right moment.
+        @return The Factory.
+    */
+    Factory* Factory::getFactoryPointer()
+    {
+      static Factory theOneAndOnlyFactoryInstance = Factory();
+      return &theOneAndOnlyFactoryInstance;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Factory.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Factory.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Factory.h	(revision 5712)
@@ -0,0 +1,101 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the Factory and the BaseFactory class.
+
+    The Factory is a singleton, containing two maps to map either the name or the network ID
+    of a class with the corresponding Identifier.
+
+    Usage:
+    ID(classname) or ID(networkID) returns the corresponding Identifier.
+
+
+    BaseObject is the parent of ClassFactory which is defined in ClassFactory.h.
+    It can't be defined in ClassFactory.h, because of circular dependencies.
+*/
+
+#ifndef _Factory_H__
+#define _Factory_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <string>
+
+namespace orxonox
+{
+    // ###############################
+    // ###         Factory         ###
+    // ###############################
+    //! The Factory is used to map the name or the network ID of a class with its Identifier.
+    class _CoreExport Factory
+    {
+        public:
+            static Identifier* getIdentifier(const std::string& name);
+            static Identifier* getIdentifier(const uint32_t id);
+            static void add(const std::string& name, Identifier* identifier);
+            static void changeNetworkID(Identifier* identifier, const uint32_t oldID, const uint32_t newID);
+            static void cleanNetworkIDs();
+            static void createClassHierarchy();
+
+            static Factory* getFactoryPointer();    // avoid overriding order problem in the static intialisation process
+
+            /** @brief Returns the factory-map. */
+            static const std::map<std::string, Identifier*>& getFacbtoryMap()
+                { return Factory::getFactoryPointer()->identifierStringMap_; }
+            /** @brief Returns the begin-iterator of the factory-map. */
+            static std::map<std::string, Identifier*>::const_iterator getFactoryMapBegin()
+                { return Factory::getFactoryPointer()->identifierStringMap_.begin(); }
+            /** @brief Returns the end-iterator of the factory-map. */
+            static std::map<std::string, Identifier*>::const_iterator getFactoryMapEnd()
+                { return Factory::getFactoryPointer()->identifierStringMap_.end(); }
+
+        private:
+            Factory() {}                            // don't create
+            Factory(const Factory& factory);        // don't copy
+            ~Factory() {}                           // don't delete
+
+            std::map<std::string, Identifier*> identifierStringMap_;            //!< The map, mapping the name with the Identifier
+            std::map<uint32_t, Identifier*> identifierNetworkIDMap_;        //!< The map, mapping the network ID with the Identifier
+    };
+
+    // ###############################
+    // ###       BaseFactory       ###
+    // ###############################
+    //! Base-class of ClassFactory. Has to be defined separate because of circular dependencies.
+    class _CoreExport BaseFactory
+    {
+        public:
+            virtual BaseObject* fabricate(BaseObject* creator) = 0;
+            virtual ~BaseFactory() {};
+    };
+}
+
+#endif /* _Factory_H__ */
Index: /code/branches/libraries2/src/libraries/core/Functor.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Functor.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Functor.h	(revision 5712)
@@ -0,0 +1,483 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ *   Inspiration: Functor by Benjamin Grauer
+ */
+
+#ifndef _Functor_H__
+#define _Functor_H__
+
+#include "CorePrereqs.h"
+
+#include "util/Debug.h"
+#include "util/MultiType.h"
+#include "util/StringUtils.h"
+
+namespace orxonox
+{
+    const unsigned int MAX_FUNCTOR_ARGUMENTS = 5;
+
+    namespace FunctionType
+    {
+        enum Value
+        {
+            Member,
+            ConstMember,
+            Static
+        };
+    }
+
+
+    template <class T>
+    inline std::string typeToString() { return "unknown"; }
+
+#define CreateTypeToStringTemplate(type) \
+    template <> \
+    inline std::string typeToString<type>() { return #type; } \
+    template <> \
+    inline std::string typeToString<type&>() { return #type; } \
+    template <> \
+    inline std::string typeToString<const type>() { return #type; } \
+    template <> \
+    inline std::string typeToString<const type&>() { return #type; }
+
+    CreateTypeToStringTemplate(int);
+    CreateTypeToStringTemplate(unsigned int);
+    CreateTypeToStringTemplate(char);
+    CreateTypeToStringTemplate(unsigned char);
+    CreateTypeToStringTemplate(short);
+    CreateTypeToStringTemplate(unsigned short);
+    CreateTypeToStringTemplate(long);
+    CreateTypeToStringTemplate(unsigned long);
+    CreateTypeToStringTemplate(long long);
+    CreateTypeToStringTemplate(unsigned long long);
+    CreateTypeToStringTemplate(float);
+    CreateTypeToStringTemplate(double);
+    CreateTypeToStringTemplate(long double);
+    CreateTypeToStringTemplate(bool);
+    CreateTypeToStringTemplate(Vector2);
+    CreateTypeToStringTemplate(Vector3);
+    CreateTypeToStringTemplate(Quaternion);
+    CreateTypeToStringTemplate(ColourValue);
+    CreateTypeToStringTemplate(Radian);
+    CreateTypeToStringTemplate(Degree);
+
+    template <>
+    inline std::string typeToString<std::string>() { return "string"; }
+    template <>
+    inline std::string typeToString<std::string&>() { return "string"; }
+    template <>
+    inline std::string typeToString<const std::string>() { return "string"; }
+    template <>
+    inline std::string typeToString<const std::string&>() { return "string"; }
+
+    class _CoreExport Functor
+    {
+        public:
+            Functor() {}
+            virtual ~Functor() {}
+
+            virtual void operator()(const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) = 0;
+
+            inline unsigned int getParamCount() const { return this->numParams_; }
+            inline bool hasReturnvalue() const { return this->hasReturnValue_; }
+            inline FunctionType::Value getType() const { return this->type_; }
+            inline const MultiType& getReturnvalue() const { return this->returnedValue_; }
+
+            const std::string& getTypenameParam(unsigned int param) const { return (param < 5) ? this->typeParam_[param] : BLANKSTRING; }
+            const std::string& getTypenameReturnvalue() const { return this->typeReturnvalue_; }
+
+            virtual void evaluateParam(unsigned int index, MultiType& param) const = 0;
+
+        protected:
+            unsigned int numParams_;
+            bool hasReturnValue_;
+            FunctionType::Value type_;
+            MultiType returnedValue_;
+
+            std::string typeReturnvalue_;
+            std::string typeParam_[MAX_FUNCTOR_ARGUMENTS];
+    };
+
+    class _CoreExport FunctorStatic : public Functor
+    {
+        public:
+            virtual ~FunctorStatic() {}
+            virtual void operator()(const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) = 0;
+    };
+
+    template <class T>
+    class FunctorMember : public Functor
+    {
+        public:
+            FunctorMember()
+            {
+                constObject_ = 0;
+                object_ = 0;
+                bConstObject_ = false;
+            }
+            virtual ~FunctorMember() {}
+
+            virtual void operator()(T* object, const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) = 0;
+            virtual void operator()(const T* object, const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) = 0;
+
+            virtual void operator()(const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null)
+            {
+                if (this->bConstObject_)
+                {
+                    if (this->constObject_)
+                        (*this)(this->constObject_, param1, param2, param3, param4, param5);
+                    else
+                    {
+                        COUT(1) << "An error occurred in Functor.h:" << std::endl;
+                        COUT(1) << "Error: No const object set." << std::endl;
+                    }
+                }
+                else
+                {
+                    if (this->object_)
+                        (*this)(this->object_, param1, param2, param3, param4, param5);
+                    else
+                    {
+                        COUT(1) << "An error occurred in Functor.h:" << std::endl;
+                        COUT(1) << "Error: No object set." << std::endl;
+                    }
+                }
+            }
+
+            FunctorMember<T>* setObject(T* object)
+            {
+                this->bConstObject_ = false;
+                this->object_ = object;
+                return this;
+            }
+
+            FunctorMember<T>* setObject(const T* object)
+            {
+                this->bConstObject_ = true;
+                this->constObject_ = object;
+                return this;
+            }
+
+        private:
+            const T* constObject_;
+            T* object_;
+            bool bConstObject_;
+    };
+
+
+
+#define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams
+#define FUNCTOR_TEMPLATE000
+#define FUNCTOR_TEMPLATE001 template <class P1>
+#define FUNCTOR_TEMPLATE002 template <class P1, class P2>
+#define FUNCTOR_TEMPLATE003 template <class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE004 template <class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE005 template <class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE010 template <class R>
+#define FUNCTOR_TEMPLATE011 template <class R, class P1>
+#define FUNCTOR_TEMPLATE012 template <class R, class P1, class P2>
+#define FUNCTOR_TEMPLATE013 template <class R, class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE014 template <class R, class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE015 template <class R, class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE100 template <class T>
+#define FUNCTOR_TEMPLATE101 template <class T, class P1>
+#define FUNCTOR_TEMPLATE102 template <class T, class P1, class P2>
+#define FUNCTOR_TEMPLATE103 template <class T, class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE104 template <class T, class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE105 template <class T, class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE110 template <class T, class R>
+#define FUNCTOR_TEMPLATE111 template <class T, class R, class P1>
+#define FUNCTOR_TEMPLATE112 template <class T, class R, class P1, class P2>
+#define FUNCTOR_TEMPLATE113 template <class T, class R, class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE114 template <class T, class R, class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE115 template <class T, class R, class P1, class P2, class P3, class P4, class P5>
+
+
+
+#define FUNCTOR_TEMPLATE_CLASSES(ismember, returnvalue, numparams) FUNCTOR_TEMPLATE_CLASSES##ismember##returnvalue##numparams
+#define FUNCTOR_TEMPLATE_CLASSES000
+#define FUNCTOR_TEMPLATE_CLASSES001 <P1>
+#define FUNCTOR_TEMPLATE_CLASSES002 <P1, P2>
+#define FUNCTOR_TEMPLATE_CLASSES003 <P1, P2, P3>
+#define FUNCTOR_TEMPLATE_CLASSES004 <P1, P2, P3, P4>
+#define FUNCTOR_TEMPLATE_CLASSES005 <P1, P2, P3, P4, P5>
+#define FUNCTOR_TEMPLATE_CLASSES010 <R>
+#define FUNCTOR_TEMPLATE_CLASSES011 <R, P1>
+#define FUNCTOR_TEMPLATE_CLASSES012 <R, P1, P2>
+#define FUNCTOR_TEMPLATE_CLASSES013 <R, P1, P2, P3>
+#define FUNCTOR_TEMPLATE_CLASSES014 <R, P1, P2, P3, P4>
+#define FUNCTOR_TEMPLATE_CLASSES015 <R, P1, P2, P3, P4, P5>
+#define FUNCTOR_TEMPLATE_CLASSES100 <T>
+#define FUNCTOR_TEMPLATE_CLASSES101 <T, P1>
+#define FUNCTOR_TEMPLATE_CLASSES102 <T, P1, P2>
+#define FUNCTOR_TEMPLATE_CLASSES103 <T, P1, P2, P3>
+#define FUNCTOR_TEMPLATE_CLASSES104 <T, P1, P2, P3, P4>
+#define FUNCTOR_TEMPLATE_CLASSES105 <T, P1, P2, P3, P4, P5>
+#define FUNCTOR_TEMPLATE_CLASSES110 <T, R>
+#define FUNCTOR_TEMPLATE_CLASSES111 <T, R, P1>
+#define FUNCTOR_TEMPLATE_CLASSES112 <T, R, P1, P2>
+#define FUNCTOR_TEMPLATE_CLASSES113 <T, R, P1, P2, P3>
+#define FUNCTOR_TEMPLATE_CLASSES114 <T, R, P1, P2, P3, P4>
+#define FUNCTOR_TEMPLATE_CLASSES115 <T, R, P1, P2, P3, P4, P5>
+
+
+
+#define FUNCTOR_TYPENAME_PARAMS(numparams) FUNCTOR_TYPENAME_PARAMS##numparams
+#define FUNCTOR_TYPENAME_PARAMS0
+#define FUNCTOR_TYPENAME_PARAMS1 this->typeParam_[0] = typeToString<P1>();
+#define FUNCTOR_TYPENAME_PARAMS2 this->typeParam_[0] = typeToString<P1>(); this->typeParam_[1] = typeToString<P2>();
+#define FUNCTOR_TYPENAME_PARAMS3 this->typeParam_[0] = typeToString<P1>(); this->typeParam_[1] = typeToString<P2>(); this->typeParam_[2] = typeToString<P3>();
+#define FUNCTOR_TYPENAME_PARAMS4 this->typeParam_[0] = typeToString<P1>(); this->typeParam_[1] = typeToString<P2>(); this->typeParam_[2] = typeToString<P3>(); this->typeParam_[3] = typeToString<P4>();
+#define FUNCTOR_TYPENAME_PARAMS5 this->typeParam_[0] = typeToString<P1>(); this->typeParam_[1] = typeToString<P2>(); this->typeParam_[2] = typeToString<P3>(); this->typeParam_[3] = typeToString<P4>(); this->typeParam_[4] = typeToString<P5>();
+
+#define FUNCTOR_TYPENAME_RETURN(returnvalue) FUNCTOR_TYPENAME_RETURN##returnvalue
+#define FUNCTOR_TYPENAME_RETURN0
+#define FUNCTOR_TYPENAME_RETURN1 this->typeReturnvalue_ = typeToString<R>();
+
+
+
+#define FUNCTOR_FUNCTION_PARAMS(numparams) FUNCTOR_FUNCTION_PARAMS##numparams
+#define FUNCTOR_FUNCTION_PARAMS0
+#define FUNCTOR_FUNCTION_PARAMS1 P1 param1
+#define FUNCTOR_FUNCTION_PARAMS2 P1 param1, P2 param2
+#define FUNCTOR_FUNCTION_PARAMS3 P1 param1, P2 param2, P3 param3
+#define FUNCTOR_FUNCTION_PARAMS4 P1 param1, P2 param2, P3 param3, P4 param4
+#define FUNCTOR_FUNCTION_PARAMS5 P1 param1, P2 param2, P3 param3, P4 param4, P5 param5
+
+#define FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) FUNCTOR_FUNCTION_RETURNVALUE##returnvalue
+#define FUNCTOR_FUNCTION_RETURNVALUE0 void
+#define FUNCTOR_FUNCTION_RETURNVALUE1 R
+
+
+
+#define FUNCTOR_FUNCTION_CALL(numparams) FUNCTOR_FUNCTION_CALL##numparams
+#define FUNCTOR_FUNCTION_CALL0
+#define FUNCTOR_FUNCTION_CALL1 param1
+#define FUNCTOR_FUNCTION_CALL2 param1, param2
+#define FUNCTOR_FUNCTION_CALL3 param1, param2, param3
+#define FUNCTOR_FUNCTION_CALL4 param1, param2, param3, param4
+#define FUNCTOR_FUNCTION_CALL5 param1, param2, param3, param4, param5
+
+#define FUNCTOR_STORE_RETURNVALUE(returnvalue, functioncall) FUNCTOR_STORE_RETURNVALUE##returnvalue(functioncall)
+#define FUNCTOR_STORE_RETURNVALUE0(functioncall) functioncall
+#define FUNCTOR_STORE_RETURNVALUE1(functioncall) this->returnedValue_ = functioncall
+
+
+
+#define FUNCTOR_EVALUATE_PARAM(numparams) FUNCTOR_EVALUATE_PARAM##numparams
+#define FUNCTOR_EVALUATE_PARAM0
+#define FUNCTOR_EVALUATE_PARAM1 \
+    if (index == 0) { param.convert<P1>(); }
+#define FUNCTOR_EVALUATE_PARAM2 \
+    if (index == 0) { param.convert<P1>(); } \
+    else if (index == 1) { param.convert<P2>(); }
+#define FUNCTOR_EVALUATE_PARAM3 \
+    if (index == 0) { param.convert<P1>(); } \
+    else if (index == 1) { param.convert<P2>(); } \
+    else if (index == 2) { param.convert<P3>(); }
+#define FUNCTOR_EVALUATE_PARAM4 \
+    if (index == 0) { param.convert<P1>(); } \
+    else if (index == 1) { param.convert<P2>(); } \
+    else if (index == 2) { param.convert<P3>(); } \
+    else if (index == 3) { param.convert<P4>(); }
+#define FUNCTOR_EVALUATE_PARAM5 \
+    if (index == 0) { param.convert<P1>(); } \
+    else if (index == 1) { param.convert<P2>(); } \
+    else if (index == 2) { param.convert<P3>(); } \
+    else if (index == 3) { param.convert<P4>(); } \
+    else if (index == 4) { param.convert<P5>(); }
+
+
+
+
+
+#define CREATE_STATIC_FUNCTOR(returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
+    class FunctorStatic##returnvalue##numparams : public FunctorStatic \
+    { \
+        public: \
+            FunctorStatic##returnvalue##numparams(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
+            { \
+                this->numParams_ = numparams; \
+                this->hasReturnValue_ = returnvalue; \
+                this->type_ = FunctionType::Static; \
+                this->functionPointer_ = functionPointer; \
+                \
+                FUNCTOR_TYPENAME_PARAMS(numparams); \
+                FUNCTOR_TYPENAME_RETURN(returnvalue); \
+            } \
+    \
+            void operator()(const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) \
+            { \
+                FUNCTOR_STORE_RETURNVALUE(returnvalue, (*this->functionPointer_)(FUNCTOR_FUNCTION_CALL(numparams))); \
+            } \
+    \
+            virtual void evaluateParam(unsigned int index, MultiType& param) const \
+            { \
+                FUNCTOR_EVALUATE_PARAM(numparams); \
+            } \
+    \
+        private: \
+            FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (*functionPointer_)(FUNCTOR_FUNCTION_PARAMS(numparams)); \
+    }; \
+    \
+    \
+    FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
+    inline FunctorStatic##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(0, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
+    { \
+        return new FunctorStatic##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(0, returnvalue, numparams) (functionPointer); \
+    }
+
+
+
+
+
+#define CREATE_MEMBER_FUNCTOR(returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    class FunctorMember##returnvalue##numparams : public FunctorMember<T> \
+    { \
+        public: \
+            FunctorMember##returnvalue##numparams(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
+            { \
+                this->numParams_ = numparams; \
+                this->hasReturnValue_ = returnvalue; \
+                this->type_ = FunctionType::Member; \
+                this->functionPointer_ = functionPointer; \
+            } \
+    \
+            void operator()(T* object, const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) \
+            { \
+                FUNCTOR_STORE_RETURNVALUE(returnvalue, (*object.*this->functionPointer_)(FUNCTOR_FUNCTION_CALL(numparams))); \
+            } \
+    \
+            void operator()(const T* object, const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) \
+            { \
+                COUT(1) << "An error occurred in Functor.h:" << std::endl; \
+                COUT(1) << "Error: Function is not const." << std::endl; \
+            } \
+    \
+            virtual void evaluateParam(unsigned int index, MultiType& param) const \
+            { \
+                FUNCTOR_EVALUATE_PARAM(numparams); \
+            } \
+    \
+        private: \
+            FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer_)(FUNCTOR_FUNCTION_PARAMS(numparams)); \
+    }; \
+    \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    class FunctorConstMember##returnvalue##numparams : public FunctorMember<T> \
+    { \
+        public: \
+            FunctorConstMember##returnvalue##numparams(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const) \
+            { \
+                this->numParams_ = numparams; \
+                this->hasReturnValue_ = returnvalue; \
+                this->type_ = FunctionType::ConstMember; \
+                this->functionPointer_ = functionPointer; \
+            } \
+    \
+            void operator()(T* object, const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) \
+            { \
+                FUNCTOR_STORE_RETURNVALUE(returnvalue, (*object.*this->functionPointer_)(FUNCTOR_FUNCTION_CALL(numparams))); \
+            } \
+    \
+            void operator()(const T* object, const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null) \
+            { \
+                FUNCTOR_STORE_RETURNVALUE(returnvalue, (*object.*this->functionPointer_)(FUNCTOR_FUNCTION_CALL(numparams))); \
+            } \
+    \
+            virtual void evaluateParam(unsigned int index, MultiType& param) const \
+            { \
+                FUNCTOR_EVALUATE_PARAM(numparams); \
+            } \
+    \
+        private: \
+            FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer_)(FUNCTOR_FUNCTION_PARAMS(numparams)) const; \
+    }; \
+    \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
+    { \
+        return new FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+    } \
+    \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const) \
+    { \
+        return new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+    }
+
+
+// disable annoying warning about forcing value to boolean
+#ifdef ORXONOX_COMPILER_MSVC
+#pragma warning(push)
+#pragma warning(disable:4100 4800)
+#endif
+
+#define CREATE_ALL_STATIC_FUNCTORS() \
+    CREATE_STATIC_FUNCTOR(0, 0); \
+    CREATE_STATIC_FUNCTOR(0, 1); \
+    CREATE_STATIC_FUNCTOR(0, 2); \
+    CREATE_STATIC_FUNCTOR(0, 3); \
+    CREATE_STATIC_FUNCTOR(0, 4); \
+    CREATE_STATIC_FUNCTOR(0, 5); \
+    CREATE_STATIC_FUNCTOR(1, 0); \
+    CREATE_STATIC_FUNCTOR(1, 1); \
+    CREATE_STATIC_FUNCTOR(1, 2); \
+    CREATE_STATIC_FUNCTOR(1, 3); \
+    CREATE_STATIC_FUNCTOR(1, 4); \
+    CREATE_STATIC_FUNCTOR(1, 5)
+
+
+#define CREATE_ALL_MEMBER_FUNCTORS() \
+    CREATE_MEMBER_FUNCTOR(0, 0); \
+    CREATE_MEMBER_FUNCTOR(0, 1); \
+    CREATE_MEMBER_FUNCTOR(0, 2); \
+    CREATE_MEMBER_FUNCTOR(0, 3); \
+    CREATE_MEMBER_FUNCTOR(0, 4); \
+    CREATE_MEMBER_FUNCTOR(0, 5); \
+    CREATE_MEMBER_FUNCTOR(1, 0); \
+    CREATE_MEMBER_FUNCTOR(1, 1); \
+    CREATE_MEMBER_FUNCTOR(1, 2); \
+    CREATE_MEMBER_FUNCTOR(1, 3); \
+    CREATE_MEMBER_FUNCTOR(1, 4); \
+    CREATE_MEMBER_FUNCTOR(1, 5)
+
+
+    CREATE_ALL_STATIC_FUNCTORS();
+    CREATE_ALL_MEMBER_FUNCTORS();
+}
+
+#ifdef ORXONOX_COMPILER_MSVC
+#pragma warning(pop)
+#endif
+
+#endif /* _Functor_H__ */
Index: /code/branches/libraries2/src/libraries/core/GUIManager.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/GUIManager.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GUIManager.cc	(revision 5712)
@@ -0,0 +1,304 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *      Benjamin Knecht
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "GUIManager.h"
+
+#include <memory>
+extern "C" {
+#include <lua.h>
+}
+#include <CEGUIDefaultLogger.h>
+#include <CEGUIExceptions.h>
+#include <CEGUIInputEvent.h>
+#include <CEGUIMouseCursor.h>
+#include <CEGUIResourceProvider.h>
+#include <CEGUISystem.h>
+#include <ogreceguirenderer/OgreCEGUIRenderer.h>
+
+#include "SpecialConfig.h" // Configures the macro below
+#ifdef CEGUILUA_USE_INTERNAL_LIBRARY
+#   include <ceguilua/CEGUILua.h>
+#else
+#   include <CEGUILua.h>
+#endif
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/OrxAssert.h"
+#include "Core.h"
+#include "Clock.h"
+#include "LuaState.h"
+#include "Resource.h"
+
+namespace orxonox
+{
+    class CEGUILogger : public CEGUI::DefaultLogger
+    {
+    public:
+	    void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
+        {
+            int orxonoxLevel = CEGUI::Standard;
+            switch (level)
+            {
+                case CEGUI::Errors:      orxonoxLevel = 1; break;
+                case CEGUI::Warnings:    orxonoxLevel = 2; break;
+                case CEGUI::Standard:    orxonoxLevel = 4; break;
+                case CEGUI::Informative: orxonoxLevel = 5; break;
+                case CEGUI::Insane:      orxonoxLevel = 6; break;
+                default: OrxAssert(false, "CEGUI log level out of range, inpect immediately!");
+            }
+            OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
+                << "CEGUI: " << message << std::endl;
+
+            CEGUI::DefaultLogger::logEvent(message, level);
+        }
+    };
+
+    static CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button);
+
+    GUIManager* GUIManager::singletonPtr_s = 0;
+
+    /**
+    @brief
+        Constructs the GUIManager by starting up CEGUI
+
+        Creates the interface to Ogre, sets up the CEGUI renderer and the Lua script module together with the Lua engine.
+        The log is set up and connected to the CEGUILogger.
+        After Lua setup tolua++-elements are linked to Lua-state to give Lua access to C++-code.
+        Finally initial Lua code is executed (maybe we can do this with the CEGUI startup script automatically).
+    @param renderWindow
+        Ogre's render window. Without this, the GUI cannot be displayed.
+    @return true if success, otherwise false
+    */
+    GUIManager::GUIManager(Ogre::RenderWindow* renderWindow, const std::pair<int, int>& mousePosition, bool bFullScreen)
+        : renderWindow_(renderWindow)
+        , resourceProvider_(0)
+    {
+        using namespace CEGUI;
+
+        COUT(3) << "Initialising CEGUI." << std::endl;
+
+        // Note: No SceneManager specified yet
+        guiRenderer_.reset(new OgreCEGUIRenderer(renderWindow_, Ogre::RENDER_QUEUE_OVERLAY, false, 3000));
+        resourceProvider_ = guiRenderer_->createResourceProvider();
+        resourceProvider_->setDefaultResourceGroup("GUI");
+
+        // setup scripting
+        luaState_.reset(new LuaState());
+        scriptModule_.reset(new LuaScriptModule(luaState_->getInternalLuaState()));
+
+        // Create our own logger to specify the filepath
+        std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
+        ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
+        // set the log level according to ours (translate by subtracting 1)
+        ceguiLogger->setLoggingLevel(
+            static_cast<LoggingLevel>(Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));
+        this->ceguiLogger_ = ceguiLogger.release();
+
+        // create the CEGUI system singleton
+        guiSystem_.reset(new System(guiRenderer_.get(), resourceProvider_, 0, scriptModule_.get()));
+
+        // Initialise the basic lua code
+        rootFileInfo_ = Resource::getInfo("InitialiseGUI.lua", "GUI");
+        this->luaState_->doFile("InitialiseGUI.lua", "GUI", false);
+
+        // Align CEGUI mouse with OIS mouse
+        guiSystem_->injectMousePosition(mousePosition.first, mousePosition.second);
+
+        // Hide the mouse cursor unless playing in fullscreen mode
+        if (!bFullScreen)
+            CEGUI::MouseCursor::getSingleton().hide();
+    }
+
+    /**
+    @brief
+        Basically shuts down CEGUI (member smart pointers) but first unloads our Tolua modules.
+    */
+    GUIManager::~GUIManager()
+    {
+    }
+
+    /**
+    @brief
+        used to tick the GUI
+    @param time
+        clock which provides time value for the GUI System
+
+        Ticking the GUI means updating it with a certain regularity.
+        The elapsed time since the last call is given in the time value provided by the clock.
+        This time value is then used to provide a fluent animation of the GUI.
+    */
+    void GUIManager::update(const Clock& time)
+    {
+        assert(guiSystem_);
+        guiSystem_->injectTimePulse(time.getDeltaTime());
+    }
+
+    /**
+    @brief
+        Tells the GUIManager which SceneManager to use
+    @param camera
+        The current camera on which the GUI should be displayed on.
+
+        In fact the GUIManager needs the SceneManager and not the Camera to display the GUI.
+        This means the GUI is not bound to a camera but rather to the SceneManager.
+        Hiding the GUI when needed can therefore not be resolved by just NOT setting the current camera.
+    */
+    void GUIManager::setCamera(Ogre::Camera* camera)
+    {
+        if (camera == NULL)
+            this->guiRenderer_->setTargetSceneManager(0);
+        else
+            this->guiRenderer_->setTargetSceneManager(camera->getSceneManager());
+    }
+
+    /**
+    @brief
+        Executes Lua code
+    @param str
+        reference to string object holding the Lua code which is to be executed
+
+        This function gives total access to the GUI. You can execute ANY Lua code here.
+    */
+    void GUIManager::executeCode(const std::string& str)
+    {
+        this->luaState_->doString(str, rootFileInfo_);
+    }
+
+    /**
+    @brief
+        Displays specified GUI on screen
+    @param name
+        The name of the GUI
+
+        The function executes the Lua function with the same name in case the GUIManager is ready.
+        For more details check out loadGUI_2.lua where the function presides.
+    */
+    void GUIManager::showGUI(const std::string& name)
+    {
+        this->luaState_->doString("showGUI(\"" + name + "\")", rootFileInfo_);
+    }
+
+    void GUIManager::keyPressed(const KeyEvent& evt)
+    {
+        guiSystem_->injectKeyDown(evt.getKeyCode());
+        guiSystem_->injectChar(evt.getText());
+    }
+    void GUIManager::keyReleased(const KeyEvent& evt)
+    {
+        guiSystem_->injectKeyUp(evt.getKeyCode());
+    }
+
+    /**
+    @brief
+        Function receiving a mouse button pressed event.
+    @param id
+        ID of the mouse button which got pressed
+
+        This function is inherited by MouseHandler and injects the event into CEGUI.
+        It is for CEGUI to process the event.
+    */
+    void GUIManager::buttonPressed(MouseButtonCode::ByEnum id)
+    {
+        try
+        {
+            guiSystem_->injectMouseButtonDown(convertButton(id));
+        }
+        catch (CEGUI::ScriptException& ex)
+        {
+            // We simply ignore the exception and proceed
+            COUT(1) << ex.getMessage() << std::endl;
+        }
+    }
+
+    /**
+    @brief
+        Function receiving a mouse button released event.
+    @param id
+        ID of the mouse button which got released
+
+        This function is inherited by MouseHandler and injects the event into CEGUI.
+        It is for CEGUI to process the event.
+    */
+    void GUIManager::buttonReleased(MouseButtonCode::ByEnum id)
+    {
+        try
+        {
+            guiSystem_->injectMouseButtonUp(convertButton(id));
+        }
+        catch (CEGUI::ScriptException& ex)
+        {
+            // We simply ignore the exception and proceed
+            COUT(1) << ex.getMessage() << std::endl;
+        }
+    }
+
+    void GUIManager::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
+    {
+        guiSystem_->injectMousePosition(static_cast<float>(abs.x), static_cast<float>(abs.y));
+    }
+    void GUIManager::mouseScrolled(int abs, int rel)
+    {
+        guiSystem_->injectMouseWheelChange(static_cast<float>(rel));
+    }
+
+    /**
+    @brief
+        converts mouse event code to CEGUI event code
+    @param button
+        code of the mouse button as we use it in Orxonox
+    @return
+        code of the mouse button as it is used by CEGUI
+
+        Simple convertion from mouse event code in Orxonox to the one used in CEGUI.
+     */
+    static inline CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button)
+    {
+        switch (button)
+        {
+        case MouseButtonCode::Left:
+            return CEGUI::LeftButton;
+
+        case MouseButtonCode::Right:
+            return CEGUI::RightButton;
+
+        case MouseButtonCode::Middle:
+            return CEGUI::MiddleButton;
+
+        case MouseButtonCode::Button3:
+            return CEGUI::X1Button;
+
+        case MouseButtonCode::Button4:
+            return CEGUI::X2Button;
+
+        default:
+            return CEGUI::NoButton;
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/GUIManager.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/GUIManager.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GUIManager.h	(revision 5712)
@@ -0,0 +1,109 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *      Benjamin Knecht
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _GUIManager_H__
+#define _GUIManager_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <string>
+#include <CEGUIForwardRefs.h>
+#include <boost/scoped_ptr.hpp>
+#include <boost/shared_ptr.hpp>
+
+#include "util/OgreForwardRefs.h"
+#include "util/Singleton.h"
+#include "input/InputHandler.h"
+
+namespace orxonox
+{
+    class PlayerInfo; // Forward declaration
+
+    /**
+    @class GUIManager
+    @brief
+        Provides a simple interface to CEGUI with tolua methods and console commands. It also acts as a key and mouse handler.
+
+        The GUIManager is a singleton and can be called anywhere when access on the GUI is needed.
+        Creation of the GUIManager is therefore not possible and the cunstructor is private.
+
+        Since the GUI needs user input, the GUIManager implements the functions needed to act as a key and/or mouse handler.
+        Those input events are then injected into CEGUI in Lua.
+    */
+    class _CoreExport GUIManager : public Singleton<GUIManager>, public InputHandler
+    {
+        friend class Singleton<GUIManager>;
+    public:
+        GUIManager(Ogre::RenderWindow* renderWindow, const std::pair<int, int>& mousePosition, bool bFullScreen);
+        ~GUIManager();
+
+        void update(const Clock& time);
+
+        void showGUI(const std::string& name);
+        void executeCode(const std::string& str);
+
+        void setCamera(Ogre::Camera* camera);
+
+        static GUIManager* getInstancePtr() { return singletonPtr_s; }
+
+        inline void setPlayer(const std::string& guiname, PlayerInfo* player)
+            { this->players_[guiname] = player; }
+        inline PlayerInfo* getPlayer(const std::string& guiname) const
+            { std::map<std::string, PlayerInfo*>::const_iterator it = this->players_.find(guiname); return (it != this->players_.end()) ? it->second : 0; }
+
+    private:
+        GUIManager(const GUIManager& instance); //!< private and undefined copy c'tor (this is a singleton class)
+
+        // keyHandler functions
+        void keyPressed (const KeyEvent& evt);
+        void keyReleased(const KeyEvent& evt);
+
+        // mouseHandler functions
+        void buttonPressed (MouseButtonCode::ByEnum id);
+        void buttonReleased(MouseButtonCode::ByEnum id);
+        void mouseMoved    (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
+        void mouseScrolled (int abs, int rel);
+
+        scoped_ptr<CEGUI::OgreCEGUIRenderer> guiRenderer_;      //!< CEGUI's interface to the Ogre Engine
+        scoped_ptr<LuaState>                 luaState_;         //!< LuaState, access point to the Lua engine
+        scoped_ptr<CEGUI::LuaScriptModule>   scriptModule_;     //!< CEGUI's script module to use Lua
+        scoped_ptr<CEGUI::System>            guiSystem_;        //!< CEGUI's main system
+        shared_ptr<ResourceInfo>             rootFileInfo_;     //!< Resource information about the root script
+        Ogre::RenderWindow*                  renderWindow_;     //!< Ogre's render window to give CEGUI access to it
+        CEGUI::ResourceProvider*             resourceProvider_; //!< CEGUI's resource provider
+        CEGUI::Logger*                       ceguiLogger_;      //!< CEGUI's logger to be able to log CEGUI errors in our log
+        std::map<std::string, PlayerInfo*>   players_;          //!< Stores the player (owner) for each gui
+
+        static GUIManager*                   singletonPtr_s;    //!< Singleton reference to GUIManager
+
+    };
+}
+
+#endif /* _GUIManager_H__ */
Index: /code/branches/libraries2/src/libraries/core/Game.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Game.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Game.cc	(revision 5712)
@@ -0,0 +1,645 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the Game class.
+*/
+
+#include "Game.h"
+
+#include <exception>
+#include <boost/weak_ptr.hpp>
+#include <CEGUIExceptions.h>
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/ScopeGuard.h"
+#include "util/Sleep.h"
+#include "util/SubString.h"
+#include "Clock.h"
+#include "CommandLine.h"
+#include "ConsoleCommand.h"
+#include "Core.h"
+#include "CoreIncludes.h"
+#include "ConfigValueIncludes.h"
+#include "GameMode.h"
+#include "GameState.h"
+
+namespace orxonox
+{
+    static void stop_game()
+        { Game::getInstance().stop(); }
+    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
+
+    std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
+    Game* Game::singletonPtr_s = 0;
+
+
+    /**
+    @brief
+        Represents one node of the game state tree.
+    */
+    struct GameStateTreeNode
+    {
+        std::string name_;
+        weak_ptr<GameStateTreeNode> parent_;
+        std::vector<shared_ptr<GameStateTreeNode> > children_;
+    };
+
+
+    /**
+    @brief
+        Another helper class for the Game singleton: we cannot derive
+        Game from OrxonoxClass because we need to handle the Identifier
+        destruction in the Core destructor.
+    */
+    class GameConfiguration : public OrxonoxClass
+    {
+    public:
+        GameConfiguration()
+        {
+            RegisterRootObject(GameConfiguration);
+            this->setConfigValues();
+        }
+
+        void setConfigValues()
+        {
+            SetConfigValue(statisticsRefreshCycle_, 250000)
+                .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
+            SetConfigValue(statisticsAvgLength_, 1000000)
+                .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
+            SetConfigValue(fpsLimit_, 50)
+                .description("Sets the desired framerate (0 for no limit).");
+        }
+
+        unsigned int statisticsRefreshCycle_;
+        unsigned int statisticsAvgLength_;
+        unsigned int fpsLimit_;
+    };
+
+
+    /**
+    @brief
+        Non-initialising constructor.
+    */
+    Game::Game(const std::string& cmdLine)
+        // Destroy factories before the Core!
+        : gsFactoryDestroyer_(Game::GameStateFactory::factories_s, &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
+    {
+        this->bAbort_ = false;
+        bChangingState_ = false;
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+        minimumSleepTime_ = 1000/*us*/;
+#else
+        minimumSleepTime_ = 0/*us*/;
+#endif
+
+        // Create an empty root state
+        this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
+
+        // Set up a basic clock to keep time
+        this->gameClock_.reset(new Clock());
+
+        // Create the Core
+        this->core_.reset(new Core(cmdLine));
+
+        // After the core has been created, we can safely instantiate the GameStates that don't require graphics
+        for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
+            it != gameStateDeclarations_s.end(); ++it)
+        {
+            if (!it->second.bGraphicsMode)
+                constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second);
+        }
+
+        // The empty root state is ALWAYS loaded!
+        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
+        this->rootStateNode_->name_ = "emptyRootGameState";
+        this->loadedTopStateNode_ = this->rootStateNode_;
+        this->loadedStates_.push_back(this->getState(rootStateNode_->name_));
+
+        // Do this after the Core creation!
+        this->configuration_.reset(new GameConfiguration());
+    }
+
+    /**
+    @brief
+        All destruction code is handled by scoped_ptrs and SimpleScopeGuards.
+    */
+    Game::~Game()
+    {
+    }
+
+    /**
+    @brief
+        Main loop of the orxonox game.
+    @note
+        We use the Ogre::Timer to measure time since it uses the most precise
+        method an any platform (however the windows timer lacks time when under
+        heavy kernel load!).
+    */
+    void Game::run()
+    {
+        if (this->requestedStateNodes_.empty())
+            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
+
+        // reset statistics
+        this->statisticsStartTime_ = 0;
+        this->statisticsTickTimes_.clear();
+        this->periodTickTime_ = 0;
+        this->periodTime_ = 0;
+        this->avgFPS_ = 0.0f;
+        this->avgTickTime_ = 0.0f;
+        this->excessSleepTime_ = 0;
+
+        // START GAME
+        // first delta time should be about 0 seconds
+        this->gameClock_->capture();
+        // A first item is required for the fps limiter
+        StatisticsTickInfo tickInfo = {0, 0};
+        statisticsTickTimes_.push_back(tickInfo);
+        while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0))
+        {
+            // Generate the dt
+            this->gameClock_->capture();
+
+            // Statistics init
+            StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
+            statisticsTickTimes_.push_back(tickInfo);
+            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
+
+            // Update the GameState stack if required
+            this->updateGameStateStack();
+
+            // Core preUpdate (doesn't throw)
+            try
+                { this->core_->preUpdate(*this->gameClock_); }
+            catch (...)
+            {
+                COUT(0) << "An exception occurred in the Core preUpdate: " << Game::getExceptionMessage() << std::endl;
+                COUT(0) << "This should really never happen! Closing the program." << std::endl;
+                this->stop();
+                break;
+            }
+
+            // Update the GameStates bottom up in the stack
+            this->updateGameStates();
+
+            // Core postUpdate (doesn't throw)
+            try
+                { this->core_->postUpdate(*this->gameClock_); }
+            catch (...)
+            {
+            COUT(0) << "An exception occurred in the Core postUpdate: " << Game::getExceptionMessage() << std::endl;
+            COUT(0) << "This should really never happen! Closing the program." << std::endl;
+                this->stop();
+                break;
+            }
+
+            // Evaluate statistics
+            this->updateStatistics();
+
+            // Limit framerate
+            this->updateFPSLimiter();
+        }
+
+        // UNLOAD all remaining states
+        while (this->loadedStates_.size() > 1)
+            this->unloadState(this->loadedStates_.back()->getName());
+        this->loadedTopStateNode_ = this->rootStateNode_;
+        this->requestedStateNodes_.clear();
+    }
+
+    void Game::updateGameStateStack()
+    {
+        while (this->requestedStateNodes_.size() > 0)
+        {
+            shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
+            assert(this->loadedTopStateNode_);
+            if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock())
+                this->unloadState(loadedTopStateNode_->name_);
+            else // has to be child
+            {
+                try
+                {
+                    this->loadState(requestedStateNode->name_);
+                }
+                catch (...)
+                {
+                    COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << Game::getExceptionMessage() << std::endl;
+                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
+                    if (this->requestedStateNodes_.size() > 1)
+                        COUT(4) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
+                    this->requestedStateNodes_.clear();
+                    break;
+                }
+            }
+            this->loadedTopStateNode_ = requestedStateNode;
+            this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
+        }
+    }
+
+    void Game::updateGameStates()
+    {
+        // Note: The first element is the empty root state, which doesn't need ticking
+        for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1;
+            it != this->loadedStates_.end(); ++it)
+        {
+            try
+            {
+                // Add tick time for most of the states
+                uint64_t timeBeforeTick = 0;
+                if ((*it)->getInfo().bIgnoreTickTime)
+                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
+                (*it)->update(*this->gameClock_);
+                if ((*it)->getInfo().bIgnoreTickTime)
+                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
+            }
+            catch (...)
+            {
+                COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << Game::getExceptionMessage() << std::endl;
+                COUT(1) << "This should really never happen!" << std::endl;
+                COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
+                shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_;
+                while (current->name_ != (*it)->getName() && current)
+                    current = current->parent_.lock();
+                if (current && current->parent_.lock())
+                    this->requestState(current->parent_.lock()->name_);
+                else
+                    this->stop();
+                break;
+            }
+        }
+    }
+
+    void Game::updateStatistics()
+    {
+        // Add the tick time of this frame (rendering time has already been subtracted)
+        uint64_t currentTime = gameClock_->getMicroseconds();
+        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
+        this->statisticsTickTimes_.back().tickLength += currentRealTime - currentTime;
+        this->periodTickTime_ += currentRealTime - currentTime;
+        if (this->periodTime_ > this->configuration_->statisticsRefreshCycle_)
+        {
+            std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
+            assert(it != this->statisticsTickTimes_.end());
+            int64_t lastTime = currentTime - this->configuration_->statisticsAvgLength_;
+            if (static_cast<int64_t>(it->tickTime) < lastTime)
+            {
+                do
+                {
+                    assert(this->periodTickTime_ >= it->tickLength);
+                    this->periodTickTime_ -= it->tickLength;
+                    ++it;
+                    assert(it != this->statisticsTickTimes_.end());
+                } while (static_cast<int64_t>(it->tickTime) < lastTime);
+                this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
+            }
+
+            uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
+            this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
+            this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
+
+            this->periodTime_ -= this->configuration_->statisticsRefreshCycle_;
+        }
+    }
+
+    void Game::updateFPSLimiter()
+    {
+        // Why configuration_->fpsLimit_ - 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too high
+        uint32_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / (configuration_->fpsLimit_ - 1));
+        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
+        while (currentRealTime < nextTime - minimumSleepTime_)
+        {
+            usleep(nextTime - currentRealTime);
+            currentRealTime = gameClock_->getRealMicroseconds();
+        }
+        // Integrate excess to avoid steady state error
+        excessSleepTime_ = currentRealTime - nextTime;
+        // Anti windup
+        if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long
+            excessSleepTime_ = 50000;
+    }
+
+    void Game::stop()
+    {
+        this->bAbort_ = true;
+    }
+
+    void Game::subtractTickTime(int32_t length)
+    {
+        assert(!this->statisticsTickTimes_.empty());
+        this->statisticsTickTimes_.back().tickLength -= length;
+        this->periodTickTime_ -= length;
+    }
+
+
+    /***** GameState related *****/
+
+    void Game::requestState(const std::string& name)
+    {
+        if (!this->checkState(name))
+        {
+            COUT(2) << "Warning: GameState named '" << name << "' doesn't exist!" << std::endl;
+            return;
+        }
+
+        if (this->bChangingState_)
+        {
+            COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
+            return;
+        }
+
+        shared_ptr<GameStateTreeNode> lastRequestedNode;
+        if (this->requestedStateNodes_.empty())
+            lastRequestedNode = this->loadedTopStateNode_;
+        else
+            lastRequestedNode = this->requestedStateNodes_.back();
+        if (name == lastRequestedNode->name_)
+        {
+            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
+            return;
+        }
+
+        // Check children first
+        std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
+        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
+        {
+            if (lastRequestedNode->children_[i]->name_ == name)
+            {
+                requestedNodes.push_back(lastRequestedNode->children_[i]);
+                break;
+            }
+        }
+
+        if (requestedNodes.empty())
+        {
+            // Check parent and all its grand parents
+            shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
+            while (currentNode != NULL)
+            {
+                if (currentNode->name_ == name)
+                    break;
+                currentNode = currentNode->parent_.lock();
+                requestedNodes.push_back(currentNode);
+            }
+        }
+
+        if (requestedNodes.empty())
+            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
+        else
+            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
+    }
+
+    void Game::requestStates(const std::string& names)
+    {
+        SubString tokens(names, ",;", " ");
+        for (unsigned int i = 0; i < tokens.size(); ++i)
+            this->requestState(tokens[i]);
+    }
+
+    void Game::popState()
+    {
+        shared_ptr<GameStateTreeNode> lastRequestedNode;
+        if (this->requestedStateNodes_.empty())
+            lastRequestedNode = this->loadedTopStateNode_;
+        else
+            lastRequestedNode = this->requestedStateNodes_.back();
+        if (lastRequestedNode != this->rootStateNode_)
+            this->requestState(lastRequestedNode->parent_.lock()->name_);
+        else
+            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
+    }
+
+    shared_ptr<GameState> Game::getState(const std::string& name)
+    {
+        GameStateMap::const_iterator it = constructedStates_.find(name);
+        if (it != constructedStates_.end())
+            return it->second;
+        else
+        {
+            std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
+            if (it != gameStateDeclarations_s.end())
+                COUT(1) << "Error: GameState '" << name << "' has not yet been loaded." << std::endl;
+            else
+                COUT(1) << "Error: Could not find GameState '" << name << "'." << std::endl;
+            return shared_ptr<GameState>();
+        }
+    }
+
+    void Game::setStateHierarchy(const std::string& str)
+    {
+        // Split string into pieces of the form whitespacesText
+        std::vector<std::pair<std::string, unsigned> > stateStrings;
+        size_t pos = 0;
+        size_t startPos = 0;
+        while (pos < str.size())
+        {
+            unsigned indentation = 0;
+            while(pos < str.size() && str[pos] == ' ')
+                ++indentation, ++pos;
+            startPos = pos;
+            while(pos < str.size() && str[pos] != ' ')
+                ++pos;
+            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
+        }
+        unsigned int currentLevel = 0;
+        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
+        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
+        {
+            std::string newStateName = it->first;
+            unsigned newLevel = it->second + 1; // empty root is 0
+            if (!this->checkState(newStateName))
+                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
+            if (newStateName == this->rootStateNode_->name_)
+                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
+            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
+            newNode->name_ = newStateName;
+
+            if (newLevel <= currentLevel)
+            {
+                do
+                    currentNode = currentNode->parent_.lock();
+                while (newLevel <= --currentLevel);
+            }
+            if (newLevel == currentLevel + 1)
+            {
+                // Add the child
+                newNode->parent_ = currentNode;
+                currentNode->children_.push_back(newNode);
+            }
+            else
+                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
+            currentNode = newNode;
+            currentLevel = newLevel;
+        }
+    }
+
+    /*** Internal ***/
+
+    void Game::loadGraphics()
+    {
+        if (!GameMode::bShowsGraphics_s)
+        {
+            core_->loadGraphics();
+            Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
+            GameMode::bShowsGraphics_s = true;
+
+            // Construct all the GameStates that require graphics
+            for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
+                it != gameStateDeclarations_s.end(); ++it)
+            {
+                if (it->second.bGraphicsMode)
+                {
+                    // Game state loading failure is serious --> don't catch
+                    shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second);
+                    if (!constructedStates_.insert(std::make_pair(
+                        it->second.stateName, gameState)).second)
+                        assert(false); // GameState was already created!
+                }
+            }
+            graphicsUnloader.Dismiss();
+        }
+    }
+
+    void Game::unloadGraphics()
+    {
+        if (GameMode::bShowsGraphics_s)
+        {
+            // Destroy all the GameStates that require graphics
+            for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();)
+            {
+                if (it->second->getInfo().bGraphicsMode)
+                    constructedStates_.erase(it++);
+                else
+                    ++it;
+            }
+
+            core_->unloadGraphics();
+            GameMode::bShowsGraphics_s = false;
+        }
+    }
+
+    bool Game::checkState(const std::string& name) const
+    {
+        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
+        if (it == gameStateDeclarations_s.end())
+            return false;
+        else
+            return true;
+    }
+
+    void Game::loadState(const std::string& name)
+    {
+        this->bChangingState_ = true;
+        LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState);
+
+        // If state requires graphics, load it
+        Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
+        if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics())
+            this->loadGraphics();
+        else
+            graphicsUnloader.Dismiss();
+
+        shared_ptr<GameState> state = this->getState(name);
+        state->activate();
+        if (!this->loadedStates_.empty())
+            this->loadedStates_.back()->activity_.topState = false;
+        this->loadedStates_.push_back(state);
+        state->activity_.topState = true;
+
+        graphicsUnloader.Dismiss();
+    }
+
+    void Game::unloadState(const std::string& name)
+    {
+        this->bChangingState_ = true;
+        try
+        {
+            shared_ptr<GameState> state = this->getState(name);
+            state->activity_.topState = false;
+            this->loadedStates_.pop_back();
+            if (!this->loadedStates_.empty())
+                this->loadedStates_.back()->activity_.topState = true;
+            state->deactivate();
+        }
+        catch (...)
+        {
+            COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Game::getExceptionMessage() << std::endl;
+            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
+        }
+        // Check if graphics is still required
+        if (!bAbort_)
+        {
+            bool graphicsRequired = false;
+            for (unsigned i = 0; i < loadedStates_.size(); ++i)
+                graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
+            if (!graphicsRequired)
+                this->unloadGraphics();
+        }
+        this->bChangingState_ = false;
+    }
+
+    /*static*/ std::string Game::getExceptionMessage()
+    {
+        std::string exceptionMessage;
+        try
+        {
+            // rethrow
+            throw;
+        }
+        catch (const std::exception& ex)
+        {
+            return ex.what();
+        }
+        catch (const CEGUI::Exception& ex)
+        {
+#if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
+            return GeneralException(ex.getMessage().c_str()).getDescription();
+#else
+            return GeneralException(ex.getMessage().c_str(), ex.getLine(),
+                ex.getFileName().c_str(), ex.getName().c_str()).getDescription();
+#endif
+        }
+        catch (...)
+        {
+            return "Unknown exception";
+        }
+    }
+
+    std::map<std::string, shared_ptr<Game::GameStateFactory> > Game::GameStateFactory::factories_s;
+
+    /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
+    {
+        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = factories_s.find(info.className);
+        assert(it != factories_s.end());
+        return it->second->fabricateInternal(info);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Game.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Game.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Game.h	(revision 5712)
@@ -0,0 +1,219 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Declaration of Game Singleton.
+ */
+
+#ifndef _Game_H__
+#define _Game_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <list>
+#include <map>
+#include <string>
+#include <vector>
+#include <boost/shared_ptr.hpp>
+#include <boost/scoped_ptr.hpp>
+#include <boost/preprocessor/cat.hpp>
+
+#include "util/Debug.h"
+#include "util/ScopeGuard.h"
+#include "util/Singleton.h"
+
+/**
+@def
+    Adds a new GameState to the Game. The second parameter is the name as string
+    and every following paramter is a constructor argument (which is usually non existent)
+*/
+#define DeclareGameState(className, stateName, bIgnoreTickTime, bGraphicsMode) \
+    static bool BOOST_PP_CAT(bGameStateDummy_##className, __LINE__) = orxonox::Game::declareGameState<className>(#className, stateName, bIgnoreTickTime, bGraphicsMode)
+
+namespace orxonox
+{
+    class GameConfiguration;
+
+    //! Helper object required before GameStates are being constructed
+    struct GameStateInfo
+    {
+        std::string stateName;
+        std::string className;
+        bool bIgnoreTickTime;
+        bool bGraphicsMode;
+    };
+
+    /**
+    @brief
+        Main class responsible for running the game.
+    @remark
+        You should only create this singleton once because it owns the Core class! (see remark there)
+    */
+    class _CoreExport Game : public Singleton<Game>
+    {
+        friend class Singleton<Game>;
+        typedef std::vector<shared_ptr<GameState> > GameStateVector;
+        typedef std::map<std::string, shared_ptr<GameState> > GameStateMap;
+        typedef shared_ptr<GameStateTreeNode> GameStateTreeNodePtr;
+
+    public:
+        Game(const std::string& cmdLine);
+        ~Game();
+
+        void setStateHierarchy(const std::string& str);
+        shared_ptr<GameState> getState(const std::string& name);
+
+        void run();
+        void stop();
+
+        void requestState(const std::string& name);
+        void requestStates(const std::string& names);
+        void popState();
+
+        const Clock& getGameClock() { return *this->gameClock_; }
+
+        float getAvgTickTime() { return this->avgTickTime_; }
+        float getAvgFPS()      { return this->avgFPS_; }
+
+        void subtractTickTime(int32_t length);
+
+        template <class T>
+        static bool declareGameState(const std::string& className, const std::string& stateName, bool bIgnoreTickTime, bool bConsoleMode);
+
+    private:
+        class _CoreExport GameStateFactory
+        {
+        public:
+            virtual ~GameStateFactory() { }
+            static shared_ptr<GameState> fabricate(const GameStateInfo& info);
+            template <class T>
+            static void createFactory(const std::string& className)
+                { factories_s[className].reset(new TemplateGameStateFactory<T>()); }
+
+            virtual shared_ptr<GameState> fabricateInternal(const GameStateInfo& info) = 0;
+            static std::map<std::string, shared_ptr<GameStateFactory> > factories_s;
+        };
+        template <class T>
+        class TemplateGameStateFactory : public GameStateFactory
+        {
+        public:
+            shared_ptr<GameState> fabricateInternal(const GameStateInfo& info)
+                { return shared_ptr<GameState>(new T(info)); }
+        };
+        // For the factory destruction
+        typedef Loki::ObjScopeGuardImpl0<std::map<std::string, shared_ptr<GameStateFactory> >, void (std::map<std::string, shared_ptr<GameStateFactory> >::*)()> ObjScopeGuard;
+
+        struct StatisticsTickInfo
+        {
+            uint64_t    tickTime;
+            uint32_t    tickLength;
+        };
+
+        Game(Game&); // don't mess with singletons
+
+        void loadGraphics();
+        void unloadGraphics();
+
+        bool checkState(const std::string& name) const;
+        void loadState(const std::string& name);
+        void unloadState(const std::string& name);
+
+        // Main loop structuring
+        void updateGameStateStack();
+        void updateGameStates();
+        void updateStatistics();
+        void updateFPSLimiter();
+
+        // ScopeGuard helper function
+        void resetChangingState() { this->bChangingState_ = false; }
+        /**
+        @brief
+            Retrieves information from an exception caught with "..."
+        @remarks
+            Never ever call this function without an exception in the stack!
+        */
+        static std::string getExceptionMessage();
+
+        scoped_ptr<Clock>                  gameClock_;
+        scoped_ptr<Core>                   core_;
+        ObjScopeGuard                      gsFactoryDestroyer_;
+        scoped_ptr<GameConfiguration>      configuration_;
+
+        GameStateMap                       constructedStates_;
+        GameStateVector                    loadedStates_;
+        GameStateTreeNodePtr               rootStateNode_;
+        GameStateTreeNodePtr               loadedTopStateNode_;
+        std::vector<GameStateTreeNodePtr>  requestedStateNodes_;
+
+        bool                               bChangingState_;
+        bool                               bAbort_;
+
+        // variables for time statistics
+        uint64_t                           statisticsStartTime_;
+        std::list<StatisticsTickInfo>      statisticsTickTimes_;
+        uint32_t                           periodTime_;
+        uint32_t                           periodTickTime_;
+        float                              avgFPS_;
+        float                              avgTickTime_;
+        int                                excessSleepTime_;
+        unsigned int                       minimumSleepTime_;
+
+        static std::map<std::string, GameStateInfo> gameStateDeclarations_s;
+        static Game* singletonPtr_s;        //!< Pointer to the Singleton
+    };
+
+    template <class T>
+    /*static*/ bool Game::declareGameState(const std::string& className, const std::string& stateName, bool bIgnoreTickTime, bool bGraphicsMode)
+    {
+        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(stateName);
+        if (it == gameStateDeclarations_s.end())
+        {
+            GameStateInfo& info = gameStateDeclarations_s[stateName];
+            info.stateName = stateName;
+            info.className = className;
+            info.bIgnoreTickTime = bIgnoreTickTime;
+            info.bGraphicsMode = bGraphicsMode;
+        }
+        else
+        {
+            COUT(0) << "Error: Cannot declare two GameStates with the same name." << std::endl;
+            COUT(0) << "       Ignoring second one ('" << stateName << "')." << std::endl;
+        }
+
+        // Create a factory to delay GameState creation
+        GameStateFactory::createFactory<T>(className);
+
+        // just a required dummy return value
+        return true;
+    }
+}
+
+#endif /* _Game_H__ */
Index: /code/branches/libraries2/src/libraries/core/GameMode.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/GameMode.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GameMode.cc	(revision 5712)
@@ -0,0 +1,43 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the GameMode class.
+*/
+
+#include "GameMode.h"
+
+namespace orxonox
+{
+    bool GameMode::bShowsGraphics_s = false;
+    bool GameMode::bHasServer_s     = false;
+    bool GameMode::bIsClient_s      = false;
+    bool GameMode::bIsStandalone_s  = false;
+    bool GameMode::bIsMaster_s      = false;
+}
Index: /code/branches/libraries2/src/libraries/core/GameMode.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/GameMode.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GameMode.h	(revision 5712)
@@ -0,0 +1,74 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Declaration of the GameMode class.
+*/
+
+#ifndef _GameMode_H__
+#define _GameMode_H__
+
+#include "CorePrereqs.h"
+
+namespace orxonox
+{
+    class _CoreExport GameMode
+    {
+        friend class Game;
+
+        public:
+            static bool showsGraphics() { return bShowsGraphics_s; }
+            static bool hasServer()     { return bHasServer_s; }
+            static bool isClient()      { return bIsClient_s; }
+            static bool isStandalone()  { return bIsStandalone_s; }
+            static bool isMaster()      { return bIsMaster_s; }
+
+            static void setHasServer    (bool val) { bHasServer_s     = val; updateIsMaster(); }
+            static void setIsClient     (bool val) { bIsClient_s      = val; updateIsMaster(); }
+            static void setIsStandalone (bool val) { bIsStandalone_s  = val; updateIsMaster(); }
+
+        private:
+            GameMode();
+            GameMode(const GameMode& inst);
+            ~GameMode();
+
+            static void updateIsMaster()
+            {
+                bIsMaster_s = (bHasServer_s || bIsStandalone_s);
+            }
+
+            static bool bShowsGraphics_s;                   //!< global variable that tells whether to show graphics
+            static bool bHasServer_s;                       //!< global variable that tells whether this is a server
+            static bool bIsClient_s;
+            static bool bIsStandalone_s;
+            static bool bIsMaster_s;
+    };
+}
+
+#endif /* _GameMode_H__ */
Index: /code/branches/libraries2/src/libraries/core/GameState.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/GameState.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GameState.cc	(revision 5712)
@@ -0,0 +1,97 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of GameState class.
+*/
+
+#include "GameState.h"
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/OrxAssert.h"
+#include "Game.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Constructor only initialises variables and sets the name permanently.
+    */
+    GameState::GameState(const GameStateInfo& info)
+        : info_(info)
+    {
+        this->activity_.activating   = false;
+        this->activity_.active       = false;
+        this->activity_.deactivating = false;
+        this->activity_.suspended    = false;
+        this->activity_.topState     = false;
+        this->activity_.updating     = false;
+    }
+
+    /**
+    @brief
+        Destructor only checks that we don't delete an active state.
+    */
+    GameState::~GameState()
+    {
+        OrxAssert(this->activity_.active == false, "Deleting an active GameState is a very bad idea..");
+    }
+
+    const std::string& GameState::getName() const
+    {
+        return info_.stateName;
+    }
+
+    void GameState::activateInternal()
+    {
+        this->activity_.activating = true;
+        this->activate();
+        this->activity_.activating = false;
+        this->activity_.active = true;
+    }
+
+    void GameState::deactivateInternal()
+    {
+        this->activity_.active = false;
+        this->activity_.deactivating = true;
+        this->activate();
+        this->activity_.deactivating = false;
+        this->activity_.suspended = false;
+        this->activity_.updating = false;
+    }
+
+    void GameState::updateInternal(const Clock& time)
+    {
+        this->activity_.updating = true;
+        this->update(time);
+        this->activity_.updating = false;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/GameState.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/GameState.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GameState.h	(revision 5712)
@@ -0,0 +1,102 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Definition of GameState class.
+*/
+
+#ifndef _GameState_H__
+#define _GameState_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <string>
+
+namespace orxonox
+{
+    /**
+    @brief
+        An implementation of a tree to manage game states.
+        This leads to a certain hierarchy that is created at runtime.
+        To actually use the structure, you will have to derive from it and
+        implement 'enter', 'leave' and 'tick'. The latter corresponds to an
+        update function.
+
+        Internally the tree is managed by two maps per node: One stores all its
+        children, grandchildren, etc. by name of the state. The other maps these
+        children states to the actual child of the node.
+        An example: Foo is a grandchildren of Bar and Foofoo is the Foo's parent.
+        Then Bar stores Foo in map by its name. The other one then maps Foo to Foofoo.
+    */
+    class _CoreExport GameState
+    {
+        friend class Game;
+
+    public:
+        /**
+        @brief
+            Gives information about what the GameState is currently doing
+        */
+        struct State
+        {
+            unsigned active       : 1;
+            unsigned activating   : 1;
+            unsigned deactivating : 1;
+            unsigned updating     : 1;
+            unsigned suspended    : 1;
+            unsigned topState     : 1;
+        };
+
+    public:
+        GameState(const GameStateInfo& info);
+        virtual ~GameState();
+
+        const std::string& getName()   const;
+        State getActivity()            const { return activity_; }
+        const GameStateInfo& getInfo() const { return info_; }
+
+    protected:
+        virtual void activate() { }
+        virtual void deactivate() { }
+        virtual void update(const Clock& time) { }
+
+    private:
+        void setActivity(State activity);
+        void activateInternal();
+        void deactivateInternal();
+        void updateInternal(const Clock& time);
+
+        const GameStateInfo& info_;
+        State                activity_;
+    };
+}
+
+#endif /* _GameState_H__ */
Index: /code/branches/libraries2/src/libraries/core/GraphicsManager.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/GraphicsManager.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GraphicsManager.cc	(revision 5712)
@@ -0,0 +1,422 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
+ *   Co-authors:
+ *      Felix Schulthess
+ *
+ */
+
+#include "GraphicsManager.h"
+
+#include <fstream>
+#include <sstream>
+#include <boost/filesystem.hpp>
+#include <boost/shared_array.hpp>
+
+#include <OgreArchiveFactory.h>
+#include <OgreArchiveManager.h>
+#include <OgreFrameListener.h>
+#include <OgreRoot.h>
+#include <OgreLogManager.h>
+#include <OgreRenderWindow.h>
+#include <OgreRenderSystem.h>
+#include <OgreResourceGroupManager.h>
+#include <OgreTextureManager.h>
+#include <OgreViewport.h>
+#include <OgreWindowEventUtilities.h>
+
+#include "SpecialConfig.h"
+#include "util/Exception.h"
+#include "util/StringUtils.h"
+#include "util/SubString.h"
+#include "Clock.h"
+#include "ConsoleCommand.h"
+#include "ConfigValueIncludes.h"
+#include "CoreIncludes.h"
+#include "Core.h"
+#include "Game.h"
+#include "GameMode.h"
+#include "Loader.h"
+#include "MemoryArchive.h"
+#include "WindowEventListener.h"
+#include "XMLFile.h"
+
+namespace orxonox
+{
+    class OgreWindowEventListener : public Ogre::WindowEventListener
+    {
+    public:
+        void windowResized     (Ogre::RenderWindow* rw)
+            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
+        void windowFocusChange (Ogre::RenderWindow* rw)
+            { orxonox::WindowEventListener::changeWindowFocus(); }
+        void windowClosed      (Ogre::RenderWindow* rw)
+            { orxonox::Game::getInstance().stop(); }
+        void windowMoved       (Ogre::RenderWindow* rw)
+            { orxonox::WindowEventListener::moveWindow(); }
+    };
+
+    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
+
+    /**
+    @brief
+        Non-initialising constructor.
+    */
+    GraphicsManager::GraphicsManager(bool bLoadRenderer)
+        : ogreWindowEventListener_(new OgreWindowEventListener())
+#if OGRE_VERSION < 0x010600
+        , memoryArchiveFactory_(new MemoryArchiveFactory())
+#endif
+        , renderWindow_(0)
+        , viewport_(0)
+    {
+        RegisterObject(GraphicsManager);
+
+        this->setConfigValues();
+
+        // Ogre setup procedure (creating Ogre::Root)
+        this->loadOgreRoot();
+        // load all the required plugins for Ogre
+        this->loadOgrePlugins();
+
+        // At first, add the root paths of the data directories as resource locations
+        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getDataPathString(), "FileSystem", "dataRoot", false);
+        // Load resources
+        resources_.reset(new XMLFile("resources.oxr", "dataRoot"));
+        resources_->setLuaSupport(false);
+        Loader::open(resources_.get());
+
+        // Only for development runs
+        if (Core::isDevelopmentRun())
+        {
+            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
+            extResources_.reset(new XMLFile("resources.oxr", "externalDataRoot"));
+            extResources_->setLuaSupport(false);
+            Loader::open(extResources_.get());
+        }
+
+        if (bLoadRenderer)
+        {
+            // Reads the ogre config and creates the render window
+            this->upgradeToGraphics();
+        }
+    }
+
+    /**
+    @brief
+        Destruction is done by the member scoped_ptrs.
+    */
+    GraphicsManager::~GraphicsManager()
+    {
+        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
+        // TODO: Destroy the console command
+    }
+
+    void GraphicsManager::setConfigValues()
+    {
+        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
+            .description("Location of the Ogre config file");
+        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
+            .description("Folder where the Ogre plugins are located.");
+        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
+            .description("Comma separated list of all plugins to load.");
+        SetConfigValue(ogreLogFile_,     "ogre.log")
+            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
+        SetConfigValue(ogreLogLevelTrivial_ , 5)
+            .description("Corresponding orxonox debug level for ogre Trivial");
+        SetConfigValue(ogreLogLevelNormal_  , 4)
+            .description("Corresponding orxonox debug level for ogre Normal");
+        SetConfigValue(ogreLogLevelCritical_, 2)
+            .description("Corresponding orxonox debug level for ogre Critical");
+    }
+
+    /**
+    @brief
+        Loads the renderer and creates the render window if not yet done so.
+    @remarks
+        This operation is irreversible without recreating the GraphicsManager!
+        So if it throws you HAVE to recreate the GraphicsManager!!!
+        It therefore offers almost no exception safety.
+    */
+    void GraphicsManager::upgradeToGraphics()
+    {
+        if (renderWindow_ != NULL)
+            return;
+
+        this->loadRenderer();
+
+#if OGRE_VERSION < 0x010600
+        // WORKAROUND: There is an incompatibility for particle scripts when trying
+        // to support both Ogre 1.4 and 1.6. The hacky solution is to create
+        // scripts for the 1.6 version and then remove the inserted "particle_system"
+        // keyword. But we need to supply these new scripts as well, which is why
+        // there is an extra Ogre::Archive dealing with in the memory.
+        using namespace Ogre;
+        ArchiveManager::getSingleton().addArchiveFactory(memoryArchiveFactory_.get());
+        const StringVector& groups = ResourceGroupManager::getSingleton().getResourceGroups();
+        // Travers all groups
+        for (StringVector::const_iterator itGroup = groups.begin(); itGroup != groups.end(); ++itGroup)
+        {
+            FileInfoListPtr files = ResourceGroupManager::getSingleton().findResourceFileInfo(*itGroup, "*.particle");
+            for (FileInfoList::const_iterator itFile = files->begin(); itFile != files->end(); ++itFile)
+            {
+                // open file
+                Ogre::DataStreamPtr input = ResourceGroupManager::getSingleton().openResource(itFile->filename, *itGroup, false);
+                std::stringstream output;
+                // Parse file and replace "particle_system" with nothing
+                while (!input->eof())
+                {
+                    std::string line = input->getLine();
+                    size_t pos = line.find("particle_system");
+                    if (pos != std::string::npos)
+                    {
+                        // 15 is the length of "particle_system"
+                        line.replace(pos, 15, "");
+                    }
+                    output << line << std::endl;
+                }
+                // Add file to the memory archive
+                shared_array<char> data(new char[output.str().size()]);
+                // Debug optimisations
+                const std::string outputStr = output.str();
+                char* rawData = data.get();
+                for (unsigned i = 0; i < outputStr.size(); ++i)
+                    rawData[i] = outputStr[i];
+                MemoryArchive::addFile("particle_scripts_ogre_1.4_" + *itGroup, itFile->filename, data, output.str().size());
+            }
+            if (!files->empty())
+            {
+                // Declare the files, but using a new group
+                ResourceGroupManager::getSingleton().addResourceLocation("particle_scripts_ogre_1.4_" + *itGroup,
+                    "Memory", "particle_scripts_ogre_1.4_" + *itGroup);
+            }
+        }
+#endif
+
+        // Initialise all resources (do this AFTER the renderer has been loaded!)
+        // Note: You can only do this once! Ogre will check whether a resource group has
+        // already been initialised. If you need to load resources later, you will have to
+        // choose another resource group.
+        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
+    }
+
+    /**
+    @brief
+        Creates the Ogre Root object and sets up the ogre log.
+    */
+    void GraphicsManager::loadOgreRoot()
+    {
+        COUT(3) << "Setting up Ogre..." << std::endl;
+
+        if (ogreConfigFile_ == "")
+        {
+            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
+            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
+        }
+        if (ogreLogFile_ == "")
+        {
+            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
+            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
+        }
+
+        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
+        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
+
+        // create a new logManager
+        // Ogre::Root will detect that we've already created a Log
+        ogreLogger_.reset(new Ogre::LogManager());
+        COUT(4) << "Ogre LogManager created" << std::endl;
+
+        // create our own log that we can listen to
+        Ogre::Log *myLog;
+        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
+        COUT(4) << "Ogre Log created" << std::endl;
+
+        myLog->setLogDetail(Ogre::LL_BOREME);
+        myLog->addListener(this);
+
+        COUT(4) << "Creating Ogre Root..." << std::endl;
+
+        // check for config file existence because Ogre displays (caught) exceptions if not
+        if (!boost::filesystem::exists(ogreConfigFilepath))
+        {
+            // create a zero sized file
+            std::ofstream creator;
+            creator.open(ogreConfigFilepath.string().c_str());
+            creator.close();
+        }
+
+        // Leave plugins file empty. We're going to do that part manually later
+        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
+
+        COUT(3) << "Ogre set up done." << std::endl;
+    }
+
+    void GraphicsManager::loadOgrePlugins()
+    {
+        // just to make sure the next statement doesn't segfault
+        if (ogrePluginsDirectory_ == "")
+            ogrePluginsDirectory_ = ".";
+
+        boost::filesystem::path folder(ogrePluginsDirectory_);
+        // Do some SubString magic to get the comma separated list of plugins
+        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '(', ')', false, '\0');
+        // Use backslash paths on Windows! file_string() already does that though.
+        for (unsigned int i = 0; i < plugins.size(); ++i)
+            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
+    }
+
+    void GraphicsManager::loadRenderer()
+    {
+        CCOUT(4) << "Configuring Renderer" << std::endl;
+
+        if (!ogreRoot_->restoreConfig())
+            if (!ogreRoot_->showConfigDialog())
+                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue failed.");
+
+        CCOUT(4) << "Creating render window" << std::endl;
+
+        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
+        // Propagate the size of the new winodw
+        this->ogreWindowEventListener_->windowResized(renderWindow_);
+
+        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
+
+        // create a full screen default viewport
+        // Note: This may throw when adding a viewport with an existing z-order!
+        //       But in our case we only have one viewport for now anyway, therefore
+        //       no ScopeGuards or anything to handle exceptions.
+        this->viewport_ = this->renderWindow_->addViewport(0, 0);
+
+        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);
+
+        // add console commands
+        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
+        ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
+        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
+    }
+
+    void GraphicsManager::update(const Clock& time)
+    {
+        Ogre::FrameEvent evt;
+        evt.timeSinceLastFrame = time.getDeltaTime();
+        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
+
+        // don't forget to call _fireFrameStarted to OGRE to make sure
+        // everything goes smoothly
+        ogreRoot_->_fireFrameStarted(evt);
+
+        // Pump messages in all registered RenderWindows
+        // This calls the WindowEventListener objects.
+        Ogre::WindowEventUtilities::messagePump();
+        // make sure the window stays active even when not focused
+        // (probably only necessary on windows)
+        this->renderWindow_->setActive(true);
+
+        // Time before rendering
+        uint64_t timeBeforeTick = time.getRealMicroseconds();
+
+        // Render frame
+        ogreRoot_->_updateAllRenderTargets();
+
+        uint64_t timeAfterTick = time.getRealMicroseconds();
+        // Subtract the time used for rendering from the tick time counter
+        Game::getInstance().subtractTickTime(timeAfterTick - timeBeforeTick);
+
+        // again, just to be sure OGRE works fine
+        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
+    }
+
+    void GraphicsManager::setCamera(Ogre::Camera* camera)
+    {
+        this->viewport_->setCamera(camera);
+    }
+
+    /**
+    @brief
+        Method called by the LogListener interface from Ogre.
+        We use it to capture Ogre log messages and handle it ourselves.
+    @param message
+        The message to be logged
+    @param lml
+        The message level the log is using
+    @param maskDebug
+        If we are printing to the console or not
+    @param logName
+        The name of this log (so you can have several listeners
+        for different logs, and identify them)
+    */
+    void GraphicsManager::messageLogged(const std::string& message,
+        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
+    {
+        int orxonoxLevel;
+        switch (lml)
+        {
+        case Ogre::LML_TRIVIAL:
+            orxonoxLevel = this->ogreLogLevelTrivial_;
+            break;
+        case Ogre::LML_NORMAL:
+            orxonoxLevel = this->ogreLogLevelNormal_;
+            break;
+        case Ogre::LML_CRITICAL:
+            orxonoxLevel = this->ogreLogLevelCritical_;
+            break;
+        default:
+            orxonoxLevel = 0;
+        }
+        OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
+            << "Ogre: " << message << std::endl;
+    }
+
+    size_t GraphicsManager::getRenderWindowHandle()
+    {
+        size_t windowHnd = 0;
+        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
+        return windowHnd;
+    }
+
+    bool GraphicsManager::isFullScreen() const
+    {
+        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
+        if (options.find("Full Screen") != options.end())
+        {
+            if (options["Full Screen"].currentValue == "Yes")
+                return true;
+            else
+                return false;
+        }
+        else
+        {
+            COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
+            return false;
+        }
+    }
+
+    void GraphicsManager::printScreen()
+    {
+        assert(this->renderWindow_);
+       
+        this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/GraphicsManager.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/GraphicsManager.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/GraphicsManager.h	(revision 5712)
@@ -0,0 +1,121 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
+ *   Co-authors:
+ *      Felix Schulthess
+ *
+ */
+
+/**
+@file
+@brief
+    Declaration of GraphicsManager Singleton.
+ */
+
+#ifndef _GraphicsManager_H__
+#define _GraphicsManager_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <string>
+#include <OgreLog.h>
+#include <boost/scoped_ptr.hpp>
+#include <boost/shared_ptr.hpp>
+
+#include "util/Singleton.h"
+#include "OrxonoxClass.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Graphics engine manager class
+    */
+    class _CoreExport GraphicsManager : public Singleton<GraphicsManager>, public OrxonoxClass, public Ogre::LogListener
+    {
+        friend class Singleton<GraphicsManager>;
+    public:
+        GraphicsManager(bool bLoadRenderer = true);
+        ~GraphicsManager();
+
+        void setConfigValues();
+
+        void update(const Clock& time);
+
+        Ogre::Viewport* getViewport()         { return this->viewport_; }
+        Ogre::RenderWindow* getRenderWindow() { return this->renderWindow_; }
+        size_t getRenderWindowHandle();
+        bool isFullScreen() const;
+
+        void upgradeToGraphics();
+        bool rendererLoaded() const { return renderWindow_ != NULL; }
+
+        void setCamera(Ogre::Camera* camera);
+
+    private:
+        GraphicsManager(GraphicsManager&); // don't mess with singletons
+
+        // OGRE initialisation
+        void loadOgreRoot();
+        void loadOgrePlugins();
+        void loadRenderer();
+
+        // event from Ogre::LogListener
+        void messageLogged(const std::string& message, Ogre::LogMessageLevel lml,
+            bool maskDebug, const std::string& logName);
+
+        // console commands
+        void printScreen();
+
+        scoped_ptr<OgreWindowEventListener> ogreWindowEventListener_; //!< Pimpl to hide OgreWindowUtilities.h
+#if OGRE_VERSION < 0x010600
+        scoped_ptr<MemoryArchiveFactory>    memoryArchiveFactory_;    //!< Stores the modified particle scripts
+#endif
+        scoped_ptr<Ogre::LogManager>        ogreLogger_;
+        scoped_ptr<Ogre::Root>              ogreRoot_;                //!< Ogre's root
+        Ogre::RenderWindow* renderWindow_;             //!< the one and only render window
+        Ogre::Viewport*     viewport_;                 //!< default full size viewport
+
+        // XML files for the resources
+        shared_ptr<XMLFile> resources_;                //!< XML with resource locations
+        shared_ptr<XMLFile> extResources_;             //!< XML with resource locations in the external path (only for dev runs)
+
+        // config values
+        std::string         ogreConfigFile_;           //!< ogre config file name
+        std::string         ogrePluginsDirectory_;     //!< Directory where the Ogre plugins are located
+        std::string         ogrePlugins_;              //!< Comma separated list of all plugins to load
+        std::string         ogreLogFile_;              //!< log file name for Ogre log messages
+        int                 ogreLogLevelTrivial_;      //!< Corresponding Orxonx debug level for LL_TRIVIAL
+        int                 ogreLogLevelNormal_;       //!< Corresponding Orxonx debug level for LL_NORMAL
+        int                 ogreLogLevelCritical_;     //!< Corresponding Orxonx debug level for LL_CRITICAL
+
+        // console commands
+        ConsoleCommand*     ccPrintScreen_;
+
+        static GraphicsManager* singletonPtr_s;        //!< Pointer to the Singleton
+    };
+}
+
+#endif /* _GraphicsManager_H__ */
Index: /code/branches/libraries2/src/libraries/core/IRC.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/IRC.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/IRC.cc	(revision 5712)
@@ -0,0 +1,139 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "IRC.h"
+
+#include <cpptcl/cpptcl.h>
+
+#include "util/Convert.h"
+#include "ConsoleCommand.h"
+#include "CoreIncludes.h"
+#include "TclThreadManager.h"
+
+namespace orxonox
+{
+    static const unsigned int IRC_TCL_THREADID  = 1421421421;
+
+    SetConsoleCommand(IRC, say,  true).accessLevel(AccessLevel::User);
+    SetConsoleCommand(IRC, msg,  false).accessLevel(AccessLevel::User);
+    SetConsoleCommand(IRC, nick, false).accessLevel(AccessLevel::User);
+
+    IRC::IRC()
+    {
+        RegisterRootObject(IRC);
+        this->interpreter_ = 0;
+    }
+
+    void IRC::initialize()
+    {
+        unsigned int threadID = IRC_TCL_THREADID;
+        this->interpreter_ = TclThreadManager::createWithId(threadID);
+
+        try
+        {
+            this->interpreter_->def("::orxonox::irc::say", IRC::tcl_say, Tcl::variadic());
+            this->interpreter_->def("::orxonox::irc::privmsg", IRC::tcl_privmsg, Tcl::variadic());
+            this->interpreter_->def("::orxonox::irc::action", IRC::tcl_action, Tcl::variadic());
+            this->interpreter_->def("::orxonox::irc::info", IRC::tcl_info, Tcl::variadic());
+        }
+        catch (Tcl::tcl_error const &e)
+        {   COUT(1) << "Tcl (IRC) error: " << e.what();   }
+        catch (std::exception const &e)
+        {   COUT(1) << "Error while initializing Tcl (IRC): " << e.what();   }
+
+        this->nickname_ = "orx" + multi_cast<std::string>(static_cast<unsigned int>(rand()));
+        TclThreadManager::execute(threadID, "set nickname " + this->nickname_);
+        TclThreadManager::execute(threadID, "source irc.tcl");
+    }
+
+    IRC& IRC::getInstance()
+    {
+        static IRC instance;
+        return instance;
+    }
+
+    bool IRC::eval(const std::string& command)
+    {
+        if (!IRC::getInstance().interpreter_)
+        {
+            IRC::getInstance().initialize();
+            COUT(1) << "Error: IRC client wasn't yet initialized, please try again." << std::endl;
+            return false;
+        }
+
+        try
+        {
+            IRC::getInstance().interpreter_->eval(command);
+            return true;
+        }
+        catch (Tcl::tcl_error const &e)
+        {   COUT(1) << "Tcl (IRC) error: " << e.what();   }
+        catch (std::exception const &e)
+        {   COUT(1) << "Error while executing Tcl (IRC): " << e.what();   }
+
+        return false;
+    }
+
+    void IRC::say(const std::string& message)
+    {
+        if (IRC::eval("irk::say $conn #orxonox {" + message + "}"))
+            IRC::tcl_say(Tcl::object(), Tcl::object(IRC::getInstance().nickname_), Tcl::object(message));
+    }
+
+    void IRC::msg(const std::string& channel, const std::string& message)
+    {
+        if (IRC::eval("irk::say $conn " + channel + " {" + message + "}"))
+            IRC::tcl_privmsg(Tcl::object(channel), Tcl::object(IRC::getInstance().nickname_), Tcl::object(message));
+    }
+
+    void IRC::nick(const std::string& nickname)
+    {
+        if (IRC::eval("irk::nick $conn " + nickname))
+            IRC::getInstance().nickname_ = nickname;
+    }
+
+    void IRC::tcl_say(Tcl::object const &channel, Tcl::object const &nick, Tcl::object const &args)
+    {
+        COUT(0) << "IRC> " << nick.get() << ": " << stripEnclosingBraces(args.get()) << std::endl;
+    }
+
+    void IRC::tcl_privmsg(Tcl::object const &query, Tcl::object const &nick, Tcl::object const &args)
+    {
+        COUT(0) << "IRC (" << query.get() << ")> " << nick.get() << ": " << stripEnclosingBraces(args.get()) << std::endl;
+    }
+
+    void IRC::tcl_action(Tcl::object const &channel, Tcl::object const &nick, Tcl::object const &args)
+    {
+        COUT(0) << "IRC> * " << nick.get() << " " << stripEnclosingBraces(args.get()) << std::endl;
+    }
+
+    void IRC::tcl_info(Tcl::object const &channel, Tcl::object const &args)
+    {
+        COUT(0) << "IRC> --> " << stripEnclosingBraces(args.get()) << std::endl;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/IRC.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/IRC.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/IRC.h	(revision 5712)
@@ -0,0 +1,66 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _IRC_H__
+#define _IRC_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include "OrxonoxClass.h"
+
+namespace orxonox
+{
+    class _CoreExport IRC : public OrxonoxClass
+    {
+        public:
+            static IRC& getInstance();
+
+            static void say(const std::string& message);
+            static void msg(const std::string& channel, const std::string& message);
+            static void nick(const std::string& nickname);
+
+            static void tcl_say(Tcl::object const &channel, Tcl::object const &nick, Tcl::object const &args);
+            static void tcl_privmsg(Tcl::object const &query, Tcl::object const &nick, Tcl::object const &args);
+            static void tcl_action(Tcl::object const &channel, Tcl::object const &nick, Tcl::object const &args);
+            static void tcl_info(Tcl::object const &channel, Tcl::object const &args);
+
+        private:
+            static bool eval(const std::string& command);
+            void initialize();
+
+            IRC();
+            IRC(const IRC& other);
+            ~IRC() {}
+
+            Tcl::interpreter* interpreter_;
+            std::string nickname_;
+    };
+}
+
+#endif /* _IRC_H__ */
Index: /code/branches/libraries2/src/libraries/core/Identifier.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Identifier.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Identifier.cc	(revision 5712)
@@ -0,0 +1,531 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the Identifier class.
+*/
+
+#include "Identifier.h"
+
+#include <ostream>
+
+#include "util/StringUtils.h"
+#include "ConfigValueContainer.h"
+#include "ConsoleCommand.h"
+#include "Factory.h"
+#include "XMLPort.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###       Identifier        ###
+    // ###############################
+    int Identifier::hierarchyCreatingCounter_s = 0;
+    unsigned int Identifier::classIDCounter_s = 0;
+
+    /**
+        @brief Constructor: No factory, no object created, new ObjectList and a unique networkID.
+    */
+    Identifier::Identifier()
+        : classID_(classIDCounter_s++)
+    {
+        this->objects_ = new ObjectListBase(this);
+
+        this->bCreatedOneObject_ = false;
+        this->bSetName_ = false;
+        this->factory_ = 0;
+        this->bLoadable_ = true;
+
+        this->bHasConfigValues_ = false;
+        this->bHasConsoleCommands_ = false;
+
+        this->children_ = new std::set<const Identifier*>();
+        this->directChildren_ = new std::set<const Identifier*>();
+
+        // Default network ID is the class ID
+        this->networkID_ = this->classID_;
+    }
+
+    /**
+        @brief Destructor: Deletes the list containing the children.
+    */
+    Identifier::~Identifier()
+    {
+        delete this->children_;
+        delete this->directChildren_;
+        delete this->objects_;
+
+        if (this->factory_)
+            delete this->factory_;
+
+        for (std::map<std::string, ConsoleCommand*>::iterator it = this->consoleCommands_.begin(); it != this->consoleCommands_.end(); ++it)
+            delete (it->second);
+        for (std::map<std::string, ConfigValueContainer*>::iterator it = this->configValues_.begin(); it != this->configValues_.end(); ++it)
+            delete (it->second);
+        for (std::map<std::string, XMLPortParamContainer*>::iterator it = this->xmlportParamContainers_.begin(); it != this->xmlportParamContainers_.end(); ++it)
+            delete (it->second);
+        for (std::map<std::string, XMLPortObjectContainer*>::iterator it = this->xmlportObjectContainers_.begin(); it != this->xmlportObjectContainers_.end(); ++it)
+            delete (it->second);
+    }
+
+    /**
+        @brief Returns the identifier map with the names as received by typeid(). This is only used internally.
+    */
+    std::map<std::string, Identifier*>& Identifier::getTypeIDIdentifierMap()
+    {
+        static std::map<std::string, Identifier*> identifiers;    //!< The map to store all Identifiers.
+        return identifiers;
+    }
+
+    /**
+        @brief Returns an identifier by name and adds it if not available
+        @param name The name of the identifier as typeid().name() suggests
+        @param proposal A pointer to a newly created identifier for the case of non existance in the map
+        @return The identifier (unique instance)
+    */
+    Identifier* Identifier::getIdentifierSingleton(const std::string& name, Identifier* proposal)
+    {
+        std::map<std::string, Identifier*>::const_iterator it = getTypeIDIdentifierMap().find(name);
+
+        if (it != getTypeIDIdentifierMap().end())
+        {
+            // There is already an entry: return it and delete the proposal
+            delete proposal;
+            return (*it).second;
+        }
+        else
+        {
+            // There is no entry: put the proposal into the map and return it
+            getTypeIDIdentifierMap()[name] = proposal;
+            return proposal;
+        }
+    }
+
+    /**
+        @brief Registers a class, which means that the name and the parents get stored.
+        @param parents A list, containing the Identifiers of all parents of the class
+        @param bRootClass True if the class is either an Interface or the BaseObject itself
+    */
+    void Identifier::initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass)
+    {
+        // Check if at least one object of the given type was created
+        if (!this->bCreatedOneObject_ && Identifier::isCreatingHierarchy())
+        {
+            // If no: We have to store the information and initialize the Identifier
+            COUT(4) << "*** ClassIdentifier: Register Class in " << this->getName() << "-Singleton -> Initialize Singleton." << std::endl;
+            if (bRootClass)
+                this->initialize(0); // If a class is derived from two interfaces, the second interface might think it's derived from the first because of the order of constructor-calls. Thats why we set parents to zero in that case.
+            else
+                this->initialize(parents);
+        }
+    }
+
+    /**
+        @brief Initializes the Identifier with a list containing all parents of the class the Identifier belongs to.
+        @param parents A list containing all parents
+    */
+    void Identifier::initialize(std::set<const Identifier*>* parents)
+    {
+        COUT(4) << "*** Identifier: Initialize " << this->name_ << "-Singleton." << std::endl;
+        this->bCreatedOneObject_ = true;
+
+        if (parents)
+        {
+            this->parents_ = (*parents);
+            this->directParents_ = (*parents);
+
+            // Iterate through all parents
+            for (std::set<const Identifier*>::iterator it = parents->begin(); it != parents->end(); ++it)
+            {
+                // Tell the parent we're one of it's children
+                (*it)->getChildrenIntern().insert((*it)->getChildrenIntern().end(), this);
+
+                // Erase all parents of our parent from our direct-parent-list
+                for (std::set<const Identifier*>::const_iterator it1 = (*it)->getParents().begin(); it1 != (*it)->getParents().end(); ++it1)
+                {
+                    // Search for the parent's parent in our direct-parent-list
+                    for (std::set<const Identifier*>::iterator it2 = this->directParents_.begin(); it2 != this->directParents_.end(); ++it2)
+                    {
+                        if ((*it1) == (*it2))
+                        {
+                            // We've found a non-direct parent in our list: Erase it
+                            this->directParents_.erase(it2);
+                            break;
+                        }
+                    }
+                }
+            }
+
+            // Now iterate through all direct parents
+            for (std::set<const Identifier*>::iterator it = this->directParents_.begin(); it != this->directParents_.end(); ++it)
+            {
+                // Tell the parent we're one of it's direct children
+                (*it)->getDirectChildrenIntern().insert((*it)->getDirectChildrenIntern().end(), this);
+
+                // Create the super-function dependencies
+                (*it)->createSuperFunctionCaller();
+            }
+        }
+    }
+
+    /**
+        @brief Destroys all Identifiers. Called when exiting the program.
+    */
+    void Identifier::destroyAllIdentifiers()
+    {
+        for (std::map<std::string, Identifier*>::iterator it = Identifier::getTypeIDIdentifierMap().begin(); it != Identifier::getTypeIDIdentifierMap().end(); ++it)
+            delete (it->second);
+    }
+
+    /**
+        @brief Sets the name of the class.
+        @param name The name
+    */
+    void Identifier::setName(const std::string& name)
+    {
+        if (!this->bSetName_)
+        {
+            this->name_ = name;
+            this->bSetName_ = true;
+            Identifier::getIdentifierMapIntern()[name] = this;
+            Identifier::getLowercaseIdentifierMapIntern()[getLowercase(name)] = this;
+        }
+    }
+
+    /**
+        @brief Creates an object of the type the Identifier belongs to.
+        @return The new object
+    */
+    BaseObject* Identifier::fabricate(BaseObject* creator)
+    {
+        if (this->factory_)
+        {
+            return this->factory_->fabricate(creator); // We have to return a BaseObject, because we don't know the exact type.
+        }
+        else
+        {
+            COUT(1) << "An error occurred in Identifier.cc:" << std::endl;
+            COUT(1) << "Error: Cannot fabricate an object of type '" << this->name_ << "'. Class has no factory." << std::endl;
+            COUT(1) << "Aborting..." << std::endl;
+            abort();
+            return NULL;
+        }
+    }
+
+    /**
+        @brief Sets the network ID to a new value and changes the entry in the Factory.
+        @param id The new network ID
+    */
+    void Identifier::setNetworkID(uint32_t id)
+    {
+        Factory::changeNetworkID(this, this->networkID_, id);
+        this->networkID_ = id;
+    }
+
+    /**
+        @brief Returns true, if the Identifier is at least of the given type.
+        @param identifier The identifier to compare with
+    */
+    bool Identifier::isA(const Identifier* identifier) const
+    {
+        return (identifier == this || (this->parents_.find(identifier) != this->parents_.end()));
+    }
+
+    /**
+        @brief Returns true, if the Identifier is exactly of the given type.
+        @param identifier The identifier to compare with
+    */
+    bool Identifier::isExactlyA(const Identifier* identifier) const
+    {
+        return (identifier == this);
+    }
+
+    /**
+        @brief Returns true, if the assigned identifier is a child of the given identifier.
+        @param identifier The identifier to compare with
+    */
+    bool Identifier::isChildOf(const Identifier* identifier) const
+    {
+        return (this->parents_.find(identifier) != this->parents_.end());
+    }
+
+    /**
+        @brief Returns true, if the assigned identifier is a direct child of the given identifier.
+        @param identifier The identifier to compare with
+    */
+    bool Identifier::isDirectChildOf(const Identifier* identifier) const
+    {
+        return (this->directParents_.find(identifier) != this->directParents_.end());
+    }
+
+    /**
+        @brief Returns true, if the assigned identifier is a parent of the given identifier.
+        @param identifier The identifier to compare with
+    */
+    bool Identifier::isParentOf(const Identifier* identifier) const
+    {
+        return (this->children_->find(identifier) != this->children_->end());
+    }
+
+    /**
+        @brief Returns true, if the assigned identifier is a direct parent of the given identifier.
+        @param identifier The identifier to compare with
+    */
+    bool Identifier::isDirectParentOf(const Identifier* identifier) const
+    {
+        return (this->directChildren_->find(identifier) != this->directChildren_->end());
+    }
+
+    /**
+        @brief Returns the map that stores all Identifiers.
+        @return The map
+    */
+    std::map<std::string, Identifier*>& Identifier::getIdentifierMapIntern()
+    {
+        static std::map<std::string, Identifier*> identifierMap;
+        return identifierMap;
+    }
+
+    /**
+        @brief Returns the map that stores all Identifiers.
+        @return The map
+    */
+    std::map<std::string, Identifier*>& Identifier::getLowercaseIdentifierMapIntern()
+    {
+        static std::map<std::string, Identifier*> lowercaseIdentifierMap;
+        return lowercaseIdentifierMap;
+    }
+
+    /**
+        @brief Adds the ConfigValueContainer of a variable, given by the string of its name.
+        @param varname The name of the variablee
+        @param container The container
+    */
+    void Identifier::addConfigValueContainer(const std::string& varname, ConfigValueContainer* container)
+    {
+        std::map<std::string, ConfigValueContainer*>::const_iterator it = this->configValues_.find(varname);
+        if (it != this->configValues_.end())
+        {
+            COUT(2) << "Warning: Overwriting config-value with name " << varname << " in class " << this->getName() << "." << std::endl;
+            delete (it->second);
+        }
+
+        this->bHasConfigValues_ = true;
+        this->configValues_[varname] = container;
+        this->configValues_LC_[getLowercase(varname)] = container;
+    }
+
+    /**
+        @brief Returns the ConfigValueContainer of a variable, given by the string of its name.
+        @param varname The name of the variable
+        @return The ConfigValueContainer
+    */
+    ConfigValueContainer* Identifier::getConfigValueContainer(const std::string& varname)
+    {
+        std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_.find(varname);
+        if (it != configValues_.end())
+            return ((*it).second);
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns the ConfigValueContainer of a variable, given by the string of its name in lowercase.
+        @param varname The name of the variable in lowercase
+        @return The ConfigValueContainer
+    */
+    ConfigValueContainer* Identifier::getLowercaseConfigValueContainer(const std::string& varname)
+    {
+        std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_LC_.find(varname);
+        if (it != configValues_LC_.end())
+            return ((*it).second);
+        else
+            return 0;
+    }
+
+    /**
+        @brief Adds a new console command of this class.
+        @param executor The executor of the command
+        @param bCreateShortcut If this is true a shortcut gets created so you don't have to add the classname to access this command
+        @return The executor of the command
+    */
+    ConsoleCommand& Identifier::addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut)
+    {
+        std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_.find(command->getName());
+        if (it != this->consoleCommands_.end())
+        {
+            COUT(2) << "Warning: Overwriting console-command with name " << command->getName() << " in class " << this->getName() << "." << std::endl;
+            delete (it->second);
+        }
+
+        this->bHasConsoleCommands_ = true;
+        this->consoleCommands_[command->getName()] = command;
+        this->consoleCommands_LC_[getLowercase(command->getName())] = command;
+
+        if (bCreateShortcut)
+            CommandExecutor::addConsoleCommandShortcut(command);
+
+        return (*command);
+    }
+
+    /**
+        @brief Returns the executor of a console command with given name.
+        @brief name The name of the requested console command
+        @return The executor of the requested console command
+    */
+    ConsoleCommand* Identifier::getConsoleCommand(const std::string& name) const
+    {
+        std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_.find(name);
+        if (it != this->consoleCommands_.end())
+            return (*it).second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns the executor of a console command with given name in lowercase.
+        @brief name The name of the requested console command in lowercae
+        @return The executor of the requested console command
+    */
+    ConsoleCommand* Identifier::getLowercaseConsoleCommand(const std::string& name) const
+    {
+        std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_LC_.find(name);
+        if (it != this->consoleCommands_LC_.end())
+            return (*it).second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns a XMLPortParamContainer that loads a parameter of this class.
+        @param paramname The name of the parameter
+        @return The container
+    */
+    XMLPortParamContainer* Identifier::getXMLPortParamContainer(const std::string& paramname)
+    {
+        std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
+        if (it != this->xmlportParamContainers_.end())
+            return ((*it).second);
+        else
+            return 0;
+    }
+
+    /**
+        @brief Adds a new XMLPortParamContainer that loads a parameter of this class.
+        @param paramname The name of the parameter
+        @param container The container
+    */
+    void Identifier::addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container)
+    {
+        std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
+        if (it != this->xmlportParamContainers_.end())
+        {
+            COUT(2) << "Warning: Overwriting XMLPortParamContainer in class " << this->getName() << "." << std::endl;
+            delete (it->second);
+        }
+
+        this->xmlportParamContainers_[paramname] = container;
+    }
+
+    /**
+        @brief Returns a XMLPortObjectContainer that attaches an object to this class.
+        @param sectionname The name of the section that contains the attachable objects
+        @return The container
+    */
+    XMLPortObjectContainer* Identifier::getXMLPortObjectContainer(const std::string& sectionname)
+    {
+        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
+        if (it != this->xmlportObjectContainers_.end())
+            return ((*it).second);
+        else
+            return 0;
+    }
+
+    /**
+        @brief Adds a new XMLPortObjectContainer that attaches an object to this class.
+        @param sectionname The name of the section that contains the attachable objects
+        @param container The container
+    */
+    void Identifier::addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container)
+    {
+        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
+        if (it != this->xmlportObjectContainers_.end())
+        {
+            COUT(2) << "Warning: Overwriting XMLPortObjectContainer in class " << this->getName() << "." << std::endl;
+            delete (it->second);
+        }
+
+        this->xmlportObjectContainers_[sectionname] = container;
+    }
+
+    /**
+        @brief Returns a XMLPortEventContainer that attaches an event to this class.
+        @param sectionname The name of the section that contains the event
+        @return The container
+    */
+    XMLPortObjectContainer* Identifier::getXMLPortEventContainer(const std::string& eventname)
+    {
+        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
+        if (it != this->xmlportEventContainers_.end())
+            return ((*it).second);
+        else
+            return 0;
+    }
+
+    /**
+        @brief Adds a new XMLPortEventContainer that attaches an event to this class.
+        @param sectionname The name of the section that contains the event
+        @param container The container
+    */
+    void Identifier::addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container)
+    {
+        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
+        if (it != this->xmlportEventContainers_.end())
+        {
+            COUT(2) << "Warning: Overwriting XMLPortEventContainer in class " << this->getName() << "." << std::endl;
+            delete (it->second);
+        }
+
+        this->xmlportEventContainers_[eventname] = container;
+    }
+
+    /**
+        @brief Lists the names of all Identifiers in a std::set<const Identifier*>.
+        @param out The outstream
+        @param list The list (or set) of Identifiers
+        @return The outstream
+    */
+    std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list)
+    {
+        for (std::set<const Identifier*>::const_iterator it = list.begin(); it != list.end(); ++it)
+            out << (*it)->getName() << " ";
+
+        return out;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Identifier.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Identifier.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Identifier.h	(revision 5712)
@@ -0,0 +1,661 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the Identifier, ClassIdentifier and SubclassIdentifier classes, implementation of the ClassIdentifier and SubclassIdentifier classes.
+
+    The Identifier contains all needed information about the class it belongs to:
+     - the name
+     - a list with all objects
+     - parents and children
+     - the factory (if available)
+     - the networkID that can be synchronised with the server
+     - all configurable variables (if available)
+
+    Every object has a pointer to the Identifier of its class. This allows the use isA(...),
+    isExactlyA(...), isChildOf(...) and isParentOf(...).
+
+    To create the class-hierarchy, the Identifier has some intern functions and variables.
+
+    Every Identifier is in fact a ClassIdentifier, but they are derived from Identifier.
+
+    SubclassIdentifier is a separated class, acting like an Identifier, but has a given class.
+    You can only assign Identifiers of exactly the given class or of a derivative to a SubclassIdentifier.
+*/
+
+#ifndef _Identifier_H__
+#define _Identifier_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <map>
+#include <set>
+#include <string>
+#include <typeinfo>
+
+#include "util/Debug.h"
+#include "util/TypeTraits.h"
+#include "MetaObjectList.h"
+#include "ObjectList.h"
+#include "ObjectListBase.h"
+#include "Super.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###       Identifier        ###
+    // ###############################
+    //! The Identifier is used to identify the class of an object and to store information about the class.
+    /**
+        The Identifier contains all needed information about the class it belongs to:
+         - the name
+         - a list with all objects
+         - parents and children
+         - the factory (if available)
+         - the networkID that can be synchronised with the server
+         - all configurable variables (if available)
+
+        Every object has a pointer to the Identifier of its class. This allows the use isA(...),
+        isExactlyA(...), isChildOf(...) and isParentOf(...).
+
+        You can't directly create an Identifier, it's just the base-class for ClassIdentifier.
+    */
+    class _CoreExport Identifier
+    {
+        template <class T>
+        friend class SubclassIdentifier;
+
+        friend class Factory;
+
+        public:
+            /** @brief Sets the Factory. @param factory The factory to assign */
+            inline void addFactory(BaseFactory* factory) { this->factory_ = factory; }
+
+            BaseObject* fabricate(BaseObject* creator);
+            bool isA(const Identifier* identifier) const;
+            bool isExactlyA(const Identifier* identifier) const;
+            bool isChildOf(const Identifier* identifier) const;
+            bool isDirectChildOf(const Identifier* identifier) const;
+            bool isParentOf(const Identifier* identifier) const;
+            bool isDirectParentOf(const Identifier* identifier) const;
+
+            /** @brief Returns true if the class can be loaded through XML. */
+            inline bool isLoadable() const { return this->bLoadable_; }
+            /** @brief Set the class to be loadable through XML or not. */
+            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
+
+            /** @brief Returns the list of all existing objects of this class. @return The list */
+            inline ObjectListBase* getObjects() const
+                { return this->objects_; }
+
+            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
+            inline const std::string& getName() const { return this->name_; }
+            void setName(const std::string& name);
+
+            virtual void updateConfigValues(bool updateChildren = true) const = 0;
+
+            /** @brief Returns the parents of the class the Identifier belongs to. @return The list of all parents */
+            inline const std::set<const Identifier*>& getParents() const { return this->parents_; }
+            /** @brief Returns the begin-iterator of the parents-list. @return The begin-iterator */
+            inline std::set<const Identifier*>::const_iterator getParentsBegin() const { return this->parents_.begin(); }
+            /** @brief Returns the end-iterator of the parents-list. @return The end-iterator */
+            inline std::set<const Identifier*>::const_iterator getParentsEnd() const { return this->parents_.end(); }
+
+            /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
+            inline const std::set<const Identifier*>& getChildren() const { return (*this->children_); }
+            /** @brief Returns the begin-iterator of the children-list. @return The begin-iterator */
+            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_->begin(); }
+            /** @brief Returns the end-iterator of the children-list. @return The end-iterator */
+            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_->end(); }
+
+            /** @brief Returns the direct parents of the class the Identifier belongs to. @return The list of all direct parents */
+            inline const std::set<const Identifier*>& getDirectParents() const { return this->directParents_; }
+            /** @brief Returns the begin-iterator of the direct-parents-list. @return The begin-iterator */
+            inline std::set<const Identifier*>::const_iterator getDirectParentsBegin() const { return this->directParents_.begin(); }
+            /** @brief Returns the end-iterator of the direct-parents-list. @return The end-iterator */
+            inline std::set<const Identifier*>::const_iterator getDirectParentsEnd() const { return this->directParents_.end(); }
+
+            /** @brief Returns the direct children the class the Identifier belongs to. @return The list of all direct children */
+            inline const std::set<const Identifier*>& getDirectChildren() const { return (*this->directChildren_); }
+            /** @brief Returns the begin-iterator of the direct-children-list. @return The begin-iterator */
+            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_->begin(); }
+            /** @brief Returns the end-iterator of the direct-children-list. @return The end-iterator */
+            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_->end(); }
+
+
+            /** @brief Returns the map that stores all Identifiers. @return The map */
+            static inline const std::map<std::string, Identifier*>& getIdentifierMap() { return Identifier::getIdentifierMapIntern(); }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapBegin() { return Identifier::getIdentifierMap().begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapEnd() { return Identifier::getIdentifierMap().end(); }
+
+            /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
+            static inline const std::map<std::string, Identifier*>& getLowercaseIdentifierMap() { return Identifier::getLowercaseIdentifierMapIntern(); }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapBegin() { return Identifier::getLowercaseIdentifierMap().begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapEnd() { return Identifier::getLowercaseIdentifierMap().end(); }
+
+
+            /** @brief Returns the map that stores all config values. @return The const_iterator */
+            inline const std::map<std::string, ConfigValueContainer*>& getConfigValueMap() const { return this->configValues_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all config values. @return The const_iterator */
+            inline std::map<std::string, ConfigValueContainer*>::const_iterator getConfigValueMapBegin() const { return this->configValues_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all config values. @return The const_iterator */
+            inline std::map<std::string, ConfigValueContainer*>::const_iterator getConfigValueMapEnd() const { return this->configValues_.end(); }
+
+            /** @brief Returns the map that stores all config values with their names in lowercase. @return The const_iterator */
+            inline const std::map<std::string, ConfigValueContainer*>& getLowercaseConfigValueMap() const { return this->configValues_LC_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all config values with their names in lowercase. @return The const_iterator */
+            inline std::map<std::string, ConfigValueContainer*>::const_iterator getLowercaseConfigValueMapBegin() const { return this->configValues_LC_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all config values with their names in lowercase. @return The const_iterator */
+            inline std::map<std::string, ConfigValueContainer*>::const_iterator getLowercaseConfigValueMapEnd() const { return this->configValues_LC_.end(); }
+
+
+            /** @brief Returns the map that stores all console commands. @return The const_iterator */
+            inline const std::map<std::string, ConsoleCommand*>& getConsoleCommandMap() const { return this->consoleCommands_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all console commands. @return The const_iterator */
+            inline std::map<std::string, ConsoleCommand*>::const_iterator getConsoleCommandMapBegin() const { return this->consoleCommands_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all console commands. @return The const_iterator */
+            inline std::map<std::string, ConsoleCommand*>::const_iterator getConsoleCommandMapEnd() const { return this->consoleCommands_.end(); }
+
+            /** @brief Returns the map that stores all console commands with their names in lowercase. @return The const_iterator */
+            inline const std::map<std::string, ConsoleCommand*>& getLowercaseConsoleCommandMap() const { return this->consoleCommands_LC_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all console commands with their names in lowercase. @return The const_iterator */
+            inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandMapBegin() const { return this->consoleCommands_LC_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all console commands with their names in lowercase. @return The const_iterator */
+            inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandMapEnd() const { return this->consoleCommands_LC_.end(); }
+
+            /** @brief Returns the map that stores all XMLPort params. @return The const_iterator */
+            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort params. @return The const_iterator */
+            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort params. @return The const_iterator */
+            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
+
+            /** @brief Returns the map that stores all XMLPort objects. @return The const_iterator */
+            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort objects. @return The const_iterator */
+            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort objects. @return The const_iterator */
+            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
+
+            /** @brief Returns the map that stores all XMLPort events. @return The const_iterator */
+            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortEventMap() const { return this->xmlportEventContainers_; }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort events. @return The const_iterator */
+            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapBegin() const { return this->xmlportEventContainers_.begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort events. @return The const_iterator */
+            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapEnd() const { return this->xmlportEventContainers_.end(); }
+
+            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
+            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
+            /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
+            inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
+
+            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
+            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
+
+            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
+            inline const uint32_t getNetworkID() const { return this->networkID_; }
+
+            /** @brief Sets the network ID to a new value. @param id The new value */
+            void setNetworkID(uint32_t id);
+
+            /** @brief Returns the unique ID of the class */
+            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
+
+            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
+            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
+            ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
+
+            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
+            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
+
+            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
+            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
+
+            void addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container);
+            XMLPortObjectContainer* getXMLPortEventContainer(const std::string& eventname);
+
+            ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
+            ConsoleCommand* getConsoleCommand(const std::string& name) const;
+            ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
+
+            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
+
+            static void destroyAllIdentifiers();
+
+        protected:
+            Identifier();
+            Identifier(const Identifier& identifier); // don't copy
+            virtual ~Identifier();
+
+            static Identifier* getIdentifierSingleton(const std::string& name, Identifier* proposal);
+            virtual void createSuperFunctionCaller() const = 0;
+
+            /** @brief Returns the map that stores all Identifiers. @return The map */
+            static std::map<std::string, Identifier*>& getIdentifierMapIntern();
+            /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
+            static std::map<std::string, Identifier*>& getLowercaseIdentifierMapIntern();
+
+            /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
+            inline std::set<const Identifier*>& getChildrenIntern() const { return (*this->children_); }
+            /** @brief Returns the direct children of the class the Identifier belongs to. @return The list of all direct children */
+            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return (*this->directChildren_); }
+
+            ObjectListBase* objects_;                                      //!< The list of all objects of this class
+
+        private:
+            /**
+                @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents.
+            */
+            inline static void startCreatingHierarchy()
+            {
+                hierarchyCreatingCounter_s++;
+                COUT(4) << "*** Identifier: Increased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
+            }
+
+            /**
+                @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents.
+            */
+            inline static void stopCreatingHierarchy()
+            {
+                hierarchyCreatingCounter_s--;
+                COUT(4) << "*** Identifier: Decreased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
+            }
+
+            static std::map<std::string, Identifier*>& getTypeIDIdentifierMap();
+
+            void initialize(std::set<const Identifier*>* parents);
+
+            std::set<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to
+            std::set<const Identifier*>* children_;                        //!< The children of the class the Identifier belongs to
+
+            std::set<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to
+            std::set<const Identifier*>* directChildren_;                  //!< The direct children of the class the Identifier belongs to
+
+            bool bCreatedOneObject_;                                       //!< True if at least one object of the given type was created (used to determine the need of storing the parents)
+            bool bSetName_;                                                //!< True if the name is set
+            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
+            std::string name_;                                             //!< The name of the class the Identifier belongs to
+            BaseFactory* factory_;                                         //!< The Factory, able to create new objects of the given class (if available)
+            static int hierarchyCreatingCounter_s;                         //!< Bigger than zero if at least one Identifier stores its parents (its an int instead of a bool to avoid conflicts with multithreading)
+            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
+            const unsigned int classID_;                                   //!< Uniquely identifies a class (might not be the same as the networkID_)
+            static unsigned int classIDCounter_s;                          //!< Static counter for the unique classIDs
+
+            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
+            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
+            std::map<std::string, ConfigValueContainer*> configValues_LC_; //!< A map to link the string of configurable variables with their ConfigValueContainer
+
+            bool bHasConsoleCommands_;                                     //!< True if this class has at least one assigned console command
+            std::map<std::string, ConsoleCommand*> consoleCommands_;       //!< All console commands of this class
+            std::map<std::string, ConsoleCommand*> consoleCommands_LC_;    //!< All console commands of this class with their names in lowercase
+
+            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
+            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
+            std::map<std::string, XMLPortObjectContainer*> xmlportEventContainers_;    //!< All events
+    };
+
+    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
+
+
+    // ###############################
+    // ###     ClassIdentifier     ###
+    // ###############################
+    //! The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
+    /**
+        ClassIdentifier is a Singleton, which means that only one object of a given type T exists.
+        This makes it possible to store information about a class, sharing them with all
+        objects of that class without defining static variables in every class.
+
+        To be really sure that not more than exactly one object exists (even with libraries),
+        ClassIdentifiers are stored in the Identifier Singleton.
+    */
+    template <class T>
+    class ClassIdentifier : public Identifier
+    {
+        #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
+        #include "Super.h"
+
+        public:
+            static ClassIdentifier<T> *getIdentifier();
+            static ClassIdentifier<T> *getIdentifier(const std::string& name);
+
+            bool initialiseObject(T* object, const std::string& className, bool bRootClass);
+
+            void updateConfigValues(bool updateChildren = true) const;
+
+        private:
+            static void initialiseIdentifier();
+            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
+            ClassIdentifier()
+            {
+                SuperFunctionInitialization<0, T>::initialize(this);
+            }
+            ~ClassIdentifier()
+            {
+                SuperFunctionDestruction<0, T>::destroy(this);
+            }
+
+            static ClassIdentifier<T>* classIdentifier_s;
+    };
+
+    template <class T>
+    ClassIdentifier<T>* ClassIdentifier<T>::classIdentifier_s = 0;
+
+    /**
+        @brief Returns the only instance of this class.
+        @return The unique Identifier
+    */
+    template <class T>
+    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
+    {
+        // check if the static field has already been filled
+        if (ClassIdentifier<T>::classIdentifier_s == 0)
+            ClassIdentifier<T>::initialiseIdentifier();
+
+        return ClassIdentifier<T>::classIdentifier_s;
+    }
+
+    /**
+        @brief Does the same as getIdentifier() but sets the name if this wasn't done yet.
+        @param name The name of this Identifier
+        @return The Identifier
+    */
+    template <class T>
+    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier(const std::string& name)
+    {
+        ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
+        identifier->setName(name);
+        return identifier;
+    }
+
+    /**
+        @brief Assigns the static field for the identifier singleton.
+    */
+    template <class T>
+    void ClassIdentifier<T>::initialiseIdentifier()
+    {
+        // Get the name of the class
+        std::string name = typeid(T).name();
+
+        // create a new identifier anyway. Will be deleted in Identifier::getIdentifier if not used.
+        ClassIdentifier<T>* proposal = new ClassIdentifier<T>();
+
+        // Get the entry from the map
+        ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*)Identifier::getIdentifierSingleton(name, proposal);
+
+        if (ClassIdentifier<T>::classIdentifier_s == proposal)
+        {
+            COUT(4) << "*** Identifier: Requested Identifier for " << name << " was not yet existing and got created." << std::endl;
+        }
+        else
+        {
+            COUT(4) << "*** Identifier: Requested Identifier for " << name << " was already existing and got assigned." << std::endl;
+        }
+    }
+
+    /**
+        @brief Adds an object of the given type to the ObjectList.
+        @param object The object to add
+    */
+    template <class T>
+    bool ClassIdentifier<T>::initialiseObject(T* object, const std::string& className, bool bRootClass)
+    {
+        if (bRootClass)
+            COUT(5) << "*** Register Root-Object: " << className << std::endl;
+        else
+            COUT(5) << "*** Register Object: " << className << std::endl;
+
+        object->identifier_ = this;
+        if (Identifier::isCreatingHierarchy())
+        {
+            if (bRootClass && !object->parents_)
+                object->parents_ = new std::set<const Identifier*>();
+
+            if (object->parents_)
+            {
+                this->initializeClassHierarchy(object->parents_, bRootClass);
+                object->parents_->insert(object->parents_->end(), this);
+            }
+
+            object->setConfigValues();
+            return true;
+        }
+        else
+        {
+            COUT(5) << "*** ClassIdentifier: Added object to " << this->getName() << "-list." << std::endl;
+            object->metaList_->add(this->objects_, this->objects_->add(new ObjectListElement<T>(object)));
+
+            // Add pointer of type T to the map in the OrxonoxClass instance that enables "dynamic_casts"
+            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
+            return false;
+        }
+    }
+
+    /**
+        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
+    */
+    template <class T>
+    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
+    {
+        if (!this->hasConfigValues())
+            return;
+
+        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
+            it->setConfigValues();
+
+        if (updateChildren)
+            for (std::set<const Identifier*>::const_iterator it = this->getChildrenBegin(); it != this->getChildrenEnd(); ++it)
+                (*it)->updateConfigValues(false);
+    }
+
+
+    // ###############################
+    // ###      orxonox_cast       ###
+    // ###############################
+    /**
+    @brief
+        Casts on object of type OrxonoxClass to any derived type that is
+        registered in the class hierarchy.
+    @return
+        Returns NULL if the cast is not possible
+    @note
+        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
+        a class forgot to register its objects.
+        Also note that the function is implemented differently for GCC/MSVC.
+    */
+    template <class T, class U>
+    FORCEINLINE T orxonox_cast(U source)
+    {
+#ifdef ORXONOX_COMPILER_MSVC
+        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
+        if (source != NULL)
+            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
+        else
+            return NULL;
+#else
+        return dynamic_cast<T>(source);
+#endif
+    }
+
+
+    // ###############################
+    // ###   SubclassIdentifier    ###
+    // ###############################
+    //! The SubclassIdentifier acts almost like an Identifier, but has some prerequisites.
+    /**
+        You can only assign an Identifier that belongs to a class T (or derived) to a SubclassIdentifier<T>.
+        If you assign something else, the program aborts.
+        Because we know the minimum type, a dynamic_cast is done, which makes it easier to create a new object.
+    */
+    template <class T>
+    class SubclassIdentifier
+    {
+        public:
+            /**
+                @brief Constructor: Automaticaly assigns the Identifier of the given class.
+            */
+            SubclassIdentifier()
+            {
+                this->identifier_ = ClassIdentifier<T>::getIdentifier();
+            }
+
+            /**
+                @brief Copyconstructor: Assigns the given Identifier.
+                @param identifier The Identifier
+            */
+            SubclassIdentifier(Identifier* identifier)
+            {
+                this->operator=(identifier);
+            }
+
+            /**
+                @brief Overloading of the = operator: assigns the identifier and checks its type.
+                @param identifier The Identifier to assign
+                @return The SubclassIdentifier itself
+            */
+            SubclassIdentifier<T>& operator=(Identifier* identifier)
+            {
+                if (!identifier || !identifier->isA(ClassIdentifier<T>::getIdentifier()))
+                {
+                    COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
+                    if (identifier)
+                    {
+                        COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
+                        COUT(1) << "Error: SubclassIdentifier<" << ClassIdentifier<T>::getIdentifier()->getName() << "> = Class(" << identifier->getName() << ") is forbidden." << std::endl;
+                    }
+                    else
+                    {
+                        COUT(1) << "Error: Can't assign NULL identifier" << std::endl;
+                    }
+                }
+                else
+                {
+                    this->identifier_ = identifier;
+                }
+                return *this;
+            }
+
+            /**
+                @brief Overloading of the * operator: returns the assigned identifier.
+            */
+            inline Identifier* operator*() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Overloading of the -> operator: returns the assigned identifier.
+            */
+            inline Identifier* operator->() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
+            */
+            inline operator Identifier*() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
+                @return The new object
+            */
+            T* fabricate(BaseObject* creator) const
+            {
+                BaseObject* newObject = this->identifier_->fabricate(creator);
+
+                // Check if the creation was successful
+                if (newObject)
+                {
+                    return orxonox_cast<T*>(newObject);
+                }
+                else
+                {
+                    // Something went terribly wrong
+                    if (this->identifier_)
+                    {
+                        COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
+                        COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
+                        COUT(1) << "Error: Couldn't fabricate a new Object." << std::endl;
+                        COUT(1) << "Aborting..." << std::endl;
+                    }
+                    else
+                    {
+                        COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
+                        COUT(1) << "Error: Couldn't fabricate a new Object - Identifier is undefined." << std::endl;
+                        COUT(1) << "Aborting..." << std::endl;
+                    }
+
+                    assert(false);
+                    return 0;
+                }
+            }
+
+            /** @brief Returns the assigned identifier. @return The identifier */
+            inline Identifier* getIdentifier() const
+                { return this->identifier_; }
+
+//            /** @brief Returns true, if the assigned identifier is at least of the given type. @param identifier The identifier to compare with */
+//            inline bool isA(const Identifier* identifier) const
+//                { return this->identifier_->isA(identifier); }
+//
+//            /** @brief Returns true, if the assigned identifier is exactly of the given type. @param identifier The identifier to compare with */
+//            inline bool isExactlyA(const Identifier* identifier) const
+//                { return this->identifier_->isExactlyA(identifier); }
+//
+//            /** @brief Returns true, if the assigned identifier is a child of the given identifier. @param identifier The identifier to compare with */
+//            inline bool isChildOf(const Identifier* identifier) const
+//                { return this->identifier_->isChildOf(identifier); }
+//
+//            /** @brief Returns true, if the assigned identifier is a direct child of the given identifier. @param identifier The identifier to compare with */
+//            inline bool isDirectChildOf(const Identifier* identifier) const
+//                { return this->identifier_->isDirectChildOf(identifier); }
+//
+//            /** @brief Returns true, if the assigned identifier is a parent of the given identifier. @param identifier The identifier to compare with */
+//            inline bool isParentOf(const Identifier* identifier) const
+//                { return this->identifier_->isParentOf(identifier); }
+//
+//            /** @brief Returns true, if the assigned identifier is a direct parent of the given identifier. @param identifier The identifier to compare with */
+//            inline bool isDirectParentOf(const Identifier* identifier) const
+//                { return this->identifier_->isDirectParentOf(identifier); }
+
+        private:
+            Identifier* identifier_;            //!< The assigned identifier
+    };
+}
+
+#endif /* _Identifier_H__ */
Index: /code/branches/libraries2/src/libraries/core/Iterator.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Iterator.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Iterator.h	(revision 5712)
@@ -0,0 +1,306 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition and implementation of the Iterator class.
+
+    The Iterator of a given class allows to iterate through an ObjectList. Objects in
+    this list are casted to the template argument of the Iterator.
+
+    Usage:
+    for (Iterator<myClass> it = anyidentifier->getObjects()->begin(); it != anyidentifier->getObjects()->end(); ++it)
+    {
+        it->someFunction(...);
+        myClass* myObject = *it;
+    }
+*/
+
+#ifndef _Iterator_H__
+#define _Iterator_H__
+
+#include "CorePrereqs.h"
+
+#include "Identifier.h"
+#include "ObjectListBase.h"
+
+namespace orxonox
+{
+    //! The Iterator allows to iterate through a given ObjectList
+    template <class T = OrxonoxClass>
+    class Iterator
+    {
+        public:
+            /**
+                @brief Constructor: Sets the element, whereon the iterator points, to zero.
+            */
+            inline Iterator()
+            {
+                this->element_ = 0;
+                this->list_ = 0;
+            }
+
+            /**
+                @brief Constructor: Sets this element to the exported element.
+                @param exp The exported element
+            */
+            inline Iterator(const ObjectListBase::Export& exp)
+            {
+                this->element_ = exp.element_;
+                this->list_ = exp.list_;
+                this->list_->registerIterator(this);
+            }
+
+            /**
+                @brief Constructor: Sets this element to the element of another Iterator.
+                @param other The other Iterator
+            */
+            inline Iterator(const Iterator<T>& other)
+            {
+                this->element_ = other.element_;
+                this->list_ = other.list_;
+                this->list_->registerIterator(this);
+            }
+
+            /**
+                @brief Constructor: Sets this element to a given element
+                @param element The element
+            */
+            template <class O>
+            inline Iterator(ObjectListElement<O>* element)
+            {
+                this->element_ = (element) ? static_cast<ObjectListBaseElement*>(element) : 0;
+                this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
+                this->list_->registerIterator(this);
+            }
+
+            /**
+                @brief Constructor: Sets this element to the element an ObjectListIterator.
+                @param other The ObjectListIterator
+            */
+            template <class O>
+            inline Iterator(const ObjectListIterator<O>& other)
+            {
+                this->element_ = (other.element_) ? static_cast<ObjectListBaseElement*>(other.element_) : 0;
+                this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
+                this->list_->registerIterator(this);
+            }
+
+            /**
+                @brief Unregisters the Iterator from the ObjectList.
+            */
+            inline ~Iterator()
+            {
+                this->list_->unregisterIterator(this);
+            }
+
+            /**
+                @brief Assigns an exported element.
+                @param exp The exported element
+            */
+            inline const Iterator<T>& operator=(const ObjectListBase::Export& exp)
+            {
+                if (this->list_)
+                    this->list_->unregisterIterator(this);
+
+                this->element_ = exp.element_;
+                this->list_ = exp.list_;
+                this->list_->registerIterator(this);
+
+                return (*this);
+            }
+
+            /**
+                @brief Assigns the element of another Iterator.
+                @param other The other Iterator
+            */
+            inline const Iterator<T>& operator=(const Iterator<T>& other)
+            {
+                if (this->list_)
+                    this->list_->unregisterIterator(this);
+
+                this->element_ = other.element_;
+                this->list_ = other.list_;
+                this->list_->registerIterator(this);
+
+                return (*this);
+            }
+
+            /**
+                @brief Assigns a given element.
+                @param element The element
+            */
+            template <class O>
+            inline const Iterator<T>& operator=(ObjectListElement<O>* element)
+            {
+                if (this->list_)
+                    this->list_->unregisterIterator(this);
+
+                this->element_ = (element) ? static_cast<ObjectListBaseElement*>(element) : 0;
+                this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
+                this->list_->registerIterator(this);
+
+                return (*this);
+                return *this;
+            }
+
+            /**
+                @brief Assigns the element of an ObjectListIterator.
+                @param other The ObjectListIterator
+            */
+            template <class O>
+            inline const Iterator<T>& operator=(const ObjectListIterator<O>& other)
+            {
+                if (this->list_)
+                    this->list_->unregisterIterator(this);
+
+                this->element_ = (other.element_) ? static_cast<ObjectListBaseElement*>(other.element_) : 0;
+                this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
+                this->list_->registerIterator(this);
+
+                return (*this);
+            }
+
+            /**
+                @brief Overloading of the ++it operator: Iterator points to the next object in the list.
+                @return The Iterator itself
+            */
+            inline const Iterator<T>& operator++()
+            {
+                if (this->element_)
+                    this->element_ = this->element_->next_;
+                return *this;
+            }
+
+            /**
+                @brief Overloading of the it++ operator: Iterator points to the next object in the list.
+                @return The Iterator itself
+            */
+            inline Iterator<T> operator++(int i)
+            {
+                Iterator<T> copy = *this;
+                if (this->element_)
+                    this->element_ = this->element_->next_;
+                return copy;
+            }
+
+            /**
+                @brief Overloading of the --it operator: Iterator points to the previous object in the list.
+                @return The Iterator itself
+            */
+            inline const Iterator<T>& operator--()
+            {
+                if (this->element_)
+                    this->element_ = this->element_->prev_;
+                return *this;
+            }
+
+            /**
+                @brief Overloading of the it-- operator: Iterator points to the previous object in the list.
+                @return The Iterator itself
+            */
+            inline Iterator<T> operator--(int i)
+            {
+                Iterator<T> copy = *this;
+                if (this->element_)
+                    this->element_ = this->element_->prev_;
+                return copy;
+            }
+
+            /**
+                @brief Overloading of the *it operator: returns the pointer to the object.
+                @return The object the Iterator points at
+            */
+            inline T* operator*() const
+            {
+                if (this->element_)
+                    return orxonox_cast<T*>(this->element_->objectBase_);
+                else
+                    return 0;
+            }
+
+            /**
+                @brief Overloading of the it-> operator: returns the pointer to the object.
+                @return The object the Iterator points at
+            */
+            inline T* operator->() const
+            {
+                if (this->element_)
+                    return orxonox_cast<T*>(this->element_->objectBase_);
+                else
+                    return 0;
+            }
+
+            /**
+                @brief Overloading of the typecast-operator to bool: returns true if the iterator points to an existing object.
+                @return True if the Iterator points to an existing object.
+            */
+            inline operator bool() const
+            {
+                return (this->element_ != 0);
+            }
+
+            /**
+                @brief Overloading of the == operator to compare with another Iterator.
+                @param compare The other Iterator
+                @return True if the iterators point to the same element
+            */
+            inline bool operator==(const Iterator<T>& compare) const
+            {
+                return (this->element_ == compare.element_);
+            }
+
+            /**
+                @brief Overloading of the != operator to compare with another Iterator.
+                @param compare The other Iterator
+                @return True if the iterators point to different elements
+            */
+            inline bool operator!=(const Iterator<T>& compare) const
+            {
+                return (this->element_ != compare.element_);
+            }
+
+            /**
+                @brief Increments the Iterator if it points at the given object.
+                @param object The object to compare with
+            */
+            inline void incrementIfEqual(OrxonoxClass* object)
+            {
+                if (this->element_ && this->element_->objectBase_ == object)
+                    this->operator++();
+            }
+
+        protected:
+            ObjectListBaseElement* element_;       //!< The element the Iterator points at
+            ObjectListBase* list_;                 //!< The list wherein the element is
+    };
+
+    typedef Iterator<OrxonoxClass> BaseIterator;
+}
+
+#endif /* _Iterator_H__ */
Index: /code/branches/libraries2/src/libraries/core/Language.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Language.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Language.cc	(revision 5712)
@@ -0,0 +1,326 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the Language and the LanguageEntry classes.
+*/
+
+#include "Language.h"
+
+#include <fstream>
+#include <boost/filesystem.hpp>
+
+#include "util/Debug.h"
+#include "Core.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###      LanguageEntry      ###
+    // ###############################
+    /**
+        @brief Constructor: Sets the default entry.
+        @param fallbackEntry The default entry
+    */
+    LanguageEntry::LanguageEntry(const std::string& fallbackEntry)
+    {
+        this->fallbackEntry_ = fallbackEntry;
+        this->localisedEntry_ = fallbackEntry; // Set the localisation to the fallback entry, for the case that no translation gets assigned
+        this->bLocalisationSet_ = false;
+    }
+
+    /**
+        @brief Sets the localisation of the entry.
+        @param localisation The localisation
+    */
+    void LanguageEntry::setLocalisation(const std::string& localisation)
+    {
+        // Check if the translation is more than just an empty string
+        if ((localisation != "") && (localisation.size() > 0))
+        {
+            this->localisedEntry_ = localisation;
+            this->bLocalisationSet_ = true;
+        }
+        else
+            this->localisedEntry_ = this->fallbackEntry_;
+    }
+
+    /**
+        @brief Sets the default entry.
+        @param fallbackEntry The default entry
+    */
+    void LanguageEntry::setDefault(const std::string& fallbackEntry)
+    {
+        // If the default entry changes and the translation wasn't set yet, use the new default entry as translation
+        if (!this->bLocalisationSet_)
+            this->localisedEntry_ = fallbackEntry;
+
+        this->fallbackEntry_ = fallbackEntry;
+    }
+
+    // ###############################
+    // ###        Language         ###
+    // ###############################
+
+    Language* Language::singletonPtr_s = 0;
+
+    /**
+        @brief Constructor: Reads the default language file and sets some values.
+    */
+    Language::Language()
+    {
+        this->defaultLanguage_ = "default";
+        this->defaultLocalisation_ = "ERROR: LANGUAGE ENTRY DOESN'T EXIST!";
+
+        // Read the default language file to create all known LanguageEntry objects
+        this->readDefaultLanguageFile();
+    }
+
+    /**
+        @brief Destructor: Deletes all language entries.
+    */
+    Language::~Language()
+    {
+        for (std::map<std::string, LanguageEntry*>::iterator it = this->languageEntries_.begin(); it != this->languageEntries_.end(); ++it)
+            delete (it->second);
+    }
+
+    /**
+        @brief Creates a new LanguageEntry with a given label and a given default entry.
+        @param label The label of the entry
+        @param entry The default entry
+        @return The created LanguageEntry object
+    */
+    LanguageEntry* Language::createEntry(const LanguageEntryLabel& label, const std::string& entry)
+    {
+        std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(label);
+
+        // Make sure we don't create a duplicate entry
+        if (it == this->languageEntries_.end())
+        {
+            LanguageEntry* newEntry = new LanguageEntry(entry);
+            newEntry->setLabel(label);
+            this->languageEntries_[label] = newEntry;
+            return newEntry;
+        }
+
+        COUT(2) << "Warning: Language entry " << label << " is duplicate in " << getFilename(this->defaultLanguage_) << "!" << std::endl;
+        return it->second;
+    }
+
+    /**
+        @brief Adds a new LanguageEntry, if it's not already existing.
+        @param label The label of the entry
+        @param entry The default entry
+    */
+    void Language::addEntry(const LanguageEntryLabel& label, const std::string& entry)
+    {
+        COUT(5) << "Language: Called addEntry with\n  label: " << label << "\n  entry: " <<  entry << std::endl;
+        std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(label);
+        if (it == this->languageEntries_.end())
+        {
+            // The entry isn't available yet, meaning it's new, so create it
+            this->createEntry(label, entry);
+        }
+        else if (it->second->getDefault().compare(entry) == 0)
+        {
+            // The entry is available and the default string is the same, so return because everything is fine
+            return;
+        }
+        else
+        {
+            // The defined default entry is not the same as in the default language file - change it to the new entry
+            it->second->setDefault(entry);
+        }
+
+        // Write the default language file because either a new entry was created or an existing entry has changed
+        this->writeDefaultLanguageFile();
+
+    }
+
+    /**
+        @brief Returns the localisation of a given entry.
+        @param label The label of the entry
+        @return The localisation
+    */
+    const std::string& Language::getLocalisation(const LanguageEntryLabel& label) const
+    {
+        std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(label);
+        if (it != this->languageEntries_.end())
+            return it->second->getLocalisation();
+        else
+        {
+            // Uh, oh, an undefined entry was requested: return the default string
+            COUT(2) << "Warning: Language entry \"" << label << "\" not found!" << std::endl;
+            return this->defaultLocalisation_;
+        }
+    }
+
+    /**
+        @brief Creates the name of the language file out of the languages name.
+        @param language The name of the language
+        @return The filename
+    */
+    std::string Language::getFilename(const std::string& language)
+    {
+        return std::string("translation_" + language + ".lang");
+    }
+
+    /**
+        @brief Reads the default language file and creates a LanguageEntry objects for every entry.
+    */
+    void Language::readDefaultLanguageFile()
+    {
+        COUT(4) << "Read default language file." << std::endl;
+
+        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
+
+        // This creates the file if it's not existing
+        std::ofstream createFile;
+        createFile.open(filepath.string().c_str(), std::fstream::app);
+        createFile.close();
+
+        // Open the file
+        std::ifstream file;
+        file.open(filepath.string().c_str(), std::fstream::in);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "An error occurred in Language.cc:" << std::endl;
+            COUT(1) << "Error: Couldn't open file " << getFilename(this->defaultLanguage_) << " to read the default language entries!" << std::endl;
+            return;
+        }
+
+        // Iterate through the file and create the LanguageEntries
+        while (file.good() && !file.eof())
+        {
+            std::string lineString;
+            std::getline(file, lineString);
+
+            // Check if the line is empty
+            if ((lineString != "") && (lineString.size() > 0))
+            {
+                size_t pos = lineString.find('=');
+
+                // Check if the length is at least 3 and if there's an entry before and behind the =
+                if (pos > 0 && pos < (lineString.size() - 1) && lineString.size() >= 3)
+                    this->createEntry(lineString.substr(0, pos), lineString.substr(pos + 1));
+                else
+                {
+                    COUT(2) << "Warning: Invalid language entry \"" << lineString << "\" in " << getFilename(this->defaultLanguage_) << std::endl;
+                }
+            }
+        }
+
+        file.close();
+    }
+
+    /**
+        @brief Reads the language file of the configured language and assigns the localisation to the corresponding LanguageEntry object.
+    */
+    void Language::readTranslatedLanguageFile()
+    {
+        COUT(4) << "Read translated language file (" << Core::getLanguage() << ")." << std::endl;
+
+        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(Core::getLanguage()));
+
+        // Open the file
+        std::ifstream file;
+        file.open(filepath.string().c_str(), std::fstream::in);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "An error occurred in Language.cc:" << std::endl;
+            COUT(1) << "Error: Couldn't open file " << getFilename(Core::getLanguage()) << " to read the translated language entries!" << std::endl;
+            Core::resetLanguage();
+            COUT(3) << "Info: Reset language to " << this->defaultLanguage_ << "." << std::endl;
+            return;
+        }
+
+        // Iterate through the file and create the LanguageEntries
+        while (file.good() && !file.eof())
+        {
+            std::string lineString;
+            std::getline(file, lineString);
+
+            // Check if the line is empty
+            if ((lineString != "") && (lineString.size() > 0))
+            {
+                size_t pos = lineString.find('=');
+
+                // Check if the length is at least 3 and if there's an entry before and behind the =
+                if (pos > 0 && pos < (lineString.size() - 1) && lineString.size() >= 3)
+                {
+                    std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(lineString.substr(0, pos));
+
+                    // Check if the entry exists
+                    if (it != this->languageEntries_.end())
+                        it->second->setLocalisation(lineString.substr(pos + 1));
+                    else
+                        this->createEntry(lineString.substr(0, pos), this->defaultLocalisation_)->setLocalisation(lineString.substr(pos + 1));
+                }
+                else
+                {
+                    COUT(2) << "Warning: Invalid language entry \"" << lineString << "\" in " << getFilename(Core::getLanguage()) << std::endl;
+                }
+            }
+        }
+
+        file.close();
+    }
+
+    /**
+        @brief Writes all default entries to the default language file.
+    */
+    void Language::writeDefaultLanguageFile() const
+    {
+        COUT(4) << "Language: Write default language file." << std::endl;
+
+        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
+
+        // Open the file
+        std::ofstream file;
+        file.open(filepath.string().c_str(), std::fstream::out);
+
+        if (!file.is_open())
+        {
+            COUT(1) << "An error occurred in Language.cc:" << std::endl;
+            COUT(1) << "Error: Couldn't open file " << getFilename(this->defaultLanguage_) << " to write the default language entries!" << std::endl;
+            return;
+        }
+
+        // Iterate through the list an write the lines into the file
+        for (std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.begin(); it != this->languageEntries_.end(); ++it)
+        {
+            file << (*it).second->getLabel() << "=" << (*it).second->getDefault() << std::endl;
+        }
+
+        file.close();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Language.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Language.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Language.h	(revision 5712)
@@ -0,0 +1,144 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the Language and the LanguageEntry class.
+
+    The Language class is used, to get a localisation of a string in the configured language.
+    The string is identified by another string, the label of the entry.
+    If the translation in the configured language isn't available, the default entry, defined in the code, is used.
+
+    Usage:
+     - Set the entry with the default string:
+       Language::getInstance()->addEntry("label of the entry", "the string to translate");
+
+     - Get the localisation of the entry in the configured language:
+       std::cout << Language::getInstance()->getLocalisation("name of the entry") << std::endl;
+*/
+
+#ifndef _Language_H__
+#define _Language_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <string>
+#include <cassert>
+#include "util/Singleton.h"
+
+#define AddLanguageEntry(label, fallbackstring) \
+    orxonox::Language::getInstance().addEntry(label, fallbackstring)
+
+#define GetLocalisation(label) \
+    orxonox::Language::getInstance().getLocalisation(label)
+
+
+namespace orxonox
+{
+    // ###############################
+    // ###      LanguageEntry      ###
+    // ###############################
+    //! The LanguageEntry class stores the default- and the translated string of a given entry in the language file.
+    class _CoreExport LanguageEntry
+    {
+        public:
+            explicit LanguageEntry(const std::string& fallbackEntry);
+            void setLocalisation(const std::string& localisation);
+            void setDefault(const std::string& fallbackEntry);
+
+            /**
+              @brief Returns the localised entry in the configured language.
+              @return The translated entry
+            */
+            inline const std::string& getLocalisation()
+                { return this->localisedEntry_; }
+
+            /**
+              @brief Returns the default entry.
+              @return The default entry
+            */
+            inline const std::string& getDefault()
+                { return this->fallbackEntry_; }
+
+            /**
+                @brief Sets the label of this entry.
+                @param label The label
+            */
+            inline void setLabel(const LanguageEntryLabel& label)
+                { this->label_ = label; }
+
+            /**
+                @brief Returns the label of this entry.
+                @return The label
+            */
+            inline const LanguageEntryLabel& getLabel() const
+                { return this->label_; }
+
+        private:
+            LanguageEntryLabel label_;              //!< The label of the entry
+            std::string fallbackEntry_;             //!< The default entry: Used, if no translation is available or no language configured
+            std::string localisedEntry_;            //!< The localised entry in the configured language
+            bool bLocalisationSet_;                 //!< True if the translation was set
+    };
+
+
+    // ###############################
+    // ###         Language        ###
+    // ###############################
+    //! The Language class manges the language files and entries and stores the LanguageEntry objects in a map.
+    class _CoreExport Language : public Singleton<Language>
+    {
+        friend class Singleton<Language>;
+        friend class CoreConfiguration;
+
+        public:
+            Language();
+            ~Language();
+
+            void addEntry(const LanguageEntryLabel& label, const std::string& entry);
+            const std::string& getLocalisation(const LanguageEntryLabel& label) const;
+
+        private:
+            Language(const Language&);
+
+            void readDefaultLanguageFile();
+            void readTranslatedLanguageFile();
+            void writeDefaultLanguageFile() const;
+            static std::string getFilename(const std::string& language);
+            LanguageEntry* createEntry(const LanguageEntryLabel& label, const std::string& entry);
+
+            std::string defaultLanguage_;                           //!< The default language
+            std::string defaultLocalisation_;                       //!< The returned string, if an entry unavailable entry is requested
+            std::map<std::string, LanguageEntry*> languageEntries_; //!< A map to store all LanguageEntry objects and their labels
+
+            static Language* singletonPtr_s;
+    };
+}
+
+#endif /* _Language_H__ */
Index: /code/branches/libraries2/src/libraries/core/Loader.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Loader.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Loader.cc	(revision 5712)
@@ -0,0 +1,375 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Loader.h"
+
+#include <sstream>
+#include <tinyxml/ticpp.h>
+#include <boost/scoped_ptr.hpp>
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/StringUtils.h"
+#include "BaseObject.h"
+#include "Iterator.h"
+#include "ObjectList.h"
+#include "LuaState.h"
+#include "Namespace.h"
+#include "Resource.h"
+#include "XMLFile.h"
+
+namespace orxonox
+{
+    std::vector<std::pair<const XMLFile*, ClassTreeMask> > Loader::files_s;
+    ClassTreeMask Loader::currentMask_s;
+
+    bool Loader::open(const XMLFile* file, const ClassTreeMask& mask)
+    {
+        Loader::add(file, mask);
+        return Loader::load(file, mask);
+    }
+
+    void Loader::close()
+    {
+        Loader::unload();
+        Loader::files_s.clear();
+    }
+
+    void Loader::close(const XMLFile* file)
+    {
+        Loader::unload(file);
+        Loader::remove(file);
+    }
+
+    void Loader::add(const XMLFile* file, const ClassTreeMask& mask)
+    {
+        if (!file)
+            return;
+        Loader::files_s.insert(Loader::files_s.end(), std::pair<const XMLFile*, ClassTreeMask>(file, mask));
+    }
+
+    void Loader::remove(const XMLFile* file)
+    {
+        if (!file)
+            return;
+        for (std::vector<std::pair<const XMLFile*, ClassTreeMask> >::iterator it = Loader::files_s.begin(); it != Loader::files_s.end(); ++it)
+        {
+            if ((*it).first == file)
+            {
+                Loader::files_s.erase(it);
+                break;
+            }
+        }
+    }
+
+    bool Loader::load(const ClassTreeMask& mask)
+    {
+        bool success = true;
+        for (std::vector<std::pair<const XMLFile*, ClassTreeMask> >::iterator it = Loader::files_s.begin(); it != Loader::files_s.end(); ++it)
+            if (!Loader::load((*it).first, (*it).second * mask))
+                success = false;
+
+        return success;
+    }
+
+    void Loader::unload(const ClassTreeMask& mask)
+    {
+        for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); )
+        {
+            if (mask.isIncluded(it->getIdentifier()))
+                delete (*(it++));
+            else
+                ++it;
+        }
+    }
+
+    bool Loader::reload(const ClassTreeMask& mask)
+    {
+        Loader::unload(mask);
+        return Loader::load(mask);
+    }
+
+    bool Loader::load(const XMLFile* file, const ClassTreeMask& mask)
+    {
+        if (!file)
+            return false;
+
+        Loader::currentMask_s = file->getMask() * mask;
+
+        std::string xmlInput;
+        if (file->getLuaSupport())
+        {
+            // Use the LuaState to replace the XML tags (calls our function)
+            scoped_ptr<LuaState> luaState(new LuaState());
+            luaState->setIncludeParser(&Loader::replaceLuaTags);
+            luaState->includeFile(file->getFilename(), file->getResourceGroup(), false);
+            xmlInput = luaState->getOutput().str();
+        }
+        else
+        {
+            shared_ptr<ResourceInfo> info = Resource::getInfo(file->getFilename(), file->getResourceGroup());
+            if (info == NULL)
+            {
+                COUT(1) << "Error: Could not find XML file '" << file->getFilename() << "'." << std::endl;
+                return false;
+            }
+            xmlInput = Resource::open(file->getFilename(), file->getResourceGroup())->getAsString();
+        }
+
+        try
+        {
+            COUT(0) << "Start loading " << file->getFilename() << "..." << std::endl;
+            COUT(3) << "Mask: " << Loader::currentMask_s << std::endl;
+
+            ticpp::Document xmlfile(file->getFilename());
+            xmlfile.Parse(xmlInput, true);
+
+            ticpp::Element rootElement;
+            rootElement.SetAttribute("name", "root");
+            rootElement.SetAttribute("bAutogenerated", true);
+
+            for (ticpp::Iterator<ticpp::Element> child = xmlfile.FirstChildElement(false); child != child.end(); child++)
+                rootElement.InsertEndChild(*child);
+
+            COUT(4) << "  creating root-namespace..." << std::endl;
+            Namespace* rootNamespace = new Namespace(0);
+            rootNamespace->setLoaderIndentation("    ");
+            rootNamespace->setFile(file);
+            rootNamespace->setNamespace(rootNamespace);
+            rootNamespace->setRoot(true);
+            rootNamespace->XMLPort(rootElement, XMLPort::LoadObject);
+
+            COUT(0) << "Finished loading " << file->getFilename() << "." << std::endl;
+
+            COUT(4) << "Namespace-tree:" << std::endl << rootNamespace->toString("  ") << std::endl;
+
+            return true;
+        }
+        catch (ticpp::Exception& ex)
+        {
+            COUT(1) << std::endl;
+            COUT(1) << "An XML-error occurred in Loader.cc while loading " << file->getFilename() << ":" << std::endl;
+            COUT(1) << ex.what() << std::endl;
+            COUT(1) << "Loading aborted." << std::endl;
+            return false;
+        }
+        catch (Exception& ex)
+        {
+            COUT(1) << std::endl;
+            COUT(1) << "A loading-error occurred in Loader.cc while loading " << file->getFilename() << ":" << std::endl;
+            COUT(1) << ex.what() << std::endl;
+            COUT(1) << "Loading aborted." << std::endl;
+            return false;
+        }
+        catch (std::exception& ex)
+        {
+            COUT(1) << std::endl;
+            COUT(1) << "An error occurred in Loader.cc while loading " << file->getFilename() << ":" << std::endl;
+            COUT(1) << ex.what() << std::endl;
+            COUT(1) << "Loading aborted." << std::endl;
+            return false;
+        }
+        catch (...)
+        {
+            COUT(1) << std::endl;
+            COUT(1) << "An unknown error occurred in Loader.cc while loading " << file->getFilename() << ":" << std::endl;
+            COUT(1) << "Loading aborted." << std::endl;
+            return false;
+        }
+    }
+
+    void Loader::unload(const XMLFile* file, const ClassTreeMask& mask)
+    {
+        if (!file)
+            return;
+        for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it; )
+        {
+            if ((it->getFile() == file) && mask.isIncluded(it->getIdentifier()))
+                delete (*(it++));
+            else
+                ++it;
+        }
+    }
+
+    bool Loader::reload(const XMLFile* file, const ClassTreeMask& mask)
+    {
+        Loader::unload(file, mask);
+        return Loader::load(file, mask);
+    }
+
+    std::string Loader::replaceLuaTags(const std::string& text)
+    {
+        // chreate map with all Lua tags
+        std::map<size_t, bool> luaTags;
+        {
+            size_t pos = 0;
+            while ((pos = text.find("<?lua", pos)) != std::string::npos)
+                luaTags[pos++] = true;
+        }
+        {
+            size_t pos = 0;
+            while ((pos = text.find("?>", pos)) != std::string::npos)
+                luaTags[pos++] = false;
+        }
+
+        // erase all tags from the map that are between two quotes
+        {
+            std::map<size_t, bool>::iterator it = luaTags.begin();
+            std::map<size_t, bool>::iterator it2 = it;
+            bool bBetweenQuotes = false;
+            size_t pos = 0;
+            while ((pos = getNextQuote(text, pos)) != std::string::npos)
+            {
+                while ((it != luaTags.end()) && (it->first < pos))
+                {
+                    if (bBetweenQuotes)
+                    {
+                        it2++;
+                        if(it->second && !(it2->second) && it2->first < pos)
+                            it = ++it2;
+                        else
+                            luaTags.erase(it++);
+                    }
+                    else
+                        ++it;
+                }
+                bBetweenQuotes = !bBetweenQuotes;
+                pos++;
+            }
+        }
+
+        // check whether on every opening <?lua tag a closing ?> tag follows
+        {
+            bool expectedValue = true;
+            for (std::map<size_t, bool>::iterator it = luaTags.begin(); it != luaTags.end(); ++it)
+            {
+                if (it->second == expectedValue)
+                    expectedValue = !expectedValue;
+                else
+                {
+                    expectedValue = false;
+                    break;
+                }
+            }
+            if (!expectedValue)
+            {
+                COUT(2) << "Warning: Error in level file" << std::endl;
+                // todo: errorhandling
+                return "";
+            }
+        }
+
+        // Use a stringstream object to speed up the parsing
+        std::ostringstream output;
+
+        // cut the original string into pieces and put them together with print() instead of lua tags
+        {
+            std::map<size_t, bool>::iterator it = luaTags.begin();
+            bool bInPrintFunction = true;
+            size_t start = 0;
+            size_t end = 0;
+
+            do
+            {
+                if (it != luaTags.end())
+                    end = (*(it++)).first;
+                else
+                    end = std::string::npos;
+
+                unsigned int equalSignCounter = 0;
+
+                if (bInPrintFunction)
+                {
+                    // count ['='[ and ]'='] and replace tags with print([[ and ]])
+                    std::string temp = text.substr(start, end - start);
+                    {
+                    size_t pos = 0;
+                    while ((pos = temp.find('[', pos)) != std::string::npos)
+                    {
+                        unsigned int tempCounter = 1;
+                        size_t tempPos = pos++;
+                        while(temp[++tempPos] == '=')
+                        {
+                            tempCounter++;
+                        }
+                        if(temp[tempPos] != '[')
+                        {
+                            tempCounter = 0;
+                        }
+                        else if(tempCounter == 0)
+                        {
+                            tempCounter = 1;
+                        }
+                        if (tempCounter > equalSignCounter)
+                            equalSignCounter = tempCounter;
+                        }
+                    }
+                    {
+                        size_t pos = 0;
+                        while ((pos = temp.find(']', pos)) != std::string::npos)
+                        {
+                            unsigned int tempCounter = 1;
+                            size_t tempPos = pos++;
+                            while(temp[++tempPos] == '=')
+                            {
+                                tempCounter++;
+                            }
+                            if(temp[tempPos] != ']')
+                            {
+                                tempCounter = 0;
+                            }
+                            else if(tempCounter == 0)
+                            {
+                                tempCounter = 1;
+                            }
+                            if (tempCounter > equalSignCounter)
+                                equalSignCounter = tempCounter;
+                        }
+                    }
+                    std::string equalSigns = "";
+                    for(unsigned int i = 0; i < equalSignCounter; i++)
+                    {
+                        equalSigns += "=";
+                    }
+                    output << "print([" + equalSigns + "[" + temp + "]" + equalSigns +"])";
+                    start = end + 5;
+                }
+                else
+                {
+                    output << text.substr(start, end - start);
+                    start = end + 2;
+                }
+
+                bInPrintFunction = !bInPrintFunction;
+            }
+            while (end != std::string::npos);
+        }
+
+        return output.str();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Loader.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Loader.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Loader.h	(revision 5712)
@@ -0,0 +1,66 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Loader_H__
+#define _Loader_H__
+
+#include "CorePrereqs.h"
+
+#include <vector>
+#include "ClassTreeMask.h"
+
+namespace orxonox
+{
+    class _CoreExport Loader
+    {
+        public:
+            static bool open(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
+            static void close();
+            static void close(const XMLFile* file);
+
+            static void add(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
+            static void remove(const XMLFile* file);
+
+            static bool load(const ClassTreeMask& mask = ClassTreeMask());
+            static void unload(const ClassTreeMask& mask = ClassTreeMask());
+            static bool reload(const ClassTreeMask& mask = ClassTreeMask());
+
+            static bool load(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
+            static void unload(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
+            static bool reload(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
+
+            static std::string replaceLuaTags(const std::string& text);
+
+            static ClassTreeMask currentMask_s;
+
+        private:
+            static std::vector<std::pair<const XMLFile*, ClassTreeMask> > files_s;
+    };
+}
+
+#endif /* _Loader_H__ */
Index: /code/branches/libraries2/src/libraries/core/LuaState.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/LuaState.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/LuaState.cc	(revision 5712)
@@ -0,0 +1,266 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Benjamin Knecht
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "LuaState.h"
+
+#include <tolua/tolua++.h>
+extern "C" {
+#include <lua.h>
+#include <lualib.h>
+}
+
+#include "util/Debug.h"
+#include "Core.h"
+#include "Resource.h"
+#include "ToluaBindCore.h"
+
+namespace orxonox
+{
+    LuaState::ToluaInterfaceMap LuaState::toluaInterfaces_s;
+    std::vector<LuaState*> LuaState::instances_s;
+
+    // Do this after declaring toluaInterfaces_s and instances_s to avoid larger problems
+    DeclareToluaInterface(Core);
+
+    LuaState::LuaState()
+        : bIsRunning_(false)
+        , includeParseFunction_(NULL)
+    {
+        // Create new lua state and configure it
+        luaState_ = lua_open();
+#if LUA_VERSION_NUM == 501
+        luaL_openlibs(luaState_);
+#else
+        luaopen_base(luaState_);
+        luaopen_string(luaState_);
+        luaopen_table(luaState_);
+        luaopen_math(luaState_);
+        luaopen_io(luaState_);
+        luaopen_debug(luaState_);
+#endif
+
+        // Open all available tolua interfaces
+        this->openToluaInterfaces(luaState_);
+
+        // Create dummy file info
+        sourceFileInfo_.reset(new ResourceInfo());
+        sourceFileInfo_->group = "General";
+        sourceFileInfo_->size = 0;
+
+        // Push this pointer
+        tolua_pushusertype(luaState_, static_cast<void*>(this), "orxonox::LuaState");
+        lua_setglobal(luaState_, "luaState");
+
+        // Parse init script
+        this->doFile("LuaStateInit.lua");
+    }
+
+    LuaState::~LuaState()
+    {
+        lua_close(luaState_);
+    }
+
+    shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
+    {
+        shared_ptr<ResourceInfo> sourceInfo;
+        if (resourceGroup != "NoResourceGroupProvided")
+            sourceInfo = Resource::getInfo(filename, resourceGroup);
+
+        // Continue search if not explicitely forbidden
+        if (bSearchOtherPaths && sourceInfo == NULL)
+        {
+            // Call might be relative to the file currently being processed
+            sourceInfo = Resource::getInfo(sourceFileInfo_->path + filename, sourceFileInfo_->group);
+            if (sourceInfo == NULL)
+            {
+                // Maybe find something in the same group but in the root path
+                sourceInfo = Resource::getInfo(filename, sourceFileInfo_->group);
+            }
+        }
+        return sourceInfo;
+    }
+
+    void LuaState::includeFile(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
+    {
+        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename, resourceGroup, bSearchOtherPaths);
+        if (sourceInfo != NULL)
+            this->includeString(Resource::open(sourceInfo->filename, sourceInfo->group)->getAsString(), sourceInfo);
+        else
+            COUT(2) << "LuaState: Cannot include file '" << filename << "' in resource group '"
+                    << (resourceGroup == "NoResourceGroupProvided" ? sourceFileInfo_->group : resourceGroup) << "': group not found." << std::endl;
+    }
+
+    void LuaState::includeString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo)
+    {
+        // Parse string with provided include parser (otherwise don't preparse at all)
+        std::string luaInput;
+        if (includeParseFunction_ != NULL)
+            luaInput = (*includeParseFunction_)(code);
+        else
+            luaInput = code;
+
+        this->doString(luaInput, sourceFileInfo);
+    }
+
+    void LuaState::doFile(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
+    {
+        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename, resourceGroup, bSearchOtherPaths);
+        if (sourceInfo != NULL)
+            this->doString(Resource::open(sourceInfo->filename, sourceInfo->group)->getAsString(), sourceInfo);
+        else
+            COUT(2) << "LuaState: Cannot do file '" << filename << "' in resource group '"
+                << (resourceGroup == "NoResourceGroupProvided" ? sourceFileInfo_->group : resourceGroup) << "': group not found." << std::endl;
+    }
+
+    void LuaState::doString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo)
+    {
+        // Save the oold source file info
+        shared_ptr<ResourceInfo> oldSourceFileInfo = sourceFileInfo_;
+        // Only override if sourceFileInfo provides useful information
+        if (sourceFileInfo != NULL)
+            sourceFileInfo_ = sourceFileInfo;
+
+        int error = 0;
+#if LUA_VERSION_NUM != 501
+        LoadS ls;
+        ls.s = code.c_str();
+        ls.size = code.size();
+        error = lua_load(luaState_, &orxonox::LuaState::lua_Chunkreader, &ls, code.c_str());
+#else
+        error = luaL_loadstring(luaState_, code.c_str());
+#endif
+
+        // execute the chunk
+        if (error == 0)
+            error = lua_pcall(luaState_, 0, 1, 0);
+        if (error != 0)
+        {
+            std::string origin;
+            if (sourceFileInfo != NULL)
+                origin = " originating from " + sourceFileInfo_->filename;
+            COUT(2) << "Error in Lua-script" << origin << ": " << lua_tostring(luaState_, -1) << std::endl;
+            // return value is nil
+            lua_pushnil(luaState_);
+        }
+        // push return value because it will get lost since the return value of this function is void
+        lua_setglobal(luaState_, "LuaStateReturnValue");
+
+        // Load the old info again
+        sourceFileInfo_ = oldSourceFileInfo;
+    }
+
+    void LuaState::luaPrint(const std::string& str)
+    {
+        output_ << str;
+    }
+
+    void LuaState::luaLog(unsigned int level, const std::string& message)
+    {
+        OutputHandler::getOutStream().setOutputLevel(level) << message << std::endl;
+    }
+
+    bool LuaState::fileExists(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
+    {
+        shared_ptr<ResourceInfo> info =  this->getFileInfo(filename, resourceGroup, bSearchOtherPaths);
+        if (info == NULL)
+            return false;
+        else
+            return true;
+    }
+
+#if LUA_VERSION_NUM != 501
+    const char * LuaState::lua_Chunkreader(lua_State *L, void *data, size_t *size)
+    {
+        LoadS* ls = static_cast<LoadS*>(data);
+        if (ls->size == 0)
+            return NULL;
+        *size = ls->size;
+        ls->size = 0;
+        return ls->s;
+    }
+#endif
+
+    /*static*/ bool LuaState::addToluaInterface(int (*function)(lua_State*), const std::string& name)
+    {
+        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
+        {
+            if (it->first == name || it->second == function)
+            {
+                COUT(2) << "Warning: Trying to add a Tolua interface with the same name or function." << std::endl;
+                return true;
+            }
+        }
+        toluaInterfaces_s[name] = function;
+
+        // Open interface in all LuaStates
+        for (std::vector<LuaState*>::const_iterator it = instances_s.begin(); it != instances_s.end(); ++it)
+            (*function)((*it)->luaState_);
+
+        // Return dummy bool
+        return true;
+    }
+
+    /*static*/ bool LuaState::removeToluaInterface(const std::string& name)
+    {
+        ToluaInterfaceMap::iterator it = toluaInterfaces_s.find(name);
+        if (it == toluaInterfaces_s.end())
+        {
+            COUT(2) << "Warning: Cannot remove Tolua interface '" << name << "': Not found" << std::endl;
+            return true;
+        }
+
+        // Close interface in all LuaStates
+        for (std::vector<LuaState*>::const_iterator itState = instances_s.begin(); itState != instances_s.end(); ++itState)
+        {
+            lua_pushnil((*itState)->luaState_);
+            lua_setglobal((*itState)->luaState_, it->first.c_str());
+        }
+
+        // Remove entry
+        toluaInterfaces_s.erase(it);
+
+        // Return dummy bool
+        return true;
+    }
+
+    /*static*/ void LuaState::openToluaInterfaces(lua_State* state)
+    {
+        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
+            (*it->second)(state);
+    }
+
+    /*static*/ void LuaState::closeToluaInterfaces(lua_State* state)
+    {
+        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
+        {
+            lua_pushnil(state);
+            lua_setglobal(state, it->first.c_str());
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/LuaState.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/LuaState.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/LuaState.h	(revision 5712)
@@ -0,0 +1,104 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Benjamin Knecht
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _LuaState_H__
+#define _LuaState_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <boost/shared_ptr.hpp>
+
+#include "util/ScopeGuard.h"
+#include "ToluaInterface.h"
+
+// tolua_begin
+namespace orxonox
+{
+    /**
+    @brief
+        Representation of an interface to lua
+    */
+    class _CoreExport LuaState
+    {
+// tolua_end
+    public:
+        LuaState();
+        ~LuaState();
+
+        void doFile(const std::string& filename, const std::string& resourceGroup = "General", bool bSearchOtherPaths = true); // tolua_export
+        void doString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo = shared_ptr<ResourceInfo>());
+
+        void includeFile(const std::string& filename, const std::string& resourceGroup = "General", bool bSearchOtherPaths = true); // tolua_export
+        void includeString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo = shared_ptr<ResourceInfo>());
+
+        void luaPrint(const std::string& str); // tolua_export
+        void luaLog(unsigned int level, const std::string& message); // tolua_export
+        bool fileExists(const std::string& filename, const std::string& resourceGroup = "General", bool bSearchOtherPaths = true); // tolua_export
+
+        const std::stringstream& getOutput() const { return output_; }
+        void clearOutput() { output_.clear(); } // tolua_export
+
+        void setIncludeParser(std::string (*function)(const std::string&)) { includeParseFunction_ = function; }
+        lua_State* getInternalLuaState() { return luaState_; }
+
+        static bool addToluaInterface(int (*function)(lua_State*), const std::string& name);
+        static bool removeToluaInterface(const std::string& name);
+        static void openToluaInterfaces(lua_State* state);
+        static void closeToluaInterfaces(lua_State* state);
+
+    private:
+        shared_ptr<ResourceInfo> getFileInfo(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths);
+
+#if LUA_VERSION_NUM != 501
+        struct LoadS
+        {
+            const char* s;
+            size_t size;
+        };
+
+        static const char * lua_Chunkreader(lua_State *L, void *data, size_t *size);
+#endif
+
+        std::stringstream output_;
+        lua_State* luaState_;
+        bool bIsRunning_;
+        shared_ptr<ResourceInfo> sourceFileInfo_;
+        std::string (*includeParseFunction_)(const std::string&);
+
+        typedef std::map<std::string, int (*)(lua_State *L)> ToluaInterfaceMap;
+        static ToluaInterfaceMap toluaInterfaces_s;
+        static std::vector<LuaState*> instances_s;
+    }; // tolua_export
+} // tolua_export
+
+#endif /* _LuaState_H__ */
Index: /code/branches/libraries2/src/libraries/core/MemoryArchive.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/MemoryArchive.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/MemoryArchive.cc	(revision 5712)
@@ -0,0 +1,133 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "MemoryArchive.h"
+
+#if OGRE_VERSION < 0x010600
+
+#include <OgreException.h>
+#include <boost/filesystem.hpp>
+
+namespace orxonox
+{
+    using namespace Ogre;
+
+    MemoryArchive::ArchiveMap MemoryArchive::archives_s;
+
+    void MemoryArchive::load()
+    {
+        if (archives_s.find(this->getName()) == archives_s.end())
+            OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, this->getName() + " - MemoryArchive not found.", "MemoryArchive");
+    }
+
+    DataStreamPtr MemoryArchive::open(const String& filename) const
+    {
+        const FileMap& files = archives_s[this->getName()];
+        FileMap::const_iterator itFile = files.find(filename);
+        if (itFile == files.end())
+            return DataStreamPtr();
+        else
+            return MemoryDataStreamPtr(new MemoryDataStream(itFile->second.first.get(), itFile->second.second));
+    }
+
+    void MemoryArchive::findFiles(const String& pattern, bool bRecursive, 
+        bool bDirs, StringVector* simpleList, FileInfoList* detailList)
+    {
+        const FileMap& files = archives_s[this->getName()];
+
+        for (FileMap::const_iterator it = files.begin(); it != files.end(); ++it)
+        {
+            boost::filesystem::path file = it->first;
+            // Check pattern
+            if (!StringUtil::match(file.string(), pattern, true))
+                continue;
+            if (bDirs)
+                file = file.parent_path();
+            if (file.empty())
+                continue;
+            if (file.has_parent_path() && !bRecursive)
+                continue;
+            if (simpleList)
+                simpleList->push_back(file.string());
+            if (detailList)
+            {
+                FileInfo fi;
+                fi.archive = this;
+                fi.filename = file.string();
+                fi.basename = file.filename();
+                fi.path = file.parent_path().string();
+                fi.compressedSize = it->second.second;
+                fi.uncompressedSize = it->second.second;
+                detailList->push_back(fi);
+            }
+        }
+    }
+    StringVectorPtr MemoryArchive::list(bool recursive, bool dirs)
+    {
+        StringVectorPtr ret(new StringVector());
+        findFiles("*", recursive, dirs, ret.getPointer(), 0);
+        return ret;
+    }
+
+    FileInfoListPtr MemoryArchive::listFileInfo(bool recursive, bool dirs)
+    {
+        FileInfoListPtr ret(new FileInfoList());
+        findFiles("*", recursive, dirs, 0, ret.getPointer());
+        return ret;
+    }
+
+    StringVectorPtr MemoryArchive::find(const String& pattern,
+                                            bool recursive, bool dirs)
+    {
+        StringVectorPtr ret(new StringVector());
+        findFiles(pattern, recursive, dirs, ret.getPointer(), 0);
+        return ret;
+    }
+
+    FileInfoListPtr MemoryArchive::findFileInfo(const String& pattern, 
+        bool recursive, bool dirs)
+    {
+        FileInfoListPtr ret(new FileInfoList());
+        findFiles(pattern, recursive, dirs, 0, ret.getPointer());
+        return ret;
+    }
+
+    bool MemoryArchive::exists(const String& filename)
+	{
+        const FileMap& files = archives_s[this->getName()];
+        return files.find(filename) != files.end();
+	}
+
+    const Ogre::String& MemoryArchiveFactory::getType(void) const
+    {
+        static std::string result("Memory");
+        return result;
+    }
+}
+
+#endif /* OGRE_VERSION < 0x010600 */
Index: /code/branches/libraries2/src/libraries/core/MemoryArchive.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/MemoryArchive.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/MemoryArchive.h	(revision 5712)
@@ -0,0 +1,101 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _MemoryArchive_H__
+#define _MemoryArchive_H__
+
+#include "CorePrereqs.h"
+#include <OgrePrerequisites.h>
+
+#if OGRE_VERSION < 0x010600
+
+#include <map>
+#include <OgreArchive.h>
+#include <OgreArchiveFactory.h>
+#include <boost/shared_array.hpp>
+
+namespace orxonox
+{
+    /**
+    @brief
+        Provides a simple mechanism of 'memory mapped IO', but compatible for Ogre 1.4
+
+        Files are stored as shared_array<char> in a static map with the archive names
+        (imaging the different archives as resource locations). This map then contains
+        yet another map with the actual files.
+        If you want to know why we make such a fuss, contact GraphicsManager::upgradeToGraphics()
+        for more information.
+    */
+    class MemoryArchive : public Ogre::Archive
+    {
+    public:
+        MemoryArchive(const Ogre::String& name, const Ogre::String& archiveType) : Ogre::Archive(name, archiveType) { }
+        ~MemoryArchive() { }
+
+        bool isCaseSensitive(void) const { return true; }
+
+        void load();
+        void unload() { }
+
+        Ogre::DataStreamPtr open(const Ogre::String& filename) const;
+
+        Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false);
+        Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false);
+
+        Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true,
+            bool dirs = false);
+        Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true,
+            bool dirs = false);
+
+        bool exists(const Ogre::String& filename);
+
+        static void addFile(const std::string& archiveName, const std::string& filename, shared_array<char> content, size_t size)
+            { archives_s[archiveName][filename] = std::make_pair(content, size); }
+
+    private:
+        void findFiles(const Ogre::String& pattern, bool bRecursive, 
+            bool bDirs, Ogre::StringVector* simpleList, Ogre::FileInfoList* detailList);
+
+        typedef std::map<std::string, std::pair<shared_array<char>, size_t> > FileMap;
+        typedef std::map<std::string, FileMap> ArchiveMap;
+        static ArchiveMap archives_s;
+    };
+
+    //! Specialisation of ArchiveFactory for MemoryArchive.
+    class _CoreExport MemoryArchiveFactory : public Ogre::ArchiveFactory
+    {
+    public:
+        const Ogre::String& getType(void) const;
+        Ogre::Archive* createInstance(const Ogre::String& name) { return new MemoryArchive(name, "Memory"); }
+        void destroyInstance(Ogre::Archive* arch)               { delete arch; }
+    };
+}
+
+#endif /* OGRE_VERSION < 0x010600 */
+
+#endif /* _MemoryArchive_H__ */
Index: /code/branches/libraries2/src/libraries/core/MetaObjectList.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/MetaObjectList.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/MetaObjectList.cc	(revision 5712)
@@ -0,0 +1,103 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the MetaObjectList class.
+*/
+
+#include "MetaObjectList.h"
+
+#include "util/Debug.h"
+#include "Identifier.h"
+#include "ObjectListBase.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###  MetaObjectListElement  ###
+    // ###############################
+    /**
+        @brief Destructor: Removes the ObjectListBaseElement from the ObjectListBase by linking next_ and prev_ of the ObjectListBaseElement.
+    */
+    MetaObjectListElement::~MetaObjectListElement()
+    {
+        COUT(5) << "*** MetaObjectList: Removing Object from " << this->list_->getIdentifier()->getName() << "-list." << std::endl;
+        this->list_->notifyIterators(this->element_->objectBase_);
+
+        if (this->element_->next_)
+            this->element_->next_->prev_ = this->element_->prev_;
+        else
+            this->list_->last_ = this->element_->prev_; // If there is no next_, we deleted the last object and have to update the last_ pointer of the list
+
+        if (this->element_->prev_)
+            this->element_->prev_->next_ = this->element_->next_;
+        else
+            this->list_->first_ = this->element_->next_; // If there is no prev_, we deleted the first object and have to update the first_ pointer of the list
+
+        delete this->element_;
+    }
+
+
+    // ###############################
+    // ###     MetaObjectList      ###
+    // ###############################
+    /**
+        @brief Constructor: Sets first_ to zero.
+    */
+    MetaObjectList::MetaObjectList()
+    {
+        this->first_ = 0;
+    }
+
+    /**
+        @brief Destructor: Removes all elements from the list, causing them to remove the stored ObjectListElement from the ObjectList.
+    */
+    MetaObjectList::~MetaObjectList()
+    {
+        MetaObjectListElement* temp;
+        while (this->first_)
+        {
+            temp = this->first_->next_;
+            delete this->first_;
+            this->first_ = temp;
+        }
+    }
+
+    /**
+        @brief Adds an ObjectList and an element of that list to the MetaObjectList.
+        @param list The ObjectList wherein the element is
+        @param element The element wherein the object is
+    */
+    void MetaObjectList::add(ObjectListBase* list, ObjectListBaseElement* element)
+    {
+        MetaObjectListElement* temp = this->first_;
+        this->first_ = new MetaObjectListElement(list, element);
+        this->first_->next_ = temp;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/MetaObjectList.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/MetaObjectList.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/MetaObjectList.h	(revision 5712)
@@ -0,0 +1,84 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the MetaObjectList class.
+
+    The MetaObjectList is a single-linked list, containing all list-elements and their
+    lists wherein the object, owning the MetaObjectList, is registered.
+    This allows much faster deletion of objects because no iteration is needed.
+*/
+
+#ifndef _MetaObjectList_H__
+#define _MetaObjectList_H__
+
+#include "CorePrereqs.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###  MetaObjectListElement  ###
+    // ###############################
+    //! The list-element of the MetaObjectList
+    class _CoreExport MetaObjectListElement
+    {
+        public:
+            /**
+                @brief Constructor: Creates the list-element with given list and element.
+            */
+            MetaObjectListElement(ObjectListBase* list, ObjectListBaseElement* element) : next_(0), element_(element), list_(list) {}
+            ~MetaObjectListElement();
+
+            MetaObjectListElement* next_;       //!< The next Element in the list
+            ObjectListBaseElement* element_;    //!< The list element, containing the object
+            ObjectListBase* list_;              //!< The list, containing the element
+    };
+
+
+    // ###############################
+    // ###     MetaObjectList      ###
+    // ###############################
+    //!  The MetaObjectList contains ObjectListBaseElements and their ObjectListBases.
+    /**
+        The MetaObjectList is a single-linked list, containing all list-elements and their
+        lists wherein the object that owns the MetaObjectList is registered.
+        This allows much faster deletion of objects because no iteration is needed.
+    */
+    class _CoreExport MetaObjectList
+    {
+        public:
+            MetaObjectList();
+            ~MetaObjectList();
+            void add(ObjectListBase* list, ObjectListBaseElement* element);
+
+            MetaObjectListElement* first_;      //!< The first element in the list
+    };
+}
+
+#endif /* _MetaObjectList_H__ */
Index: /code/branches/libraries2/src/libraries/core/Namespace.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Namespace.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Namespace.cc	(revision 5712)
@@ -0,0 +1,182 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Namespace.h"
+
+#include <set>
+
+#include "NamespaceNode.h"
+#include "CoreIncludes.h"
+#include "XMLPort.h"
+#include "util/SubString.h"
+
+namespace orxonox
+{
+    CreateFactory(Namespace);
+
+    Namespace::Namespace(BaseObject* creator) : BaseObject(creator),
+      bAutogeneratedFileRootNamespace_(false),
+      bRoot_(false),
+      operator_("or")
+    {
+        RegisterObject(Namespace);
+    }
+
+    Namespace::~Namespace()
+    {
+        if (this->bRoot_)
+            for (std::set<NamespaceNode*>::iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); ++it)
+                delete (*it);
+    }
+
+    /**
+        @brief XML loading and saving.
+        @param xmlelement The XML-element
+        @param loading Loading (true) or saving (false)
+        @return The XML-element
+    */
+    void Namespace::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(Namespace, XMLPort, xmlelement, mode);
+
+        std::string name = this->getName();
+        size_t pos = 0;
+        while ((pos = name.find(',')) != std::string::npos)
+            name.replace(pos, 1, " ");
+        while ((pos = name.find(';')) != std::string::npos)
+            name.replace(pos, 1, " ");
+        while ((pos = name.find('\n')) != std::string::npos)
+            name.replace(pos, 1, " ");
+        while ((pos = name.find('\t')) != std::string::npos)
+            name.replace(pos, 1, " ");
+        SubString tokens(name, " ", "", false, '\\', true, '"', true, '\0', '\0', true, '\0');
+        if (this->bRoot_)
+        {
+            this->representingNamespaces_.insert(new NamespaceNode(this->getName()));
+        }
+        else
+        {
+            for (unsigned int i = 0; i < tokens.size(); i++)
+            {
+                for (std::set<NamespaceNode*>::iterator it = this->getNamespace()->representingNamespaces_.begin(); it != this->getNamespace()->representingNamespaces_.end(); ++it)
+                {
+                    std::set<NamespaceNode*> temp = (*it)->getNodeRelative(tokens[i]);
+                    this->representingNamespaces_.insert(temp.begin(), temp.end());
+                }
+            }
+        }
+
+        XMLPortParam(Namespace, "operator", setOperator, getOperator, xmlelement, mode);
+        XMLPortParam(Namespace, "bAutogenerated", setAutogenerated, isAutogenerated, xmlelement, mode);
+
+        if (this->bAutogeneratedFileRootNamespace_)
+        {
+            for (std::set<NamespaceNode*>::iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); ++it)
+            {
+                (*it)->setRoot(true);
+                (*it)->setHidden(true);
+            }
+        }
+
+        XMLPortObjectExtended(Namespace, BaseObject, "", loadObjects, saveObjects, xmlelement, mode, true, false);
+    }
+
+    void Namespace::loadObjects(BaseObject* object)
+    {
+        object->setNamespace(this);
+    }
+
+    const BaseObject* Namespace::saveObjects(unsigned int index) const
+    {
+        return 0; // todo
+    }
+
+    bool Namespace::includes(const Namespace* ns) const
+    {
+        for (std::set<NamespaceNode*>::const_iterator it1 = this->representingNamespaces_.begin(); it1 != this->representingNamespaces_.end(); ++it1)
+        {
+            for (std::set<NamespaceNode*>::const_iterator it2 = ns->representingNamespaces_.begin(); it2 != ns->representingNamespaces_.end(); ++it2)
+            {
+                if ((*it1)->includes(*it2))
+                {
+                    if (this->operator_ == "or")
+                        return true;
+
+                    if (this->operator_ == "not")
+                        return false;
+                }
+                else
+                {
+                    if (this->operator_ == "and")
+                        return false;
+                }
+            }
+        }
+
+        if (this->operator_ == "or")
+            return false;
+        else if (this->operator_ == "and")
+            return true;
+        else if (this->operator_ == "not")
+            return true;
+
+        return false;
+    }
+
+    std::string Namespace::toString() const
+    {
+        std::string output;
+
+        int i = 0;
+        for (std::set<NamespaceNode*>::const_iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); i++, ++it)
+        {
+            if (i > 0)
+                output += " / ";
+
+            output += (*it)->toString();
+        }
+
+        return output;
+    }
+
+    std::string Namespace::toString(const std::string& indentation) const
+    {
+        std::string output;
+
+        int i = 0;
+        for (std::set<NamespaceNode*>::const_iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); i++, ++it)
+        {
+            if (i > 0)
+                output += "\n";
+
+            output += (*it)->toString(indentation);
+        }
+
+        return output;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Namespace.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Namespace.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Namespace.h	(revision 5712)
@@ -0,0 +1,78 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Namespace_H__
+#define _Namespace_H__
+
+#include "CorePrereqs.h"
+
+#include <set>
+#include <string>
+#include "BaseObject.h"
+
+namespace orxonox
+{
+    class Namespace : public BaseObject
+    {
+        public:
+            Namespace(BaseObject* creator);
+            virtual ~Namespace();
+
+            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+
+            void loadObjects(BaseObject* object);
+            const BaseObject* saveObjects(unsigned int index) const;
+
+            void setAutogenerated(bool bAutogenerated)
+                { this->bAutogeneratedFileRootNamespace_ = bAutogenerated; }
+            bool isAutogenerated() const
+                { return this->bAutogeneratedFileRootNamespace_; }
+
+            void setOperator(const std::string& op)
+                { this->operator_ = op; }
+            const std::string& getOperator() const
+                { return this->operator_; }
+
+            void setRoot(bool bRoot)
+                { this->bRoot_ = bRoot; }
+
+            bool includes(const Namespace* ns) const;
+            bool isIncludedIn(const Namespace* ns) const { return ns->includes(this); }
+
+            std::string toString() const;
+            std::string toString(const std::string& indentation) const;
+
+        private:
+            std::set<NamespaceNode*> representingNamespaces_;
+            bool bAutogeneratedFileRootNamespace_;
+            bool bRoot_;
+            std::string operator_;
+    };
+}
+
+#endif /* _Namespace_H__ */
Index: /code/branches/libraries2/src/libraries/core/NamespaceNode.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/NamespaceNode.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/NamespaceNode.cc	(revision 5712)
@@ -0,0 +1,174 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "NamespaceNode.h"
+#include "util/Debug.h"
+
+namespace orxonox
+{
+    NamespaceNode::NamespaceNode(const std::string& name, NamespaceNode* parent)
+    {
+        this->name_ = name;
+        this->parent_ = parent;
+        this->bRoot_ = false;
+        this->bHidden_ = false;
+    }
+
+    NamespaceNode::~NamespaceNode()
+    {
+        for (std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); )
+            delete ((*(it++)).second);
+    }
+
+    std::set<NamespaceNode*> NamespaceNode::getNodeRelative(const std::string& name)
+    {
+        std::set<NamespaceNode*> nodes;
+
+        if ((name.size() == 0) || (name == ""))
+        {
+            nodes.insert(this);
+        }
+        else
+        {
+            size_t pos = name.find("::");
+            std::string firstPart = name;
+            std::string secondPart;
+
+            if (pos != std::string::npos)
+            {
+                firstPart = name.substr(0, pos);
+                secondPart = name.substr(pos + 2, std::string::npos);
+            }
+
+            if (firstPart == "..")
+            {
+                if (this->bRoot_)
+                {
+                    COUT(2) << "Warning: Can't go to enclosing namespace with '..' operator in namespace " << this->name_ << ", namespace is root." << std::endl;
+                    nodes = this->getNodeRelative(secondPart);
+                }
+                else if (!this->parent_)
+                {
+                    COUT(2) << "Warning: Can't go to enclosing namespace with '..' operator in namespace " << this->name_ << ", no parent namespace set." << std::endl;
+                    nodes = this->getNodeRelative(secondPart);
+                }
+                else
+                {
+                    nodes = this->parent_->getNodeRelative(secondPart);
+                }
+            }
+            else if (name.find('@') != 0)
+            {
+                std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.find(firstPart);
+                if (it == this->subnodes_.end())
+                    it = this->subnodes_.insert(this->subnodes_.begin(), std::pair<std::string, NamespaceNode*>(firstPart, new NamespaceNode(firstPart, this)));
+
+                if ((*it).second->isHidden())
+                {
+                    COUT(2) << "Warning: Subnamespace '" << firstPart << "' in namespace '" << this->name_ << "' is hidden and can't be accessed." << std::endl;
+                    nodes.insert(this);
+                }
+                else
+                {
+                    nodes = (*it).second->getNodeRelative(secondPart);
+                }
+            }
+            else
+            {
+                bool bFoundMatchingNamespace = false;
+
+                for (std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it)
+                {
+                    if ((*it).first.find(firstPart) == ((*it).first.size() - firstPart.size()))
+                    {
+                        std::set<NamespaceNode*> temp2 = (*it).second->getNodeRelative(secondPart);
+                        nodes.insert(temp2.begin(), temp2.end());
+                        bFoundMatchingNamespace = true;
+                    }
+                }
+
+                if (!bFoundMatchingNamespace)
+                {
+                    COUT(2) << "Warning: No file included with name '" << firstPart.substr(1, std::string::npos) << "' at this part of the level file, using parent namespace instead." << std::endl;
+                    nodes = this->getNodeRelative(secondPart);
+                }
+            }
+        }
+
+        return nodes;
+    }
+
+    bool NamespaceNode::includes(const NamespaceNode* ns) const
+    {
+        if (ns == this)
+        {
+            return true;
+        }
+        else
+        {
+            for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it)
+                if ((*it).second->includes(ns))
+                    return true;
+        }
+
+        return false;
+    }
+
+    std::string NamespaceNode::toString() const
+    {
+        std::string output = this->name_;
+
+        if (this->subnodes_.size() > 0)
+        {
+            output += " (";
+
+            int i = 0;
+            for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); i++, ++it)
+            {
+                if (i > 0)
+                    output += ", ";
+
+                output += (*it).second->toString();
+            }
+
+            output += ")";
+        }
+
+        return output;
+    }
+
+    std::string NamespaceNode::toString(const std::string& indentation) const
+    {
+        std::string output = (indentation + this->name_ + "\n");
+
+        for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it)
+            output += (*it).second->toString(indentation + "  ");
+
+        return output;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/NamespaceNode.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/NamespaceNode.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/NamespaceNode.h	(revision 5712)
@@ -0,0 +1,68 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _NamespaceNode_H__
+#define _NamespaceNode_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <set>
+#include <string>
+
+namespace orxonox
+{
+    class NamespaceNode
+    {
+        public:
+            NamespaceNode(const std::string& name, NamespaceNode* parent = 0);
+            ~NamespaceNode();
+
+            std::set<NamespaceNode*> getNodeRelative(const std::string& name);
+
+            void setRoot(bool bRoot) { this->bRoot_ = bRoot; }
+            void setHidden(bool bHidden) { this->bHidden_ = bHidden; }
+
+            bool isRoot() const { return this->bRoot_; }
+            bool isHidden() const { return this->bHidden_; }
+
+            bool includes(const NamespaceNode*) const;
+
+            std::string toString() const;
+            std::string toString(const std::string& indentation) const;
+
+        private:
+            std::string name_;
+            NamespaceNode* parent_;
+            std::map<std::string, NamespaceNode*> subnodes_;
+            bool bHidden_;
+            bool bRoot_;
+    };
+}
+
+#endif /* _NamespaceNode_H__ */
Index: /code/branches/libraries2/src/libraries/core/ObjectList.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ObjectList.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ObjectList.h	(revision 5712)
@@ -0,0 +1,79 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition and implementation of the ObjectList class.
+
+    The ObjectList is a wrapper of an ObjectListBase of a given class.
+    Use Iterator<class> to iterate through all objects of the class.
+*/
+
+#ifndef _ObjectList_H__
+#define _ObjectList_H__
+
+#include "CorePrereqs.h"
+
+#include "Identifier.h"
+#include "ObjectListIterator.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###       ObjectList        ###
+    // ###############################
+    //! The ObjectList contains all objects of the given class.
+    /**
+        Wraps the ObjectListBase of the corresponding Identifier.
+        Use ObjectListIterator<class> to iterate through all objects in the list.
+    */
+    template <class T>
+    class ObjectList
+    {
+        public:
+            typedef ObjectListIterator<T> iterator;
+
+            /** @brief Returns an Iterator to the first element in the list. @return The Iterator */
+            inline static ObjectListElement<T>* begin()
+                { return ((ObjectListElement<T>*)ClassIdentifier<T>::getIdentifier()->getObjects()->begin().element_); }
+
+            /** @brief Returns an Iterator to the element after the last element in the list. @return The Iterator */
+            inline static ObjectListElement<T>* end()
+                { return ((ObjectListElement<T>*)ClassIdentifier<T>::getIdentifier()->getObjects()->end().element_); }
+
+            /** @brief Returns an Iterator to the last element in the list. @return The Iterator */
+            inline static ObjectListElement<T>* rbegin()
+                { return ((ObjectListElement<T>*)ClassIdentifier<T>::getIdentifier()->getObjects()->rbegin().element_); }
+
+            /** @brief Returns an Iterator to the element before the first element in the list. @return The Iterator */
+            inline static ObjectListElement<T>* rend()
+                { return ((ObjectListElement<T>*)ClassIdentifier<T>::getIdentifier()->getObjects()->rend().element_); }
+    };
+}
+
+#endif /* _ObjectList_H__ */
Index: /code/branches/libraries2/src/libraries/core/ObjectListBase.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ObjectListBase.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ObjectListBase.cc	(revision 5712)
@@ -0,0 +1,106 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the ObjectListBase class.
+
+    The ObjectListBase is a double-linked list, used by Identifiers to store all objects of a given class.
+    Newly created objects are added through the RegisterObject-macro in its constructor.
+*/
+
+#include "ObjectListBase.h"
+
+#include <set>
+#include "Identifier.h"
+#include "Iterator.h"
+#include "ObjectListIterator.h"
+
+namespace orxonox
+{
+    /**
+        @brief Constructor: Sets default values.
+    */
+    ObjectListBase::ObjectListBase(Identifier* identifier)
+    {
+        this->identifier_ = identifier;
+        this->first_ = 0;
+        this->last_ = 0;
+    }
+
+    /**
+        @brief Destructor: Deletes all list-elements, but NOT THE OBJECTS.
+    */
+    ObjectListBase::~ObjectListBase()
+    {
+        ObjectListBaseElement* temp;
+        while (this->first_)
+        {
+            temp = this->first_->next_;
+            delete this->first_;
+            this->first_ = temp;
+        }
+    }
+
+    /**
+        @brief Increases all Iterators that currently point on the given element (because it gets removed).
+        @param element The element that gets removed
+    */
+    void ObjectListBase::notifyIterators(OrxonoxClass* object) const
+    {
+        for (std::vector<void*>::const_iterator it = this->iterators_.begin(); it != this->iterators_.end(); ++it)
+            ((Iterator<OrxonoxClass>*)(*it))->incrementIfEqual(object);
+        for (std::vector<void*>::const_iterator it = this->objectListIterators_.begin(); it != this->objectListIterators_.end(); ++it)
+            ((ObjectListIterator<OrxonoxClass>*)(*it))->incrementIfEqual(object);
+    }
+
+    /**
+        @brief Adds a new object to the end of the list.
+        @param object The object to add
+        @return The pointer to the new ObjectListBaseElement, needed by the MetaObjectList of the added object
+    */
+    ObjectListBaseElement* ObjectListBase::add(ObjectListBaseElement* element)
+    {
+        if (!this->last_)
+        {
+            // If the list is empty
+            this->last_ = element;
+            this->first_ = this->last_; // There's only one object in the list now
+        }
+        else
+        {
+            // If the list isn't empty
+            ObjectListBaseElement* temp = this->last_;
+            this->last_ = element;
+            this->last_->prev_ = temp;
+            temp->next_ = this->last_;
+        }
+
+        return this->last_;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/ObjectListBase.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ObjectListBase.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ObjectListBase.h	(revision 5712)
@@ -0,0 +1,150 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of the ObjectListBase class.
+
+    The ObjectListBase is a double-linked list, used by Identifiers to store all objects of a given class.
+    Newly created objects are added through the RegisterObject-macro in its constructor.
+*/
+
+#ifndef _ObjectListBase_H__
+#define _ObjectListBase_H__
+
+#include "CorePrereqs.h"
+
+#include <vector>
+#include "OrxonoxClass.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###  ObjectListBaseElement  ###
+    // ###############################
+    //! The list-element of the ObjectListBase
+    class _CoreExport ObjectListBaseElement
+    {
+        public:
+            /**
+                @brief Constructor: Creates the list-element with an object.
+                @param object The object to store
+            */
+            ObjectListBaseElement(OrxonoxClass* objectBase) : next_(0), prev_(0), objectBase_(objectBase) {}
+
+            ObjectListBaseElement* next_;       //!< The next element in the list
+            ObjectListBaseElement* prev_;       //!< The previous element in the list
+            OrxonoxClass* objectBase_;
+    };
+
+
+    // ###############################
+    // ###    ObjectListElement    ###
+    // ###############################
+    //! The list-element that actually contains the object
+    template <class T>
+    class ObjectListElement : public ObjectListBaseElement
+    {
+        public:
+            ObjectListElement(T* object) : ObjectListBaseElement(static_cast<OrxonoxClass*>(object)), object_(object) {}
+            T* object_;              //!< The object
+    };
+
+
+    // ###############################
+    // ###     ObjectListBase      ###
+    // ###############################
+    //! The ObjectListBase contains all objects of a given class.
+    /**
+        The ObjectListBase is used by Identifiers to store all objects of their given class.
+        Use ObjectList<T> to get the list of all T's and Iterator<T> to iterate through them.
+    */
+    class _CoreExport ObjectListBase
+    {
+        friend class MetaObjectListElement;
+
+        public:
+            ObjectListBase(Identifier* identifier);
+            ~ObjectListBase();
+
+            ObjectListBaseElement* add(ObjectListBaseElement* element);
+
+            struct Export
+            {
+                Export(ObjectListBase* list, ObjectListBaseElement* element) : list_(list), element_(element) {}
+                ObjectListBase* list_;
+                ObjectListBaseElement* element_;
+            };
+
+            /** @brief Returns a pointer to the first element in the list. @return The element */
+            inline Export begin() { return ObjectListBase::Export(this, this->first_); }
+            /** @brief Returns a pointer to the element after the last element in the list. @return The element */
+            inline Export end() { return ObjectListBase::Export(this, 0); }
+            /** @brief Returns a pointer to the last element in the list. @return The element */
+            inline Export rbegin() { return ObjectListBase::Export(this, this->last_); }
+            /** @brief Returns a pointer to the element in front of the first element in the list. @return The element */
+            inline Export rend() { return ObjectListBase::Export(this, 0); }
+
+            inline void registerIterator(void* iterator) { this->iterators_.push_back(iterator); }
+            inline void unregisterIterator(void* iterator)
+            {
+                for (unsigned int i = 0; i < this->iterators_.size(); ++i)
+                {
+                    if (iterators_[i] == iterator)
+                    {
+                        iterators_.erase(iterators_.begin() + i);
+                        break;
+                    }
+                }
+            }
+            inline void registerObjectListIterator(void* iterator) { this->objectListIterators_.push_back(iterator); }
+            inline void unregisterObjectListIterator(void* iterator)
+            {
+                for (unsigned int i = 0; i < this->objectListIterators_.size(); ++i)
+                {
+                    if (objectListIterators_[i] == iterator)
+                    {
+                        objectListIterators_.erase(objectListIterators_.begin() + i);
+                        break;
+                    }
+                }
+            }
+            void notifyIterators(OrxonoxClass* object) const;
+
+            inline Identifier* getIdentifier() const { return this->identifier_; }
+
+        private:
+            Identifier* identifier_;                 //!< The Iterator owning this list
+            ObjectListBaseElement* first_;           //!< The first element in the list
+            ObjectListBaseElement* last_;            //!< The last element in the list
+            std::vector<void*> iterators_;           //!< A list of Iterators pointing on an element in this list
+            std::vector<void*> objectListIterators_; //!< A list of ObjectListIterators pointing on an element in this list
+    };
+}
+
+#endif /* _ObjectListBase_H__ */
Index: /code/branches/libraries2/src/libraries/core/ObjectListIterator.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ObjectListIterator.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ObjectListIterator.h	(revision 5712)
@@ -0,0 +1,233 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition and implementation of the Iterator class.
+
+    The ObjectListIterator of a given class allows to iterate through the
+    ObjectList of this class, containing all objects of that type.
+    This is the only way to access the objects stored in an ObjectList.
+
+    Usage:
+    for (ObjectListIterator<myClass> it = ObjectList<myClass>::begin(); it != ObjectList<myClass>::end(); ++it)
+    {
+        it->someFunction(...);
+        myClass* myObject = *it;
+    }
+*/
+
+#ifndef _ObjectListIterator_H__
+#define _ObjectListIterator_H__
+
+#include "CorePrereqs.h"
+#include "Identifier.h"
+#include "ObjectList.h"
+
+namespace orxonox
+{
+    //! The Iterator allows to iterate through the ObjectList of a given class.
+    template <class T>
+    class ObjectListIterator
+    {
+        template <class I>
+        friend class Iterator;
+
+        public:
+            /**
+                @brief Constructor: Sets the element, whereon the ObjectListIterator points, to zero.
+            */
+            inline ObjectListIterator()
+            {
+                this->element_ = 0;
+                ClassIdentifier<T>::getIdentifier()->getObjects()->registerObjectListIterator(this);
+            }
+
+            /**
+                @brief Constructor: Sets this element to a given element.
+                @param element The element to start with
+            */
+            inline ObjectListIterator(ObjectListElement<T>* element)
+            {
+                this->element_ = element;
+                ClassIdentifier<T>::getIdentifier()->getObjects()->registerObjectListIterator(this);
+            }
+
+            /**
+                @brief Constructor: Sets this element to the element of another ObjectListIterator.
+                @param other The other ObjectListIterator
+            */
+            inline ObjectListIterator(const ObjectListIterator<T>& other)
+            {
+                this->element_ = other.element_;
+                ClassIdentifier<T>::getIdentifier()->getObjects()->registerObjectListIterator(this);
+            }
+
+            /**
+                @brief Unregisters the ObjectListIterator from the ObjectList.
+            */
+            inline ~ObjectListIterator()
+            {
+                ClassIdentifier<T>::getIdentifier()->getObjects()->unregisterObjectListIterator(this);
+            }
+
+            /**
+                @brief Assigns an ObjectListElement.
+                @param element The ObjectListElement
+            */
+            inline const ObjectListIterator<T>& operator=(ObjectListElement<T>* element)
+            {
+                this->element_ = element;
+                return (*this);
+            }
+
+            /**
+                @brief Assigns the element of another ObjectListIterator.
+                @param element The other ObjectListIterator
+            */
+            inline const ObjectListIterator<T>& operator=(const ObjectListIterator<T>& other)
+            {
+                this->element_ = other.element_;
+                return (*this);
+            }
+
+            /**
+                @brief Overloading of the ++it operator: ObjectListIterator points to the next object in the list.
+                @return The ObjectListIterator itself
+            */
+            inline const ObjectListIterator<T>& operator++()
+            {
+                if (this->element_)
+                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
+                return *this;
+            }
+
+            /**
+                @brief Overloading of the it++ operator: ObjectListIterator points to the next object in the list.
+                @return The ObjectListIterator itself
+            */
+            inline ObjectListIterator<T> operator++(int i)
+            {
+                ObjectListIterator<T> copy = *this;
+                if (this->element_)
+                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
+                return copy;
+            }
+
+            /**
+                @brief Overloading of the --it operator: ObjectListIterator points to the previous object in the list.
+                @return The ObjectListIterator itself
+            */
+            inline const ObjectListIterator<T>& operator--()
+            {
+                if (this->element_)
+                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
+                return *this;
+            }
+
+            /**
+                @brief Overloading of the it-- operator: ObjectListIterator points to the previous object in the list.
+                @return The ObjectListIterator itself
+            */
+            inline ObjectListIterator<T> operator--(int i)
+            {
+                ObjectListIterator<T> copy = *this;
+                if (this->element_)
+                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
+                return copy;
+            }
+
+            /**
+                @brief Overloading of the *it operator: returns the pointer to the object.
+                @return The object the ObjectListIterator points at
+            */
+            inline T* operator*() const
+            {
+                if (this->element_)
+                    return this->element_->object_;
+                else
+                    return 0;
+            }
+
+            /**
+                @brief Overloading of the it-> operator: returns the pointer to the object.
+                @return The object the ObjectListIterator points at
+            */
+            inline T* operator->() const
+            {
+                if (this->element_)
+                    return this->element_->object_;
+                else
+                    return 0;
+            }
+
+            /**
+                @brief Overloading of the typecast-operator to bool: returns true if the ObjectListIterator points to an existing object.
+                @return True if the ObjectListIterator points to an existing object.
+            */
+            inline operator bool() const
+            {
+                return (this->element_ != 0);
+            }
+
+            /**
+                @brief Overloading of the == operator to compare with another ObjectListIterator.
+                @param compare The other ObjectListIterator
+                @return True if the ObjectListIterator point to the same element
+            */
+            inline bool operator==(const ObjectListIterator<T>& compare) const
+            {
+                return (this->element_ == compare.element_);
+            }
+
+            /**
+                @brief Overloading of the != operator to compare with another ObjectListIterator.
+                @param compare The other ObjectListIterator
+                @return True if the ObjectListIterator point to different elements
+            */
+            inline bool operator!=(const ObjectListIterator<T>& compare) const
+            {
+                return (this->element_ != compare.element_);
+            }
+
+            /**
+                @brief Increments the ObjectListIterator if it points at the given object.
+                @param object The object to compare with
+            */
+            inline void incrementIfEqual(OrxonoxClass* object)
+            {
+                if (this->element_ && this->element_->objectBase_ == object)
+                    this->operator++();
+            }
+
+        private:
+            ObjectListElement<T>* element_;        //!< The element the Iterator points at
+    };
+}
+
+#endif /* _ObjectListIterator_H__ */
Index: /code/branches/libraries2/src/libraries/core/OrxonoxClass.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/OrxonoxClass.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/OrxonoxClass.cc	(revision 5712)
@@ -0,0 +1,137 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the OrxonoxClass Class.
+*/
+
+#include "OrxonoxClass.h"
+
+#include "MetaObjectList.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    /** @brief Constructor: Sets the default values. */
+    OrxonoxClass::OrxonoxClass()
+    {
+        this->identifier_ = 0;
+        this->parents_ = 0;
+        this->metaList_ = new MetaObjectList();
+    }
+
+    /** @brief Destructor: Deletes, if existing, the list of the parents. */
+    OrxonoxClass::~OrxonoxClass()
+    {
+        delete this->metaList_;
+
+        // parents_ exists only if isCreatingHierarchy() of the associated Identifier returned true while creating the class
+        if (this->parents_)
+            delete this->parents_;
+    }
+
+    /** @brief Returns true if the objects class is of the given type or a derivative. */
+    bool OrxonoxClass::isA(const Identifier* identifier)
+        { return this->getIdentifier()->isA(identifier); }
+    /** @brief Returns true if the objects class is exactly of the given type. */
+    bool OrxonoxClass::isExactlyA(const Identifier* identifier)
+        { return this->getIdentifier()->isExactlyA(identifier); }
+    /** @brief Returns true if the objects class is a child of the given type. */
+    bool OrxonoxClass::isChildOf(const Identifier* identifier)
+        { return this->getIdentifier()->isChildOf(identifier); }
+    /** @brief Returns true if the objects class is a direct child of the given type. */
+    bool OrxonoxClass::isDirectChildOf(const Identifier* identifier)
+        { return this->getIdentifier()->isDirectChildOf(identifier); }
+    /** @brief Returns true if the objects class is a parent of the given type. */
+    bool OrxonoxClass::isParentOf(const Identifier* identifier)
+        { return this->getIdentifier()->isParentOf(identifier); }
+    /** @brief Returns true if the objects class is a direct parent of the given type. */
+    bool OrxonoxClass::isDirectParentOf(const Identifier* identifier)
+        { return this->getIdentifier()->isDirectParentOf(identifier); }
+
+
+    /** @brief Returns true if the objects class is of the given type or a derivative. */
+    template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B>* identifier)
+        { return this->getIdentifier()->isA(identifier->getIdentifier()); }
+    /** @brief Returns true if the objects class is exactly of the given type. */
+    template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B>* identifier)
+        { return this->getIdentifier()->isExactlyA(identifier->getIdentifier()); }
+    /** @brief Returns true if the objects class is a child of the given type. */
+    template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B>* identifier)
+        { return this->getIdentifier()->isChildOf(identifier->getIdentifier()); }
+    /** @brief Returns true if the objects class is a direct child of the given type. */
+    template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B>* identifier)
+        { return this->getIdentifier()->isDirectChildOf(identifier->getIdentifier()); }
+    /** @brief Returns true if the objects class is a parent of the given type. */
+    template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B>* identifier)
+        { return this->getIdentifier()->isParentOf(identifier->getIdentifier()); }
+    /** @brief Returns true if the objects class is a direct parent of the given type. */
+    template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B>* identifier)
+        { return this->getIdentifier()->isDirectParentOf(identifier->getIdentifier()); }
+
+
+    /** @brief Returns true if the objects class is of the given type or a derivative. */
+    template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B> identifier)
+        { return this->getIdentifier()->isA(identifier.getIdentifier()); }
+    /** @brief Returns true if the objects class is exactly of the given type. */
+    template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B> identifier)
+        { return this->getIdentifier()->isExactlyA(identifier.getIdentifier()); }
+    /** @brief Returns true if the objects class is a child of the given type. */
+    template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B> identifier)
+        { return this->getIdentifier()->isChildOf(identifier.getIdentifier()); }
+    /** @brief Returns true if the objects class is a direct child of the given type. */
+    template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B> identifier)
+        { return this->getIdentifier()->isDirectChildOf(identifier.getIdentifier()); }
+    /** @brief Returns true if the objects class is a parent of the given type. */
+    template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B> identifier)
+        { return this->getIdentifier()->isParentOf(identifier.getIdentifier()); }
+    /** @brief Returns true if the objects class is a direct parent of the given type. */
+    template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B> identifier)
+        { return this->getIdentifier()->isDirectParentOf(identifier.getIdentifier()); }
+
+
+    /** @brief Returns true if the objects class is of the given type or a derivative. */
+    bool OrxonoxClass::isA(const OrxonoxClass* object)
+        { return this->getIdentifier()->isA(object->getIdentifier()); }
+    /** @brief Returns true if the objects class is exactly of the given type. */
+    bool OrxonoxClass::isExactlyA(const OrxonoxClass* object)
+        { return this->getIdentifier()->isExactlyA(object->getIdentifier()); }
+    /** @brief Returns true if the objects class is a child of the given type. */
+    bool OrxonoxClass::isChildOf(const OrxonoxClass* object)
+        { return this->getIdentifier()->isChildOf(object->getIdentifier()); }
+    /** @brief Returns true if the objects class is a direct child of the given type. */
+    bool OrxonoxClass::isDirectChildOf(const OrxonoxClass* object)
+        { return this->getIdentifier()->isDirectChildOf(object->getIdentifier()); }
+    /** @brief Returns true if the objects class is a parent of the given type. */
+    bool OrxonoxClass::isParentOf(const OrxonoxClass* object)
+        { return this->getIdentifier()->isParentOf(object->getIdentifier()); }
+    /** @brief Returns true if the objects class is a direct child of the given type. */
+    bool OrxonoxClass::isDirectParentOf(const OrxonoxClass* object)
+        { return this->getIdentifier()->isDirectParentOf(object->getIdentifier()); }
+}
Index: /code/branches/libraries2/src/libraries/core/OrxonoxClass.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/OrxonoxClass.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/OrxonoxClass.h	(revision 5712)
@@ -0,0 +1,128 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Declaration of the OrxonoxClass Class.
+
+    All objects and interfaces of the game-logic (not the engine) are derived from OrxonoxClass.
+    It stores the Identifier and the MetaObjectList and has all needed functions to create and use the class-hierarchy.
+*/
+
+#ifndef _OrxonoxClass_H__
+#define _OrxonoxClass_H__
+
+#include "CorePrereqs.h"
+
+#include <set>
+#include <vector>
+
+namespace orxonox
+{
+    //! The class all objects and interfaces of the game-logic (not the engine) are derived from.
+    /**
+        The BaseObject and Interfaces are derived with 'virtual public OrxonoxClass' from OrxonoxClass.
+        OrxonoxClass is needed to create the class-hierarchy at startup and to store the Identifier and the MetaObjectList.
+    */
+    class _CoreExport OrxonoxClass
+    {
+        template <class T>
+        friend class ClassIdentifier;
+
+        public:
+            OrxonoxClass();
+            virtual ~OrxonoxClass();
+
+            /** @brief Function to collect the SetConfigValue-macro calls. */
+            void setConfigValues() {};
+
+            /** @brief Returns the Identifier of the object. @return The Identifier */
+            inline Identifier* getIdentifier() const { return this->identifier_; }
+
+            bool isA(const Identifier* identifier);
+            bool isExactlyA(const Identifier* identifier);
+            bool isChildOf(const Identifier* identifier);
+            bool isDirectChildOf(const Identifier* identifier);
+            bool isParentOf(const Identifier* identifier);
+            bool isDirectParentOf(const Identifier* identifier);
+
+            template <class B> bool isA(const SubclassIdentifier<B>* identifier);
+            template <class B> bool isExactlyA(const SubclassIdentifier<B>* identifier);
+            template <class B> bool isChildOf(const SubclassIdentifier<B>* identifier);
+            template <class B> bool isDirectChildOf(const SubclassIdentifier<B>* identifier);
+            template <class B> bool isParentOf(const SubclassIdentifier<B>* identifier);
+            template <class B> bool isDirectParentOf(const SubclassIdentifier<B>* identifier);
+
+            template <class B> bool isA(const SubclassIdentifier<B> identifier);
+            template <class B> bool isExactlyA(const SubclassIdentifier<B> identifier);
+            template <class B> bool isChildOf(const SubclassIdentifier<B> identifier);
+            template <class B> bool isDirectChildOf(const SubclassIdentifier<B> identifier);
+            template <class B> bool isParentOf(const SubclassIdentifier<B> identifier);
+            template <class B> bool isDirectParentOf(const SubclassIdentifier<B> identifier);
+
+            bool isA(const OrxonoxClass* object);
+            bool isExactlyA(const OrxonoxClass* object);
+            bool isChildOf(const OrxonoxClass* object);
+            bool isDirectChildOf(const OrxonoxClass* object);
+            bool isParentOf(const OrxonoxClass* object);
+            bool isDirectParentOf(const OrxonoxClass* object);
+
+            /**
+            @brief
+                Returns a valid pointer of any derived type that is
+                registered in the class hierarchy.
+            @return
+                Returns NULL if the no pointer was found.
+            */
+            template <class T>
+            FORCEINLINE T* getDerivedPointer(unsigned int classID)
+            {
+                for (int i = this->objectPointers_.size() - 1; i >= 0; --i)
+                {
+                    if (this->objectPointers_[i].first == classID)
+                        return static_cast<T*>(this->objectPointers_[i].second);
+                }
+                return NULL;
+            }
+            //! Const version of getDerivedPointer
+            template <class T>
+            FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
+            {
+                return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID);
+            }
+
+        private:
+            Identifier* identifier_;                   //!< The Identifier of the object
+            std::set<const Identifier*>* parents_;     //!< List of all parents of the object
+            MetaObjectList* metaList_;                 //!< MetaObjectList, containing all ObjectLists and ObjectListElements the object is registered in
+            //! 'Fast map' that holds this-pointers of all derived types
+            std::vector<std::pair<unsigned int, void*> > objectPointers_;
+    };
+}
+
+#endif /* _OrxonoxClass_H__ */
Index: /code/branches/libraries2/src/libraries/core/Resource.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Resource.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Resource.cc	(revision 5712)
@@ -0,0 +1,69 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Resource.h"
+#include <OgreResourceGroupManager.h>
+
+namespace orxonox
+{
+    std::string Resource::DEFAULT_GROUP(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+    DataStreamPtr Resource::open(const std::string& name, const std::string& group, bool bSearchGroupsIfNotFound)
+    {
+        return Ogre::ResourceGroupManager::getSingleton().openResource(name, group, bSearchGroupsIfNotFound);
+    }
+
+    DataStreamListPtr Resource::openMulti(const std::string& pattern, const std::string& group)
+    {
+        return Ogre::ResourceGroupManager::getSingleton().openResources(pattern, group);
+    }
+
+    bool Resource::exists(const std::string& name, const std::string& group)
+    {
+        return Ogre::ResourceGroupManager::getSingleton().resourceExists(group, name);
+    }
+
+    shared_ptr<ResourceInfo> Resource::getInfo(const std::string& name, const std::string& group)
+    {
+        Ogre::FileInfoListPtr infos = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(group, name);
+        for (std::vector<Ogre::FileInfo>::const_iterator it = infos->begin(); it != infos->end(); ++it)
+        {
+            if (it->filename == name)
+            {
+                shared_ptr<ResourceInfo> ptr(new ResourceInfo());
+                ptr->filename = name;
+                ptr->path = it->path;
+                ptr->basename = it->basename;
+                ptr->group = group;
+                ptr->size = it->uncompressedSize;
+                return ptr;
+            }
+        }
+        return shared_ptr<ResourceInfo>();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Resource.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Resource.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Resource.h	(revision 5712)
@@ -0,0 +1,134 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Core_Resource_H__
+#define _Core_Resource_H__
+
+#include "CorePrereqs.h"
+
+#include <boost/shared_ptr.hpp>
+#include <OgreDataStream.h>
+
+namespace orxonox
+{
+    // Import the Ogre::DataStreamList
+    using Ogre::DataStreamList;
+    using Ogre::DataStreamListPtr;
+
+    //! Stores basic information about a Resource from Ogre
+    struct ResourceInfo
+    {
+        //! The file's fully qualified name
+        std::string filename;
+        //! Path name; separated by '/' and ending with '/'
+        std::string path;
+        //! Base filename
+        std::string basename;
+        //! Resource group the file is in
+        std::string group;
+        //! Uncompressed size
+        size_t size;
+    };
+
+    /**
+    @brief
+        Provides simple functions to easily access the Ogre::ResourceGroupManager
+    */
+    class _CoreExport Resource
+    {
+        // Docs by Ogre::ResourceGroupManager.h
+    public:
+		/**
+        @brief
+            Open a single resource by name and return a DataStream
+            pointing at the source of the data.
+        @param name
+            The name of the resource to locate.
+            Even if resource locations are added recursively, you
+            must provide a fully qualified name to this method.
+        @param groupName
+            The name of the resource group; this determines which 
+            locations are searched. 
+        @param searchGroupsIfNotFound
+            If true, if the resource is not found in 
+            the group specified, other groups will be searched.
+        @return
+            Shared pointer to data stream containing the data. Will be
+            destroyed automatically when no longer referenced.
+		*/
+        static DataStreamPtr open(const std::string& name,
+            const std::string& group = Resource::DEFAULT_GROUP,
+            bool bSearchGroupsIfNotFound = false);
+
+		/**
+        @brief
+            Open all resources matching a given pattern (which can contain
+            the character '*' as a wildcard), and return a collection of 
+            DataStream objects on them.
+        @param pattern
+            The pattern to look for. If resource locations have been
+            added recursively, subdirectories will be searched too so this
+            does not need to be fully qualified.
+        @param groupName
+            The resource group; this determines which locations
+            are searched.
+        @return
+            Shared pointer to a data stream list , will be
+            destroyed automatically when no longer referenced
+		*/
+        static DataStreamListPtr openMulti(const std::string& pattern, const std::string& group = Resource::DEFAULT_GROUP);
+
+        /**
+            Find out if the named file exists in a group. 
+        @param filename
+            Fully qualified name of the file to test for
+        @param group
+            The name of the resource group
+        */
+        static bool exists(const std::string& name, const std::string& group = Resource::DEFAULT_GROUP);
+
+        /**
+            Get struct with information about group, path and size.
+        @param filename
+            Fully qualified name of the file to test for
+        @param group
+            The name of the resource group
+        */
+        static shared_ptr<ResourceInfo> getInfo(const std::string& name, const std::string& group = Resource::DEFAULT_GROUP);
+
+        //! Name of the default resource group (usually "General")
+        static std::string DEFAULT_GROUP;
+
+    private:
+        Resource();
+        ~Resource();
+        Resource(const Resource& instance);
+    };
+}
+
+#endif /* _Core_Resource_H__ */
Index: /code/branches/libraries2/src/libraries/core/Shell.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Shell.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Shell.cc	(revision 5712)
@@ -0,0 +1,397 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Shell.h"
+
+#include "util/OutputHandler.h"
+#include "CommandExecutor.h"
+#include "CoreIncludes.h"
+#include "ConfigValueIncludes.h"
+#include "Core.h"
+#include "ConsoleCommand.h"
+
+#define SHELL_UPDATE_LISTENERS(function) \
+    for (std::list<ShellListener*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); ) \
+        (*(it++))->function()
+
+namespace orxonox
+{
+    SetConsoleCommand(Shell, clearShell, true);
+    SetConsoleCommand(Shell, history, true);
+
+    SetConsoleCommandShortcut(OutputHandler, log);
+    SetConsoleCommandShortcut(OutputHandler, error);
+    SetConsoleCommandShortcut(OutputHandler, warning);
+    SetConsoleCommandShortcut(OutputHandler, info);
+    SetConsoleCommandShortcut(OutputHandler, debug);
+
+    Shell* Shell::singletonPtr_s = 0;
+
+    Shell::Shell()
+    {
+        int level = Core::getSoftDebugLevel(OutputHandler::LD_Shell);
+        Core::setSoftDebugLevel(OutputHandler::LD_Shell, -1);
+
+        RegisterRootObject(Shell);
+
+        this->scrollPosition_ = 0;
+        this->maxHistoryLength_ = 100;
+        this->historyPosition_ = 0;
+        this->historyOffset_ = 0;
+        this->finishedLastLine_ = true;
+        this->bAddOutputLevel_ = false;
+
+        this->clearLines();
+
+        this->inputBuffer_ = new InputBuffer();
+        this->configureInputBuffer();
+
+        this->outputBuffer_.registerListener(this);
+        OutputHandler::getOutStream().setOutputBuffer(&this->outputBuffer_);
+
+        // Get a config file for the command history
+        this->commandHistoryConfigFileType_ = ConfigFileManager::getInstance().getNewConfigFileType();
+        ConfigFileManager::getInstance().setFilename(this->commandHistoryConfigFileType_, "commandHistory.ini");
+
+        this->setConfigValues();
+
+        Core::setSoftDebugLevel(OutputHandler::LD_Shell, level);
+    }
+
+    Shell::~Shell()
+    {
+        OutputHandler::getOutStream().setOutputBuffer(0);
+        if (this->inputBuffer_)
+            delete this->inputBuffer_;
+    }
+
+    void Shell::setConfigValues()
+    {
+        SetConfigValueGeneric(commandHistoryConfigFileType_, maxHistoryLength_, 100)
+            .callback(this, &Shell::commandHistoryLengthChanged);
+        SetConfigValueGeneric(commandHistoryConfigFileType_, historyOffset_, 0)
+            .callback(this, &Shell::commandHistoryOffsetChanged);
+        SetConfigValueVectorGeneric(commandHistoryConfigFileType_, commandHistory_, std::vector<std::string>());
+    }
+
+    void Shell::commandHistoryOffsetChanged()
+    {
+        if (this->historyOffset_ >= this->maxHistoryLength_)
+            this->historyOffset_ = 0;
+    }
+
+    void Shell::commandHistoryLengthChanged()
+    {
+        this->commandHistoryOffsetChanged();
+
+        while (this->commandHistory_.size() > this->maxHistoryLength_)
+        {
+            unsigned int index = this->commandHistory_.size() - 1;
+            this->commandHistory_.erase(this->commandHistory_.begin() + index);
+            ModifyConfigValue(commandHistory_, remove, index);
+        }
+    }
+
+    void Shell::configureInputBuffer()
+    {
+        this->inputBuffer_->registerListener(this, &Shell::inputChanged, true);
+        this->inputBuffer_->registerListener(this, &Shell::execute, '\r', false);
+        this->inputBuffer_->registerListener(this, &Shell::hintandcomplete, '\t', true);
+        this->inputBuffer_->registerListener(this, &Shell::backspace, '\b', true);
+        this->inputBuffer_->registerListener(this, &Shell::deletechar, KeyCode::Delete);
+        this->inputBuffer_->registerListener(this, &Shell::exit, static_cast<char>(27), true);
+        this->inputBuffer_->registerListener(this, &Shell::cursor_right, KeyCode::Right);
+        this->inputBuffer_->registerListener(this, &Shell::cursor_left, KeyCode::Left);
+        this->inputBuffer_->registerListener(this, &Shell::cursor_end, KeyCode::End);
+        this->inputBuffer_->registerListener(this, &Shell::cursor_home, KeyCode::Home);
+        this->inputBuffer_->registerListener(this, &Shell::history_up, KeyCode::Up);
+        this->inputBuffer_->registerListener(this, &Shell::history_down, KeyCode::Down);
+        this->inputBuffer_->registerListener(this, &Shell::scroll_up, KeyCode::PageUp);
+        this->inputBuffer_->registerListener(this, &Shell::scroll_down, KeyCode::PageDown);
+    }
+
+    void Shell::clearShell()
+    {
+        Shell::getInstance().clearLines();
+    }
+
+    void Shell::history()
+    {
+        Shell& instance = Shell::getInstance();
+
+        for (unsigned int i = instance.historyOffset_; i < instance.commandHistory_.size(); ++i)
+            instance.addLine(instance.commandHistory_[i], -1);
+        for (unsigned int i =  0; i < instance.historyOffset_; ++i)
+            instance.addLine(instance.commandHistory_[i], -1);
+    }
+
+    void Shell::registerListener(ShellListener* listener)
+    {
+        this->listeners_.insert(this->listeners_.end(), listener);
+    }
+
+    void Shell::unregisterListener(ShellListener* listener)
+    {
+        for (std::list<ShellListener*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); )
+        {
+            if ((*it) == listener)
+                this->listeners_.erase(it++);
+            else
+                ++it;
+        }
+    }
+
+    void Shell::setCursorPosition(unsigned int cursor)
+    {
+        this->inputBuffer_->setCursorPosition(cursor);
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::setInput(const std::string& input)
+    {
+        this->inputBuffer_->set(input);
+        this->inputChanged();
+    }
+
+    void Shell::addLine(const std::string& line, int level)
+    {
+        int original_level = OutputHandler::getOutStream().getOutputLevel();
+        OutputHandler::getOutStream().setOutputLevel(level);
+
+        if (!this->finishedLastLine_)
+            this->outputBuffer_ << std::endl;
+
+        this->outputBuffer_ << line << std::endl;
+        OutputHandler::getOutStream().setOutputLevel(original_level);
+    }
+
+    void Shell::clearLines()
+    {
+        this->lines_.clear();
+        this->scrollIterator_ = this->lines_.begin();
+
+        this->scrollPosition_ = 0;
+        this->finishedLastLine_ = true;
+
+        SHELL_UPDATE_LISTENERS(linesChanged);
+    }
+
+    std::list<std::string>::const_iterator Shell::getNewestLineIterator() const
+    {
+        if (this->scrollPosition_)
+            return this->scrollIterator_;
+        else
+            return this->lines_.begin();
+    }
+
+    std::list<std::string>::const_iterator Shell::getEndIterator() const
+    {
+        return this->lines_.end();
+    }
+
+    void Shell::addToHistory(const std::string& command)
+    {
+        ModifyConfigValue(commandHistory_, set, this->historyOffset_, command);
+        this->historyPosition_ = 0;
+        ModifyConfigValue(historyOffset_, set, (this->historyOffset_ + 1) % this->maxHistoryLength_);
+    }
+
+    std::string Shell::getFromHistory() const
+    {
+        unsigned int index = mod(static_cast<int>(this->historyOffset_) - static_cast<int>(this->historyPosition_), this->maxHistoryLength_);
+        if (index < this->commandHistory_.size() && this->historyPosition_ != 0)
+            return this->commandHistory_[index];
+        else
+            return "";
+    }
+
+    void Shell::outputChanged()
+    {
+        std::string output;
+        bool newline;
+        do
+        {
+            newline = this->outputBuffer_.getLine(&output);
+
+            if (!newline && output == "")
+                break;
+
+            if (this->finishedLastLine_)
+            {
+                if (this->bAddOutputLevel_)
+                    output.insert(0, 1, static_cast<char>(OutputHandler::getOutStream().getOutputLevel()));
+
+                this->lines_.insert(this->lines_.begin(), output);
+
+                if (this->scrollPosition_)
+                    this->scrollPosition_++;
+                else
+                    this->scrollIterator_ = this->lines_.begin();
+
+                this->finishedLastLine_ = newline;
+
+                if (!this->scrollPosition_)
+                {
+                    SHELL_UPDATE_LISTENERS(lineAdded);
+                }
+            }
+            else
+            {
+                (*this->lines_.begin()) += output;
+                this->finishedLastLine_ = newline;
+                SHELL_UPDATE_LISTENERS(onlyLastLineChanged);
+            }
+
+        } while (newline);
+    }
+
+    void Shell::inputChanged()
+    {
+        SHELL_UPDATE_LISTENERS(inputChanged);
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::execute()
+    {
+        this->addToHistory(this->inputBuffer_->get());
+        this->addLine(this->inputBuffer_->get(), 0);
+
+        if (!CommandExecutor::execute(this->inputBuffer_->get()))
+            this->addLine("Error: Can't execute \"" + this->inputBuffer_->get() + "\".", 1);
+
+        this->clear();
+    }
+
+    void Shell::hintandcomplete()
+    {
+        this->inputBuffer_->set(CommandExecutor::complete(this->inputBuffer_->get()));
+        this->addLine(CommandExecutor::hint(this->inputBuffer_->get()), -1);
+
+        this->inputChanged();
+    }
+
+    void Shell::backspace()
+    {
+        this->inputBuffer_->removeBehindCursor();
+        SHELL_UPDATE_LISTENERS(inputChanged);
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::deletechar()
+    {
+        this->inputBuffer_->removeAtCursor();
+        SHELL_UPDATE_LISTENERS(inputChanged);
+    }
+
+    void Shell::clear()
+    {
+        this->inputBuffer_->clear();
+        this->historyPosition_ = 0;
+        SHELL_UPDATE_LISTENERS(inputChanged);
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::cursor_right()
+    {
+        this->inputBuffer_->increaseCursor();
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::cursor_left()
+    {
+        this->inputBuffer_->decreaseCursor();
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::cursor_end()
+    {
+        this->inputBuffer_->setCursorToEnd();
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::cursor_home()
+    {
+        this->inputBuffer_->setCursorToBegin();
+        SHELL_UPDATE_LISTENERS(cursorChanged);
+    }
+
+    void Shell::history_up()
+    {
+        if (this->historyPosition_ < this->commandHistory_.size())
+        {
+            this->historyPosition_++;
+            this->inputBuffer_->set(this->getFromHistory());
+        }
+    }
+
+    void Shell::history_down()
+    {
+        if (this->historyPosition_ > 0)
+        {
+            this->historyPosition_--;
+            this->inputBuffer_->set(this->getFromHistory());
+        }
+    }
+
+    void Shell::scroll_up()
+    {
+        if (this->scrollIterator_ != this->lines_.end())
+        {
+            ++this->scrollIterator_;
+            ++this->scrollPosition_;
+
+            SHELL_UPDATE_LISTENERS(linesChanged);
+        }
+    }
+
+    void Shell::scroll_down()
+    {
+        if (this->scrollIterator_ != this->lines_.begin())
+        {
+            --this->scrollIterator_;
+            --this->scrollPosition_;
+
+            SHELL_UPDATE_LISTENERS(linesChanged);
+        }
+    }
+
+    void Shell::exit()
+    {
+        if (this->inputBuffer_->getSize() > 0)
+        {
+            this->clear();
+            return;
+        }
+
+        this->clear();
+        this->scrollPosition_ = 0;
+        this->scrollIterator_ = this->lines_.begin();
+
+        SHELL_UPDATE_LISTENERS(exit);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Shell.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Shell.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Shell.h	(revision 5712)
@@ -0,0 +1,153 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Shell_H__
+#define _Shell_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <list>
+#include <string>
+#include <vector>
+
+#include "util/OutputBuffer.h"
+#include "input/InputBuffer.h"
+#include "OrxonoxClass.h"
+#include "ConfigFileManager.h"
+
+namespace orxonox
+{
+    class _CoreExport ShellListener
+    {
+        friend class Shell;
+
+        public:
+            virtual ~ShellListener() {}
+
+        private:
+            virtual void linesChanged() {}
+            virtual void onlyLastLineChanged() {}
+            virtual void lineAdded() {}
+            virtual void inputChanged() {}
+            virtual void cursorChanged() {}
+            virtual void exit() {}
+    };
+
+    class _CoreExport Shell : public Singleton<Shell>, virtual public OrxonoxClass, public OutputBufferListener
+    {
+        friend class Singleton<Shell>;
+        public:
+            Shell();
+            virtual ~Shell();
+
+            static void clearShell();
+            static void history();
+
+            virtual void setConfigValues();
+            void commandHistoryOffsetChanged();
+            void commandHistoryLengthChanged();
+
+            void registerListener(ShellListener* listener);
+            void unregisterListener(ShellListener* listener);
+
+            inline InputBuffer* getInputBuffer()
+                { return this->inputBuffer_; }
+            inline OutputBuffer& getOutputBuffer()
+                { return this->outputBuffer_; }
+
+            void setCursorPosition(unsigned int cursor);
+            inline unsigned int getCursorPosition() const
+                { return this->inputBuffer_->getCursorPosition(); }
+
+            void setInput(const std::string& input);
+
+            inline void clearInput()
+                { this->setInput(""); }
+            inline std::string getInput() const
+                { return this->inputBuffer_->get(); }
+
+            std::list<std::string>::const_iterator getNewestLineIterator() const;
+            std::list<std::string>::const_iterator getEndIterator() const;
+
+            void addLine(const std::string& line, int level = 0);
+            void clearLines();
+
+            inline unsigned int getNumLines() const
+                { return this->lines_.size(); }
+            inline unsigned int getScrollPosition() const
+                { return this->scrollPosition_; }
+
+            inline void addOutputLevel(bool bAddOutputLevel)
+                { this->bAddOutputLevel_ = bAddOutputLevel; }
+
+        private:
+            Shell(const Shell& other);
+
+            void configureInputBuffer();
+
+            void addToHistory(const std::string& command);
+            std::string getFromHistory() const;
+
+            virtual void outputChanged();
+            void inputChanged();
+            void execute();
+            void hintandcomplete();
+            void backspace();
+            void deletechar();
+            void clear();
+            void cursor_right();
+            void cursor_left();
+            void cursor_end();
+            void cursor_home();
+            void history_up();
+            void history_down();
+            void scroll_up();
+            void scroll_down();
+            void exit();
+
+            std::list<ShellListener*> listeners_;
+            InputBuffer* inputBuffer_;
+            OutputBuffer outputBuffer_;
+            bool finishedLastLine_;
+            std::list<std::string> lines_;
+            std::list<std::string>::const_iterator scrollIterator_;
+            unsigned int scrollPosition_;
+            std::vector<std::string> commandHistory_;
+            unsigned int maxHistoryLength_;
+            unsigned int historyPosition_;
+            unsigned int historyOffset_;
+            bool bAddOutputLevel_;
+
+            ConfigFileType commandHistoryConfigFileType_;
+
+            static Shell* singletonPtr_s;
+    };
+}
+
+#endif /* _Shell_H__ */
Index: /code/branches/libraries2/src/libraries/core/Super.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Super.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Super.h	(revision 5712)
@@ -0,0 +1,585 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of all super-function related macros.
+
+    This file defines all macros needed to add a new "super-function".
+    If you add a super-function, you can call SUPER(myclass, functionname) inside your
+    code and the function of the parentclass gets called. This is comparable with
+    super.functionname() in Java or other languages.
+
+    This works only with virtual functions that return nothing (void) and belong to
+    classes that have an Identifier. Arguments however are supported.
+
+    To add a new super-function, you have process 4 steps:
+
+    1) Add a new SUPER macro
+       This allows you to call the super-function in your code.
+       Location: This file (Super.h), marked with --> HERE <-- comments (1/3)
+
+    2) Call the SUPER_FUNCTION_GLOBAL_DECLARATION_PART1/2 macros.
+       This defines some global classes and templates, needed to create and call the super-functions.
+       Location: This file (Super.h), marked with --> HERE <-- comments (2/3)
+
+    3) Call the SUPER_INTRUSIVE_DECLARATION macro.
+       This will be included into the declaration of ClassIdentifier<T>.
+       Location: This file (Super.h), marked with --> HERE <-- comments (3/3)
+
+    4) Call the SUPER_FUNCTION macro.
+       This defines a partially specialized template that will decide if a class is "super" to another class.
+       If the check returns true, a SuperFunctionCaller gets created, which will be used by the SUPER macro.
+       You have to add this into the header-file of the baseclass of the super-function (the class that first
+       implements the function), below the class declaration. You can't call it directly in this file, because
+       otherwise you had to include the headerfile right here, which would cause some ugly backdependencies,
+       include loops and slower compilation.
+       Dont forget to include Super.h in the header-file.
+       Location: The header-file of the baseclass (Baseclass.h), below the class declaration
+*/
+
+#ifndef _Super_H__
+#define _Super_H__
+
+#include "CorePrereqs.h"
+
+#include "util/Debug.h"
+#include "Event.h"
+
+///////////////////////
+// Macro definitions //
+///////////////////////
+
+//// Common macros ////
+
+    /**
+        @brief Declares a new super-function by creating a specialized template. Add this below the class declaration of the baseclass.
+        @param functionnumber Each super-function needs a unique number, starting with zero, increasing by one
+        @param baseclass The baseclass of the super-function (~the root)
+        @param functionname The name of the super-function
+        @param purevirtualbase "true" if the function is pure virtual in the baseclass, "false" if the function is implemented (without "")
+    */
+    #define SUPER_FUNCTION(functionnumber, baseclass, functionname, purevirtualbase) \
+        template <class T, int templatehack2> \
+        struct SuperFunctionCondition<functionnumber, T, 0, templatehack2> \
+        { \
+            static void check() \
+            { \
+                SuperFunctionCondition<functionnumber, T, 0, templatehack2>::apply(static_cast<T*>(0)); \
+                SuperFunctionCondition<functionnumber + 1, T, 0, templatehack2>::check(); \
+            } \
+            \
+            static void apply(void* temp) {} \
+            \
+            static void apply(baseclass* temp) \
+            { \
+                ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier(); \
+                for (std::set<const Identifier*>::iterator it = identifier->getDirectChildrenIntern().begin(); it != identifier->getDirectChildrenIntern().end(); ++it) \
+                { \
+                    if (((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ && ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_) \
+                    { \
+                        delete ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_; \
+                        ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = 0; \
+                        ((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ = false; \
+                    } \
+                    \
+                    if (!((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_) \
+                    { \
+                        COUT(5) << "Added SuperFunctionCaller for " << #functionname << ": " << ClassIdentifier<T>::getIdentifier()->getName() << " <- " << ((ClassIdentifier<T>*)(*it))->getName() << std::endl; \
+                        ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_##functionname <T>; \
+                    } \
+                } \
+            } \
+        }; \
+        \
+        SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND##purevirtualbase(functionnumber, baseclass)
+
+    #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND0(functionnumber, baseclass) SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDfalse(functionnumber, baseclass)
+    #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND1(functionnumber, baseclass) SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDtrue(functionnumber, baseclass)
+    #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDfalse(functionnumber, baseclass)
+    #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDtrue(functionnumber, baseclass) \
+        template <int templatehack2> \
+        struct SuperFunctionCondition<functionnumber, baseclass, 0, templatehack2> \
+        { \
+            static void check() \
+            { \
+                SuperFunctionCondition<functionnumber + 1, baseclass, 0, templatehack2>::check(); \
+            } \
+        };
+
+
+    /*
+    //// Comments about the macro ////
+
+        // Partially specialized template (templatehack is now specialized too).
+        //
+        // This ensures the compiler takes THIS template if the header-file of the super-function
+        // is included. In any other case, the compiler just uses the fallback template which is
+        // defined in this file.
+        template <class T, templatehack2>
+        struct SuperFunctionCondition<functionnumber, T, 0, templatehack2>
+        {
+            static void check()
+            {
+                // This call to the apply-function is the whole check. By calling the function with
+                // a T* pointer, the right function get's called.
+                SuperFunctionCondition<functionnumber, T, 0, templatehack2>::apply(static_cast<T*>(0));
+
+                // Go go the check for of next super-function (functionnumber + 1)
+                SuperFunctionCondition<functionnumber + 1, T, 0, templatehack2>::check();
+            }
+
+            // This function gets called if T is not a child of the baseclass.
+            // The function does nothing.
+            static void apply(void* temp) {}
+
+            // This function gets called if T is a child of the baseclass and can therefore be converted.
+            // The function adds a SuperFunctionCaller to the Identifier of all subclasses of T.
+            static void apply(baseclass* temp)
+            {
+                ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
+
+                // Iterate through all children
+                for (std::set<const Identifier*>::iterator it = identifier->getDirectChildrenIntern().begin(); it != identifier->getDirectChildrenIntern().end(); ++it)
+                {
+                    // Check if the caller is a fallback-caller
+                    if (((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ && ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_)
+                    {
+                        // Delete the fallback caller an prepare to get a real caller
+                        delete ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_;
+                        ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = 0;
+                        ((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ = false;
+                    }
+
+                    // Check if there's not already a caller
+                    if (!((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_)
+                    {
+                        // Add the SuperFunctionCaller
+                        COUT(5) << "adding functionpointer to " << ((ClassIdentifier<T>*)(*it))->getName() << std::endl;
+                        ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_##functionname <T>;
+                    }
+                }
+            }
+        };
+        SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND##purevirtualbase
+
+
+        // The following piece of code is only added if purevirtualbase = true
+
+        // Explicit specialization of the Condition template for the baseclass to avoid
+        // errors if the function is pure virtual in the baseclass.
+        template <int templatehack2> \
+        struct SuperFunctionCondition<functionnumber, baseclass, 0, templatehack2> \
+        { \
+            // The check function acts like the fallback - it advances to the check for the next super-function (functionnumber + 1)
+            static void check() \
+            { \
+                SuperFunctionCondition<functionnumber + 1, baseclass, 0, templatehack2>::check(); \
+            } \
+        };
+    */
+
+    // SUPER-macro: Calls Parent::functionname() where Parent is the direct parent of classname
+    #ifdef ORXONOX_COMPILER_MSVC
+        #define SUPER(classname, functionname, ...) \
+            __super::functionname(__VA_ARGS__)
+    #else
+        #define SUPER(classname, functionname, ...) \
+            SUPER_##functionname(classname, functionname, __VA_ARGS__)
+    #endif
+
+    // helper macro: for functions without arguments
+    #define SUPER_NOARGS(classname, functionname) \
+        (*ClassIdentifier<classname>::getIdentifier()->superFunctionCaller_##functionname##_)(this)
+
+    // helper macro: for functions with arguments
+    #define SUPER_ARGS(classname, functionname, ...) \
+        (*ClassIdentifier<classname>::getIdentifier()->superFunctionCaller_##functionname##_)(this, __VA_ARGS__)
+
+
+//// Function-specific macros ////
+
+    /*
+        Add a macro for each super-function
+
+        Example (no arguments):
+        #define SUPER_myfunction(classname, functionname, ...) \
+            SUPER_NOARGS(classname, functionname)
+
+        Example (with arguments):
+        #define SUPER_myfunction(classname, functionname, ...) \
+            SUPER_ARGS(classname, functionname, __VA_ARGS__)
+    */
+
+    // (1/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
+    #define SUPER_XMLPort(classname, functionname, ...) \
+        SUPER_ARGS(classname, functionname, __VA_ARGS__)
+
+    #define SUPER_tick(classname, functionname, ...) \
+        SUPER_ARGS(classname, functionname, __VA_ARGS__)
+
+    #define SUPER_changedActivity(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_changedVisibility(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_processEvent(classname, functionname, ...) \
+        SUPER_ARGS(classname, functionname, __VA_ARGS__)
+
+    #define SUPER_changedScale(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_changedMainState(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_changedOwner(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_changedOverlayGroup(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_changedName(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+
+    #define SUPER_changedGametype(classname, functionname, ...) \
+        SUPER_NOARGS(classname, functionname)
+    // (1/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
+
+
+namespace orxonox
+{
+    /////////////////////////////////////////////////////////////////////////////////////////////////////
+    // This code gets included by Identifier.h and every other header file that needs a super-function //
+    /////////////////////////////////////////////////////////////////////////////////////////////////////
+
+    //// Common code ////
+
+        // Base templates
+        /**
+            @brief Creates the SuperFunctionCaller if T is a child of the super-functions baseclass.
+        */
+        template <int functionnumber, class T, int templatehack1, int templatehack2>
+        struct SuperFunctionCondition
+        {
+            static void check() {}
+        };
+
+        /**
+            @brief Initializes the SuperFunctionCaller-pointer with zero.
+        */
+        template <int functionnumber, class T>
+        struct SuperFunctionInitialization
+        {
+            static void initialize(ClassIdentifier<T>* identifier) {}
+        };
+
+        /**
+            @brief Deletes the SuperFunctionCaller.
+        */
+        template <int functionnumber, class T>
+        struct SuperFunctionDestruction
+        {
+            static void destroy(ClassIdentifier<T>* identifier) {}
+        };
+
+
+    //// Function-specific code ////
+
+        /**
+            @brief Creates the needed objects and templates to call a super-function.
+            @param functionnumber Each super-function needs a unique number, starting with zero, increasing by one
+            @param functionname The name of the super-function
+            @param hasarguments "false" if the function doesn't take any arguments, "true" if it does (without "")
+            @param ... Variadic: If the function takes arguments, add them here with type and name. Example: int myvalue, float myothervalue
+        */
+        #define SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(functionnumber, functionname, hasarguments, ...) \
+            template <class T, int templatehack1, int templatehack2> \
+            struct SuperFunctionCondition<functionnumber, T, templatehack1, templatehack2> \
+            { \
+                static void check() \
+                { \
+                    SuperFunctionCondition<functionnumber + 1, T, templatehack1, templatehack2>::check(); \
+                } \
+            }; \
+            \
+            class _CoreExport SuperFunctionCaller_##functionname \
+            { \
+                public: \
+                    virtual void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) = 0; \
+                    virtual ~SuperFunctionCaller_##functionname () {} \
+            }; \
+            \
+            template <class T> \
+            class SuperFunctionClassCaller_purevirtualfallback_##functionname : public SuperFunctionCaller_##functionname \
+            { \
+                public: \
+                    inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) \
+                    { \
+                    } \
+            }; \
+            \
+            template <class T> \
+            struct SuperFunctionInitialization<functionnumber, T> \
+            { \
+                static void initialize(ClassIdentifier<T>* identifier) \
+                { \
+                    identifier->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_purevirtualfallback_##functionname <T>; \
+                    identifier->bSuperFunctionCaller_##functionname##_isFallback_ = true; \
+                    SuperFunctionInitialization<functionnumber + 1, T>::initialize(identifier); \
+                } \
+            }; \
+            \
+            template <class T> \
+            struct SuperFunctionDestruction<functionnumber, T> \
+            { \
+                static void destroy(ClassIdentifier<T>* identifier) \
+                { \
+                    if (identifier->superFunctionCaller_##functionname##_) \
+                        delete identifier->superFunctionCaller_##functionname##_; \
+                    SuperFunctionDestruction<functionnumber + 1, T>::destroy(identifier); \
+                } \
+            }; \
+            \
+            template <class T> \
+            class SuperFunctionClassCaller_##functionname : public SuperFunctionCaller_##functionname \
+            { \
+                public: \
+                    inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) \
+                    { \
+                        (dynamic_cast<T*>(object))->T:: functionname
+
+        /*
+            JUST ADD THE FUNCTION ARGUMENTS BETWEEN BOTH MACROS, ENCLOSED BY BRACKETS
+            EXAMPLE:
+
+              SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(0, myfunction, true, int myvalue, float myothervalue) <-- !!! DONT ADD A SEMICOLON HERE !!!
+                (myvalue, myothervalue)
+              SUPER_FUNCTION_GLOBAL_DECLARATION_PART2
+        */
+
+        #define SUPER_FUNCTION_GLOBAL_DECLARATION_PART2 \
+                                                        ; \
+                    } \
+            };
+
+        #define SUPER_CALL_ARGUMENTSfalse(...) OrxonoxClass* object
+        #define SUPER_CALL_ARGUMENTS0(...)     OrxonoxClass* object
+        #define SUPER_CALL_ARGUMENTStrue(...) OrxonoxClass* object, __VA_ARGS__
+        #define SUPER_CALL_ARGUMENTS1(...)    OrxonoxClass* object, __VA_ARGS__
+
+
+    /*
+    //// COMMENTS ABOUT THE MACRO ////
+
+        // Partially specialized template (templatehack not yet specialized, this
+        // will be done by the real condition in the header-file of the super-function)
+        // Only used as fallback
+        template <class T, int templatehack1, int templatehack2>
+        struct SuperFunctionCondition<functionnumber, T, templatehack1, templatehack2>
+        {
+            // If this function gets called, the header-file of the super function is not
+            // included, so this fallback template (templatehack not specialized) is used
+            static void check()
+            {
+                // Calls the condition-check of the next super-function (functionnumber + 1)
+                SuperFunctionCondition<functionnumber + 1, T, templatehack1, templatehack2>::check();
+            }
+        };
+
+        // Baseclass of the super-function caller. The real call will be done by a
+        // templatized subclass through the virtual () operator.
+        class _CoreExport SuperFunctionCaller_##functionname
+        {
+            public:
+                virtual void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) = 0;
+                virtual ~SuperFunctionCaller_##functionname () {}
+        };
+
+        // Fallback if the base is pure virtual
+        template <class T>
+        class SuperFunctionClassCaller_purevirtualfallback_##functionname : public SuperFunctionCaller_##functionname
+        {
+            public:
+                // Fallback does nothing
+                inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) )
+                {
+                }
+        };
+
+        // Initializes the SuperFunctionCaller-pointer with a fallback caller in case the base function is pure virtual
+        template <class T>
+        struct SuperFunctionInitialization<functionnumber, T>
+        {
+            static void initialize(ClassIdentifier<T>* identifier)
+            {
+                identifier->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_purevirtualfallback_##functionname <T>;
+                identifier->bSuperFunctionCaller_##functionname##_isFallback_ = true;
+
+                // Calls the initialization of the next super-function (functionnumber + 1)
+                SuperFunctionInitialization<functionnumber + 1, T>::initialize(identifier);
+            }
+        };
+
+        // Deletes the SuperFunctionCaller.
+        template <class T>
+        struct SuperFunctionDestruction<functionnumber, T>
+        {
+            static void destroy(ClassIdentifier<T>* identifier)
+            {
+                if (identifier->superFunctionCaller_##functionname##_)
+                    delete identifier->superFunctionCaller_##functionname##_;
+
+                // Calls the destruction of the next super-function (functionnumber + 1)
+                SuperFunctionDestruction<functionnumber + 1, T>::destroy(identifier);
+            }
+        };
+
+        // The real super-function caller: Calls T::functionname()
+        // T should be the parent, but this will be done by the spezialized condition template
+        template <class T>
+        class SuperFunctionClassCaller_##functionname : public SuperFunctionCaller_##functionname
+        {
+            public:
+                // @brief Calls the function.
+                // @param object The object to call the function on
+                // @param ... The arguments of the function
+                inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) )
+                {
+                    (dynamic_cast<T*>(object))->T:: functionname ( Call the function with it's arguments );
+                }
+        }
+    */
+
+
+    //// Execute the code for each super-function ////
+
+        // (2/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(0, XMLPort, true, Element& xmlelement, XMLPort::Mode mode)
+            (xmlelement, mode)
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(1, tick, true, float dt)
+            (dt)
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(2, changedActivity, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(3, changedVisibility, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, processEvent, true, Event& event)
+            (event)
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(5, changedScale, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedMainState, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOwner, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedOverlayGroup, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedName, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(10, changedGametype, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+        // (2/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
+
+}
+
+#else /* _Super_H__ */
+  #ifdef SUPER_INTRUSIVE_DECLARATION_INCLUDE
+
+//////////////////////////////////////////////////////////////////////////
+// This code gets included within the declaration of ClassIdentifier<T> //
+//////////////////////////////////////////////////////////////////////////
+
+//// Common code ////
+
+    private:
+
+        template <int functionnumber, class TT, int templatehack1, int templatehack2>
+        friend struct SuperFunctionCondition;
+
+        // Creates the super-function-callers by calling the first SuperFunctionCondition check
+        // This get's called within the initialization of an Identifier
+        virtual void createSuperFunctionCaller() const
+        {
+            SuperFunctionCondition<0, T, 0, 0>::check();
+        }
+
+
+//// Function-specific code ////
+
+    public:
+        /**
+            @brief Adds a pointer to the SuperFunctionCaller as a member of ClassIdentifier.
+            @param functionname The name of the super-function
+        */
+        #ifndef SUPER_INTRUSIVE_DECLARATION
+          #define SUPER_INTRUSIVE_DECLARATION(functionname) \
+            SuperFunctionCaller_##functionname * superFunctionCaller_##functionname##_; \
+            bool bSuperFunctionCaller_##functionname##_isFallback_
+        #endif
+
+
+//// Execute the code for each super-function ////
+
+    // (3/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
+    SUPER_INTRUSIVE_DECLARATION(XMLPort);
+    SUPER_INTRUSIVE_DECLARATION(tick);
+    SUPER_INTRUSIVE_DECLARATION(changedActivity);
+    SUPER_INTRUSIVE_DECLARATION(changedVisibility);
+    SUPER_INTRUSIVE_DECLARATION(processEvent);
+    SUPER_INTRUSIVE_DECLARATION(changedScale);
+    SUPER_INTRUSIVE_DECLARATION(changedMainState);
+    SUPER_INTRUSIVE_DECLARATION(changedOwner);
+    SUPER_INTRUSIVE_DECLARATION(changedOverlayGroup);
+    SUPER_INTRUSIVE_DECLARATION(changedName);
+    SUPER_INTRUSIVE_DECLARATION(changedGametype);
+    // (3/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
+
+
+    #undef SUPER_INTRUSIVE_DECLARATION_INCLUDE
+  #endif /* SUPER_INTRUSIVE_DECLARATION_INCLUDE */
+#endif /* _Super_H__ */
Index: /code/branches/libraries2/src/libraries/core/TclBind.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/TclBind.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/TclBind.cc	(revision 5712)
@@ -0,0 +1,206 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "TclBind.h"
+
+#include <exception>
+#include <string>
+#include <cpptcl/cpptcl.h>
+
+#include "SpecialConfig.h"
+#include "util/Debug.h"
+#include "util/StringUtils.h"
+#include "CommandExecutor.h"
+#include "ConsoleCommand.h"
+#include "Core.h"
+#include "TclThreadManager.h"
+
+namespace orxonox
+{
+    SetConsoleCommandShortcut(TclBind, tcl);
+    SetConsoleCommandShortcut(TclBind, bgerror);
+
+    TclBind* TclBind::singletonPtr_s = 0;
+
+    TclBind::TclBind(const std::string& datapath)
+    {
+        this->interpreter_ = 0;
+        this->bSetTclDataPath_ = false;
+        this->setDataPath(datapath);
+    }
+
+    TclBind::~TclBind()
+    {
+        if (this->interpreter_)
+            delete this->interpreter_;
+    }
+
+    void TclBind::setDataPath(const std::string& datapath)
+    {
+        // String has POSIX slashes
+        this->tclDataPath_ = datapath + "tcl" + '/';
+        this->bSetTclDataPath_ = true;
+
+        this->initializeTclInterpreter();
+    }
+
+    void TclBind::initializeTclInterpreter()
+    {
+        if (this->bSetTclDataPath_ && !this->interpreter_)
+        {
+            this->interpreter_ = this->createTclInterpreter();
+
+            this->interpreter_->def("::orxonox::query", TclBind::tcl_query, Tcl::variadic());
+            this->interpreter_->def("::orxonox::crossquery", TclThreadManager::tcl_crossquery, Tcl::variadic());
+            this->interpreter_->def("execute", TclBind::tcl_execute, Tcl::variadic());
+            this->interpreter_->def("::orxonox::crossexecute", TclThreadManager::tcl_crossexecute, Tcl::variadic());
+
+            try
+            {
+                this->interpreter_->eval("proc query        {args}    { ::orxonox::query $args }");
+                this->interpreter_->eval("proc crossquery   {id args} { ::orxonox::crossquery 0 $id $args }");
+                this->interpreter_->eval("proc crossexecute {id args} { ::orxonox::crossquery 0 $id $args }");
+                this->interpreter_->eval("proc running      {}        { return 1 }");
+                this->interpreter_->eval("set id 0");
+                this->interpreter_->eval("rename exit ::tcl::exit; proc exit {} { execute exit }");
+            }
+            catch (Tcl::tcl_error const &e)
+            {   COUT(1) << "Tcl error while creating Tcl-interpreter: " << e.what() << std::endl;   }
+            catch (std::exception const &e)
+            {   COUT(1) << "Error while creating Tcl-interpreter: " << e.what() << std::endl;   }
+            catch (...)
+            {   COUT(1) << "Error while creating Tcl-interpreter." << std::endl;   }
+        }
+    }
+
+    Tcl::interpreter* TclBind::createTclInterpreter()
+    {
+        Tcl::interpreter* interpreter = new Tcl::interpreter();
+        std::string libpath = TclBind::getTclLibraryPath();
+
+        try
+        {
+            if (libpath != "")
+                interpreter->eval("set tcl_library \"" + libpath + "\"");
+
+            Tcl_Init(interpreter->get());
+
+            interpreter->eval("source \"" + TclBind::getInstance().tclDataPath_ + "/init.tcl\"");
+        }
+        catch (Tcl::tcl_error const &e)
+        {   COUT(1) << "Tcl error while creating Tcl-interpreter: " << e.what() << std::endl; COUT(1) << "Error: Tcl isn't properly initialized. Orxonox might possibly not work like that." << std::endl;   }
+        catch (std::exception const &e)
+        {   COUT(1) << "Error while creating Tcl-interpreter: " << e.what() << std::endl; COUT(1) << "Error: Tcl isn't properly initialized. Orxonox might possibly not work like that." << std::endl;   }
+        catch (...)
+        {   COUT(1) << "Error while creating Tcl-interpreter." << std::endl; COUT(1) << "Error: Tcl isn't properly initialized. Orxonox might possibly not work like that." << std::endl;   }
+
+        return interpreter;
+    }
+
+    std::string TclBind::getTclLibraryPath()
+    {
+#ifdef DEPENDENCY_PACKAGE_ENABLE
+        if (Core::isDevelopmentRun())
+            return (std::string(specialConfig::dependencyLibraryDirectory) + "/tcl");
+        else
+            return (Core::getRootPathString() + "lib/tcl");
+#else
+        return "";
+#endif
+    }
+
+    std::string TclBind::tcl_query(Tcl::object const &args)
+    {
+        COUT(4) << "Tcl_query: " << args.get() << std::endl;
+
+        std::string command = stripEnclosingBraces(args.get());
+
+        if (!CommandExecutor::execute(command, false))
+        {
+            COUT(1) << "Error: Can't execute command \"" << command << "\"!" << std::endl;
+        }
+
+        if (CommandExecutor::getLastEvaluation().hasReturnvalue())
+            return CommandExecutor::getLastEvaluation().getReturnvalue().getString();
+
+        return "";
+    }
+
+    void TclBind::tcl_execute(Tcl::object const &args)
+    {
+        COUT(4) << "Tcl_execute: " << args.get() << std::endl;
+        std::string command = stripEnclosingBraces(args.get());
+
+        if (!CommandExecutor::execute(command, false))
+        {
+            COUT(1) << "Error: Can't execute command \"" << command << "\"!" << std::endl;
+        }
+    }
+
+    std::string TclBind::tcl(const std::string& tclcode)
+    {
+        if (TclBind::getInstance().interpreter_)
+        {
+            try
+            {
+                std::string output = TclBind::getInstance().interpreter_->eval("uplevel #0 " + tclcode);
+                if (output != "")
+                {
+                    COUT(0) << "tcl> " << output << std::endl;
+                }
+                return output;
+            }
+            catch (Tcl::tcl_error const &e)
+            {   COUT(1) << "tcl> Error: " << e.what() << std::endl;   }
+            catch (std::exception const &e)
+            {   COUT(1) << "Error while executing Tcl: " << e.what() << std::endl;   }
+        }
+
+        return "";
+    }
+
+    void TclBind::bgerror(std::string error)
+    {
+        COUT(1) << "Tcl background error: " << stripEnclosingBraces(error) << std::endl;
+    }
+
+    bool TclBind::eval(const std::string& tclcode)
+    {
+        try
+        {
+            TclBind::getInstance().interpreter_->eval(tclcode);
+            return true;
+        }
+        catch (Tcl::tcl_error const &e)
+        {   COUT(1) << "Tcl error: " << e.what() << std::endl;   }
+        catch (std::exception const &e)
+        {   COUT(1) << "Error while executing Tcl: " << e.what() << std::endl;   }
+
+        return false;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/TclBind.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/TclBind.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/TclBind.h	(revision 5712)
@@ -0,0 +1,74 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _TclBind_H__
+#define _TclBind_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <string>
+#include "util/Singleton.h"
+
+namespace orxonox
+{
+    class _CoreExport TclBind : public Singleton<TclBind>
+    {
+        friend class Singleton<TclBind>;
+        public:
+            TclBind(const std::string& datapath);
+            ~TclBind();
+
+            static std::string tcl(const std::string& tclcode);
+            static void bgerror(std::string error);
+
+            void setDataPath(const std::string& datapath);
+            const std::string& getTclDataPath() const { return this->tclDataPath_; }
+            static std::string getTclLibraryPath();
+
+            void initializeTclInterpreter();
+            static Tcl::interpreter* createTclInterpreter();
+            Tcl::interpreter* getTclInterpreter() const { return this->interpreter_; }
+
+            static std::string tcl_query(Tcl::object const &args);
+            static void tcl_execute(Tcl::object const &args);
+
+            static bool eval(const std::string& tclcode);
+
+        private:
+            TclBind(const TclBind& other);
+
+            Tcl::interpreter* interpreter_;
+            std::string tclDataPath_;
+            bool bSetTclDataPath_;
+
+            static TclBind* singletonPtr_s;
+    };
+}
+
+#endif /* _TclBind_H__ */
Index: /code/branches/libraries2/src/libraries/core/TclThreadList.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/TclThreadList.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/TclThreadList.h	(revision 5712)
@@ -0,0 +1,263 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _TclThreadList_H__
+#define _TclThreadList_H__
+
+#include "CorePrereqs.h"
+
+#include <list>
+
+#include <boost/thread/condition_variable.hpp>
+#include <boost/thread/shared_mutex.hpp>
+#include <boost/thread/locks.hpp>
+
+namespace orxonox
+{
+    template <class T>
+    class TclThreadList
+    {
+        public:
+            void push_front(const T& value);
+            void push_back(const T& value);
+            template <class InputIterator> void insert(typename std::list<T>::iterator position, InputIterator begin, InputIterator end);
+
+            void wait_and_pop_front(T* value);
+            void wait_and_pop_back(T* value);
+            bool try_pop_front(T* value);
+            bool try_pop_back(T* value);
+            void clear();
+
+            size_t size() const;
+            bool empty() const;
+            bool is_in(const T& value) const;
+
+            /**
+                @brief Returns a reference to the list. Don't forget to lock the mutex (see @ref getMutex).
+            */
+            inline std::list<T>& getList()
+                { return this->list_; }
+
+            /**
+                @brief Returns a reference to the list. Don't forget to lock the mutex (see @ref getMutex).
+            */
+            inline const std::list<T>& getList() const
+                { return this->list_; }
+
+            /**
+                @brief Returns a reference to the mutex which might be useful if you want to iterate through the list (see @ref begin and @ref end).
+            */
+            inline boost::shared_mutex& getMutex() const
+                { return this->mutex_; }
+
+        private:
+            std::list<T>                  list_;        ///< A standard list for type T
+            mutable boost::shared_mutex   mutex_;       ///< A mutex to grant exclusive access to the list
+            boost::condition_variable_any condition_;   ///< A condition variable to wake threads waiting for the mutex to become ready
+    };
+
+    /**
+        @brief Pushes a new element to the front of the list. A unique_lock is needed.
+    */
+    template <class T>
+    void TclThreadList<T>::push_front(const T& value)
+    {
+        boost::unique_lock<boost::shared_mutex> lock(this->mutex_);
+        this->list_.push_front(value);
+        lock.unlock();                  // unlock the mutex...
+        this->condition_.notify_all();  // ...then call notify_all to wake threads waiting in wait_and_pop_front/back
+    }
+
+    /**
+        @brief Pushes a new element to the back of the list. A unique_lock is needed.
+    */
+    template <class T>
+    void TclThreadList<T>::push_back(const T& value)
+    {
+        boost::unique_lock<boost::shared_mutex> lock(this->mutex_);
+        this->list_.push_back(value);
+        lock.unlock();                  // unlock the mutex...
+        this->condition_.notify_all();  // ...then call notify_all to wake threads waiting in wait_and_pop_front/back
+    }
+
+    /**
+        @brief Inserts new elements into the list. A unique_lock is needed.
+    */
+    template <class T>
+    template <class InputIterator> void TclThreadList<T>::insert(typename std::list<T>::iterator position, InputIterator begin, InputIterator end)
+    {
+        boost::unique_lock<boost::shared_mutex> lock(this->mutex_);
+        this->list_.insert(position, begin, end);
+        lock.unlock();                  // unlock the mutex...
+        this->condition_.notify_all();  // ...then call notify_all to wake threads waiting in wait_and_pop_front/back
+    }
+
+    /**
+        @brief Waits until the list contains at least one element and then pops and returns the front element.
+        @param value The front value will be stored in the variable referenced by this pointer.
+    */
+    template <class T>
+    void TclThreadList<T>::wait_and_pop_front(T* value)
+    {
+        boost::unique_lock<boost::shared_mutex> lock(this->mutex_);
+
+        while (this->list_.empty())       // check if there's an element in the list
+            this->condition_.wait(lock);  // wait until the condition becomes true (a notification comes from push_front, push_back or insert
+
+        *value = this->list_.front();
+        this->list_.pop_front();
+    }
+
+    /**
+        @brief Waits until the list contains at least one element and then pops and returns the back element.
+        @param value The back value will be stored in the variable referenced by this pointer.
+    */
+    template <class T>
+    void TclThreadList<T>::wait_and_pop_back(T* value)
+    {
+        boost::unique_lock<boost::shared_mutex> lock(this->mutex_);
+
+        while (this->list_.empty())       // check if there's an element in the list
+            this->condition_.wait(lock);  // wait until the condition becomes true (a notification comes from push_front, push_back or insert
+
+        *value = this->list_.back();
+        this->list_.pop_back();
+    }
+
+    /**
+        @brief Pops and returns the front element if there's at least one element in the list.
+        @param value The front value will be stored in the variable referenced by this pointer.
+        @return Returns true if there was at least one element in the list (which got poped). If the list was empty, false is returned immediately.
+
+        Needs a unique_lock if there's an element to pop. If not, shared_lock is sufficient.
+    */
+    template <class T>
+    bool TclThreadList<T>::try_pop_front(T* value)
+    {
+        boost::upgrade_lock<boost::shared_mutex> lock(this->mutex_); // gain shared lock
+
+        if (this->list_.empty())
+        {
+            // No elements - return immediately
+            return false;
+        }
+        else
+        {
+            // At least one element - write it into the passed variable and pop it from the list
+            boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock); // upgrade to unique lock to modify the list
+            *value = this->list_.front();
+            this->list_.pop_front();
+        }
+        return true;
+    }
+
+    /**
+        @brief Pops and returns the back element if there's at least one element in the list.
+        @param value The back value will be stored in the variable referenced by this pointer.
+        @return Returns true if there was at least one element in the list (which got poped). If the list was empty, false is returned immediately.
+
+        Needs a unique_lock if there's an element to pop. If not, shared_lock is sufficient.
+    */
+    template <class T>
+    bool TclThreadList<T>::try_pop_back(T* value)
+    {
+        boost::upgrade_lock<boost::shared_mutex> lock(this->mutex_); // gain shared lock
+
+        if (this->list_.empty())
+        {
+            // No elements - return immediately
+            return false;
+        }
+        else
+        {
+            // At least one element - write it into the passed variable and pop it from the list
+            boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock); // upgrade to unique lock to modify the list
+            *value = this->list_.back();
+            this->list_.pop_back();
+        }
+        return true;
+    }
+
+    /**
+        @brief Clears the list. A unique_lock is needed.
+    */
+    template <class T>
+    void TclThreadList<T>::clear()
+    {
+        boost::unique_lock<boost::shared_mutex> lock(this->mutex_);
+        this->list_.clear();
+    }
+
+    /**
+        @brief Returns the size of the list. A shared_lock is needed.
+
+        Warning: Don't change the list based on the result of size(). Use an atomic function instead. Other threads may change the list
+        beween your call to size() and your further actions, so be careful and use this function only if you really want nothing else than
+        just the size of the list.
+    */
+    template <class T>
+    size_t TclThreadList<T>::size() const
+    {
+        boost::shared_lock<boost::shared_mutex> lock(this->mutex_);
+        return this->list_.size();
+    }
+
+    /**
+        @brief Returns true if the list is empty, false otherwise. A shared_lock is needed.
+
+        Warning: Don't change the list based on the result of empty(). Use an atomic function instead. Other threads may change the list
+        beween your call to empty() and your further actions, so be careful and use this function only if you really want nothing else than
+        just if the list is empty or not.
+    */
+    template <class T>
+    bool TclThreadList<T>::empty() const
+    {
+        boost::shared_lock<boost::shared_mutex> lock(this->mutex_);
+        return this->list_.empty();
+    }
+
+    /**
+        @brief Returns true if a given element is in the list, false otherwise. A shared_lock is needed.
+
+        Warning: The result of this function might be wrong just one instruction after the call. Use this function just to get information
+        about a temporary snapshot and don't change the list based on the result of this function.
+    */
+    template <class T>
+    bool TclThreadList<T>::is_in(const T& value) const
+    {
+        boost::shared_lock<boost::shared_mutex> lock(this->mutex_);
+
+        for (typename std::list<T>::const_iterator it = this->list_.begin(); it != this->list_.end(); ++it)
+            if (*it == value)
+                return true;
+
+        return false;
+    }
+}
+
+#endif /* _TclThreadList_H__ */
Index: /code/branches/libraries2/src/libraries/core/TclThreadManager.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/TclThreadManager.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/TclThreadManager.cc	(revision 5712)
@@ -0,0 +1,672 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "TclThreadManager.h"
+
+#include <boost/bind.hpp>
+#include <boost/thread/thread.hpp>
+#include <boost/thread/locks.hpp>
+#include <boost/thread/shared_mutex.hpp>
+#include <OgreTimer.h>
+#include <cpptcl/cpptcl.h>
+
+#include "util/Convert.h"
+#include "Clock.h"
+#include "CommandExecutor.h"
+#include "ConsoleCommand.h"
+#include "CoreIncludes.h"
+#include "TclBind.h"
+#include "TclThreadList.h"
+
+namespace orxonox
+{
+    const float TCLTHREADMANAGER_MAX_CPU_USAGE = 0.50f;
+
+    SetConsoleCommandShortcutAlias(TclThreadManager, execute, "tclexecute").argumentCompleter(0, autocompletion::tclthreads());
+    SetConsoleCommandShortcutAlias(TclThreadManager, query,   "tclquery"  ).argumentCompleter(0, autocompletion::tclthreads());
+    SetConsoleCommand(TclThreadManager, create,  false);
+    SetConsoleCommand(TclThreadManager, destroy, false).argumentCompleter(0, autocompletion::tclthreads());
+    SetConsoleCommand(TclThreadManager, execute, false).argumentCompleter(0, autocompletion::tclthreads());
+    SetConsoleCommand(TclThreadManager, query,   false).argumentCompleter(0, autocompletion::tclthreads());
+    SetConsoleCommand(TclThreadManager, source,  false).argumentCompleter(0, autocompletion::tclthreads());
+
+    /**
+        @brief A struct containing all information about a Tcl-interpreter
+    */
+    struct TclInterpreterBundle
+    {
+        TclInterpreterBundle()
+        {
+            this->lock_ = new boost::unique_lock<boost::mutex>(this->mutex_, boost::defer_lock);
+            this->bRunning_ = true;
+        }
+
+        ~TclInterpreterBundle()
+        {
+            delete this->lock_;
+        }
+
+        unsigned int                      id_;             ///< The id of the interpreter
+        Tcl::interpreter*                 interpreter_;    ///< The Tcl-interpreter
+        boost::mutex                      mutex_;          ///< A mutex to lock the interpreter while it's being used
+        boost::unique_lock<boost::mutex>* lock_;           ///< The corresponding lock for the mutex
+        TclThreadList<std::string>        queue_;          ///< The command queue for commands passed by execute(command)
+        TclThreadList<unsigned int>       queriers_;       ///< A list containing the id's of all other threads sending a query to this interpreter (to avoid circular queries and deadlocks)
+        bool                              bRunning_;       ///< This variable stays true until destroy() gets called
+    };
+
+    TclThreadManager* TclThreadManager::singletonPtr_s = 0;
+
+    /**
+        @brief Constructor
+        @param interpreter A pointer to the standard Tcl-interpreter (see @ref TclBind)
+    */
+    TclThreadManager::TclThreadManager(Tcl::interpreter* interpreter)
+    {
+        RegisterRootObject(TclThreadManager);
+
+        this->numInterpreterBundles_ = 0;
+
+        this->interpreterBundlesMutex_ = new boost::shared_mutex();
+        this->mainInterpreterMutex_ = new boost::mutex();
+        this->messageQueue_ = new TclThreadList<std::string>();
+
+        TclInterpreterBundle* newbundle = new TclInterpreterBundle();
+        newbundle->id_ = 0;
+        newbundle->interpreter_ = interpreter;
+        newbundle->lock_->lock();
+
+        {
+            boost::unique_lock<boost::shared_mutex> lock(*this->interpreterBundlesMutex_);
+            this->interpreterBundles_[0] = newbundle;
+        }
+    }
+
+    /**
+        @brief Destructor
+    */
+    TclThreadManager::~TclThreadManager()
+    {
+        delete this->interpreterBundlesMutex_;
+//        delete this->mainInterpreterMutex_; // <-- temporary disabled to avoid crash if a thread is still actively queriyng
+        delete this->messageQueue_;
+    }
+
+    /**
+        @brief The "main loop" of the TclThreadManager. Creates new threads if needed and handles queries and queued commands for the main interpreter.
+    */
+    void TclThreadManager::update(const Clock& time)
+    {
+        // Get the bundle of the main interpreter (0)
+        TclInterpreterBundle* bundle = this->getInterpreterBundle(0);
+        if (bundle)
+        {
+            // Unlock the mutex to allow other threads accessing the main interpreter
+            bundle->lock_->unlock();
+
+            // Lock the main interpreter mutex once to synchronize with threads that want to query the main interpreter
+            {
+                boost::unique_lock<boost::mutex> lock(*this->mainInterpreterMutex_);
+            }
+
+            // Lock the mutex again to gain exclusive access to the interpreter for the rest of the mainloop
+            bundle->lock_->lock();
+
+            // Execute commands in the queues of the threaded interpreters
+            {
+                boost::shared_lock<boost::shared_mutex> lock(*this->interpreterBundlesMutex_);
+                for (std::map<unsigned int, TclInterpreterBundle*>::const_iterator it = this->interpreterBundles_.begin(); it != this->interpreterBundles_.end(); ++it)
+                {
+                    if (it->first == 0)
+                        continue; // We'll handle the default interpreter later (and without threads of course)
+
+                    TclInterpreterBundle* bundle = it->second;
+                    if (!bundle->queue_.empty())
+                    {
+                        // There are commands in the queue
+                        try
+                        {
+                            if (!bundle->lock_->owns_lock() && bundle->lock_->try_lock())
+                            {
+                                // We sucessfully obtained a lock for the interpreter
+                                std::string command;
+                                if (bundle->queue_.try_pop_front(&command))
+                                {
+                                    // Start a thread to execute the command
+                                    boost::thread(boost::bind(&tclThread, bundle, command));
+                                }
+                                else
+                                {
+                                    // Somehow the queue become empty (maybe multiple consumers) - unlock the mutex
+                                    bundle->lock_->unlock();
+                                }
+                            }
+                        }
+                        catch (...)
+                        {
+                            // A lock error occurred - this is possible if the lock gets locked between !bundle->lock_->owns_lock() and bundle->lock_->try_lock()
+                            // This isn't too bad, just continue
+                        }
+                    }
+                }
+            }
+
+            // Execute commands in the message queue
+            if (!this->messageQueue_->empty())
+            {
+                std::string command;
+                while (true)
+                {
+                    // Pop the front value from the list (break the loop if there are no elements in the list)
+                    if (!this->messageQueue_->try_pop_front(&command))
+                        break;
+
+                    // Execute the command
+                    CommandExecutor::execute(command, false);
+                }
+            }
+
+            // Execute commands in the queue of the main interpreter
+            if (!bundle->queue_.empty())
+            {
+                // Calculate the time we have until we reach the maximal cpu usage
+                unsigned long maxtime = (unsigned long)(time.getDeltaTime() * 1000000 * TCLTHREADMANAGER_MAX_CPU_USAGE);
+
+                Ogre::Timer timer;
+                std::string command;
+
+                while (timer.getMicroseconds() < maxtime)
+                {
+                    // Pop the front value from the list (break the loop if there are no elements in the list)
+                    if (!bundle->queue_.try_pop_front(&command))
+                        break;
+
+                    // Execute the command
+                    CommandExecutor::execute(command, false);
+                }
+            }
+        }
+    }
+
+    /**
+        @brief Creates a new Tcl-interpreter.
+    */
+    unsigned int TclThreadManager::create()
+    {
+        TclThreadManager::getInstance().numInterpreterBundles_++;
+        TclThreadManager::createWithId(TclThreadManager::getInstance().numInterpreterBundles_);
+        COUT(0) << "Created new Tcl-interpreter with ID " << TclThreadManager::getInstance().numInterpreterBundles_ << std::endl;
+        return TclThreadManager::getInstance().numInterpreterBundles_;
+    }
+
+    /**
+        @brief Creates a new Tcl-interpreter with a given id.
+
+        Use with caution - if the id collides with an already existing interpreter, this call will fail.
+        This will also be a problem, if the auto-numbered interpreters (by using create()) reach an id
+        which was previously used in this function. Use high numbers to be safe.
+    */
+    Tcl::interpreter* TclThreadManager::createWithId(unsigned int id)
+    {
+        TclInterpreterBundle* newbundle = new TclInterpreterBundle();
+        newbundle->id_ = id;
+        newbundle->interpreter_ = TclBind::createTclInterpreter();
+
+        TclThreadManager::initialize(newbundle);
+
+        {
+            // Add the new bundle to the map
+            boost::unique_lock<boost::shared_mutex> lock(*TclThreadManager::getInstance().interpreterBundlesMutex_);
+            TclThreadManager::getInstance().interpreterBundles_[id] = newbundle;
+        }
+
+        return newbundle->interpreter_;
+    }
+
+    void TclThreadManager::initialize(TclInterpreterBundle* bundle)
+    {
+        std::string id_string = getConvertedValue<unsigned int, std::string>(bundle->id_);
+
+        // Initialize the new interpreter
+        try
+        {
+            // Define the functions which are implemented in C++
+            bundle->interpreter_->def("::orxonox::execute",      TclThreadManager::tcl_execute,      Tcl::variadic());
+            bundle->interpreter_->def("::orxonox::crossexecute", TclThreadManager::tcl_crossexecute, Tcl::variadic());
+            bundle->interpreter_->def("::orxonox::query",        TclThreadManager::tcl_query,        Tcl::variadic());
+            bundle->interpreter_->def("::orxonox::crossquery",   TclThreadManager::tcl_crossquery,   Tcl::variadic());
+            bundle->interpreter_->def("::orxonox::running",      TclThreadManager::tcl_running);
+
+            // Create threadspecific shortcuts for the functions above
+            bundle->interpreter_->def("execute",      TclThreadManager::tcl_execute,      Tcl::variadic());
+            bundle->interpreter_->def("crossexecute", TclThreadManager::tcl_crossexecute, Tcl::variadic());
+            bundle->interpreter_->eval("proc query      {args}    { ::orxonox::query " + id_string + " $args }");
+            bundle->interpreter_->eval("proc crossquery {id args} { ::orxonox::crossquery " + id_string + " $id $args }");
+            bundle->interpreter_->eval("proc running    {}        { return [::orxonox::running " + id_string + "] }");
+
+            // Define a variable containing the thread id
+            bundle->interpreter_->eval("set id " + id_string);
+
+            // Use our own exit function to avoid shutting down the whole program instead of just the interpreter
+            bundle->interpreter_->eval("rename exit ::tcl::exit");
+            bundle->interpreter_->eval("proc exit {} { execute TclThreadManager destroy " + id_string + " }");
+
+            // Redefine some native functions
+            bundle->interpreter_->eval("rename while ::tcl::while");
+            bundle->interpreter_->eval("rename ::orxonox::while while");
+            bundle->interpreter_->eval("rename for ::tcl::for");
+            bundle->interpreter_->eval("rename ::orxonox::for for");
+        }
+        catch (const Tcl::tcl_error& e)
+        {   bundle->interpreter_ = 0; COUT(1) << "Tcl error while creating Tcl-interpreter (" << id_string << "): " << e.what() << std::endl;   }
+        catch (const std::exception& e)
+        {   bundle->interpreter_ = 0; COUT(1) << "Error while creating Tcl-interpreter (" << id_string << "): " << e.what() << std::endl;   }
+        catch (...)
+        {   bundle->interpreter_ = 0; COUT(1) << "An error occurred while creating a new Tcl-interpreter (" << id_string << ")" << std::endl;   }
+    }
+
+    /**
+        @brief Stops and destroys a given Tcl-interpreter
+    */
+    void TclThreadManager::destroy(unsigned int id)
+    {
+        // TODO
+        // Not yet implemented
+        TclInterpreterBundle* bundle = TclThreadManager::getInstance().getInterpreterBundle(id);
+        if (bundle)
+        {
+            bundle->bRunning_ = false;
+        }
+    }
+
+    /**
+        @brief Sends a command to the queue of a given Tcl-interpreter
+        @param id The id of the target interpreter
+        @param command The command to be sent
+    */
+    void TclThreadManager::execute(unsigned int target_id, const std::string& command)
+    {
+        TclThreadManager::getInstance()._execute(target_id, command);
+    }
+
+    /**
+        @brief This function can be called from Tcl to execute a console command.
+
+        Commands which shall be executed are put into a queue and processed as soon as the
+        main thread feels ready to do so. The queue may also be full which results in a temporary
+        suspension of the calling thread until the queue gets ready again.
+    */
+    void TclThreadManager::tcl_execute(const Tcl::object& args)
+    {
+        TclThreadManager::getInstance()._execute(0, stripEnclosingBraces(args.get()));
+    }
+
+    /**
+        @brief This function can be called from Tcl to send a command to the queue of any interpreter.
+        @param target_id The id of the target thread
+    */
+    void TclThreadManager::tcl_crossexecute(int target_id, const Tcl::object& args)
+    {
+        TclThreadManager::getInstance()._execute(static_cast<unsigned int>(target_id), stripEnclosingBraces(args.get()));
+    }
+
+    /**
+        @brief Sends a command to the queue of a given Tcl-interpreter
+        @param id The id of the target interpreter
+        @param command The command to be sent
+    */
+    void TclThreadManager::_execute(unsigned int target_id, const std::string& command)
+    {
+        TclInterpreterBundle* bundle = this->getInterpreterBundle(target_id);
+        if (bundle)
+            bundle->queue_.push_back(command);
+    }
+
+
+    /**
+        @brief Sends a query to a given Tcl-interpreter and waits for the result
+        @param id The id of the target interpreter
+        @param command The command to be sent
+        @return The result of the command
+    */
+    std::string TclThreadManager::query(unsigned int target_id, const std::string& command)
+    {
+        return TclThreadManager::getInstance()._query(0, target_id, command);
+    }
+
+    /**
+        @brief This function can be called from Tcl to send a query to the main thread.
+        @param source_id The id of the calling thread
+
+        A query waits for the result of the command. This means, the calling thread will be blocked until
+        the main thread answers the query. In return, the main thread sends the result of the console
+        command back to Tcl.
+    */
+    std::string TclThreadManager::tcl_query(int source_id, const Tcl::object& args)
+    {
+        return TclThreadManager::getInstance()._query(static_cast<unsigned int>(source_id), 0, stripEnclosingBraces(args.get()), true);
+    }
+
+    /**
+        @brief This function can be called from Tcl to send a query to another thread.
+        @param source_id The id of the calling thread
+        @param target_id The id of the target thread
+    */
+    std::string TclThreadManager::tcl_crossquery(int source_id, int target_id, const Tcl::object& args)
+    {
+        return TclThreadManager::getInstance()._query(static_cast<unsigned int>(source_id), static_cast<unsigned int>(target_id), stripEnclosingBraces(args.get()));
+    }
+
+    /**
+        @brief This function performs a query to any Tcl interpreter
+        @param source_id The id of the calling thread
+        @param target_id The id of the target thread
+        @param command The command to send as a query
+        @param bUseCommandExecutor Only used if the target_id is 0 (which references the main interpreter). In this case it means if the command should be passed to the CommandExecutor (true) or to the main Tcl interpreter (false). This is true when called by tcl_query and false when called by tcl_crossquery.
+    */
+    std::string TclThreadManager::_query(unsigned int source_id, unsigned int target_id, const std::string& command, bool bUseCommandExecutor)
+    {
+        TclInterpreterBundle* source_bundle = this->getInterpreterBundle(source_id);
+        TclInterpreterBundle* target_bundle = this->getInterpreterBundle(target_id);
+        std::string output;
+
+        if (source_bundle && target_bundle)
+        {
+            // At this point we assume the mutex of source_bundle to be locked (because it's executing this query right now an waits for the return value)
+            // We can safely use it's querier list (because there's no other place in the code using the list except this query - and the interpreter can't start more than one query)
+
+            if ((source_bundle->id_ == target_bundle->id_) || source_bundle->queriers_.is_in(target_bundle->id_))
+            {
+                // This query would lead to a deadlock - return with an error
+                TclThreadManager::error("Error: Circular query (" + this->dumpList(source_bundle->queriers_.getList()) + " " + getConvertedValue<unsigned int, std::string>(source_bundle->id_) \
+                            + " -> " + getConvertedValue<unsigned int, std::string>(target_bundle->id_) \
+                            + "), couldn't query Tcl-interpreter with ID " + getConvertedValue<unsigned int, std::string>(target_bundle->id_) \
+                            + " from other interpreter with ID " + getConvertedValue<unsigned int, std::string>(source_bundle->id_) + ".");
+            }
+            else
+            {
+                boost::unique_lock<boost::mutex> lock(target_bundle->mutex_, boost::try_to_lock);
+                boost::unique_lock<boost::mutex> mainlock(*this->mainInterpreterMutex_, boost::defer_lock);
+
+                if (!lock.owns_lock() && source_bundle->id_ != 0)
+                {
+                    // We couldn't obtain the try_lock immediately and we're not the main interpreter - wait until the lock becomes possible (note: the main interpreter won't wait and instead returns an error - see below)
+                    if (target_bundle->id_ == 0)
+                    {
+                        // We're querying the main interpreter - use the main interpreter mutex to synchronize
+                        mainlock.lock();
+                        lock.lock();
+                    }
+                    else
+                    {
+                        // We're querying a threaded interpreter - no synchronization needed
+                        lock.lock();
+                    }
+                }
+
+                if (lock.owns_lock())
+                {
+                    // Now the mutex of target_bundle is also locked an we can update the querier list
+                    target_bundle->queriers_.insert(target_bundle->queriers_.getList().begin(), source_bundle->queriers_.getList().begin(), source_bundle->queriers_.getList().end());
+                    target_bundle->queriers_.push_back(source_bundle->id_);
+
+                    // Perform the query (note: this happens in the main thread because we need the returnvalue)
+                    if (target_bundle->id_ == 0 && bUseCommandExecutor)
+                    {
+                        // It's a query to the CommandExecutor
+                        TclThreadManager::debug("TclThread_query -> CE: " + command);
+                        if (!CommandExecutor::execute(command, false))
+                            TclThreadManager::error("Error: Can't execute command \"" + command + "\"!");
+
+                        if (CommandExecutor::getLastEvaluation().hasReturnvalue())
+                            output = CommandExecutor::getLastEvaluation().getReturnvalue().getString();
+                    }
+                    else
+                    {
+                        // It's a query to a Tcl interpreter
+                        TclThreadManager::debug("TclThread_query: " + command);
+
+                        output = TclThreadManager::eval(target_bundle, command, "query");
+                    }
+
+                    // Clear the queriers list of the target
+                    target_bundle->queriers_.clear();
+
+                    // Unlock the mutex of the target_bundle
+                    lock.unlock();
+
+                    // Finally unlock the main interpreter lock if necessary
+                    if (mainlock.owns_lock())
+                        mainlock.unlock();
+                }
+                else
+                {
+                    // This happens if the main thread tries to query a busy interpreter
+                    // To avoid a lock of the main thread, we simply don't proceed with the query in this case
+                    TclThreadManager::error("Error: Couldn't query Tcl-interpreter with ID " + getConvertedValue<unsigned int, std::string>(target_bundle->id_) + ", interpreter is busy right now.");
+                }
+            }
+
+        }
+
+        return output;
+    }
+
+    /**
+        @brief Creates a non-interactive Tcl-interpreter which executes a file.
+    */
+    void TclThreadManager::source(const std::string& file)
+    {
+        boost::thread(boost::bind(&sourceThread, file));
+    }
+
+    /**
+        @brief This function can be called from Tcl to ask if the thread is still suposed to be running.
+        @param id The id of the thread in question
+    */
+    bool TclThreadManager::tcl_running(int id)
+    {
+        TclInterpreterBundle* bundle = TclThreadManager::getInstance().getInterpreterBundle(static_cast<unsigned int>(id));
+        if (bundle)
+            return bundle->bRunning_;
+        else
+            return false;
+    }
+
+    /**
+        @brief Returns the interpreter bundle with the given id.
+        @param id The id of the interpreter
+        @return The interpreter or 0 if the id doesn't exist
+    */
+    TclInterpreterBundle* TclThreadManager::getInterpreterBundle(unsigned int id)
+    {
+        boost::shared_lock<boost::shared_mutex> lock(*this->interpreterBundlesMutex_);
+
+        std::map<unsigned int, TclInterpreterBundle*>::const_iterator it = this->interpreterBundles_.find(id);
+        if (it != this->interpreterBundles_.end())
+        {
+            return it->second;
+        }
+        else
+        {
+            TclThreadManager::error("Error: No Tcl-interpreter with ID " + getConvertedValue<unsigned int, std::string>(id) + " existing.");
+            return 0;
+        }
+    }
+
+    /**
+        @brief Returns a string containing all elements of a unsigned-integer-list separated by spaces.
+    */
+    std::string TclThreadManager::dumpList(const std::list<unsigned int>& list)
+    {
+        std::string output = "";
+        for (std::list<unsigned int>::const_iterator it = list.begin(); it != list.end(); ++it)
+        {
+            if (it != list.begin())
+                output += " ";
+
+            output += getConvertedValue<unsigned int, std::string>(*it);
+        }
+        return output;
+    }
+
+    /**
+        @brief Returns a list with the numbers of all existing Tcl-interpreters.
+
+        This function is used by the auto completion function.
+    */
+    std::list<unsigned int> TclThreadManager::getThreadList() const
+    {
+        boost::shared_lock<boost::shared_mutex> lock(*this->interpreterBundlesMutex_);
+
+        std::list<unsigned int> threads;
+        for (std::map<unsigned int, TclInterpreterBundle*>::const_iterator it = this->interpreterBundles_.begin(); it != this->interpreterBundles_.end(); ++it)
+            if (it->first > 0 && it->first <= this->numInterpreterBundles_) // only list autonumbered interpreters (created with create()) - exclude the default interpreter 0 and all manually numbered interpreters)
+                threads.push_back(it->first);
+        return threads;
+    }
+
+    /**
+        @brief A helper function to print errors in a thread safe manner.
+    */
+    void TclThreadManager::error(const std::string& error)
+    {
+        TclThreadManager::getInstance().messageQueue_->push_back("error " + error);
+    }
+
+    /**
+        @brief A helper function to print debug information in a thread safe manner.
+    */
+    void TclThreadManager::debug(const std::string& error)
+    {
+        TclThreadManager::getInstance().messageQueue_->push_back("debug " + error);
+    }
+
+    /**
+        @brief Evaluates a Tcl command without throwing exceptions (which may rise problems on certain machines).
+        @return The Tcl return value
+
+        Errors are reported through the @ref error function.
+    */
+    std::string TclThreadManager::eval(TclInterpreterBundle* bundle, const std::string& command, const std::string& action)
+    {
+        Tcl_Interp* interpreter = bundle->interpreter_->get();
+        int cc = Tcl_Eval(interpreter, command.c_str());
+
+        Tcl::details::result result(interpreter);
+
+        if (cc != TCL_OK)
+        {
+            TclThreadManager::error("Tcl error (" + action + ", ID " + getConvertedValue<unsigned int, std::string>(bundle->id_) + "): " + static_cast<std::string>(result));
+            return "";
+        }
+        else
+        {
+            return result;
+        }
+    }
+
+    ////////////////
+    // The Thread //
+    ////////////////
+
+    /**
+        @brief The main function of the thread. Executes a Tcl command.
+        @param bundle The interpreter bundle containing all necessary variables
+        @param command the Command to execute
+    */
+    void tclThread(TclInterpreterBundle* bundle, std::string command)
+    {
+        TclThreadManager::debug("TclThread_execute: " + command);
+
+        TclThreadManager::eval(bundle, command, "execute");
+
+        bundle->lock_->unlock();
+    }
+
+    /**
+        @brief The main function of a non-interactive source thread. Executes the file.
+        @param file The name of the file that should be executed by the non-interactive interpreter.
+    */
+    void sourceThread(std::string file)
+    {
+        TclThreadManager::debug("TclThread_source: " + file);
+
+        // Prepare the command-line arguments
+        const int argc = 2;
+        char* argv[argc];
+        argv[0] = "tclthread";
+        argv[1] = const_cast<char*>(file.c_str());
+
+        // Start the Tcl-command Tcl_Main with the Tcl_OrxonoxAppInit hook
+        Tcl_Main(argc, argv, Tcl_OrxonoxAppInit);
+
+//        Tcl::object object(file);
+//        int cc = Tcl_FSEvalFile(bundle->interpreter_->get(), object.get_object());
+//        Tcl::details::result result(bundle->interpreter_->get());
+//        if (cc != TCL_OK)
+//            TclThreadManager::error("Tcl error (source, ID " + getConvertedValue<unsigned int, std::string>(bundle->id_) + "): " + static_cast<std::string>(result));
+//
+//        // Unlock the mutex
+//        bundle->lock_->unlock();
+    }
+
+    /**
+        @brief A tcl-init hook to inject the non-interactive Tcl-interpreter into the TclThreadManager.
+    */
+    int Tcl_OrxonoxAppInit(Tcl_Interp* interp)
+    {
+        // Create a new interpreter bundle
+        unsigned int id = TclThreadManager::create();
+        TclInterpreterBundle* bundle = TclThreadManager::getInstance().getInterpreterBundle(id);
+
+        // Replace the default interpreter in the bundle with the non-interactive one (passed as an argument to this function)
+        if (bundle->interpreter_)
+            delete bundle->interpreter_;
+        bundle->interpreter_ = new Tcl::interpreter(interp, true);
+
+        // Initialize the non-interactive interpreter (like in @ref TclBind::createTclInterpreter but exception safe)
+        std::string libpath = TclBind::getTclLibraryPath();
+        if (libpath != "")
+            TclThreadManager::eval(bundle, "set tcl_library \"" + libpath + "\"", "source");
+        int cc = Tcl_Init(interp);
+        TclThreadManager::eval(bundle, "source \"" + TclBind::getInstance().getTclDataPath() + "/init.tcl\"", "source");
+
+        // Initialize the non-interactive interpreter also with the thread-specific stuff
+        TclThreadManager::initialize(bundle);
+
+        // Lock the mutex (this will be locked until the thread finishes - no chance to interact with the interpreter)
+        bundle->lock_->lock();
+
+        // Return to Tcl_Main
+        if (!bundle->interpreter_)
+            return TCL_ERROR;
+        else
+            return cc;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/TclThreadManager.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/TclThreadManager.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/TclThreadManager.h	(revision 5712)
@@ -0,0 +1,102 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _TclThreadManager_H__
+#define _TclThreadManager_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <list>
+#include <map>
+#include <string>
+
+#include "util/Singleton.h"
+#include "OrxonoxClass.h"
+
+struct Tcl_Interp;
+
+namespace orxonox
+{
+    class _CoreExport TclThreadManager : public Singleton<TclThreadManager>, public OrxonoxClass
+    {
+        friend class Singleton<TclThreadManager>;
+        friend class TclBind;
+        friend _CoreExport void tclThread(TclInterpreterBundle* bundle, std::string command);
+        friend _CoreExport void sourceThread(std::string file);
+        friend _CoreExport int Tcl_OrxonoxAppInit(Tcl_Interp* interp);
+
+        public:
+            TclThreadManager(Tcl::interpreter* interpreter);
+            virtual ~TclThreadManager();
+
+            static unsigned int      create();
+            static Tcl::interpreter* createWithId(unsigned int id);
+            static void              destroy(unsigned int id);
+            static void              execute(unsigned int target_id, const std::string& command);
+            static std::string       query(unsigned int target_id, const std::string& command);
+            static void              source(const std::string& file);
+
+            static void error(const std::string& error);
+            static void debug(const std::string& error);
+
+            void update(const Clock& time);
+
+            std::list<unsigned int> getThreadList() const;
+
+        private:
+            static void tcl_execute(const Tcl::object& args);
+            static void tcl_crossexecute(int target_id, const Tcl::object& args);
+            static std::string tcl_query(int source_id, const Tcl::object& args);
+            static std::string tcl_crossquery(int source_id, int target_id, const Tcl::object& args);
+            static bool tcl_running(int id);
+
+            void _execute(unsigned int target_id, const std::string& command);
+            std::string _query(unsigned int source_id, unsigned int target_id, const std::string& command, bool bUseCommandExecutor = false);
+
+            TclInterpreterBundle* getInterpreterBundle(unsigned int id);
+            std::string dumpList(const std::list<unsigned int>& list);
+
+            static void initialize(TclInterpreterBundle* bundle);
+            static std::string eval(TclInterpreterBundle* bundle, const std::string& command, const std::string& action);
+
+            static TclThreadManager* singletonPtr_s;                            ///< Singleton pointer
+
+            unsigned int numInterpreterBundles_;                                ///< Number of created Tcl-interpreters (only used for auto-numbered interpreters, not affected by @ref createWithId)
+            std::map<unsigned int, TclInterpreterBundle*> interpreterBundles_;  ///< A map containing all Tcl-interpreters
+            boost::shared_mutex* interpreterBundlesMutex_;                      ///< A mutex used to synchronize threads when accessing @ref interpreterBundles_
+            TclThreadList<std::string>* messageQueue_;                          ///< A queue to pass messages from Tcl-threads to the main thread
+            boost::mutex* mainInterpreterMutex_;                                ///< A mutex to synchronize queries to the main interpreter
+    };
+
+    _CoreExport void tclThread(TclInterpreterBundle* bundle, std::string command);
+    _CoreExport void sourceThread(std::string file);
+    _CoreExport int Tcl_OrxonoxAppInit(Tcl_Interp* interp);
+}
+
+#endif /* _TclThreadManager_H__ */
Index: /code/branches/libraries2/src/libraries/core/Template.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Template.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Template.cc	(revision 5712)
@@ -0,0 +1,181 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Template.h"
+
+#include <tinyxml/tinyxml.h>
+#include <tinyxml/ticpp.h>
+
+#include "util/Debug.h"
+#include "core/CoreIncludes.h"
+#include "core/XMLPort.h"
+
+namespace orxonox
+{
+    CreateFactory(Template);
+
+    Template::Template(BaseObject* creator) : BaseObject(creator)
+    {
+        this->xmlelement_ = new TiXmlElement("");
+
+        RegisterObject(Template);
+
+        this->bIsLink_ = false;
+        this->bLoadDefaults_ = true;
+        this->bIsReturningXMLElement_ = false;
+        this->baseclassIdentifier_ = 0;
+    }
+
+    Template::~Template()
+    {
+        Template::getTemplateMap().erase(this->getName());
+        delete this->xmlelement_;
+    }
+
+    void Template::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(Template, XMLPort, xmlelement, mode);
+
+        XMLPortParam(Template, "link",      setLink,         getLink,         xmlelement, mode);
+        XMLPortParam(Template, "baseclass", setBaseclass,    getBaseclass,    xmlelement, mode);
+        XMLPortParam(Template, "defaults",  setLoadDefaults, getLoadDefaults, xmlelement, mode).defaultValues(true);
+
+        Element* element = xmlelement.FirstChildElement(false);
+        if (element)
+        {
+            TiXmlElement* tixmlelement = static_cast<TiXmlElement*>(element->GetTiXmlPointer());
+            if (tixmlelement)
+                this->setXMLElement(*tixmlelement);
+        }
+    }
+
+    void Template::changedName()
+    {
+        SUPER(Template, changedName);
+
+        if (this->getName() != "")
+        {
+            std::map<std::string, Template*>::iterator it;
+            it = Template::getTemplateMap().find(this->getOldName());
+            if (it != Template::getTemplateMap().end())
+                Template::getTemplateMap().erase(it);
+
+            it = Template::getTemplateMap().find(this->getName());
+            if (it != Template::getTemplateMap().end())
+                COUT(2) << "Warning: Template with name \"" << this->getName() << "\" already exists." << std::endl;
+            else
+                Template::getTemplateMap()[this->getName()] = this;
+        }
+    }
+
+    void Template::setXMLElement(const TiXmlElement& xmlelement)
+    {
+        *this->xmlelement_ = xmlelement;
+    }
+
+    const TiXmlElement& Template::getXMLElement() const
+    {
+        if (this->bIsLink_)
+        {
+            Template* temp = Template::getTemplate(this->link_);
+            if (temp)
+            {
+                if (!temp->bIsReturningXMLElement_)
+                {
+                    this->bIsReturningXMLElement_ = true;
+                    const TiXmlElement& element = temp->getXMLElement();
+                    this->bIsReturningXMLElement_ = false;
+                    return element;
+                }
+                else
+                {
+                    COUT(2) << "Warning: Linking from " << this->getName() << " to " << this->link_ << " leads to an infinite loop. Returning own element." << std::endl;
+                }
+            }
+            else
+            {
+                COUT(2) << "Warning: " << this->link_ << " is not an existing Template name. Returning own element." << std::endl;
+            }
+        }
+
+        return *this->xmlelement_;
+    }
+
+    void Template::setBaseclass(const std::string& baseclass)
+    {
+        this->baseclassIdentifier_ = ClassByString(baseclass);
+        if (this->baseclassIdentifier_)
+            this->baseclass_ = baseclass;
+    }
+
+    void Template::applyOn(BaseObject* object)
+    {
+        if (this->baseclassIdentifier_)
+        {
+            if (!object->isA(this->baseclassIdentifier_))
+            {
+                COUT(1) << "Error: Can't apply template (name: " << this->getName() << "), object (name: " << object->getName() << ", class: " << object->getIdentifier()->getName() << ") is not a " << this->baseclassIdentifier_->getName() << std::endl;
+                return;
+            }
+        }
+
+        COUT(4) << object->getLoaderIndentation() << " aplying Template \"" << this->getName() << "\"..." << std::endl;
+
+        Element temp = &const_cast<TiXmlElement&>(this->getXMLElement());
+
+        if (this->bLoadDefaults_)
+            object->XMLPort(temp, XMLPort::LoadObject);
+        else
+            object->XMLPort(temp, XMLPort::ExpandObject);
+    }
+
+    std::map<std::string, Template*>& Template::getTemplateMap()
+    {
+        static std::map<std::string, Template*> templateMap;
+        return templateMap;
+    }
+
+    Template* Template::getTemplate(const std::string& name)
+    {
+        std::map<std::string, Template*>::iterator it = Template::getTemplateMap().find(name);
+        if (it != Template::getTemplateMap().end())
+            return it->second;
+        else
+        {
+            COUT(2) << "Warning: Template with name " << name << " doesn't exist." << std::endl;
+            return 0;
+        }
+    }
+
+    void Template::apply(const std::string& name, BaseObject* object)
+    {
+        std::map<std::string, Template*>::iterator it = Template::getTemplateMap().find(name);
+        if (it != Template::getTemplateMap().end())
+            it->second->applyOn(object);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Template.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Template.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Template.h	(revision 5712)
@@ -0,0 +1,85 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Template_H__
+#define _Template_H__
+
+#include "CorePrereqs.h"
+
+#include <map>
+#include <string>
+#include "BaseObject.h"
+
+namespace orxonox
+{
+    class _CoreExport Template : public BaseObject
+    {
+        public:
+            Template(BaseObject* creator);
+            virtual ~Template();
+
+            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+            virtual void changedName();
+
+            inline void setLink(const std::string& link)
+                { this->link_ = link; this->bIsLink_ = (link != ""); }
+            inline const std::string& getLink() const
+                { return this->link_; }
+
+            inline void setLoadDefaults(bool bLoadDefaults)
+                { this->bLoadDefaults_ = bLoadDefaults; }
+            inline bool getLoadDefaults() const
+                { return this->bLoadDefaults_; }
+
+            void setXMLElement(const TiXmlElement& xmlelement);
+            const TiXmlElement& getXMLElement() const;
+
+            void setBaseclass(const std::string& baseclass);
+            inline const std::string& getBaseclass() const
+                { return this->baseclass_; }
+            inline Identifier* getBaseclassIdentifier() const
+                { return this->baseclassIdentifier_; }
+
+            void applyOn(BaseObject* object);
+
+            static std::map<std::string, Template*>& getTemplateMap();
+            static Template* getTemplate(const std::string& name);
+            static void apply(const std::string& name, BaseObject* object);
+
+        private:
+            TiXmlElement* xmlelement_;
+            std::string link_;
+            std::string baseclass_;
+            Identifier* baseclassIdentifier_;
+            bool bIsLink_;
+            bool bLoadDefaults_;
+            mutable bool bIsReturningXMLElement_;
+    };
+}
+
+#endif /* _Template_H__ */
Index: /code/branches/libraries2/src/libraries/core/Thread.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/Thread.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Thread.cc	(revision 5712)
@@ -0,0 +1,129 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Oliver Scheuss
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Thread.h"
+
+#include <cassert>
+#include <boost/thread/thread.hpp>
+#include <boost/bind.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/thread/thread_time.hpp>
+
+#include "util/Sleep.h"
+#include "Executor.h"
+
+namespace orxonox
+{
+    boost::posix_time::millisec THREAD_WAIT_BEFORE_DETACH(1000);
+    
+    
+    Thread::Thread():
+        executor_(0),
+        isWorking_(false),
+        stopThread_(false)
+    {
+        this->executorMutex_ = new boost::mutex;
+        this->isWorkingMutex_ = new boost::mutex;
+        this->stopThreadMutex_ = new boost::mutex;
+        this->workerThread_ = new boost::thread( boost::bind(&Thread::threadLoop, this) );
+    }
+    
+    Thread::~Thread()
+    {
+        this->stopThreadMutex_->lock();
+        this->stopThread_ = true;
+        this->stopThreadMutex_->unlock();
+        if( !this->workerThread_->timed_join( THREAD_WAIT_BEFORE_DETACH ) )
+            assert(0); // this should not happen
+        delete this->workerThread_;
+        delete this->executorMutex_;
+        delete this->stopThreadMutex_;
+        delete this->isWorkingMutex_;
+    }
+    
+    bool Thread::isWorking()
+    {
+      this->isWorkingMutex_->lock();
+      bool isWorking = this->isWorking_;
+      this->isWorkingMutex_->unlock();
+      return isWorking;
+    }
+    
+    bool Thread::evaluateExecutor( Executor* executor )
+    {
+        this->isWorkingMutex_->lock();
+        this->isWorking_=true;
+        this->isWorkingMutex_->unlock();
+        this->executorMutex_->lock();
+        this->executor_ = executor;
+        this->executorMutex_->unlock();
+        return true;
+    }
+    
+    void Thread::threadLoop()
+    {
+        bool stopThread = false;
+        while( !stopThread )
+        {
+            //this->executorMutex_->lock();
+            Executor* executor = this->executor_;
+            //this->executorMutex_->unlock();
+            if( executor )
+            {
+                (*executor)();
+                this->executorMutex_->lock();
+                delete this->executor_;
+                this->executor_ = 0;
+                this->executorMutex_->unlock();
+                this->isWorkingMutex_->lock();
+                this->isWorking_=false;
+                this->isWorkingMutex_->unlock();
+            }
+            else
+            {
+                this->workerThread_->yield();
+            }
+            //this->stopThreadMutex_->lock();
+            stopThread = this->stopThread_;
+            //this->stopThreadMutex_->unlock();
+        }
+    }
+    
+    void Thread::waitUntilFinished()
+    {
+        bool stillWorking = true;
+        while( stillWorking )
+        {
+            this->isWorkingMutex_->lock();
+            stillWorking = this->isWorking_;
+            this->isWorkingMutex_->unlock();
+            if( stillWorking )
+                msleep( 1 );
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/Thread.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/Thread.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/Thread.h	(revision 5712)
@@ -0,0 +1,64 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Oliver Scheuss
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Thread_H__
+#define _Thread_H__
+
+#include "CorePrereqs.h"
+
+namespace boost{
+  class recursive_mutex;
+}
+
+ namespace orxonox
+{
+    class _CoreExport Thread
+    {
+    public:
+        Thread();
+        virtual ~Thread();
+
+        bool isWorking();
+        void waitUntilFinished();
+        bool evaluateExecutor( Executor* executor );
+
+    private:
+        void            threadLoop();
+        
+        Executor*       executor_;
+        bool            isWorking_;
+        bool            stopThread_;
+        boost::thread*  workerThread_;
+        boost::mutex*   executorMutex_;
+        boost::mutex*     isWorkingMutex_;
+        boost::mutex*   stopThreadMutex_;
+    };
+
+ }
+
+#endif /* _Thread_H__ */
Index: /code/branches/libraries2/src/libraries/core/ThreadPool.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/ThreadPool.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ThreadPool.cc	(revision 5712)
@@ -0,0 +1,115 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Oliver Scheuss
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "ThreadPool.h"
+#include "Thread.h"
+#include <cassert>
+
+namespace orxonox
+{
+
+    ThreadPool::ThreadPool()
+    {
+    }
+    
+    ThreadPool::~ThreadPool()
+    {
+        unsigned int a = this->setNrOfThreads(0);
+        assert(a == 0);
+    }
+    
+    void ThreadPool::addThreads( unsigned int nr )
+    {
+        for( unsigned int i=0; i<nr; i++ )
+            this->threadPool_.push_back(new Thread());
+    }
+    unsigned int ThreadPool::removeThreads( unsigned int nr )
+    {
+        unsigned int i=0;
+        std::vector<Thread*>::iterator it;
+        for( it = this->threadPool_.begin(); it != threadPool_.end() && i<nr; )
+        {
+            if( ! (*it)->isWorking() )
+            {
+                Thread* temp = *it;
+                it=this->threadPool_.erase( it );
+                delete temp;
+                ++i;
+            }
+            else
+              ++it;
+        }
+        return i;
+    }
+    unsigned int ThreadPool::setNrOfThreads( unsigned int nr )
+    {
+        unsigned int currentsize = this->threadPool_.size();
+        if ( nr < currentsize )
+            return currentsize - removeThreads( currentsize - nr );
+        else if ( nr == currentsize )
+            return currentsize;
+        else
+        {
+            addThreads( nr - currentsize );
+            return nr;
+        }
+    }
+    
+    bool ThreadPool::passFunction( Executor* executor, bool addThread )
+    {
+        std::vector<Thread*>::iterator it;
+        for ( it=this->threadPool_.begin(); it!=this->threadPool_.end(); ++it )
+        {
+            if ( ! (*it)->isWorking() )
+            {
+                bool b = (*it)->evaluateExecutor( executor );
+                assert(b); // if b is false then there is some code error
+                return true;
+            }
+        }
+        if ( addThread )
+        {
+            addThreads( 1 );
+            bool b = this->threadPool_.back()->evaluateExecutor( executor ); // access the last element
+            assert(b);
+            return true;
+        }
+        else
+            return false;
+    }
+    
+    void ThreadPool::synchronise()
+    {
+        std::vector<Thread*>::iterator it;
+        for ( it=this->threadPool_.begin(); it!=this->threadPool_.end(); ++it )
+        {
+            (*it)->waitUntilFinished();
+        }
+    }
+
+}
Index: /code/branches/libraries2/src/libraries/core/ThreadPool.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ThreadPool.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ThreadPool.h	(revision 5712)
@@ -0,0 +1,57 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Oliver Scheuss
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _ThreadPool_H__
+#define _ThreadPool_H__
+
+#include "CorePrereqs.h"
+
+#include <vector>
+
+ namespace orxonox
+{
+    class _CoreExport ThreadPool
+    {
+    public:
+        ThreadPool();
+        virtual ~ThreadPool();
+        
+        void addThreads( unsigned int nr );
+        unsigned int removeThreads( unsigned int nr );
+        unsigned int setNrOfThreads( unsigned int nr );
+        
+        bool passFunction( Executor* executor, bool addThread=false );
+        void synchronise();
+        
+    private:
+        std::vector<Thread*> threadPool_;
+        
+    };
+}
+
+#endif /* _ThreadPool_H__ */
Index: /code/branches/libraries2/src/libraries/core/ToluaInterface.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/ToluaInterface.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/ToluaInterface.h	(revision 5712)
@@ -0,0 +1,45 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+    This is required because tolua would parse this macro in LuaState.h and fail
+*/
+
+#ifndef _ToluaInterface_H__
+#define _ToluaInterface_H__
+
+#include "CorePrereqs.h"
+#include <boost/preprocessor/cat.hpp>
+
+// Macro for declaring a tolua interface of a library/module
+#define DeclareToluaInterface(libraryName) \
+    static bool BOOST_PP_CAT(bDummy##libraryName, __LINE__) = orxonox::LuaState::addToluaInterface(&tolua_##libraryName##_open, #libraryName); \
+    static Loki::ScopeGuardImpl1<bool (*)(const std::string&), std::string> BOOST_PP_CAT(dummy##libraryName, __LINE__)(&orxonox::LuaState::removeToluaInterface, #libraryName)
+
+#endif /* _ToluaInterface_H__ */
Index: /code/branches/libraries2/src/libraries/core/WindowEventListener.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/WindowEventListener.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/WindowEventListener.cc	(revision 5712)
@@ -0,0 +1,64 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "WindowEventListener.h"
+#include "CoreIncludes.h"
+
+namespace orxonox
+{
+    unsigned int WindowEventListener::windowWidth_s  = 0;
+    unsigned int WindowEventListener::windowHeight_s = 0;
+
+    WindowEventListener::WindowEventListener()
+    {
+        RegisterRootObject(WindowEventListener);
+    }
+
+    //! Calls all registered objects
+    /*static*/ void WindowEventListener::moveWindow()
+    {
+        for (ObjectList<WindowEventListener>::iterator it = ObjectList<WindowEventListener>::begin(); it; ++it)
+            it->windowMoved();
+    }
+
+    //! Calls all registered objects and sets the static variables
+    /*static*/ void WindowEventListener::resizeWindow(unsigned int newWidth, unsigned int newHeight)
+    {
+        windowWidth_s = newWidth;
+        windowHeight_s = newHeight;
+        for (ObjectList<WindowEventListener>::iterator it = ObjectList<WindowEventListener>::begin(); it; ++it)
+            it->windowResized(newWidth, newHeight);
+    }
+
+    //! Calls all registered objects
+    /*static*/ void WindowEventListener::changeWindowFocus()
+    {
+        for (ObjectList<WindowEventListener>::iterator it = ObjectList<WindowEventListener>::begin(); it; ++it)
+            it->windowFocusChanged();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/WindowEventListener.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/WindowEventListener.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/WindowEventListener.h	(revision 5712)
@@ -0,0 +1,71 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _WindowEventListener_H__
+#define _WindowEventListener_H__
+
+#include "CorePrereqs.h"
+#include "OrxonoxClass.h"
+
+namespace orxonox
+{
+    //! Interface for receiving window events like resize, moved and focusChanged
+    class _CoreExport WindowEventListener : virtual public OrxonoxClass
+    {
+        friend class OgreWindowEventListener;
+
+        protected:
+            WindowEventListener();
+            virtual ~WindowEventListener() { }
+
+            //! Returns the current render window width
+            unsigned int getWindowWidth() const { return windowWidth_s; }
+            //! Returns the current render window height
+            unsigned int getWindowHeight() const { return windowHeight_s; }
+
+        private:
+            //! Window has been moved
+            virtual void windowMoved() { }
+
+            //! Window has resized
+            virtual void windowResized(unsigned int newWidth, unsigned int newHeight) { }
+
+            //! Window has lost/gained focus
+            virtual void windowFocusChanged() { }
+
+            static void moveWindow();
+            static void resizeWindow(unsigned int newWidth, unsigned int newHeight);
+            static void changeWindowFocus();
+
+            //! Static variable that holds the latest distributed information
+            static unsigned int windowWidth_s;
+            static unsigned int windowHeight_s;
+    };
+}
+
+#endif /* _WindowEventListener_H__ */
Index: /code/branches/libraries2/src/libraries/core/XMLFile.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/XMLFile.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/XMLFile.h	(revision 5712)
@@ -0,0 +1,69 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _XMLFile_H__
+#define _XMLFile_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include "ClassTreeMask.h"
+
+namespace orxonox
+{
+    class _CoreExport XMLFile
+    {
+        public:
+            XMLFile(const std::string& filename, const std::string& resourceGroup = "General")
+                : filename_(filename)
+                , group_(resourceGroup)
+                , bLuaSupport_(true)
+            { }
+            XMLFile(const ClassTreeMask& mask, const std::string& filename, const std::string& resourceGroup = "General")
+                : filename_(filename)
+                , group_(resourceGroup)
+                , mask_(mask)
+                , bLuaSupport_(true)
+            { }
+
+            void setLuaSupport(bool val) { bLuaSupport_ = val; }
+
+            const std::string& getFilename() const { return this->filename_; }
+            const std::string& getResourceGroup() const { return this->group_; }
+            const ClassTreeMask& getMask() const { return this->mask_; }
+            bool getLuaSupport() const { return this->bLuaSupport_; }
+
+        private:
+            std::string filename_;
+            std::string group_;
+            ClassTreeMask mask_;
+            bool bLuaSupport_; // Default is true
+    };
+}
+
+#endif /* _XMLFile_H__ */
Index: /code/branches/libraries2/src/libraries/core/XMLNameListener.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/XMLNameListener.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/XMLNameListener.cc	(revision 5712)
@@ -0,0 +1,38 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "XMLNameListener.h"
+#include "CoreIncludes.h"
+
+namespace orxonox
+{
+    XMLNameListener::XMLNameListener()
+    {
+        RegisterRootObject(XMLNameListener);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/XMLNameListener.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/XMLNameListener.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/XMLNameListener.h	(revision 5712)
@@ -0,0 +1,47 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _XMLNameListener_H__
+#define _XMLNameListener_H__
+
+#include "CorePrereqs.h"
+#include "OrxonoxClass.h"
+
+namespace orxonox
+{
+    class _CoreExport XMLNameListener : virtual public OrxonoxClass
+    {
+        public:
+            XMLNameListener();
+            virtual ~XMLNameListener() {}
+
+            virtual void loadedNewXMLName(BaseObject* object) = 0;
+    };
+}
+
+#endif /* _XMLNameListener_H__ */
Index: /code/branches/libraries2/src/libraries/core/XMLPort.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/XMLPort.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/XMLPort.cc	(revision 5712)
@@ -0,0 +1,43 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "XMLPort.h"
+
+#include "Loader.h"
+#include "Namespace.h"
+
+namespace orxonox
+{
+    // ################################
+    // ###  XMLPortObjectContainer  ###
+    // ################################
+    bool XMLPortObjectContainer::identifierIsIncludedInLoaderMask(const Identifier* identifier)
+    {
+        return ((!this->bApplyLoaderMask_) || identifier->isA(ClassIdentifier<Namespace>::getIdentifier()) || Loader::currentMask_s.isIncluded(identifier));
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/XMLPort.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/XMLPort.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/XMLPort.h	(revision 5712)
@@ -0,0 +1,692 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Declaration of the XMLPort helper classes and macros.
+
+    XMLPort is a virtual function of every BaseObject. Every object can change this function.
+    The XMLPort function gets called with an XMLElement, containing all attributes and
+    subclasses the object gets from the levelfile.
+
+    This file declares classes and macros to simplify XML-parsing.
+*/
+
+#ifndef _XMLPort_H__
+#define _XMLPort_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <string>
+#include <tinyxml/ticpp.h>
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/MultiType.h"
+#include "util/OrxAssert.h"
+#include "Factory.h"
+#include "Identifier.h"
+#include "Executor.h"
+#include "BaseObject.h"
+
+// ------------
+// XMLPortParam
+
+/**
+    @brief Declares an XML attribute with a name, which will be set through load- and savefunctions.
+    @param classname The name of the class owning this param
+    @param paramname The name of the attribute
+    @param loadfunction A function to set the param in the object with a given value (~a set-function)
+    @param savefunction A function to get the value of the param from the object (~a get-function)
+    @param xmlelement The XMLElement, you get this from the XMLPort function
+    @param mode The mode (load or save), you get this from the XMLPort function
+
+    In the XML file, a param or attribute will be set like this:
+    <classname paramname="value" />
+
+    The macro will then call loadfunction(value) to set the given value (or call savefunction() to
+    write an existing value to an XML file).
+*/
+#define XMLPortParam(classname, paramname, loadfunction, savefunction, xmlelement, mode) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
+    XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, classname, this, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode)
+
+/**
+    @brief Declares an XML attribute with a name, which will be set through a variable.
+    @param classname The name of the class owning this param
+    @param paramname The name of the attribute
+    @param variable Name of the variable used to save and load the value
+    @param xmlelement The XMLElement, you get this from the XMLPort function
+    @param mode The mode (load or save), you get this from the XMLPort function
+
+    In the XML file, a param or attribute will be set like this:
+    <classname paramname="value" />
+
+    The macro will then store "value" in the variable or read it when saving.
+*/
+#define XMLPortParamVariable(classname, paramname, variable, xmlelement, mode) \
+    XMLPortVariableHelperClass xmlcontainer##variable##dummy(static_cast<void*>(&variable)); \
+    static ExecutorMember<orxonox::XMLPortVariableHelperClass>* xmlcontainer##variable##loadexecutor = static_cast<ExecutorMember<orxonox::XMLPortVariableHelperClass>*>(orxonox::createExecutor(orxonox::createFunctor(orxonox::XMLPortVariableHelperClass::getLoader(variable)), std::string( #classname ) + "::" + #variable + "loader")); \
+    static ExecutorMember<orxonox::XMLPortVariableHelperClass>* xmlcontainer##variable##saveexecutor = static_cast<ExecutorMember<orxonox::XMLPortVariableHelperClass>*>(orxonox::createExecutor(orxonox::createFunctor(orxonox::XMLPortVariableHelperClass::getSaver (variable)), std::string( #classname ) + "::" + #variable + "saver" )); \
+    XMLPortParamGeneric(xmlcontainer##variable, classname, orxonox::XMLPortVariableHelperClass, &xmlcontainer##variable##dummy, paramname, xmlcontainer##variable##loadexecutor, xmlcontainer##variable##saveexecutor, xmlelement, mode)
+
+/**
+    @brief This is the same as XMLPortParam, but you can set the template arguments needed to store the loadfunction.
+
+    Sometimes the name of the loadfunction is ambiguous (example: setPosition(Vector3) or
+    setPosition(float, float, float)). In this case, you can choose the right function by
+    telling the types of the functionparams. In our example, this would be either
+    > XMLPortParamTemplate(classname, paramname, loadfunction, savefunction, xmlelement, mode, Vector3);
+    or
+    > XMLPortParamTemplate(classname, paramname, loadfunction, savefunction, xmlelement, mode, float, float, float);
+    You don't have to use this, if there exist only one function with the given name.
+*/
+#define XMLPortParamTemplate(classname, paramname, loadfunction, savefunction, xmlelement, mode, ...) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
+    XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, classname, this, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode)
+
+// --------------------
+// XMLPortParamLoadOnly
+
+/**
+    @brief Declares an XML attribute with a name, which can be set through a loadfunction.
+
+    This is the same as XMLPortParam, but you don't need a savefunction (get-function). Therefore,
+    this param won't be saved in an XML file, but you can add the attribute manually an it will be
+    loaded.
+
+    This might be helpful in cases, when you have several options to set a value, for example the
+    rotation. You can set the rotation with a quaternion, but you could also use three angles.
+    When saving the object, only one of both options has to be saved; this is, where this macro helps.
+*/
+#define XMLPortParamLoadOnly(classname, paramname, loadfunction, xmlelement, mode) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##0##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    XMLPortParamGeneric(xmlcontainer##loadfunction##0, classname, classname, this, paramname, xmlcontainer##loadfunction##0##loadexecutor, 0, xmlelement, mode)
+/**
+    @brief This is the same as XMLPortParamTemplate, but for load-only attributes (see XMLPortParamLoadOnly).
+*/
+#define XMLPortParamLoadOnlyTemplate(classname, paramname, loadfunction, xmlelement, mode, ...) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##0##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    XMLPortParamGeneric(xmlcontainer##loadfunction##0, classname, classname, this, paramname, xmlcontainer##loadfunction##0##loadexecutor, 0, xmlelement, mode)
+
+// ------------------
+// XMLPortParamExtern
+
+/**
+    @brief This is the same as XMLPortParam, but for attributes in an extern class.
+    @param classname The name of the class owning the object owning the attribute
+    @param externclass The name of the extern class (the objects class)
+    @param object The name of the object of the extern class (a member of the main class)
+    @param paramname The name of the attribute
+    @param loadfunction The function to set the attribute inside of the member object.
+    @param loadfunction The function to get the attribute from the member object
+
+    Sometimes you'll have a member object in your class, which has it's own load- and savefunctions.
+    With this macro, you can simply use them instead of writing your own functions.
+
+    @example
+    Your class is called SpaceShip and this class has an object (myPilot_) of class Pilot. Pilot has a name
+    and two functions, setName(name) and getName(). Now you want an attribute "pilotname" in your
+    SpaceShip class. Instead of writing wrapper functions, you can simply use the XMLPortParamExtern
+    macro:
+    > XMLPortParamExtern(SpaceShip, Pilot, myPilot_, "pilotname", setName, getName, xmlelement, mode);
+*/
+#define XMLPortParamExtern(classname, externclass, object, paramname, loadfunction, savefunction, xmlelement, mode) \
+    static ExecutorMember<externclass>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&externclass::loadfunction), std::string( #externclass ) + "::" + #loadfunction); \
+    static ExecutorMember<externclass>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&externclass::savefunction), std::string( #externclass ) + "::" + #savefunction); \
+    XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, externclass, object, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode);
+/**
+    @brief This is the same as XMLPortParamTemplate, but for extern attributes (see XMLPortParamExtern).
+*/
+#define XMLPortParamExternTemplate(classname, externclass, object, paramname, loadfunction, savefunction, xmlelement, mode, ...) \
+    static ExecutorMember<externclass>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<externclass, __VA_ARGS__ >(&externclass::loadfunction), std::string( #externclass ) + "::" + #loadfunction); \
+    static ExecutorMember<externclass>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&externclass::savefunction), std::string( #externclass ) + "::" + #savefunction); \
+    XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, externclass, object, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode);
+
+// -------------------
+// XMLPortParamGeneric
+
+/**
+    @brief This is the generic XMLPort param macro, which is used by all six specialized macros above.
+*/
+#define XMLPortParamGeneric(containername, classname, objectclass, object, paramname, loadexecutor, saveexecutor, xmlelement, mode) \
+    orxonox::XMLPortClassParamContainer<objectclass>* containername = static_cast<orxonox::XMLPortClassParamContainer<objectclass>*>(ClassIdentifier<classname>::getIdentifier()->getXMLPortParamContainer(paramname)); \
+    if (!containername) \
+    { \
+        containername = new orxonox::XMLPortClassParamContainer<objectclass>(std::string(paramname), ClassIdentifier<classname>::getIdentifier(), loadexecutor, saveexecutor); \
+        ClassIdentifier<classname>::getIdentifier()->addXMLPortParamContainer(paramname, containername); \
+    } \
+    containername->port(static_cast<BaseObject*>(this), object, xmlelement, mode)
+
+// --------------------
+// XMLPortObjectExtended
+
+/**
+    @brief Declares a possible sub-object that can be added in the XML file.
+    @param classname The name of the class that uses this macro
+    @param objectclass The baseclass of objects that can be added
+    @param sectionname The name of the subsection in the XML file that encloses the sub-objects ("" means no subsection)
+    @param loadfunction The function to add a new object to the class
+    @param loadfunction The function to get all added objects from the class
+    @param xmlelement The XMLElement (recieved through the XMLPort function)
+    @param mode The mode (load/save) (received through the XMLPort function)
+    @param bApplyLoaderMask If this is true, an added sub-object gets loaded only if it's class is included in the Loaders ClassTreeMask (this is usually false)
+    @param bLoadBefore If this is true, the sub-object gets loaded (through XMLPort) BEFORE it gets added to the main class (this is usually true)
+
+    bApplyLoaderMask is usually false for the following reason:
+    If the loaders mask says, for example, "load only SpaceShips" and you added weapons to the
+    SpaceShips, then the Weapons will still be loaded (which is most probably what you want).
+    Of course, if there are "standalone" weapons in the level, they wont be loaded.
+
+    If bLoadBefore is true, an added object already has all attributes set (like it's name). This is most
+    likely the best option, so this is usually true.
+
+    @note
+    The load- and savefunctions have to follow an exactly defined protocol.
+    Loadfunction:
+      The loadfunction gets a pointer to the object.
+      > void loadfunction(objectclass* pointer);
+
+    Savefunction:
+      The savefunction gets an index, starting with 0. For every returnvalue != 0, the savefunction
+      gets called again, but with index + 1. It's the functions responsibility to do something smart
+      with the index and to return 0 if all objects were returned.
+      > objectclass* savefunction(unsigned int index) const;
+
+      Possible implementation:
+        objectclass* savefunction(unsigned int index) const
+        {
+          if (index < number_of_added_objects_)
+            return my_added_objects[index];
+          else
+            return 0;
+        }
+
+    @example
+    Possible usage of the macro:
+    > XMLPortObject(SpaceShip, Weapon, "weapons", addWeapon, getWeapon, xmlelement, mode, false, true);
+
+    Now you can add weapons through the XML file:
+    <SpaceShip someattribute="..." ...>
+      <weapons>
+        <Weapon someattribute="..." ... />
+        <Weapon someattribute="..." ... />
+        <Weapon someattribute="..." ... />
+      </weapons>
+    </SpaceShip>
+
+    Note that "weapons" is the subsection. This allows you to add more types of sub-objects. In our example,
+    you could add pilots, blinking lights or other stuff. If you don't want a subsection, just use "" (an
+    empty string). Then you can add sub-objects directly into the mainclass.
+*/
+#define XMLPortObjectExtended(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode, bApplyLoaderMask, bLoadBefore) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
+    XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, bApplyLoaderMask, bLoadBefore)
+/**
+    @brief This is the same as XMLPortObjectExtended, but you can specify the loadfunction by adding the param types. See XMLPortParamTemplate for more details about the types.
+*/
+#define XMLPortObjectExtendedTemplate(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode, bApplyLoaderMask, bLoadBefore, ...) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
+    XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, bApplyLoaderMask, bLoadBefore)
+
+// -------------
+// XMLPortObject
+
+/**
+    @brief This is the same as XMLPortObjectExtended, but bApplyLoaderMask is false and bLoadBefore is true by default.
+*/
+#define XMLPortObject(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
+    XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, false, true)
+/**
+    @brief This is the same as XMLPortObject, but you can specify the loadfunction by adding the param types. See XMLPortParamTemplate for more details about the types.
+*/
+#define XMLPortObjectTemplate(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode, ...) \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
+    static ExecutorMember<classname>* xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
+    XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, false, true)
+
+// --------------------
+// XMLPortObjectGeneric
+
+/**
+    @brief Generic XMLPortObject macro, that gets called by all other XMLPortObject macros above.
+*/
+#define XMLPortObjectGeneric(containername, classname, objectclass, sectionname, loadexecutor, saveexecutor, xmlelement, mode, bApplyLoaderMask, bLoadBefore) \
+    orxonox::XMLPortClassObjectContainer<classname, objectclass>* containername = (orxonox::XMLPortClassObjectContainer<classname, objectclass>*)(ClassIdentifier<classname>::getIdentifier()->getXMLPortObjectContainer(sectionname)); \
+    if (!containername) \
+    { \
+        containername = new orxonox::XMLPortClassObjectContainer<classname, objectclass>(std::string(sectionname), ClassIdentifier<classname>::getIdentifier(), loadexecutor, saveexecutor, bApplyLoaderMask, bLoadBefore); \
+        ClassIdentifier<classname>::getIdentifier()->addXMLPortObjectContainer(sectionname, containername); \
+    } \
+    containername->port(this, xmlelement, mode)
+
+
+namespace orxonox
+{
+    // ###############################
+    // ###  XMLPortParamContainer  ###
+    // ###############################
+    class _CoreExport XMLPortParamContainer
+    {
+    public:
+        enum ParseResult
+        {
+            PR_not_started,
+            PR_finished,
+            PR_waiting_for_default_values
+        };
+
+        public:
+            XMLPortParamContainer()
+                { this->parseResult_ = PR_not_started; }
+            virtual ~XMLPortParamContainer() {}
+
+            inline const std::string& getName() const
+                { return this->paramname_; }
+
+            virtual XMLPortParamContainer& description(const std::string description) = 0;
+            virtual const std::string& getDescription() = 0;
+
+            virtual XMLPortParamContainer& defaultValue(unsigned int index, const MultiType& param) = 0;
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1) = 0;
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2) = 0;
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3) = 0;
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4) = 0;
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5) = 0;
+
+        protected:
+            std::string paramname_;
+            ParseResult parseResult_;
+            Identifier* identifier_;
+            BaseObject* owner_;
+    };
+
+    template <class T>
+    class XMLPortClassParamContainer : public XMLPortParamContainer
+    {
+        struct ParseParams
+        {
+            T* object;
+            Element* xmlelement;
+            XMLPort::Mode mode;
+        };
+
+        public:
+            XMLPortClassParamContainer(const std::string paramname, Identifier* identifier, ExecutorMember<T>* loadexecutor, ExecutorMember<T>* saveexecutor)
+            {
+                this->paramname_ = paramname;
+                this->identifier_ = identifier;
+                this->loadexecutor_ = loadexecutor;
+                this->saveexecutor_ = saveexecutor;
+            }
+
+            ~XMLPortClassParamContainer()
+            {
+                assert(this->loadexecutor_);
+                delete this->loadexecutor_;
+                if (this->saveexecutor_)
+                    delete this->saveexecutor_;
+            }
+
+            XMLPortParamContainer& port(BaseObject* owner, T* object, Element& xmlelement, XMLPort::Mode mode)
+            {
+                OrxAssert(owner, "XMLPortParamContainer must have a BaseObject as owner.");
+                this->owner_ = owner;
+                this->parseParams_.object = object;
+                this->parseParams_.xmlelement = &xmlelement;
+                this->parseParams_.mode = mode;
+
+                if ((mode == XMLPort::LoadObject) || (mode == XMLPort::ExpandObject))
+                {
+                    try
+                    {
+                        if (this->owner_->lastLoadedXMLElement_ != &xmlelement)
+                        {
+                            this->owner_->xmlAttributes_.clear();
+                            // Iterate through the attributes manually in order to make them case insensitive
+                            Attribute* attribute = xmlelement.FirstAttribute(false);
+                            while (attribute != 0)
+                            {
+                                this->owner_->xmlAttributes_[getLowercase(attribute->Name())] = attribute->Value();
+                                attribute = attribute->Next(false);
+                            }
+                            this->owner_->lastLoadedXMLElement_ = &xmlelement;
+                        }
+                        std::map<std::string, std::string>::const_iterator it = this->owner_->xmlAttributes_.find(getLowercase(this->paramname_));
+                        std::string attributeValue("");
+                        if (it != this->owner_->xmlAttributes_.end())
+                            attributeValue = it->second;
+
+                        // TODO: Checking the iterator would be better since then we can have strings with value "" as well.
+                        //       Unfortunately this does not seem to work with the Executor parser yet.
+                        if ((!attributeValue.empty()) || ((mode != XMLPort::ExpandObject) && this->loadexecutor_->allDefaultValuesSet()))
+                        {
+                            COUT(5) << this->owner_->getLoaderIndentation() << "Loading parameter " << this->paramname_ << " in " << this->identifier_->getName() << " (objectname " << this->owner_->getName() << ")." << std::endl << this->owner_->getLoaderIndentation();
+                            if (this->loadexecutor_->parse(object, attributeValue, ",") || (mode  == XMLPort::ExpandObject))
+                                this->parseResult_ = PR_finished;
+                            else
+                                this->parseResult_ = PR_waiting_for_default_values;
+                        }
+                        else if (mode == XMLPort::ExpandObject)
+                            this->parseResult_ = PR_finished;
+                        else
+                            this->parseResult_ = PR_waiting_for_default_values;
+                    }
+                    catch (ticpp::Exception& ex)
+                    {
+                        COUT(1) << std::endl;
+                        COUT(1) << "An error occurred in XMLPort.h while loading attribute '" << this->paramname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << this->owner_->getName() << ") in " << this->owner_->getFilename() << ":" << std::endl;
+                        COUT(1) << ex.what() << std::endl;
+                    }
+                }
+                else
+                {
+                    if (this->saveexecutor_)
+                    {
+//                        xmlelement.SetAttribute(this->paramname_, "...");
+                    }
+                }
+
+                return (*this);
+            }
+
+            XMLPortParamContainer& port(BaseObject* owner, const ParseParams& parseParams)
+            {
+                return this->port(owner, parseParams.object, *parseParams.xmlelement, parseParams.mode);
+            }
+
+            XMLPortParamContainer& portIfWaitingForDefaultValues(const ParseResult& result, const ParseParams& params)
+            {
+                if (result == PR_waiting_for_default_values)
+                    return this->port(this->owner_, params);
+                else
+                    return (*this);
+            }
+
+            virtual XMLPortParamContainer& description(const std::string description)
+                { this->loadexecutor_->setDescription(description); return (*this); }
+            virtual const std::string& getDescription()
+                { return this->loadexecutor_->getDescription(); }
+
+            virtual XMLPortParamContainer& defaultValue(unsigned int index, const MultiType& param)
+            {
+                if (!this->loadexecutor_->defaultValueSet(index))
+                    this->loadexecutor_->setDefaultValue(index, param);
+                return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
+            }
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1)
+            {
+                if (!this->loadexecutor_->defaultValueSet(0))
+                    this->loadexecutor_->setDefaultValues(param1);
+                return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
+            }
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2)
+            {
+                if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)))
+                    this->loadexecutor_->setDefaultValues(param1, param2);
+                return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
+            }
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3)
+            {
+                if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)) || (!this->loadexecutor_->defaultValueSet(2)))
+                    this->loadexecutor_->setDefaultValues(param1, param2, param3);
+                return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
+            }
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4)
+            {
+                if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)) || (!this->loadexecutor_->defaultValueSet(2)) || (!this->loadexecutor_->defaultValueSet(3)))
+                    this->loadexecutor_->setDefaultValues(param1, param2, param3, param4);
+                return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
+            }
+            virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5)
+            {
+                if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)) || (!this->loadexecutor_->defaultValueSet(2)) || (!this->loadexecutor_->defaultValueSet(3)) || (!this->loadexecutor_->defaultValueSet(4)))
+                    this->loadexecutor_->setDefaultValues(param1, param2, param3, param4, param5);
+                return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
+            }
+
+        private:
+            ExecutorMember<T>* loadexecutor_;
+            ExecutorMember<T>* saveexecutor_;
+            ParseParams parseParams_;
+    };
+
+
+    // ################################
+    // ###  XMLPortObjectContainer  ###
+    // ################################
+    class _CoreExport XMLPortObjectContainer
+    {
+        public:
+            XMLPortObjectContainer()
+                { this->bApplyLoaderMask_ = false; }
+            virtual ~XMLPortObjectContainer() {}
+
+            inline const std::string& getName() const
+                { return this->sectionname_; }
+
+            virtual XMLPortObjectContainer& description(const std::string description) = 0;
+            virtual const std::string& getDescription() = 0;
+
+            bool identifierIsIncludedInLoaderMask(const Identifier* identifier);
+
+        protected:
+            std::string sectionname_;
+            bool bApplyLoaderMask_;
+            bool bLoadBefore_;
+            Identifier* identifier_;
+    };
+
+    template <class T, class O>
+    class XMLPortClassObjectContainer : public XMLPortObjectContainer
+    {
+        public:
+            XMLPortClassObjectContainer(const std::string sectionname, Identifier* identifier, ExecutorMember<T>* loadexecutor, ExecutorMember<T>* saveexecutor, bool bApplyLoaderMask, bool bLoadBefore)
+            {
+                this->sectionname_ = sectionname;
+                this->identifier_ = identifier;
+                this->loadexecutor_ = loadexecutor;
+                this->saveexecutor_ = saveexecutor;
+                this->bApplyLoaderMask_ = bApplyLoaderMask;
+                this->bLoadBefore_ = bLoadBefore;
+            }
+
+            ~XMLPortClassObjectContainer()
+            {
+                assert(this->loadexecutor_);
+                delete this->loadexecutor_;
+                if (this->saveexecutor_)
+                    delete this->saveexecutor_;
+            }
+
+            XMLPortObjectContainer& port(T* object, Element& xmlelement, XMLPort::Mode mode)
+            {
+                if ((mode == XMLPort::LoadObject) || (mode == XMLPort::ExpandObject))
+                {
+                    try
+                    {
+                        Element* xmlsubelement;
+                        if ((this->sectionname_ != "") && (this->sectionname_.size() > 0))
+                            xmlsubelement = xmlelement.FirstChildElement(this->sectionname_, false);
+                        else
+                            xmlsubelement = &xmlelement;
+
+                        if (xmlsubelement)
+                        {
+                            for (ticpp::Iterator<ticpp::Element> child = xmlsubelement->FirstChildElement(false); child != child.end(); child++)
+                            {
+                                Identifier* identifier = Factory::getIdentifier(child->Value());
+                                if (identifier)
+                                {
+                                    if (identifier->isA(ClassIdentifier<O>::getIdentifier()))
+                                    {
+                                        if (identifier->isLoadable())
+                                        {
+                                            if (this->identifierIsIncludedInLoaderMask(identifier))
+                                            {
+                                                try
+                                                {
+                                                    COUT(4) << object->getLoaderIndentation() << "fabricating " << child->Value() << "..." << std::endl;
+
+                                                    BaseObject* newObject = identifier->fabricate(static_cast<BaseObject*>(object));
+                                                    assert(newObject);
+                                                    newObject->setLoaderIndentation(object->getLoaderIndentation() + "  ");
+
+                                                    O* castedObject = orxonox_cast<O*>(newObject);
+                                                    assert(castedObject);
+
+                                                    if (this->bLoadBefore_)
+                                                    {
+                                                        newObject->XMLPort(*child, XMLPort::LoadObject);
+                                                        COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (objectname " << newObject->getName() << ") to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ")" << std::endl;
+                                                    }
+                                                    else
+                                                    {
+                                                        COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (object not yet loaded) to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ")" << std::endl;
+                                                    }
+
+                                                    COUT(5) << object->getLoaderIndentation();
+                                                    (*this->loadexecutor_)(object, castedObject);
+
+                                                    if (!this->bLoadBefore_)
+                                                        newObject->XMLPort(*child, XMLPort::LoadObject);
+
+                                                    COUT(5) << object->getLoaderIndentation() << "...fabricated " << child->Value() << " (objectname " << newObject->getName() << ")." << std::endl;
+                                                }
+                                                catch (AbortLoadingException& ex)
+                                                {
+                                                    COUT(1) << "An error occurred while loading object, abort loading..." << std::endl;
+                                                    throw ex;
+                                                }
+                                                catch (std::exception& ex)
+                                                {
+                                                    COUT(1) << "An error occurred while loading object:" << std::endl;
+                                                    COUT(1) << ex.what() << std::endl;
+                                                }
+                                                catch (...)
+                                                {
+                                                    COUT(1) << "An unknown error occurred while loading object." << std::endl;
+                                                }
+                                            }
+                                        }
+                                        else
+                                        {
+                                            COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not loadable." << std::endl;
+                                        }
+                                    }
+                                    else
+                                    {
+                                        COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not a '" << ClassIdentifier<O>::getIdentifier()->getName() << "'." << std::endl;
+                                    }
+                                }
+                                else
+                                {
+                                    if (this->sectionname_ != "")
+                                    {
+                                        COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not a valid classname." << std::endl;
+                                    }
+                                    else
+                                    {
+                                        // It's probably just another subsection
+                                    }
+                                }
+                            }
+                        }
+                    }
+                    catch (ticpp::Exception& ex)
+                    {
+                        COUT(1) << std::endl;
+                        COUT(1) << "An error occurred in XMLPort.h while loading a '" << ClassIdentifier<O>::getIdentifier()->getName() << "' in '" << this->sectionname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << object->getName() << ") in " << object->getFilename() << ":" << std::endl;
+                        COUT(1) << ex.what() << std::endl;
+                    }
+                }
+                else
+                {
+                }
+
+                return (*this);
+            }
+
+            virtual XMLPortObjectContainer& description(const std::string description)
+                { this->loadexecutor_->setDescription(description); return (*this); }
+            virtual const std::string& getDescription()
+                { return this->loadexecutor_->getDescription(); }
+
+        private:
+            ExecutorMember<T>* loadexecutor_;
+            ExecutorMember<T>* saveexecutor_;
+    };
+
+
+    // ####################################
+    // ###  XMLPortVariableHelperClass  ###
+    // ####################################
+    /**
+    @brief
+        Helper class to load and save simple variables with XMLPort.
+
+        getLoader and getSaver were necessary to get the type T with
+        the help of template function type deduction (const T& is unused).
+        These functions return the adress of save<T> or load<T>.
+    */
+    class XMLPortVariableHelperClass
+    {
+        public:
+            XMLPortVariableHelperClass(void* var)
+                : variable_(var)
+                { }
+
+            template <class T>
+            void load(const T& value)
+                { *static_cast<T*>(this->variable_) = value; }
+
+            template <class T>
+            const T& save()
+                { return *static_cast<T*>(this->variable_); }
+
+            template <class T>
+            static void (XMLPortVariableHelperClass::*getLoader(const T& var))(const T& value)
+                { return &XMLPortVariableHelperClass::load<T>; }
+
+            template <class T>
+            static const T& (XMLPortVariableHelperClass::*getSaver(const T& var))()
+                { return &XMLPortVariableHelperClass::save<T>; }
+
+        private:
+            void* variable_;
+    };
+}
+
+#endif /* _XMLPort_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/Button.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/Button.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/Button.cc	(revision 5712)
@@ -0,0 +1,257 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the different input handlers.
+*/
+
+#include "Button.h"
+
+#include "util/Convert.h"
+#include "util/SubString.h"
+#include "util/StringUtils.h"
+#include "util/Debug.h"
+#include "core/ConsoleCommand.h"
+#include "core/CommandEvaluation.h"
+#include "core/CommandExecutor.h"
+#include "core/ConfigValueContainer.h"
+
+namespace orxonox
+{
+    /**
+    @note
+        bButtonThresholdUser_: We set it to true so that setConfigValues in KeyBinder sets the value
+        correctly the first time. It is then set to false first and changed later in Button::parse().
+    */
+    Button::Button()
+        : configContainer_(0)
+        , bButtonThresholdUser_(false)
+        , paramCommandBuffer_(0)
+    {
+        nCommands_[0]=0;
+        nCommands_[1]=0;
+        nCommands_[2]=0;
+    }
+
+    Button::~Button()
+    {
+        this->clear();
+
+        if (this->configContainer_)
+            delete this->configContainer_;
+    }
+
+    void Button::clear()
+    {
+        for (unsigned int j = 0; j < 3; j++)
+        {
+            if (nCommands_[j])
+            {
+                // delete all commands and the command pointer array
+                for (unsigned int i = 0; i < nCommands_[j]; i++)
+                    delete commands_[j][i];
+                delete[] commands_[j];
+                commands_[j] = 0;
+                nCommands_[j] = 0;
+            }
+        }
+    }
+
+    void Button::readConfigValue(ConfigFileType configFile)
+    {
+        // create/get ConfigValueContainer
+        if (!configContainer_)
+        {
+            configContainer_ = new ConfigValueContainer(configFile, 0, groupName_, name_, "", name_);
+            configContainer_->callback(this, &Button::parse);
+        }
+        configContainer_->getValue(&bindingString_, this);
+    }
+
+    void Button::parse()
+    {
+        // delete all commands
+        clear();
+
+        if (isEmpty(bindingString_))
+            return;
+
+        // reset this to false first when parsing (was true before when parsing for the first time)
+        bButtonThresholdUser_ = false;
+
+        // use std::vector for a temporary dynamic array
+        std::vector<BaseCommand*> commands[3];
+
+        // separate the commands
+        SubString commandStrings(bindingString_, "|", SubString::WhiteSpaces, false,
+            '\\', false, '"', false, '(', ')', false, '\0');
+
+        for (unsigned int iCommand = 0; iCommand < commandStrings.size(); iCommand++)
+        {
+            if (commandStrings[iCommand] != "")
+            {
+                SubString tokens(commandStrings[iCommand], " ", SubString::WhiteSpaces, false,
+                    '\\', false, '"', false, '(', ')', false, '\0');
+
+                KeybindMode::Value mode = KeybindMode::None;
+                float paramModifier = 1.0f;
+                std::string commandStr = "";
+
+                for (unsigned int iToken = 0; iToken < tokens.size(); ++iToken)
+                {
+                    std::string token = getLowercase(tokens[iToken]);
+
+                    if (token == "onpress")
+                        mode = KeybindMode::OnPress;
+                    else if (token == "onrelease")
+                        mode = KeybindMode::OnRelease;
+                    else if (token == "onhold")
+                        mode = KeybindMode::OnHold;
+                    else if (token == "buttonthreshold")
+                    {
+                        // for real axes, we can feed a ButtonThreshold argument
+                        ++iToken;
+                        if (iToken == tokens.size())
+                            continue;
+                        // may fail, but doesn't matter (default value already set)
+                        if (!convertValue(&buttonThreshold_, tokens[iToken + 1]))
+                            parseError("Could not parse 'ButtonThreshold' argument. \
+                                Switching to default value.", true);
+                        else
+                            this->bButtonThresholdUser_ = true;
+                    }
+                    else if (token == "scale")
+                    {
+                        ++iToken;
+                        if (iToken == tokens.size() || !convertValue(&paramModifier, tokens[iToken]))
+                            parseError("Could not parse 'scale' argument. Switching to default value.", true);
+                    }
+                    else
+                    {
+                        // no input related argument
+                        // we interpret everything from here as a command string
+                        while (iToken != tokens.size())
+                            commandStr += tokens[iToken++] + " ";
+                    }
+                }
+
+                if (commandStr == "")
+                {
+                    parseError("No command string given.", false);
+                    continue;
+                }
+
+                // evaluate the command
+                CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
+                if (!eval.isValid())
+                {
+                    parseError("Command evaluation failed.", true);
+                    continue;
+                }
+
+                // check for param command
+                int paramIndex = eval.getConsoleCommand()->getInputConfiguredParam_();
+                if (paramIndex >= 0)
+                {
+                    // parameter supported command
+                    ParamCommand* cmd = new ParamCommand();
+                    cmd->scale_ = paramModifier;
+
+                    // add command to the buffer if not yet existing
+                    for (unsigned int iParamCmd = 0; iParamCmd < paramCommandBuffer_->size(); iParamCmd++)
+                    {
+                        if ((*paramCommandBuffer_)[iParamCmd]->evaluation_.getConsoleCommand()
+                            == eval.getConsoleCommand())
+                        {
+                            // already in list
+                            cmd->paramCommand_ = (*paramCommandBuffer_)[iParamCmd];
+                            break;
+                        }
+                    }
+                    if (cmd->paramCommand_ == 0)
+                    {
+                        cmd->paramCommand_ = new BufferedParamCommand();
+                        paramCommandBuffer_->push_back(cmd->paramCommand_);
+                        cmd->paramCommand_->evaluation_ = eval;
+                        cmd->paramCommand_->paramIndex_ = paramIndex;
+                    }
+
+
+                    // we don't know whether this is an actual axis or just a button
+                    if (mode == KeybindMode::None)
+                    {
+                        if (!addParamCommand(cmd))
+                        {
+                            mode = eval.getConsoleCommand()->getKeybindMode();
+                            commands[mode].push_back(cmd);
+                        }
+                    }
+                }
+                else
+                {
+                    SimpleCommand* cmd = new SimpleCommand();
+                    cmd->evaluation_ = eval;
+
+                    if (mode == KeybindMode::None)
+                        mode = eval.getConsoleCommand()->getKeybindMode();
+
+                    commands[mode].push_back(cmd);
+                }
+            }
+        }
+
+        for (unsigned int j = 0; j < 3; j++)
+        {
+            nCommands_[j] = commands[j].size();
+            if (nCommands_[j])
+            {
+                commands_[j] = new BaseCommand*[nCommands_[j]];
+                for (unsigned int i = 0; i < commands[j].size(); i++)
+                    commands_[j][i] = commands[j][i];
+            }
+            else
+                commands_[j] = 0;
+        }
+    }
+
+    inline void Button::parseError(std::string message, bool serious)
+    {
+        if (serious)
+        {
+            COUT(2) << "Error while parsing binding for button/axis " << this->name_ << ". "
+                << message << std::endl;
+        }
+        else
+        {
+            COUT(3) << "Warning while parsing binding for button/axis " << this->name_ << ". "
+                << message << std::endl;
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/Button.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/Button.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/Button.h	(revision 5712)
@@ -0,0 +1,91 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Different definitions of input processing.
+*/
+
+#ifndef _Button_H__
+#define _Button_H__
+
+#include "InputPrereqs.h"
+
+#include <string>
+#include <vector>
+#include "InputCommands.h"
+#include "core/ConfigFileManager.h"
+
+namespace orxonox
+{
+    class _CoreExport Button
+    {
+    public:
+        Button();
+        virtual ~Button();
+        virtual void clear();
+        virtual bool addParamCommand(ParamCommand* command) { return false; }
+        void parse();
+        void readConfigValue(ConfigFileType configFile);
+        bool execute(KeybindMode::Value mode, float abs = 1.0f, float rel = 1.0f);
+
+        //! Container to allow for better configValue support
+        ConfigValueContainer* configContainer_;
+        //! The configured string value
+        std::string bindingString_;
+        //! Name of the trigger as strings
+        std::string name_;
+        //! Name of the group of input triggers
+        std::string groupName_;
+        //! Basic commands for OnPress, OnHold and OnRelease
+        BaseCommand** commands_[3];
+        //! Number of basic commands
+        unsigned int nCommands_[3];
+        //! Says how much it takes for an analog axis to trigger a button
+        //! Note: This variable is here to have only one parse() function.
+        float buttonThreshold_;
+        bool bButtonThresholdUser_;
+        //! Pointer to the list of parametrised commands
+        std::vector<BufferedParamCommand*>* paramCommandBuffer_;
+
+    private:
+        void parseError(std::string message, bool serious);
+    };
+
+    inline bool Button::execute(KeybindMode::Value mode, float abs, float rel)
+    {
+        // execute all the parsed commands in the string
+        for (unsigned int iCommand = 0; iCommand < nCommands_[mode]; iCommand++)
+            commands_[mode][iCommand]->execute(abs, rel);
+        return true;
+    }
+
+}
+
+#endif /* _Button_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/CMakeLists.txt
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/CMakeLists.txt	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/CMakeLists.txt	(revision 5712)
@@ -0,0 +1,14 @@
+ADD_SOURCE_FILES(CORE_SRC_FILES
+  Button.cc
+  HalfAxis.cc
+  InputBuffer.cc
+  InputCommands.cc
+  InputManager.cc
+  InputState.cc
+  JoyStick.cc
+  JoyStickQuantityListener.cc
+  KeyBinder.cc
+  Keyboard.cc
+  KeyDetector.cc
+  Mouse.cc
+)
Index: /code/branches/libraries2/src/libraries/core/input/HalfAxis.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/HalfAxis.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/HalfAxis.cc	(revision 5712)
@@ -0,0 +1,65 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the different input handlers.
+*/
+
+#include "HalfAxis.h"
+#include "core/CommandEvaluation.h"
+
+namespace orxonox
+{
+    void HalfAxis::clear()
+    {
+        Button::clear();
+        if (nParamCommands_)
+        {
+            // delete all commands and the command pointer array
+            for (unsigned int i = 0; i < nParamCommands_; i++)
+                delete paramCommands_[i];
+            delete[] paramCommands_;
+            nParamCommands_ = 0;
+        }
+    }
+
+    bool HalfAxis::addParamCommand(ParamCommand* command)
+    {
+        ParamCommand** cmds = paramCommands_;
+        paramCommands_ = new ParamCommand*[++nParamCommands_];
+        unsigned int i;
+        for (i = 0; i < nParamCommands_ - 1; i++)
+            paramCommands_[i] = cmds[i];
+        paramCommands_[i] = command;
+        if (nParamCommands_ > 1)
+            delete[] cmds;
+        return true;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/HalfAxis.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/HalfAxis.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/HalfAxis.h	(revision 5712)
@@ -0,0 +1,81 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Different definitions of input processing.
+*/
+
+#ifndef _HalfAxis_H__
+#define _HalfAxis_H__
+
+#include "InputPrereqs.h"
+
+#include "Button.h"
+#include "InputCommands.h"
+
+namespace orxonox
+{
+    class _CoreExport HalfAxis : public Button
+    {
+    public:
+        HalfAxis()
+            : relVal_(0.0f)
+            , absVal_(0.0f)
+            , paramCommands_(0)
+            , nParamCommands_(0)
+            , pressed_(false)
+            , hasChanged_(false)
+        { }
+        using Button::execute;
+        bool execute();
+        bool addParamCommand(ParamCommand* command);
+        void clear();
+
+        // axis related
+        float relVal_;
+        float absVal_;
+        ParamCommand** paramCommands_;
+        unsigned int nParamCommands_;
+
+        // button related
+        bool pressed_;
+        bool hasChanged_;
+    };
+
+    inline bool HalfAxis::execute()
+    {
+        bool success = true;
+        for (unsigned int i = 0; i < nParamCommands_; i++)
+            success = paramCommands_[i]->execute(absVal_, relVal_) && success;
+        return success;
+    }
+}
+
+#endif /* _HalfAxis_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputBuffer.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputBuffer.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputBuffer.cc	(revision 5712)
@@ -0,0 +1,262 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      Reto Grieder
+ *
+ */
+
+#include "InputBuffer.h"
+
+#include "util/Clipboard.h"
+#include "core/CoreIncludes.h"
+#include "core/ConfigValueIncludes.h"
+
+namespace orxonox
+{
+    InputBuffer::InputBuffer()
+    {
+        RegisterRootObject(InputBuffer);
+
+        this->buffer_ = "";
+        this->cursor_ = 0;
+        this->allowedChars_ = "abcdefghijklmnopqrstuvwxyz \
+                               ABCDEFGHIJKLMNOPQRSTUVWXYZ \
+                               äëïöüÄËÏÖÜáâàéêèíîìóôòúûù \
+                               0123456789 \
+                               \\\"(){}[]<>.:,;_-+*/=!?|$&%^~#";
+
+        this->lastKey_ = KeyCode::Unassigned;
+        this->timeSinceKeyPressed_ = 0.0f;
+        this->timeSinceKeyRepeated_ = 0.0f;
+        this->keysToRepeat_ = 0;
+
+        setConfigValues();
+    }
+
+    InputBuffer::InputBuffer(const std::string& allowedChars)
+    {
+        RegisterRootObject(InputBuffer);
+
+        this->allowedChars_ = allowedChars;
+        this->buffer_ = "";
+        this->cursor_ = 0;
+
+        this->lastKey_ = KeyCode::Unassigned;
+        this->timeSinceKeyPressed_ = 0.0f;
+        this->timeSinceKeyRepeated_ = 0.0f;
+        this->keysToRepeat_ = 0;
+
+        setConfigValues();
+    }
+
+    InputBuffer::~InputBuffer()
+    {
+        for (std::list<BaseInputBufferListenerTuple*>::const_iterator it = this->listeners_.begin();
+            it != this->listeners_.end(); ++it)
+            delete *it;
+    }
+
+    void InputBuffer::setConfigValues()
+    {
+        SetConfigValue(keyRepeatDeleay_, 0.4).description("Key repeat deleay of the input buffer");
+        SetConfigValue(keyRepeatTime_, 0.022).description("Key repeat time of the input buffer");
+
+        if (keyRepeatDeleay_ < 0.0)
+        {
+            ResetConfigValue(keyRepeatDeleay_);
+        }
+        if (keyRepeatTime_ < 0.0)
+        {
+            ResetConfigValue(keyRepeatTime_);
+        }
+    }
+
+    void InputBuffer::set(const std::string& input, bool update)
+    {
+        this->clear(false);
+        this->insert(input, update);
+    }
+
+    void InputBuffer::insert(const std::string& input, bool update)
+    {
+        for (unsigned int i = 0; i < input.size(); ++i)
+        {
+            this->insert(input[i], false);
+
+            if (update)
+                this->updated(input[i], false);
+        }
+
+        if (update)
+            this->updated();
+    }
+
+    void InputBuffer::insert(const char& input, bool update)
+    {
+        if (this->charIsAllowed(input))
+        {
+            this->buffer_.insert(this->cursor_, 1, input);
+            ++this->cursor_;
+        }
+
+        if (update)
+            this->updated(input, true);
+    }
+
+    void InputBuffer::clear(bool update)
+    {
+        this->buffer_ = "";
+        this->cursor_ = 0;
+
+        if (update)
+            this->updated();
+    }
+
+    void InputBuffer::removeBehindCursor(bool update)
+    {
+        if (this->cursor_ > 0)
+        {
+            --this->cursor_;
+            this->buffer_.erase(this->cursor_, 1);
+
+            if (update)
+                this->updated();
+        }
+    }
+
+    void InputBuffer::removeAtCursor(bool update)
+    {
+        if (this->cursor_ < this->buffer_.size())
+        {
+            this->buffer_.erase(this->cursor_, 1);
+
+            if (update)
+                this->updated();
+        }
+    }
+
+    void InputBuffer::updated()
+    {
+        for (std::list<BaseInputBufferListenerTuple*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it)
+        {
+            if ((*it)->bListenToAllChanges_)
+                (*it)->callFunction();
+        }
+    }
+
+    void InputBuffer::updated(const char& update, bool bSingleInput)
+    {
+        for (std::list<BaseInputBufferListenerTuple*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it)
+        {
+            if ((!(*it)->trueKeyFalseChar_) && ((*it)->bListenToAllChanges_ || ((*it)->char_ == update)) && (!(*it)->bOnlySingleInput_ || bSingleInput))
+                (*it)->callFunction();
+        }
+    }
+
+    bool InputBuffer::charIsAllowed(const char& input)
+    {
+        if (this->allowedChars_ == "")
+            return true;
+        else
+            return (this->allowedChars_.find(input) != std::string::npos);
+    }
+
+
+    void InputBuffer::processKey(const KeyEvent& evt)
+    {
+        if (evt.isModifierDown(KeyboardModifier::Alt) && evt.getKeyCode() == KeyCode::Tab)
+            return;
+
+        for (std::list<BaseInputBufferListenerTuple*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it)
+        {
+            if ((*it)->trueKeyFalseChar_ && ((*it)->key_ == evt.getKeyCode()))
+                (*it)->callFunction();
+        }
+
+        if (evt.isModifierDown(KeyboardModifier::Ctrl))
+        {
+            if (evt.getKeyCode() == KeyCode::V)
+                this->insert(fromClipboard());
+            else if (evt.getKeyCode() == KeyCode::C)
+                toClipboard(this->buffer_);
+            else if (evt.getKeyCode() == KeyCode::X)
+            {
+                toClipboard(this->buffer_);
+                this->clear();
+            }
+        }
+        else if (evt.isModifierDown(KeyboardModifier::Shift))
+        {
+            if (evt.getKeyCode() == KeyCode::Insert)
+                this->insert(fromClipboard());
+            else if (evt.getKeyCode() == KeyCode::Delete)
+            {
+                toClipboard(this->buffer_);
+                this->clear();
+            }
+        }
+
+        this->insert(static_cast<char>(evt.getText()));
+    }
+
+    /**
+        @brief This update() function is called by the InputManager if the InputBuffer is active.
+        @param dt Delta time
+    */
+    void InputBuffer::keyboardUpdated(float dt)
+    {
+        timeSinceKeyPressed_ += dt;
+        if (keysToRepeat_ < 10 && timeSinceKeyPressed_ > keyRepeatDeleay_)
+        {
+            // initial time out has gone by, start repeating keys
+            while (timeSinceKeyPressed_ - timeSinceKeyRepeated_ > keyRepeatTime_)
+            {
+                timeSinceKeyRepeated_ += keyRepeatTime_;
+                keysToRepeat_++;
+            }
+        }
+    }
+
+    void InputBuffer::buttonPressed(const KeyEvent& evt)
+    {
+        lastKey_ = evt.getKeyCode();
+        timeSinceKeyPressed_ = 0.0;
+        timeSinceKeyRepeated_ = keyRepeatDeleay_;
+        keysToRepeat_ = 0;
+
+        processKey(evt);
+    }
+
+    void InputBuffer::buttonHeld(const KeyEvent& evt)
+    {
+        if (evt.getKeyCode() == lastKey_)
+        {
+            while (keysToRepeat_)
+            {
+                processKey(evt);
+                keysToRepeat_--;
+            }
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/InputBuffer.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputBuffer.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputBuffer.h	(revision 5712)
@@ -0,0 +1,188 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      Reto Grieder
+ *
+ */
+
+#ifndef _InputBuffer_H__
+#define _InputBuffer_H__
+
+#include "InputPrereqs.h"
+
+#include <list>
+#include <string>
+#include "core/OrxonoxClass.h"
+#include "InputHandler.h"
+
+namespace orxonox
+{
+    class BaseInputBufferListenerTuple
+    {
+    public:
+        BaseInputBufferListenerTuple(bool bListenToAllChanges, bool bOnlySingleInput,
+            bool trueKeyFalseChar, char _char, KeyCode::ByEnum key)
+            : bListenToAllChanges_(bListenToAllChanges), bOnlySingleInput_(bOnlySingleInput),
+              trueKeyFalseChar_(trueKeyFalseChar), char_(_char), key_(key)
+        { }
+        virtual ~BaseInputBufferListenerTuple() { }
+        virtual void callFunction() = 0;
+        bool bListenToAllChanges_;
+        bool bOnlySingleInput_;
+        bool trueKeyFalseChar_;
+        char char_;
+        KeyCode::ByEnum key_;
+    };
+
+    template <class T>
+    class InputBufferListenerTuple : public BaseInputBufferListenerTuple
+    {
+    public:
+        InputBufferListenerTuple(T* listener, void (T::*function)(), bool bListenToAllChanges,
+            bool bOnlySingleInput, bool trueKeyFalseChar, char _char, KeyCode::ByEnum key)
+            : BaseInputBufferListenerTuple(bListenToAllChanges, bOnlySingleInput, trueKeyFalseChar, _char, key),
+              listener_(listener), function_(function)
+        { }
+        virtual ~InputBufferListenerTuple() { }
+        void callFunction()
+        {
+            (listener_->*function_)();
+        }
+        T* listener_;
+        void (T::*function_)();
+    };
+
+    class _CoreExport InputBuffer : public InputHandler, public OrxonoxClass
+    {
+        public:
+            InputBuffer();
+            ~InputBuffer();
+            InputBuffer(const std::string& allowedChars);
+
+            void setConfigValues();
+
+            template <class T>
+            void registerListener(T* listener, void (T::*function)(), bool bOnlySingleInput)
+            {
+                InputBufferListenerTuple<T>* newTuple = new InputBufferListenerTuple<T>(listener, (void (T::*)())function, true, bOnlySingleInput, false, '\0', KeyCode::Unassigned);
+                this->listeners_.insert(this->listeners_.end(), newTuple);
+            }
+            template <class T>
+            void registerListener(T* listener, void (T::*function)() const, bool bOnlySingleInput)
+            {
+                InputBufferListenerTuple<T>* newTuple = new InputBufferListenerTuple<T>(listener, (void (T::*)())function, true, bOnlySingleInput, false, '\0', KeyCode::Unassigned);
+                this->listeners_.insert(this->listeners_.end(), newTuple);
+            }
+            template <class T>
+            void registerListener(T* listener, void (T::*function)(), char _char, bool bOnlySingleInput)
+            {
+                InputBufferListenerTuple<T>* newTuple = new InputBufferListenerTuple<T>(listener, (void (T::*)())function, false, bOnlySingleInput, false, _char, KeyCode::Unassigned);
+                this->listeners_.insert(this->listeners_.end(), newTuple);
+            }
+            template <class T>
+            void registerListener(T* listener, void (T::*function)() const, char _char, bool bOnlySingleInput)
+            {
+                InputBufferListenerTuple<T>* newTuple = new InputBufferListenerTuple<T>(listener, (void (T::*)())function, false, bOnlySingleInput, false, _char, KeyCode::Unassigned);
+                this->listeners_.insert(this->listeners_.end(), newTuple);
+            }
+
+            template <class T>
+            void registerListener(T* listener, void (T::*function)(), KeyCode::ByEnum key)
+            {
+                InputBufferListenerTuple<T>* newTuple = new InputBufferListenerTuple<T>(listener, (void (T::*)())function, false, true, true, '\0', key);
+                this->listeners_.insert(this->listeners_.end(), newTuple);
+            }
+            template <class T>
+            void registerListener(T* listener, void (T::*function)() const, KeyCode::ByEnum key)
+            {
+                InputBufferListenerTuple<T>* newTuple = new InputBufferListenerTuple<T>(listener, (void (T::*)())function, false, true, true, '\0', key);
+                this->listeners_.insert(this->listeners_.end(), newTuple);
+            }
+
+            template <class T>
+            void unregisterListener(T* listener)
+            {
+                for (std::list<BaseInputBufferListenerTuple*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); )
+                {
+                    InputBufferListenerTuple<T>* refListener = static_cast<InputBufferListenerTuple<T>*>(*it);
+                    if (refListener && refListener->listener_ == listener)
+                        this->listeners_.erase(it++);
+                    else
+                        it++;
+                }
+            }
+
+            void set(const std::string& input, bool update = true);
+            void insert(const std::string& input, bool update = true);
+            void insert(const char& input, bool update = true);
+            void clear(bool update = true);
+            void removeAtCursor(bool update = true);
+            void removeBehindCursor(bool update = true);
+
+            void updated();
+            void updated(const char& update, bool bSingleInput);
+
+            inline const std::string& get() const
+                { return this->buffer_; }
+            inline unsigned int getSize() const
+                { return this->buffer_.size(); }
+
+            inline unsigned int getCursorPosition() const
+                { return this->cursor_; }
+            inline void setCursorPosition(unsigned int cursor)
+                { if (cursor <= this->buffer_.size()) { this->cursor_ = cursor; } }
+            inline void setCursorToEnd()
+                { this->cursor_ = this->buffer_.size(); }
+            inline void setCursorToBegin()
+                { this->cursor_ = 0; }
+            inline void increaseCursor()
+                { if (this->cursor_ < this->buffer_.size()) { ++this->cursor_; } }
+            inline void decreaseCursor()
+                { if (this->cursor_ > 0) { --this->cursor_; } }
+
+        private:
+            bool charIsAllowed(const char& input);
+
+            void buttonPressed(const KeyEvent& evt);
+            void buttonHeld   (const KeyEvent& evt);
+            void processKey   (const KeyEvent& evt);
+
+            void keyboardUpdated(float dt);
+
+            std::string buffer_;
+            std::list<BaseInputBufferListenerTuple*> listeners_;
+            std::string allowedChars_;
+            unsigned int cursor_;
+
+            KeyCode::ByEnum lastKey_;
+            float timeSinceKeyPressed_;
+            float timeSinceKeyRepeated_;
+            int keysToRepeat_;
+
+            float keyRepeatDeleay_;
+            float keyRepeatTime_;
+    };
+}
+
+#endif /* _InputBuffer_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputCommands.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputCommands.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputCommands.cc	(revision 5712)
@@ -0,0 +1,97 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the different input handlers.
+*/
+
+#include "InputCommands.h"
+#include "util/Math.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###  BufferedParamCommand   ###
+    // ###############################
+
+    /**
+    @brief
+        Executes a buffered command. This is used for commands with additional
+        parameters.
+    @return
+        True if command execution was successful or value was zero.
+    */
+    bool BufferedParamCommand::execute()
+    {
+        if (this->abs_ != 0.0f || this->rel_ != 0.0f)
+        {
+            evaluation_.setEvaluatedParameter(paramIndex_, Vector2(abs_, rel_));
+            // reset
+            rel_ = 0.0;
+            abs_ = 0.0;
+            return evaluation_.execute();
+        }
+        else
+            return true;
+    }
+
+    // ###############################
+    // #####    ParamCommand     #####
+    // ###############################
+
+    /**
+    @brief
+        Executes a parameter command. The commmand string is not directly executed,
+        but instead stored in a buffer list so that values can be combined.
+    @return
+        Always true.
+    */
+    bool ParamCommand::execute(float abs, float rel)
+    {
+        BufferedParamCommand& cmd = *paramCommand_;
+        // command has an additional parameter
+        if (rel != 0.0f)
+        {
+            // calculate relative movement.
+            // scale_ says how much one keystroke is
+            cmd.rel_ += scale_ * rel;
+        }
+
+        if (abs != 0.0f)
+        {
+            cmd.abs_ += scale_ * abs;
+            if (cmd.abs_ > 1.0)
+                cmd.abs_ = 1.0;
+            if (cmd.abs_ < -1.0)
+                cmd.abs_ = -1.0;
+        }
+        return true;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/InputCommands.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputCommands.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputCommands.h	(revision 5712)
@@ -0,0 +1,92 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Different definitions of input processing.
+*/
+
+#ifndef _InputCommands_H__
+#define _InputCommands_H__
+
+#include "InputPrereqs.h"
+#include "core/CommandEvaluation.h"
+
+namespace orxonox
+{
+    class _CoreExport BufferedParamCommand
+    {
+    public:
+        BufferedParamCommand() : abs_(0.0f), rel_(0.0), paramIndex_(-1) { }
+        bool execute();
+
+        float abs_;
+        float rel_;
+        int paramIndex_;
+        CommandEvaluation evaluation_;
+    };
+
+    class _CoreExport BaseCommand
+    {
+    public:
+        virtual ~BaseCommand() { }
+        virtual bool execute(float abs = 1.0f, float rel = 1.0f) = 0;
+    };
+
+    class _CoreExport SimpleCommand : public BaseCommand
+    {
+    public:
+        bool execute(float abs = 1.0f, float rel = 1.0f);
+
+        CommandEvaluation evaluation_;
+    };
+
+    /**
+    @brief
+        Executes a simple command with no additional paramters.
+    @return 
+        True if command execution was successful, false otherwise.
+    */
+    inline bool SimpleCommand::execute(float abs, float rel)
+    {
+        return evaluation_.execute();
+    }
+
+    class _CoreExport ParamCommand : public BaseCommand
+    {
+    public:
+        ParamCommand() : scale_(1.0f), paramCommand_(0) { }
+        bool execute(float abs = 1.0f, float rel = 1.0f);
+
+        float scale_;
+        BufferedParamCommand* paramCommand_;
+    };
+}
+
+#endif /* _InputCommands_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputDevice.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputDevice.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputDevice.h	(revision 5712)
@@ -0,0 +1,233 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of InputDevice and InputDeviceTemplated
+*/
+
+#ifndef _InputDevice_H__
+#define _InputDevice_H__
+
+#include "InputPrereqs.h"
+
+#include <vector>
+#include <ois/OISInputManager.h>
+
+#include "util/Debug.h"
+#include "core/Clock.h"
+#include "InputState.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Abstract base class for all input devices (mouse, keyboard and joy sticks).
+
+        It provides common virtual functions to be used by the InputManager.
+    */
+    class InputDevice
+    {
+    public:
+        //! Only resets the members
+        InputDevice(unsigned int id) : bCalibrating_(false), deviceID_(id) { }
+        virtual ~InputDevice() { }
+        //! Returns the device class (derived) name as string
+        virtual std::string getClassName() const = 0;
+        //! Updates the device which should in turn distribute events
+        virtual void update(const Clock& time) = 0;
+        //! Clear all button related buffers
+        virtual void clearBuffers() = 0;
+
+        //! Start calibrating (only useful for joy sticks)
+        void startCalibration()
+        {
+            bCalibrating_ = true;
+            this->calibrationStarted();
+        }
+
+        //! Stop calibrating and evaluate the data (only useful for joy sticks)
+        void stopCalibration()
+        {
+            this->calibrationStopped();
+            bCalibrating_ = false;
+        }
+
+        //! Returns a reference to the internal input state vector. Use with care!
+        std::vector<InputState*>& getStateListRef() { return this->inputStates_; }
+        //! Returns the ID of the device (the same as in InputDeviceEnumerator for mouse and keyboard)
+        unsigned int getDeviceID() const { return this->deviceID_; }
+        //! Tells whether the device is in calibration mode
+        bool isCalibrating() const { return bCalibrating_; }
+
+    protected:
+        //! To be ovrridden by the subclass
+        virtual void calibrationStarted() { }
+        //! To be ovrridden by the subclass
+        virtual void calibrationStopped() { }
+
+        //! List of all input states that receive events from this device
+        std::vector<InputState*> inputStates_;
+
+    private:
+        InputDevice(const InputDevice& rhs); //!< Don't use!
+
+        bool bCalibrating_;                  //!< Whether the device is in calibration mode
+        const unsigned int deviceID_;        //!< ID of the device (the same as in InputDeviceEnumerator for mouse and keyboard)
+    };
+
+    /**
+    @brief
+        Heavily templated base class for all three input devices.
+
+        The purpose of this class is not to provide an interface but rather
+        to reduce code redundancy. This concerns device creation and destruction
+        as well as common code for button events (press, release, hold).
+
+        In order to derive from this class you have to supply it with a struct
+        as template parameter that contains the necessary type traits.
+    */
+    template <class Traits>
+    class InputDeviceTemplated : public InputDevice
+    {
+        typedef typename Traits::DeviceClass DeviceClass;
+        typedef typename Traits::OISDeviceClass OISDeviceClass;
+        typedef typename Traits::ButtonType ButtonType;
+        typedef typename Traits::ButtonTypeParam ButtonTypeParam;
+        static const OIS::Type OISDeviceValue = Traits::OISDeviceValue;
+
+    public:
+        //! Creates the OIS device
+        InputDeviceTemplated(unsigned int id, OIS::InputManager* oisInputManager)
+            : InputDevice(id)
+            , oisInputManager_(oisInputManager)
+        {
+            oisDevice_ = static_cast<OISDeviceClass*>(oisInputManager_->createInputObject(OISDeviceValue, true));
+            // Note: after the static_cast here, the casted this pointer becomes
+            //       invalid right until the subclass has been constructed!
+            oisDevice_->setEventCallback(static_cast<DeviceClass*>(this));
+            COUT(4) << "Instantiated a " << this->getClassName() << std::endl;
+        }
+
+        //! Destroys the OIS device
+        virtual ~InputDeviceTemplated()
+        {
+            try
+            {
+                oisInputManager_->destroyInputObject(oisDevice_);
+            }
+            catch (...)
+            {
+                COUT(1) << this->getClassName() << " destruction failed! Potential resource leak!" << std::endl;
+            }
+        }
+
+        //! Captures OIS events (which then get distributed to the derived class) and creates the button held events
+        void update(const Clock& time)
+        {
+            oisDevice_->capture();
+
+            // Call all the states with the held button event
+            for (unsigned int iB = 0; iB < pressedButtons_.size(); ++iB)
+                for (unsigned int iS = 0; iS < inputStates_.size(); ++iS)
+                    inputStates_[iS]->buttonEvent<ButtonEvent::THold, Traits>(
+                        this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(pressedButtons_[iB]));
+
+            // Call states with device update events
+            for (unsigned int i = 0; i < inputStates_.size(); ++i)
+                inputStates_[i]->update(time.getDeltaTime(), this->getDeviceID());
+
+            static_cast<DeviceClass*>(this)->updateImpl(time);
+        }
+
+        //! Clears the list of pressed buttons and calls the derived class's method
+        void clearBuffers()
+        {
+            pressedButtons_.clear();
+            static_cast<DeviceClass*>(this)->clearBuffersImpl();
+        }
+
+        // Returns a pointer to the OIS device
+        OISDeviceClass* getOISDevice()   { return this->oisDevice_; }
+        // Returns the name of the derived class as string
+        std::string getClassName() const { return DeviceClass::getClassNameImpl(); }
+
+    protected:
+        //! Common code for all button pressed events (updates pressed buttons list and calls the input states)
+        FORCEINLINE void buttonPressed(ButtonTypeParam button)
+        {
+            // check whether the button already is in the list (can happen when focus was lost)
+            unsigned int iButton = 0;
+            while (iButton < pressedButtons_.size() && pressedButtons_[iButton] != button)
+                iButton++;
+            if (iButton == pressedButtons_.size())
+                pressedButtons_.push_back(button);
+            else
+                return; // Button already pressed
+
+            // Call states
+            for (unsigned int i = 0; i < inputStates_.size(); ++i)
+                inputStates_[i]->buttonEvent<ButtonEvent::TPress, Traits>(this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(button));
+        }
+
+        //! Common code for all button released events (updates pressed buttons list and calls the input states)
+        FORCEINLINE void buttonReleased(ButtonTypeParam button)
+        {
+            // remove the button from the pressedButtons_ list
+            for (unsigned int iButton = 0; iButton < pressedButtons_.size(); iButton++)
+            {
+                if (pressedButtons_[iButton] == button)
+                {
+                    pressedButtons_.erase(pressedButtons_.begin() + iButton);
+                    break;
+                }
+            }
+
+            // Call states
+            for (unsigned int i = 0; i < inputStates_.size(); ++i)
+                inputStates_[i]->buttonEvent<ButtonEvent::TRelease, Traits>(this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(button));
+        }
+
+        //! Managed pointer to the OIS device
+        OISDeviceClass* oisDevice_;
+
+    private:
+        //!< Fallback dummy function for static polymorphism
+        void clearBuffersImpl() { }
+        //!< Fallback dummy function for static polymorphism
+        void updateImpl(const Clock& time) { }
+        //!< Fallback dummy function for static polymorphism
+        ButtonType& getButtonEventArg(ButtonType& button) { return button; }
+
+        std::vector<ButtonType> pressedButtons_; //!< List of all buttons that are currently pressed down
+        OIS::InputManager* oisInputManager_;     //!< Pointer to the OIS InputManager that can create and destroy devices
+    };
+}
+
+#endif /* _InputDevice_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputHandler.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputHandler.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputHandler.h	(revision 5712)
@@ -0,0 +1,148 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _InputHandler_H__
+#define _InputHandler_H__
+
+#include "InputPrereqs.h"
+#include "util/Math.h"
+
+namespace orxonox
+{
+    namespace ButtonEvent
+    {
+        //! Helper enum to deploy events with the help of templates
+        enum Value
+        {
+            Press,
+            Release,
+            Hold
+        };
+
+        //! Enables function overloading with integer values
+        template <ButtonEvent::Value Event>
+        struct EnumToType { };
+        typedef EnumToType<Press>   TPress;
+        typedef EnumToType<Release> TRelease;
+        typedef EnumToType<Hold>    THold;
+    }
+
+    namespace KeyboardModifier
+    {
+        //! Keyboard modifiers (shift, ctrl and alt)
+        enum Enum
+        {
+            Shift = 0x0000001,
+            Ctrl  = 0x0000010,
+            Alt   = 0x0000100
+        };
+    }
+
+    //! Event argument for key events
+    class _CoreExport KeyEvent
+    {
+    public:
+        KeyEvent(const OIS::KeyEvent& evt)
+            : key_(static_cast<KeyCode::ByEnum>(evt.key))
+            , text_(evt.text)
+            , modifiers_(0)
+        { }
+        bool operator==(const KeyEvent& rhs) const
+            { return rhs.key_ == key_; }
+        bool operator!=(const KeyEvent& rhs) const
+            { return rhs.key_ != key_; }
+        void setModifiers(int modifiers)
+            { modifiers_ = modifiers; }
+
+        bool isModifierDown(KeyboardModifier::Enum modifier) const
+            { return static_cast<KeyboardModifier::Enum>(modifier & modifiers_); }
+        KeyCode::ByEnum getKeyCode() const
+            { return key_; }
+        unsigned int getText() const { return text_; }
+
+    private:
+        KeyCode::ByEnum key_;
+        unsigned int text_;
+        int modifiers_;
+    };
+
+    /**
+    @brief
+        Base class for all input handlers like KeyBinder, InputBuffer, etc.
+
+        Derive from this class if you wish to receive input events.
+        But keep in mind that this is pointless wihtout first having an InputState.
+    @note
+        The definitions for the button events with the weird arguments are simply
+        to avoid redunant code in the input devices.
+    */
+    class _CoreExport InputHandler
+    {
+    public:
+        virtual ~InputHandler() { }
+
+        template<class T> void buttonEvent(unsigned int device, const T& button, ButtonEvent::TPress)
+            { this->buttonPressed(button); }
+        template<class T> void buttonEvent(unsigned int device, const T& button, ButtonEvent::TRelease)
+            { this->buttonReleased(button); }
+        template<class T> void buttonEvent(unsigned int device, const T& button, ButtonEvent::THold)
+            { this->buttonHeld(button); }
+        void buttonEvent(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::TPress)
+            { this->buttonPressed(device - InputDeviceEnumerator::FirstJoyStick, button); }
+        void buttonEvent(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::TRelease)
+            { this->buttonReleased(device - InputDeviceEnumerator::FirstJoyStick, button); }
+        void buttonEvent(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::THold)
+            { this->buttonHeld(device - InputDeviceEnumerator::FirstJoyStick, button); }
+
+        virtual void buttonPressed (const KeyEvent& evt) { }
+        virtual void buttonReleased(const KeyEvent& evt) { }
+        virtual void buttonHeld    (const KeyEvent& evt) { }
+
+        virtual void buttonPressed (MouseButtonCode::ByEnum button) { }
+        virtual void buttonReleased(MouseButtonCode::ByEnum button) { }
+        virtual void buttonHeld    (MouseButtonCode::ByEnum button) { }
+        virtual void mouseMoved    (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize) { }
+        virtual void mouseScrolled (int abs, int rel) { }
+
+        virtual void buttonPressed (unsigned int joyStick, JoyStickButtonCode::ByEnum button) { }
+        virtual void buttonReleased(unsigned int joyStick, JoyStickButtonCode::ByEnum button) { }
+        virtual void buttonHeld    (unsigned int joyStick, JoyStickButtonCode::ByEnum button) { }
+        virtual void axisMoved     (unsigned int joyStick, unsigned int axis, float value){ }
+
+        virtual void keyboardUpdated(float dt) { }
+        virtual void mouseUpdated   (float dt) { }
+        virtual void joyStickUpdated(unsigned int joyStick, float dt) { }
+
+        virtual void allDevicesUpdated(float dt) { }
+
+        //! Use this input handler if you want to occupy a device in an input state.
+        static InputHandler EMPTY;
+    };
+}
+
+#endif /* _InputHandler_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputManager.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputManager.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputManager.cc	(revision 5712)
@@ -0,0 +1,724 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the InputManager and a static variable from the InputHandler.
+*/
+
+#include "InputManager.h"
+
+#include <cassert>
+#include <climits>
+#include <ois/OISException.h>
+#include <ois/OISInputManager.h>
+#include <boost/foreach.hpp>
+
+#include "util/Convert.h"
+#include "util/Exception.h"
+#include "util/ScopeGuard.h"
+#include "core/Clock.h"
+#include "core/CoreIncludes.h"
+#include "core/ConfigValueIncludes.h"
+#include "core/ConsoleCommand.h"
+#include "core/CommandLine.h"
+#include "core/Functor.h"
+#include "core/GraphicsManager.h"
+
+#include "InputBuffer.h"
+#include "KeyDetector.h"
+#include "JoyStick.h"
+#include "JoyStickQuantityListener.h"
+#include "Mouse.h"
+#include "Keyboard.h"
+
+namespace orxonox
+{
+    SetCommandLineSwitch(keyboard_no_grab).information("Whether not to exclusively grab the keyboard");
+
+    // Abuse of this source file for the InputHandler
+    InputHandler InputHandler::EMPTY;
+
+    InputManager* InputManager::singletonPtr_s = 0;
+
+    //! Defines the |= operator for easier use.
+    inline InputManager::State operator|=(InputManager::State& lval, InputManager::State rval)
+    {
+        return (lval = (InputManager::State)(lval | rval));
+    }
+
+    //! Defines the &= operator for easier use.
+    inline InputManager::State operator&=(InputManager::State& lval, int rval)
+    {
+        return (lval = (InputManager::State)(lval & rval));
+    }
+
+    // ############################################################
+    // #####                  Initialisation                  #####
+    // ##########                                        ##########
+    // ############################################################
+    InputManager::InputManager()
+        : internalState_(Bad)
+        , oisInputManager_(0)
+        , devices_(2)
+        , bExclusiveMouse_(false)
+        , emptyState_(0)
+        , keyDetector_(0)
+        , calibratorCallbackHandler_(0)
+    {
+        RegisterRootObject(InputManager);
+
+        CCOUT(4) << "Constructing..." << std::endl;
+
+        this->setConfigValues();
+
+        this->loadDevices();
+
+        // Lowest priority empty InputState
+        emptyState_ = createInputState("empty", false, false, InputStatePriority::Empty);
+        emptyState_->setHandler(&InputHandler::EMPTY);
+        activeStates_[emptyState_->getPriority()] = emptyState_;
+
+        // KeyDetector to evaluate a pressed key's name
+        InputState* detector = createInputState("detector", false, false, InputStatePriority::Detector);
+        // Create a callback to avoid buttonHeld events after the key has been detected
+        FunctorMember<InputManager>* bufferFunctor = createFunctor(&InputManager::clearBuffers);
+        bufferFunctor->setObject(this);
+        detector->setLeaveFunctor(bufferFunctor);
+        keyDetector_ = new KeyDetector();
+        detector->setHandler(keyDetector_);
+
+        // Joy stick calibration helper callback
+        InputState* calibrator = createInputState("calibrator", false, false, InputStatePriority::Calibrator);
+        calibrator->setHandler(&InputHandler::EMPTY);
+        calibratorCallbackHandler_ = new InputBuffer();
+        calibratorCallbackHandler_->registerListener(this, &InputManager::stopCalibration, '\r', true);
+        calibrator->setKeyHandler(calibratorCallbackHandler_);
+
+        this->updateActiveStates();
+
+        {
+            // calibrate console command
+            FunctorMember<InputManager>* functor = createFunctor(&InputManager::calibrate);
+            functor->setObject(this);
+            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "calibrate"), true);
+        }
+        {
+            // reload console command
+            FunctorMember<InputManager>* functor = createFunctor(&InputManager::reload);
+            functor->setObject(this);
+            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "reload"), false);
+        }
+
+        CCOUT(4) << "Construction complete." << std::endl;
+        internalState_ = Nothing;
+    }
+
+    void InputManager::setConfigValues()
+    {
+    }
+
+    /**
+    @brief
+        Creates the OIS::InputMananger, the keyboard, the mouse and
+        the joys ticks. If either of the first two fail, this method throws an exception.
+    @param windowWidth
+        The width of the render window
+    @param windowHeight
+        The height of the render window
+    */
+    void InputManager::loadDevices()
+    {
+        CCOUT(4) << "Loading input devices..." << std::endl;
+
+        // When loading the devices they should not already be loaded
+        assert(internalState_ & Bad);
+        assert(devices_[InputDeviceEnumerator::Mouse] == 0);
+        assert(devices_[InputDeviceEnumerator::Keyboard] == 0);
+        assert(devices_.size() == InputDeviceEnumerator::FirstJoyStick);
+
+        // Fill parameter list
+        OIS::ParamList paramList;
+        size_t windowHnd = GraphicsManager::getInstance().getRenderWindowHandle();
+        paramList.insert(std::make_pair("WINDOW", multi_cast<std::string>(windowHnd)));
+#if defined(ORXONOX_PLATFORM_WINDOWS)
+        paramList.insert(std::make_pair("w32_keyboard", "DISCL_NONEXCLUSIVE"));
+        paramList.insert(std::make_pair("w32_keyboard", "DISCL_FOREGROUND"));
+        paramList.insert(std::make_pair("w32_mouse", "DISCL_FOREGROUND"));
+        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
+        {
+            // Disable Windows key plus special keys (like play, stop, next, etc.)
+            paramList.insert(std::make_pair("w32_keyboard", "DISCL_NOWINKEY"));
+            paramList.insert(std::make_pair("w32_mouse", "DISCL_EXCLUSIVE"));
+        }
+        else
+            paramList.insert(std::make_pair("w32_mouse", "DISCL_NONEXCLUSIVE"));
+#elif defined(ORXONOX_PLATFORM_LINUX)
+        // Enabling this is probably a bad idea, but whenever orxonox crashes, the setting stays on
+        // Trouble might be that the Pressed event occurs a bit too often...
+        paramList.insert(std::make_pair("XAutoRepeatOn", "true"));
+
+        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
+        {
+            if (CommandLine::getValue("keyboard_no_grab").getBool())
+                paramList.insert(std::make_pair("x11_keyboard_grab", "false"));
+            else
+                paramList.insert(std::make_pair("x11_keyboard_grab", "true"));
+            paramList.insert(std::make_pair("x11_mouse_grab",  "true"));
+            paramList.insert(std::make_pair("x11_mouse_hide", "true"));
+        }
+        else
+        {
+            paramList.insert(std::make_pair("x11_keyboard_grab", "false"));
+            paramList.insert(std::make_pair("x11_mouse_grab",  "false"));
+            paramList.insert(std::make_pair("x11_mouse_hide", "false"));
+        }
+#endif
+
+        try
+        {
+            oisInputManager_ = OIS::InputManager::createInputSystem(paramList);
+            // Exception-safety
+            Loki::ScopeGuard guard = Loki::MakeGuard(OIS::InputManager::destroyInputSystem, oisInputManager_);
+            CCOUT(ORX_DEBUG) << "Created OIS input manager." << std::endl;
+
+            if (oisInputManager_->getNumberOfDevices(OIS::OISKeyboard) > 0)
+                devices_[InputDeviceEnumerator::Keyboard] = new Keyboard(InputDeviceEnumerator::Keyboard, oisInputManager_);
+            else
+                ThrowException(InitialisationFailed, "InputManager: No keyboard found, cannot proceed!");
+
+            // Successful initialisation
+            guard.Dismiss();
+        }
+        catch (const std::exception& ex)
+        {
+            oisInputManager_ = NULL;
+            internalState_ |= Bad;
+            ThrowException(InitialisationFailed, "Could not initialise the input system: " << ex.what());
+        }
+
+        this->loadMouse();
+        this->loadJoySticks();
+
+        // Reorder states in case some joy sticks were added/removed
+        this->updateActiveStates();
+
+        CCOUT(4) << "Input devices loaded." << std::endl;
+    }
+
+    //! Creates a new orxonox::Mouse
+    void InputManager::loadMouse()
+    {
+        if (oisInputManager_->getNumberOfDevices(OIS::OISMouse) > 0)
+        {
+            try
+            {
+                devices_[InputDeviceEnumerator::Mouse] = new Mouse(InputDeviceEnumerator::Mouse, oisInputManager_);
+            }
+            catch (const std::exception& ex)
+            {
+                CCOUT(2) << "Warning: Failed to create Mouse:" << ex.what() << std::endl
+                         << "Proceeding without mouse support." << std::endl;
+            }
+        }
+        else
+            CCOUT(ORX_WARNING) << "Warning: No mouse found! Proceeding without mouse support." << std::endl;
+    }
+
+    //! Creates as many joy sticks as are available.
+    void InputManager::loadJoySticks()
+    {
+        for (int i = 0; i < oisInputManager_->getNumberOfDevices(OIS::OISJoyStick); i++)
+        {
+            try
+            {
+                devices_.push_back(new JoyStick(InputDeviceEnumerator::FirstJoyStick + i, oisInputManager_));
+            }
+            catch (const std::exception& ex)
+            {
+                CCOUT(2) << "Warning: Failed to create joy stick: " << ex.what() << std::endl;
+            }
+        }
+
+        // inform all JoyStick Device Number Listeners
+        std::vector<JoyStick*> joyStickList;
+        for (unsigned int i = InputDeviceEnumerator::FirstJoyStick; i < devices_.size(); ++i)
+            joyStickList.push_back(static_cast<JoyStick*>(devices_[i]));
+        JoyStickQuantityListener::changeJoyStickQuantity(joyStickList);
+    }
+
+    void InputManager::setKeyDetectorCallback(const std::string& command)
+    {
+        this->keyDetector_->setCallbackCommand(command);
+    }
+
+    // ############################################################
+    // #####                    Destruction                   #####
+    // ##########                                        ##########
+    // ############################################################
+
+    InputManager::~InputManager()
+    {
+        CCOUT(3) << "Destroying..." << std::endl;
+
+        // Destroy calibrator helper handler and state
+        delete keyDetector_;
+        this->destroyState("calibrator");
+        // Destroy KeyDetector and state
+        delete calibratorCallbackHandler_;
+        this->destroyState("detector");
+        // destroy the empty InputState
+        this->destroyStateInternal(this->emptyState_);
+
+        // destroy all user InputStates
+        while (statesByName_.size() > 0)
+            this->destroyStateInternal((*statesByName_.rbegin()).second);
+
+        if (!(internalState_ & Bad))
+            this->destroyDevices();
+
+        CCOUT(3) << "Destruction complete." << std::endl;
+    }
+
+    /**
+    @brief
+        Destoys all input devices (joy sticks, mouse, keyboard and OIS::InputManager)
+    @throw
+        Method does not throw
+    */
+    void InputManager::destroyDevices()
+    {
+        CCOUT(4) << "Destroying devices..." << std::endl;
+
+        BOOST_FOREACH(InputDevice*& device, devices_)
+        {
+            if (device == NULL)
+                continue;
+            std::string className = device->getClassName();
+            try
+            {
+                delete device;
+                device = 0;
+                CCOUT(4) << className << " destroyed." << std::endl;
+            }
+            catch (...)
+            {
+                CCOUT(1) << className << " destruction failed! Potential resource leak!" << std::endl;
+            }
+        }
+        devices_.resize(InputDeviceEnumerator::FirstJoyStick);
+
+        assert(oisInputManager_ != NULL);
+        try
+        {
+            OIS::InputManager::destroyInputSystem(oisInputManager_);
+        }
+        catch (...)
+        {
+            CCOUT(1) << "OIS::InputManager destruction failed! Potential resource leak!" << std::endl;
+        }
+        oisInputManager_ = NULL;
+
+        internalState_ |= Bad;
+        CCOUT(4) << "Destroyed devices." << std::endl;
+    }
+
+    // ############################################################
+    // #####                     Reloading                    #####
+    // ##########                                        ##########
+    // ############################################################
+
+    void InputManager::reload()
+    {
+        if (internalState_ & Ticking)
+        {
+            // We cannot destroy OIS right now, because reload was probably
+            // caused by a user clicking on a GUI item. The stack trace would then
+            // include an OIS method. So it would be a very bad thing to destroy it..
+            internalState_ |= ReloadRequest;
+        }
+        else if (internalState_ & Calibrating)
+            CCOUT(2) << "Warning: Cannot reload input system. Joy sticks are currently being calibrated." << std::endl;
+        else
+            reloadInternal();
+    }
+
+    //! Internal reload method. Destroys the OIS devices and loads them again.
+    void InputManager::reloadInternal()
+    {
+        CCOUT(3) << "Reloading ..." << std::endl;
+
+        this->destroyDevices();
+        this->loadDevices();
+
+        internalState_ &= ~Bad;
+        internalState_ &= ~ReloadRequest;
+        CCOUT(4) << "Reloading complete." << std::endl;
+    }
+
+    // ############################################################
+    // #####                  Runtime Methods                 #####
+    // ##########                                        ##########
+    // ############################################################
+
+    void InputManager::update(const Clock& time)
+    {
+        if (internalState_ & Bad)
+            ThrowException(General, "InputManager was not correctly reloaded.");
+
+        else if (internalState_ & ReloadRequest)
+            reloadInternal();
+
+        // check for states to leave
+        if (!stateLeaveRequests_.empty())
+        {
+            for (std::set<InputState*>::iterator it = stateLeaveRequests_.begin();
+                it != stateLeaveRequests_.end(); ++it)
+            {
+                (*it)->left();
+                // just to be sure that the state actually is registered
+                assert(statesByName_.find((*it)->getName()) != statesByName_.end());
+
+                activeStates_.erase((*it)->getPriority());
+                if ((*it)->getPriority() < InputStatePriority::HighPriority)
+                    (*it)->setPriority(0);
+                updateActiveStates();
+            }
+            stateLeaveRequests_.clear();
+        }
+
+        // check for states to enter
+        if (!stateEnterRequests_.empty())
+        {
+            for (std::set<InputState*>::const_iterator it = stateEnterRequests_.begin();
+                it != stateEnterRequests_.end(); ++it)
+            {
+                // just to be sure that the state actually is registered
+                assert(statesByName_.find((*it)->getName()) != statesByName_.end());
+
+                if ((*it)->getPriority() == 0)
+                {
+                    // Get smallest possible priority between 1 and maxStateStackSize_s
+                    for(std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin();
+                        rit != activeStates_.rend(); ++rit)
+                    {
+                        if (rit->first < InputStatePriority::HighPriority)
+                        {
+                            (*it)->setPriority(rit->first + 1);
+                            break;
+                        }
+                    }
+                    // In case no normal handler was on the stack
+                    if ((*it)->getPriority() == 0)
+                        (*it)->setPriority(1);
+                }
+                activeStates_[(*it)->getPriority()] = (*it);
+                updateActiveStates();
+                (*it)->entered();
+            }
+            stateEnterRequests_.clear();
+        }
+
+        // check for states to destroy
+        if (!stateDestroyRequests_.empty())
+        {
+            for (std::set<InputState*>::iterator it = stateDestroyRequests_.begin();
+                it != stateDestroyRequests_.end(); ++it)
+            {
+                destroyStateInternal((*it));
+            }
+            stateDestroyRequests_.clear();
+        }
+
+        // check whether a state has changed its EMPTY situation
+        bool bUpdateRequired = false;
+        for (std::map<int, InputState*>::iterator it = activeStates_.begin(); it != activeStates_.end(); ++it)
+        {
+            if (it->second->hasExpired())
+            {
+                it->second->resetExpiration();
+                bUpdateRequired = true;
+            }
+        }
+        if (bUpdateRequired)
+            updateActiveStates();
+
+        // mark that we now start capturing and distributing input
+        internalState_ |= Ticking;
+
+        // Capture all the input and handle it
+        BOOST_FOREACH(InputDevice* device, devices_)
+            if (device != NULL)
+                device->update(time);
+
+        // Update the states
+        for (unsigned int i = 0; i < activeStatesTicked_.size(); ++i)
+            activeStatesTicked_[i]->update(time.getDeltaTime());
+
+        internalState_ &= ~Ticking;
+    }
+
+    /**
+    @brief
+        Updates the currently active states (according to activeStates_) for each device.
+        Also, a list of all active states (no duplicates!) is compiled for the general update().
+    */
+    void InputManager::updateActiveStates()
+    {
+        assert((internalState_ & InputManager::Ticking) == 0);
+        // temporary resize
+        for (unsigned int i = 0; i < devices_.size(); ++i)
+        {
+            if (devices_[i] == NULL)
+                continue;
+            std::vector<InputState*>& states = devices_[i]->getStateListRef();
+            bool occupied = false;
+            states.clear();
+            for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin(); rit != activeStates_.rend(); ++rit)
+            {
+                if (rit->second->isInputDeviceEnabled(i) && (!occupied || rit->second->bAlwaysGetsInput_))
+                {
+                    states.push_back(rit->second);
+                    if (!rit->second->bTransparent_)
+                        occupied = true;
+                }
+            }
+        }
+
+        // update tickables (every state will only appear once)
+        // Using a std::set to avoid duplicates
+        std::set<InputState*> tempSet;
+        for (unsigned int i = 0; i < devices_.size(); ++i)
+            if (devices_[i] != NULL)
+                for (unsigned int iState = 0; iState < devices_[i]->getStateListRef().size(); ++iState)
+                    tempSet.insert(devices_[i]->getStateListRef()[iState]);
+
+        // copy the content of the std::set back to the actual vector
+        activeStatesTicked_.clear();
+        for (std::set<InputState*>::const_iterator it = tempSet.begin();it != tempSet.end(); ++it)
+            activeStatesTicked_.push_back(*it);
+
+        // Check whether we have to change the mouse mode
+        std::vector<InputState*>& mouseStates = devices_[InputDeviceEnumerator::Mouse]->getStateListRef();
+        if (mouseStates.empty() && bExclusiveMouse_ ||
+            !mouseStates.empty() && mouseStates.front()->getIsExclusiveMouse() != bExclusiveMouse_)
+        {
+            bExclusiveMouse_ = !bExclusiveMouse_;
+            if (!GraphicsManager::getInstance().isFullScreen())
+                this->reloadInternal();
+        }
+    }
+
+    void InputManager::clearBuffers()
+    {
+        BOOST_FOREACH(InputDevice* device, devices_)
+            if (device != NULL)
+                device->clearBuffers();
+    }
+
+    void InputManager::calibrate()
+    {
+        COUT(0) << "Move all joy stick axes fully in all directions." << std::endl
+                << "When done, put the axex in the middle position and press enter." << std::endl;
+
+        BOOST_FOREACH(InputDevice* device, devices_)
+            if (device != NULL)
+                device->startCalibration();
+
+        internalState_ |= Calibrating;
+        enterState("calibrator");
+    }
+
+    //! Tells all devices to stop the calibration and evaluate it. Buffers are being cleared as well!
+    void InputManager::stopCalibration()
+    {
+        BOOST_FOREACH(InputDevice* device, devices_)
+            if (device != NULL)
+                device->stopCalibration();
+
+        // restore old input state
+        leaveState("calibrator");
+        internalState_ &= ~Calibrating;
+        // Clear buffers to prevent button hold events
+        this->clearBuffers();
+
+        COUT(0) << "Calibration has been stored." << std::endl;
+    }
+
+    //! Gets called by WindowEventListener upon focus change --> clear buffers 
+    void InputManager::windowFocusChanged()
+    {
+        this->clearBuffers();
+    }
+
+    std::pair<int, int> InputManager::getMousePosition() const
+    {
+        Mouse* mouse = static_cast<Mouse*>(devices_[InputDeviceEnumerator::Mouse]);
+        if (mouse != NULL)
+        {
+            const OIS::MouseState state = mouse->getOISDevice()->getMouseState();
+            return std::make_pair(state.X.abs, state.Y.abs);
+        }
+        else
+            return std::make_pair(0, 0);
+    }
+
+    // ############################################################
+    // #####                    Input States                  #####
+    // ##########                                        ##########
+    // ############################################################
+
+    InputState* InputManager::createInputState(const std::string& name, bool bAlwaysGetsInput, bool bTransparent, InputStatePriority priority)
+    {
+        if (name == "")
+            return 0;
+        if (statesByName_.find(name) == statesByName_.end())
+        {
+            if (priority >= InputStatePriority::HighPriority || priority == InputStatePriority::Empty)
+            {
+                // Make sure we don't add two high priority states with the same priority
+                for (std::map<std::string, InputState*>::const_iterator it = this->statesByName_.begin();
+                    it != this->statesByName_.end(); ++it)
+                {
+                    if (it->second->getPriority() == priority)
+                    {
+                        COUT(2) << "Warning: Could not add an InputState with the same priority '"
+                            << static_cast<int>(priority) << "' != 0." << std::endl;
+                        return 0;
+                    }
+                }
+            }
+            InputState* state = new InputState(name, bAlwaysGetsInput, bTransparent, priority);
+            statesByName_[name] = state;
+
+            return state;
+        }
+        else
+        {
+            COUT(2) << "Warning: Could not add an InputState with the same name '" << name << "'." << std::endl;
+            return 0;
+        }
+    }
+
+    InputState* InputManager::getState(const std::string& name)
+    {
+        std::map<std::string, InputState*>::iterator it = statesByName_.find(name);
+        if (it != statesByName_.end())
+            return it->second;
+        else
+            return 0;
+    }
+
+    bool InputManager::enterState(const std::string& name)
+    {
+        // get pointer from the map with all stored handlers
+        std::map<std::string, InputState*>::const_iterator it = statesByName_.find(name);
+        if (it != statesByName_.end())
+        {
+            // exists
+            if (activeStates_.find(it->second->getPriority()) == activeStates_.end())
+            {
+                // not active
+                if (stateDestroyRequests_.find(it->second) == stateDestroyRequests_.end())
+                {
+                    // not scheduled for destruction
+                    // prevents a state being added multiple times
+                    stateEnterRequests_.insert(it->second);
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    bool InputManager::leaveState(const std::string& name)
+    {
+        if (name == "empty")
+        {
+            COUT(2) << "InputManager: Leaving the empty state is not allowed!" << std::endl;
+            return false;
+        }
+        // get pointer from the map with all stored handlers
+        std::map<std::string, InputState*>::const_iterator it = statesByName_.find(name);
+        if (it != statesByName_.end())
+        {
+            // exists
+            if (activeStates_.find(it->second->getPriority()) != activeStates_.end())
+            {
+                // active
+                stateLeaveRequests_.insert(it->second);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    bool InputManager::destroyState(const std::string& name)
+    {
+        if (name == "empty")
+        {
+            COUT(2) << "InputManager: Removing the empty state is not allowed!" << std::endl;
+            return false;
+        }
+        std::map<std::string, InputState*>::iterator it = statesByName_.find(name);
+        if (it != statesByName_.end())
+        {
+            if (activeStates_.find(it->second->getPriority()) != activeStates_.end())
+            {
+                // The state is still active. We have to postpone
+                stateLeaveRequests_.insert(it->second);
+                stateDestroyRequests_.insert(it->second);
+            }
+            else if (this->internalState_ & Ticking)
+            {
+                // cannot remove state while ticking
+                stateDestroyRequests_.insert(it->second);
+            }
+            else
+                destroyStateInternal(it->second);
+
+            return true;
+        }
+        return false;
+    }
+
+    //! Destroys an InputState internally.
+    void InputManager::destroyStateInternal(InputState* state)
+    {
+        assert(state && !(this->internalState_ & Ticking));
+        std::map<int, InputState*>::iterator it = this->activeStates_.find(state->getPriority());
+        if (it != this->activeStates_.end())
+        {
+            this->activeStates_.erase(it);
+            updateActiveStates();
+        }
+        statesByName_.erase(state->getName());
+        delete state;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/InputManager.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputManager.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputManager.h	(revision 5712)
@@ -0,0 +1,215 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _InputManager_H__
+#define _InputManager_H__
+
+#include "InputPrereqs.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "util/Singleton.h"
+#include "core/WindowEventListener.h"
+#include "InputState.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Manages the input devices (mouse, keyboard, joy sticks) and the input states.
+
+        Every input device has its own wrapper class which does the actualy input event
+        distribution. The InputManager only creates reloads (on request) those devices.
+
+        The other functionality concerns handling InputStates. They act as a layer
+        between InputHandlers (like the KeyBinder or the GUIManager) and InputDevices.
+        InputStates are memory managed by the IputManager. You cannot create or destroy
+        them on your own. Therefore all states get destroyed with the InputManager d'tor.
+    @note
+        - The actual lists containing all the InputStates for a specific device are stored
+          in the InputDevices themselves.
+        - The devices_ vector always has at least two elements: Keyboard (first) and mouse.
+          You best access them intenally with InputDeviceEnumerator::Keyboard/Mouse
+          The first joy stick is accessed with InputDeviceEnumerator::FirstJoyStick.
+        - Keyboard construction is mandatory , mouse and joy sticks are not.
+          If the OIS::InputManager or the Keyboard fail, an exception is thrown.
+    */
+    class _CoreExport InputManager : public Singleton<InputManager>, public WindowEventListener
+    {
+        friend class Singleton<InputManager>;
+    public:
+        //! Represents internal states of the InputManager.
+        enum State
+        {
+            Nothing       = 0x00,
+            Bad           = 0x02,
+            Ticking       = 0x04,
+            Calibrating   = 0x08,
+            ReloadRequest = 0x10,
+        };
+
+        /**
+        @brief
+            Loads the devices and initialises the KeyDetector and the Calibrator.
+            
+            If either the OIS input system and/or the keyboard could not be created,
+            the constructor fails with an std::exception.
+        */
+        InputManager();
+        //! Destroys all devices AND all input states!
+        ~InputManager();
+        void setConfigValues();
+
+        /**
+        @brief
+            Updates the devices (which distribute the input events) and the input states.
+
+            Any InpuStates changes (destroy, enter, leave) and happens here. If a reload request
+            was submitted while updating, the request wil be postponed until the next update call.
+        */
+        void update(const Clock& time);
+        //! Clears all input device buffers. This usually only includes the pressed button list.
+        void clearBuffers();
+        //! Starts joy stick calibration.
+        void calibrate();
+        /**
+        @brief
+            Reloads all the input devices. Use this method to initialise new joy sticks.
+        @note
+            Only reloads immediately if the call stack doesn't include the update() method.
+        */
+        void reload();
+
+        //-------------------------------
+        // Input States
+        //-------------------------------
+        /**
+        @brief
+            Creates a new InputState that gets managed by the InputManager.
+        @remarks
+            The InputManager will take care of the state completely. That also
+            means it gets deleted when the InputManager is destroyed!
+        @param name
+            Unique name of the InputState when referenced as string
+        @param priority
+            Priority matters when multiple states are active. You can specify any
+            number, but 1 - 99 is preferred (99 means high priority).
+        */
+        InputState* createInputState(const std::string& name, bool bAlwaysGetsInput = false, bool bTransparent = false, InputStatePriority priority = InputStatePriority::Dynamic);
+        /**
+        @brief
+            Returns a pointer to a InputState referenced by name.
+        @return
+            Returns NULL if state was not found.
+        */
+        InputState* getState(const std::string& name);
+        /**
+        @brief
+            Activates a specific input state.
+            It might not be actually activated if the priority is too low!
+        @return
+            False if name was not found, true otherwise.
+        */
+        bool enterState(const std::string& name);
+        /**
+        @brief
+            Deactivates a specific input state.
+        @return
+            False if name was not found, true otherwise.
+        */
+        bool leaveState(const std::string& name);
+        /**
+        @brief
+            Removes and destroys an input state.
+        @return
+            True if removal was successful, false if name was not found.
+        @remarks
+            - You can't remove the internal states "empty", "calibrator" and "detector".
+            - The removal process is being postponed if InputManager::update() is currently running.
+        */
+        bool destroyState(const std::string& name);
+
+        //-------------------------------
+        // Various getters and setters
+        //-------------------------------
+        //! Sets the the name of the command used by the KeyDetector as callback.
+        void setKeyDetectorCallback(const std::string& command);
+        //! Returns the number of joy stick that have been created since the c'tor or last call to reload().
+        unsigned int getJoyStickQuantity() const
+            { return devices_.size() - InputDeviceEnumerator::FirstJoyStick; }
+        //! Returns a pointer to the OIS InputManager. Only you if you know what you're doing!
+        OIS::InputManager* getOISInputManager() { return this->oisInputManager_; }
+        std::pair<int, int> getMousePosition() const;
+
+    private: // functions
+        // don't mess with a Singleton
+        InputManager(const InputManager&);
+
+        // Intenal methods
+        void loadDevices();
+        void loadMouse();
+        void loadJoySticks();
+        void destroyDevices();
+
+        void stopCalibration();
+        void reloadInternal();
+
+        void destroyStateInternal(InputState* state);
+        void updateActiveStates();
+
+        // From WindowEventListener
+        void windowFocusChanged();
+
+    private: // variables
+        State                               internalState_;        //!< Current internal state
+        OIS::InputManager*                  oisInputManager_;      //!< OIS input manager
+        std::vector<InputDevice*>           devices_;              //!< List of all input devices (keyboard, mouse, joy sticks)
+        bool                                bExclusiveMouse_;      //!< Currently applied mouse mode
+
+        // some internally handled states and handlers
+        InputState*                         emptyState_;           //!< Lowest priority states (makes handling easier)
+        KeyDetector*                        keyDetector_;          //!< KeyDetector instance
+        //! InputBuffer that reacts to the Enter key when calibrating the joy sticks
+        InputBuffer*                        calibratorCallbackHandler_;
+
+        std::map<std::string, InputState*>  statesByName_;         //!< Contains all the created input states by name
+        std::map<int, InputState*>          activeStates_;         //!< Contains all active input states by priority (std::map is sorted!)
+        std::vector<InputState*>            activeStatesTicked_;   //!< Like activeStates_, but only contains the ones that currently receive events
+
+        std::set<InputState*>               stateEnterRequests_;   //!< Requests to enter a new state
+        std::set<InputState*>               stateLeaveRequests_;   //!< Requests to leave a running state
+        std::set<InputState*>               stateDestroyRequests_; //!< Requests to destroy a state
+
+        static InputManager*                singletonPtr_s;        //!< Pointer reference to the singleton
+    };
+}
+
+#endif /* _InputManager_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputPrereqs.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputPrereqs.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputPrereqs.h	(revision 5712)
@@ -0,0 +1,452 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Declarations of all key/button/axis code enumeration and string literals
+    and an input device enumeration.
+*/
+
+#ifndef _InputPrereqs_H__
+#define _InputPrereqs_H__
+
+#include "core/CorePrereqs.h"
+
+#include <ois/OISKeyboard.h>
+#include <ois/OISMouse.h>
+#include <ois/OISJoyStick.h>
+
+namespace orxonox
+{
+    //-----------------------------------------------------------------------
+    // Code enumerations
+    //-----------------------------------------------------------------------
+
+    namespace KeyCode
+    {
+        const unsigned int numberOfKeys = 0xEE; // 238
+
+        //! Key codes as enumeration
+        enum ByEnum
+        {
+            Unassigned    = OIS::KC_UNASSIGNED,
+            Escape        = OIS::KC_ESCAPE,
+            NumRow1       = OIS::KC_1,
+            NumRow2       = OIS::KC_2,
+            NumRow3       = OIS::KC_3,
+            NumRow4       = OIS::KC_4,
+            NumRow5       = OIS::KC_5,
+            NumRow6       = OIS::KC_6,
+            NumRow7       = OIS::KC_7,
+            NumRow8       = OIS::KC_8,
+            NumRow9       = OIS::KC_9,
+            NumRow0       = OIS::KC_0,
+            Minus         = OIS::KC_MINUS,           // - on main keyboard
+            Equals        = OIS::KC_EQUALS,
+            Back          = OIS::KC_BACK,            // backspace
+            Tab           = OIS::KC_TAB,
+            Q             = OIS::KC_Q,
+            W             = OIS::KC_W,
+            E             = OIS::KC_E,
+            R             = OIS::KC_R,
+            T             = OIS::KC_T,
+            Y             = OIS::KC_Y,
+            U             = OIS::KC_U,
+            I             = OIS::KC_I,
+            O             = OIS::KC_O,
+            P             = OIS::KC_P,
+            LeftBracket   = OIS::KC_LBRACKET,
+            RightBracket  = OIS::KC_RBRACKET,
+            Return        = OIS::KC_RETURN,          // Enter on main keyboard
+            LeftControl   = OIS::KC_LCONTROL,
+            A             = OIS::KC_A,
+            S             = OIS::KC_S,
+            D             = OIS::KC_D,
+            F             = OIS::KC_F,
+            G             = OIS::KC_G,
+            H             = OIS::KC_H,
+            J             = OIS::KC_J,
+            K             = OIS::KC_K,
+            L             = OIS::KC_L,
+            Semicolon     = OIS::KC_SEMICOLON,
+            Apostrophe    = OIS::KC_APOSTROPHE,
+            Grave         = OIS::KC_GRAVE,           // accent
+            LeftShift     = OIS::KC_LSHIFT,
+            Backslash     = OIS::KC_BACKSLASH,
+            Z             = OIS::KC_Z,
+            X             = OIS::KC_X,
+            C             = OIS::KC_C,
+            V             = OIS::KC_V,
+            B             = OIS::KC_B,
+            N             = OIS::KC_N,
+            M             = OIS::KC_M,
+            Comma         = OIS::KC_COMMA,
+            Period        = OIS::KC_PERIOD,          // . on main keyboard
+            Slash         = OIS::KC_SLASH,           // / on main keyboard
+            RightShift    = OIS::KC_RSHIFT,
+            Multiply      = OIS::KC_MULTIPLY,        // * on numeric keypad
+            LeftAlt       = OIS::KC_LMENU,           // left Alt
+            Space         = OIS::KC_SPACE,
+            CapsLock      = OIS::KC_CAPITAL,
+            F1            = OIS::KC_F1,
+            F2            = OIS::KC_F2,
+            F3            = OIS::KC_F3,
+            F4            = OIS::KC_F4,
+            F5            = OIS::KC_F5,
+            F6            = OIS::KC_F6,
+            F7            = OIS::KC_F7,
+            F8            = OIS::KC_F8,
+            F9            = OIS::KC_F9,
+            F10           = OIS::KC_F10,
+            NumLock       = OIS::KC_NUMLOCK,
+            ScrollLock    = OIS::KC_SCROLL,          // Scroll Lock
+            Numpad7       = OIS::KC_NUMPAD7,
+            Numpad8       = OIS::KC_NUMPAD8,
+            Numpad9       = OIS::KC_NUMPAD9,
+            NumpadSubtract= OIS::KC_SUBTRACT,        // - on numeric keypad
+            Numpad4       = OIS::KC_NUMPAD4,
+            Numpad5       = OIS::KC_NUMPAD5,
+            Numpad6       = OIS::KC_NUMPAD6,
+            NumpadAdd     = OIS::KC_ADD,             // + on numeric keypad
+            Numpad1       = OIS::KC_NUMPAD1,
+            Numpad2       = OIS::KC_NUMPAD2,
+            Numpad3       = OIS::KC_NUMPAD3,
+            Numpad0       = OIS::KC_NUMPAD0,
+            NumpadPeriod  = OIS::KC_DECIMAL,         // . on numeric keypad
+            LessThan      = OIS::KC_OEM_102,         // < > | on UK/Germany keyboards
+            F11           = OIS::KC_F11,
+            F12           = OIS::KC_F12,
+            F13           = OIS::KC_F13,             //                     (NEC PC98)
+            F14           = OIS::KC_F14,             //                     (NEC PC98)
+            F15           = OIS::KC_F15,             //                     (NEC PC98)
+            Kana          = OIS::KC_KANA,            // (Japanese keyboard)
+            ABNT_C1       = OIS::KC_ABNT_C1,         // / ? on Portugese (Brazilian) keyboards
+            Convert       = OIS::KC_CONVERT,         // (Japanese keyboard)
+            NoConvert     = OIS::KC_NOCONVERT,       // (Japanese keyboard)
+            Yen           = OIS::KC_YEN,             // (Japanese keyboard)
+            ABNT_C2       = OIS::KC_ABNT_C2,         // Numpad . on Portugese (Brazilian) keyboards
+            NumpadEquals  = OIS::KC_NUMPADEQUALS,    // = on numeric keypad (NEC PC98)
+            PreviousTrack = OIS::KC_PREVTRACK,       // Previous Track (KC_CIRCUMFLEX on Japanese keyboard)
+            AT            = OIS::KC_AT,              //                     (NEC PC98)
+            Colon         = OIS::KC_COLON,           //                     (NEC PC98)
+            Underline     = OIS::KC_UNDERLINE,       //                     (NEC PC98)
+            Kanji         = OIS::KC_KANJI,           // (Japanese keyboard)
+            Stop          = OIS::KC_STOP,            //                     (NEC PC98)
+            AX            = OIS::KC_AX,              //                     (Japan AX)
+            Unlabeled     = OIS::KC_UNLABELED,       //                        (J3100)
+            NextTrack     = OIS::KC_NEXTTRACK,       // Next Track
+            NumpadEnter   = OIS::KC_NUMPADENTER,     // Enter on numeric keypad
+            RightControl  = OIS::KC_RCONTROL,
+            Mute          = OIS::KC_MUTE,            // Mute
+            Calculator    = OIS::KC_CALCULATOR,      // Calculator
+            PlayPause     = OIS::KC_PLAYPAUSE,       // Play / Pause
+            MediaStop     = OIS::KC_MEDIASTOP,       // Media Stop
+            VolumeDown    = OIS::KC_VOLUMEDOWN,      // Volume -
+            VolumeUp      = OIS::KC_VOLUMEUP,        // Volume +
+            WebHome       = OIS::KC_WEBHOME,         // Web home
+            NumpadComma   = OIS::KC_NUMPADCOMMA,     // , on numeric keypad (NEC PC98)
+            Divide        = OIS::KC_DIVIDE,          // / on numeric keypad
+            SystemRequest = OIS::KC_SYSRQ,
+            RightAlt      = OIS::KC_RMENU,           // right Alt
+            Pause         = OIS::KC_PAUSE,           // Pause
+            Home          = OIS::KC_HOME,            // Home on arrow keypad
+            Up            = OIS::KC_UP,              // UpArrow on arrow keypad
+            PageUp        = OIS::KC_PGUP,            // PgUp on arrow keypad
+            Left          = OIS::KC_LEFT,            // LeftArrow on arrow keypad
+            Right         = OIS::KC_RIGHT,           // RightArrow on arrow keypad
+            End           = OIS::KC_END,             // End on arrow keypad
+            Down          = OIS::KC_DOWN,            // DownArrow on arrow keypad
+            PageDown      = OIS::KC_PGDOWN,          // PgDn on arrow keypad
+            Insert        = OIS::KC_INSERT,          // Insert on arrow keypad
+            Delete        = OIS::KC_DELETE,          // Delete on arrow keypad
+            LeftWindows   = OIS::KC_LWIN,            // Left Windows key
+            RightWindows  = OIS::KC_RWIN,            // Right Windows key
+            Apps          = OIS::KC_APPS,            // AppMenu key
+            Power         = OIS::KC_POWER,           // System Power
+            Sleep         = OIS::KC_SLEEP,           // System Sleep
+            Wake          = OIS::KC_WAKE,            // System Wake
+            WebSearch     = OIS::KC_WEBSEARCH,       // Web Search
+            WebFavorites  = OIS::KC_WEBFAVORITES,    // Web Favorites
+            WebRefresh    = OIS::KC_WEBREFRESH,      // Web Refresh
+            WebStop       = OIS::KC_WEBSTOP,         // Web Stop
+            WebForward    = OIS::KC_WEBFORWARD,      // Web Forward
+            WebBack       = OIS::KC_WEBBACK,         // Web Back
+            MyComputer    = OIS::KC_MYCOMPUTER,      // My Computer
+            Mail          = OIS::KC_MAIL,            // Mail
+            MediaSelect   = OIS::KC_MEDIASELECT      // Media Select
+        };
+        
+        //! Key codes as strings
+        const char* const ByString[] =
+        {
+            "Unassigned",
+            "Escape",
+            "NumRow1", "NumRow2", "NumRow3", "NumRow4", "NumRow5",
+            "NumRow6", "NumRow7", "NumRow8", "NumRow9", "NumRow0",
+            "Minus", "Equals", "Back", "Tab",
+            "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P",
+            "LeftBracket", "RightBracket",
+            "Return", "LeftControl",
+            "A", "S", "D", "F", "G", "H", "J", "K", "L",
+            "Semicolon", "Apostrophe", "Grave",
+            "LeftShift", "Backslash",
+            "Z", "X", "C", "V", "B", "N", "M",
+            "Comma", "Period", "Slash",
+            "RightShift",
+            "Multiply",
+            "LeftAlt",
+            "Space",
+            "CapsLock",
+            "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
+            "NumLock", "ScrollLock",
+            "Numpad7", "Numpad8", "Numpad9",
+            "NumpadSubtract",
+            "Numpad4", "Numpad5", "Numpad6",
+            "NumpadAdd",
+            "Numpad1", "Numpad2", "Numpad3", "Numpad0",
+            "NumpadPeriod",
+            "","",
+            "LessThan",
+            "F11", "F12",
+            "","","","","","","","","","","",
+            "F13", "F14", "F15",
+            "","","","","","","","","","",
+            "Kana",
+            "","",
+            "ABNT_C1",
+            "","","","","",
+            "Convert",
+            "",
+            "NoConvert",
+            "",
+            "Yen",
+            "ABNT_C2",
+            "","","","","","","","","","","","","","",
+            "NumpadEquals",
+            "","",
+            "PreviousTrack",
+            "AT",
+            "Colon", "Underline",
+            "Kanji",
+            "Stop",
+            "AX",
+            "Unlabeled",
+            "NextTrack",
+            "","",
+            "NumpadEnter",
+            "RightControl",
+            "","",
+            "Mute",
+            "Calculator",
+            "PlayPause",
+            "",
+            "MediaStop",
+            "","","","","","","","","",
+            "VolumeDown",
+            "",
+            "VolumeUp",
+            "",
+            "WebHome",
+            "NumpadComma",
+            "",
+            "Divide",
+            "",
+            "SystemRequest",
+            "RightAlt",
+            "","","","","","","","","","","","",
+            "Pause",
+            "",
+            "Home",
+            "UP",
+            "PageUp",
+            "",
+            "Left",
+            "",
+            "Right",
+            "",
+            "End", "Down", "PageDown", "Insert", "Delete",
+            "","","","","","","",
+            "LeftWindows", "RightWindows", "Apps",
+            "Power", "Sleep",
+            "","","",
+            "Wake",
+            "",
+            "WebSearch", "WebFavorites", "WebRefresh", "WebStop", "WebForward", "WebBack",
+            "MyComputer", "Mail", "MediaSelect"
+        };
+    }
+
+
+    namespace MouseButtonCode
+    {
+        const unsigned int numberOfButtons = 8;
+
+        //! Mouse button codes as enumeration
+        enum ByEnum
+        {
+            Left    = OIS::MB_Left,
+            Right   = OIS::MB_Right,
+            Middle  = OIS::MB_Middle,
+            Button3 = OIS::MB_Button3,
+            Button4 = OIS::MB_Button4,
+            Button5 = OIS::MB_Button5,
+            Button6 = OIS::MB_Button6,
+            Button7 = OIS::MB_Button7,
+        };
+
+        // Mouse button codes as strings
+        const char* const ByString[] =
+        {
+            "Left",
+            "Right",
+            "Middle",
+            "Button3",
+            "Button4",
+            "Button5",
+            "Button6",
+            "Button7",
+        };
+    }
+
+    namespace MouseAxisCode
+    {
+        const unsigned int numberOfAxes = 2;
+
+        // Mouse axis codes as enumeration
+        enum ByEnum
+        {
+            X,
+            Y
+        };
+
+        // Mouse axis codes as strings
+        const char* const ByString[] =
+        {
+            "X",
+            "Y"
+        };
+    }
+
+
+    namespace JoyStickButtonCode
+    {
+        const unsigned int numberOfButtons = 64;
+
+        // Joy stick button codes as enumeration
+        enum ByEnum
+        {
+            Button0       =  0, Button1       =  1, Button2       =  2, Button3       =  3,
+            Button4       =  4, Button5       =  5, Button6       =  6, Button7       =  7,
+            Button8       =  8, Button9       =  9, Button10      = 10, Button11      = 11,
+            Button12      = 12, Button13      = 13, Button14      = 14, Button15      = 15,
+            Button16      = 16, Button17      = 17, Button18      = 18, Button19      = 19,
+            Button20      = 20, Button21      = 21, Button22      = 22, Button23      = 23,
+            Button24      = 24, Button25      = 25, Button26      = 26, Button27      = 27,
+            Button28      = 28, Button29      = 29, Button30      = 30, Button31      = 31,
+
+            POV0North     = 32, POV0South     = 33, POV0East      = 34, POV0West      = 35,
+            POV0NorthEast = 36, POV0SouthEast = 37, POV0NorthWest = 38, POV0SouthWest = 39,
+
+            POV1North     = 40, POV1South     = 41, POV1East      = 42, POV1West      = 43,
+            POV1NorthEast = 44, POV1SouthEast = 45, POV1NorthWest = 46, POV1SouthWest = 47,
+
+            POV2North     = 48, POV2South     = 49, POV2East      = 50, POV2West      = 51,
+            POV2NorthEast = 52, POV2SouthEast = 53, POV2NorthWest = 54, POV2SouthWest = 55,
+
+            POV3North     = 56, POV3South     = 57, POV3East      = 58, POV3West      = 59,
+            POV3NorthEast = 60, POV3SouthEast = 61, POV3NorthWest = 62, POV3SouthWest = 63,
+        };
+
+        // Joy stick button codes as strings
+        const char* const ByString[] =
+        {
+            "Button00",      "Button01",      "Button02",      "Button03",
+            "Button04",      "Button05",      "Button06",      "Button07",
+            "Button08",      "Button09",      "Button10",      "Button11",
+            "Button12",      "Button13",      "Button14",      "Button15",
+            "Button16",      "Button17",      "Button18",      "Button19",
+            "Button20",      "Button21",      "Button22",      "Button23",
+            "Button24",      "Button25",      "Button26",      "Button27",
+            "Button28",      "Button29",      "Button30",      "Button31",
+            "POV0North",     "POV0South",     "POV0East",      "POV0West",
+            "POV0NorthEast", "POV0SouthEast", "POV0NorthWest", "POV0SouthWest",
+            "POV1North",     "POV1South",     "POV1East",      "POV1West",
+            "POV1NorthEast", "POV1SouthEast", "POV1NorthWest", "POV1SouthWest",
+            "POV2North",     "POV2South",     "POV2East",      "POV2West",
+            "POV2NorthEast", "POV2SouthEast", "POV2NorthWest", "POV2SouthWest",
+            "POV3North",     "POV3South",     "POV3East",      "POV3West",
+            "POV3NorthEast", "POV3SouthEast", "POV3NorthWest", "POV3SouthWest"
+        };
+    }
+
+    namespace JoyStickAxisCode
+    {
+        const unsigned int numberOfAxes = 24;
+
+        // Joy stick axis codes as enumeration
+        enum ByEnum
+        {
+            Slider0 =  0, Slider1 =  1, Slider2 =  2, Slider3 =  3,
+            Slider4 =  4, Slider5 =  5, Slider6 =  6, Slider7 =  7,
+            Axis0   =  8, Axis1   =  9, Axis2   = 10, Axis3   = 11,
+            Axis4   = 12, Axis5   = 13, Axis6   = 14, Axis7   = 15,
+            Axis8   = 16, Axis9   = 17, Axis10  = 18, Axis11  = 19,
+            Axis12  = 20, Axis13  = 21, Axis14  = 22, Axis15  = 23
+        };
+
+        // Joy stick axis codes as strings
+        const char* const ByString[] =
+        {
+            "Slider0", "Slider1", "Slider2", "Slider3",
+            "Slider4", "Slider5", "Slider6", "Slider7",
+            "Axis00",  "Axis01",  "Axis02",  "Axis03",
+            "Axis04",  "Axis05",  "Axis06",  "Axis07",
+            "Axis08",  "Axis09",  "Axis10",  "Axis11",
+            "Axis12",  "Axis13",  "Axis14",  "Axis15"
+        };
+    }
+
+
+    //-----------------------------------------------------------------------
+    // Miscellaneous
+    //-----------------------------------------------------------------------
+
+    namespace InputDeviceEnumerator
+    {
+        //! Used to access the devices in an array
+        enum Value
+        {
+            Keyboard = 0,
+            Mouse = 1,
+            FirstJoyStick = 2
+        };
+    }
+}
+
+#endif /* _InputPrereqs_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/InputState.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputState.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputState.cc	(revision 5712)
@@ -0,0 +1,112 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "InputState.h"
+#include "core/Functor.h"
+
+namespace orxonox
+{
+    //! Sets priority of it's a high priority and resizes the handler list
+    InputState::InputState(const std::string& name, bool bAlwaysGetsInput, bool bTransparent, InputStatePriority priority)
+        : name_(name)
+        , bAlwaysGetsInput_(bAlwaysGetsInput)
+        , bTransparent_(bTransparent)
+        , bExclusiveMouse_(true)
+        , bExpired_(true)
+        , handlers_(2)
+        , joyStickHandlerAll_(0)
+        , enterFunctor_(0)
+        , leaveFunctor_(0)
+    {
+        if (priority >= InputStatePriority::HighPriority || priority == InputStatePriority::Empty)
+            priority_ = priority;
+        else
+            priority_ = 0;
+
+        handlers_.resize(InputDeviceEnumerator::FirstJoyStick + this->getJoyStickList().size(), NULL);
+    }
+
+    bool InputState::isInputDeviceEnabled(unsigned int device)
+    {
+        if (device < handlers_.size())
+            return handlers_[device] != NULL;
+        else
+            return false;
+    }
+
+    //! Called by JoyStickQuantityListener upon joy stick adding/removal
+    void InputState::JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList)
+    {
+        unsigned int oldSize = handlers_.size();
+        handlers_.resize(InputDeviceEnumerator::FirstJoyStick + joyStickList.size(), NULL);
+
+        for (unsigned int i = oldSize; i < handlers_.size(); ++i)
+            handlers_[i] = joyStickHandlerAll_;
+
+        bExpired_ = true;
+    }
+
+    bool InputState::setJoyStickHandler(InputHandler* handler, unsigned int joyStick)
+    {
+        unsigned device = joyStick + firstJoyStickIndex_s;
+        if (joyStick >= handlers_.size() - device)
+            return false;
+
+        handlers_[device] = handler;
+        bExpired_ = true;
+        return true;
+    }
+
+    void InputState::setJoyStickHandler(InputHandler* handler)
+    {
+        joyStickHandlerAll_ = handler;
+        for (unsigned int i = firstJoyStickIndex_s; i < handlers_.size(); ++i)
+            handlers_[i] = handler;
+        bExpired_ = true;
+    }
+
+    void InputState::setHandler(InputHandler* handler)
+    {
+        setKeyHandler(handler);
+        setMouseHandler(handler);
+        setJoyStickHandler(handler);
+    }
+
+    void InputState::entered()
+    {
+        if (enterFunctor_)
+            (*enterFunctor_)();
+            
+    }
+
+    void InputState::left()
+    {
+        if (leaveFunctor_)
+            (*leaveFunctor_)();
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/InputState.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/InputState.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/InputState.h	(revision 5712)
@@ -0,0 +1,242 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _InputState_H__
+#define _InputState_H__
+
+#include "InputPrereqs.h"
+
+#include <cassert>
+#include <string>
+#include <vector>
+
+#include "util/OrxEnum.h"
+#include "InputHandler.h"
+#include "JoyStickQuantityListener.h"
+
+namespace orxonox
+{
+    //! Enumeration wrapper for input state priorities
+    struct InputStatePriority : OrxEnum<InputStatePriority>
+    {
+        OrxEnumConstructors(InputStatePriority);
+
+        static const int Empty        = -1;
+        static const int Dynamic      = 0;
+
+        static const int HighPriority = 1000;
+        static const int Console      = HighPriority + 0;
+        static const int Calibrator   = HighPriority + 1;
+        static const int Detector     = HighPriority + 2;
+    };
+
+    /**
+    @brief
+        InputStates allow you to customise the input event targets at runtime.
+
+        The general idea is a stack: Every activated InputState will be pushed on
+        that stack and only the top one gets the input events. This is done for
+        every device (keyboard, mouse, all joy sticks) separately to allow
+        for intance keyboard input capturing for the console while you can still
+        steer a ship with the mouse.
+        There are two exceptions to this behaviour though:
+        - If an InputState is created with the 'Transparent' parameter on, the
+          state will not prevent input from getting to the state below it on the stack.
+          This can be useful for instance if you need to deploy input to multiple
+          handlers: Simply create two InputStates and make the high priority one transparent.
+        - If an InputState is created with the 'AlwaysGetsInput' parameter on, then
+          the state will always receive input as long as it is activated.
+        - Note: If you mark an InputState with both parameters on, then it will
+          not influence ony other InputState at all.
+
+    @par Priorities
+        Every InputState has a priority when on the stack, but mostly this
+        priority is dynamic (InputStatePriority::Dynamic) which means that a state
+        pushed onto the stack will simply have a higher priority than the top one.
+        This behaviour really only applies to normal states that don't have
+        a high priority (InputStatePriority::HighPriority). These 'special' ones
+        are used for features like the KeyDetector or the console. Use with care!
+
+    @par Exclusive/Non-Exclusive mouse Mode
+        You can select a specific mouse mode that tells whether the application
+        should have exclusive accessto it or not.
+        When in non-exclusive mode, you can move the mouse out of the window
+        like with any other normal window (only for windowed mode!).
+        The setting is dictated by the topmost InputState that gets mouse events.
+    */
+    class _CoreExport InputState : public JoyStickQuantityListener
+    {
+        friend class InputManager;
+
+        //! Marks the index in the handler vector for the keyboard handler
+        static const InputDeviceEnumerator::Value keyboardIndex_s = InputDeviceEnumerator::Keyboard;
+        //! Marks the index in the handler vector for the mouse handler
+        static const InputDeviceEnumerator::Value mouseIndex_s = InputDeviceEnumerator::Mouse;
+        //! Marks the index in the handler vector for the first joy stick handler
+        static const InputDeviceEnumerator::Value firstJoyStickIndex_s = InputDeviceEnumerator::FirstJoyStick;
+
+    public:
+        //! Sets the keyboard event handler (overwrites if there already was one!)
+        void setKeyHandler     (InputHandler* handler)
+            { handlers_[keyboardIndex_s] = handler; bExpired_ = true; }
+        //! Sets the mouse event handler (overwrites if there already was one!)
+        void setMouseHandler   (InputHandler* handler)
+            { handlers_[mouseIndex_s]    = handler; bExpired_ = true; }
+        /**
+        @brief
+            Sets the joy stick event handler for one specific joy stick (overwrites if there already was one!)
+        @return
+            Returns false if the specified device was not found
+        */
+        bool setJoyStickHandler(InputHandler* handler, unsigned int joyStick);
+        //! Sets the joy stick event handler for all joy sticks (overwrites if there already was one!)
+        void setJoyStickHandler(InputHandler* handler);
+        //! Sets an InputHandler to be used for all devices
+        void setHandler        (InputHandler* handler);
+
+        void setIsExclusiveMouse(bool value) { bExclusiveMouse_ = value; this->bExpired_ = true; }
+        bool getIsExclusiveMouse() const { return bExclusiveMouse_; }
+
+        //! Returns the name of the state (which is unique!)
+        const std::string& getName() const { return name_; }
+        //! Returns the priority of the state (which is unique if != 0)
+        int getPriority()            const { return priority_; }
+
+        //! Tells whether there a handler installed for a specific device
+        bool isInputDeviceEnabled(unsigned int device);
+
+        //! Returns true if the handler situation has changed
+        bool hasExpired()      { return this->bExpired_; }
+        //! Call this if you have applied the changes resulting from changed handlers
+        void resetExpiration() { bExpired_ = false; }
+
+        //! Updates one specific device handler with #device#Updated
+        void update(float dt, unsigned int device);
+        //! Updates all handlers with allDevicesUpdated
+        void update(float dt);
+
+        //! Generic function that distributes all 9 button events
+        template <typename EventType, class Traits>
+        void buttonEvent(unsigned int device, const typename Traits::ButtonTypeParam button);
+
+        //! Event handler
+        void mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
+        //! Event handler
+        void mouseScrolled(int abs, int rel);
+        //! Event handler
+        void joyStickAxisMoved(unsigned int device, unsigned int axis, float value);
+
+        // Functors
+        //! Called when the state is being activated (even if it doesn't get any events afterwards!)
+        void entered();
+        //! Called upon deactivation of the state
+        void left();
+        //! Sets a functor to be called upon activation of the state
+        void setEnterFunctor(Functor* functor) { this->enterFunctor_ = functor; }
+        //! Sets a functor to be called upon deactivation of the state
+        void setLeaveFunctor(Functor* functor) { this->leaveFunctor_ = functor; }
+
+    private:
+        InputState(const std::string& name, bool bAlwaysGetsInput, bool bTransparent, InputStatePriority priority);
+        ~InputState() { }
+
+        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+
+        //! Sets the priority (only to be used by the InputManager!)
+        void setPriority(int priority) { priority_ = priority; }
+
+        const std::string           name_;                  //!< Name of the state
+        const bool                  bAlwaysGetsInput_;      //!< See class declaration for explanation
+        const bool                  bTransparent_;          //!< See class declaration for explanation
+        bool                        bExclusiveMouse_;       //!< See class declaration for explanation
+        int                         priority_;              //!< Current priority (might change)
+        bool                        bExpired_;              //!< See hasExpired()
+        std::vector<InputHandler*>  handlers_;              //!< Vector with all handlers where the index is the device ID
+        //! Handler to be used for all joy sticks (needs to be saved in case another joy stick gets attached)
+        InputHandler*               joyStickHandlerAll_;
+        Functor*                    enterFunctor_;          //!< Functor to be executed on enter
+        Functor*                    leaveFunctor_;          //!< Functor to be executed on leave
+    };
+
+    FORCEINLINE void InputState::update(float dt)
+    {
+        for (unsigned int i = 0; i < handlers_.size(); ++i)
+            if (handlers_[i] != NULL)
+                handlers_[i]->allDevicesUpdated(dt);
+    }
+
+    FORCEINLINE void InputState::update(float dt, unsigned int device)
+    {
+        switch (device)
+        {
+        case InputDeviceEnumerator::Keyboard:
+            if (handlers_[keyboardIndex_s] != NULL)
+                handlers_[keyboardIndex_s]->keyboardUpdated(dt);
+            break;
+
+        case InputDeviceEnumerator::Mouse:
+            if (handlers_[mouseIndex_s] != NULL)
+                handlers_[mouseIndex_s]->mouseUpdated(dt);
+            break;
+
+        default: // joy sticks
+            if (handlers_[device] != NULL)
+                handlers_[device]->joyStickUpdated(device - firstJoyStickIndex_s, dt);
+            break;
+        }
+    }
+
+    template <typename EventType, class Traits>
+    FORCEINLINE void InputState::buttonEvent(unsigned int device, const typename Traits::ButtonTypeParam button)
+    {
+        assert(device < handlers_.size());
+        if (handlers_[device] != NULL)
+            handlers_[device]->buttonEvent(device, button, EventType());
+    }
+
+    FORCEINLINE void InputState::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
+    {
+        if (handlers_[mouseIndex_s] != NULL)
+            handlers_[mouseIndex_s]->mouseMoved(abs, rel, clippingSize);
+    }
+
+    FORCEINLINE void InputState::mouseScrolled(int abs, int rel)
+    {
+        if (handlers_[mouseIndex_s] != NULL)
+            handlers_[mouseIndex_s]->mouseScrolled(abs, rel);
+    }
+
+    FORCEINLINE void InputState::joyStickAxisMoved(unsigned int device, unsigned int axis, float value)
+    {
+        assert(device < handlers_.size());
+        if (handlers_[device] != NULL)
+            handlers_[device]->axisMoved(device - firstJoyStickIndex_s, axis, value);
+    }
+}
+
+#endif /* _InputState_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/JoyStick.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/JoyStick.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/JoyStick.cc	(revision 5712)
@@ -0,0 +1,261 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "JoyStick.h"
+
+#include <climits>
+#include <ois/OISJoyStick.h>
+#include <boost/foreach.hpp>
+
+#include "core/ConfigFileManager.h"
+#include "core/ConfigValueIncludes.h"
+#include "core/CoreIncludes.h"
+#include "util/Convert.h"
+#include "InputState.h"
+
+namespace orxonox
+{
+    //! Helper function that loads the config value vector of one coefficient
+    void loadCalibration(std::vector<int>& list, const std::string& sectionName, const std::string& valueName, size_t size, int defaultValue);
+
+    std::vector<std::string> JoyStick::deviceNames_s;
+
+    JoyStick::JoyStick(unsigned int id, OIS::InputManager* oisInputManager)
+        : super(id, oisInputManager)
+    {
+        RegisterRootObject(JoyStick);
+        this->setConfigValues();
+        // Initialise POV and Slider states
+        this->clearBuffersImpl();
+
+        // Generate unique name
+        if (oisDevice_->vendor().empty())
+            deviceName_ = "Unknown_";
+        else
+        {
+            std::string name = oisDevice_->vendor();
+            replaceCharacters(name, ' ', '_');
+            deviceName_ = name + "_";
+        }
+        deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Button))  + "_";
+        deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Axis))    + "_";
+        deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Slider))  + "_";
+        deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_POV));
+        //deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Vector3));
+
+        BOOST_FOREACH(std::string& idString, deviceNames_s)
+        {
+            if (deviceName_ == idString)
+            {
+                // Make the ID unique for this execution time.
+                deviceName_ += "_" + multi_cast<std::string>(this->getDeviceName());
+                break;
+            }
+        }
+
+        COUT(4) << "Created OIS joy stick with ID " << deviceName_ << std::endl;
+
+        // Load calibration
+        size_t axes = sliderAxes_s + static_cast<size_t>(oisDevice_->getNumberOfComponents(OIS::OIS_Axis));
+        loadCalibration(configMinValues_,  deviceName_, "MinValue",  axes,  -32768);
+        loadCalibration(configMaxValues_,  deviceName_, "MaxValue",  axes,   32768);
+        loadCalibration(configZeroValues_, deviceName_, "ZeroValue", axes, 0);
+        this->evaluateCalibration();
+    }
+
+    //! Callback for the joy stick calibration config file.
+    void JoyStick::calibrationFileCallback()
+    {
+        ConfigFileManager::getInstance().setFilename(ConfigFileType::JoyStickCalibration, calibrationFilename_);
+    }
+
+    void JoyStick::setConfigValues()
+    {
+        SetConfigValue(calibrationFilename_, "joystick_calibration.ini")
+            .description("Ini filename for the the joy stick calibration data.")
+            .callback(this, &JoyStick::calibrationFileCallback);
+    }
+
+    void loadCalibration(std::vector<int>& list, const std::string& sectionName, const std::string& valueName, size_t size, int defaultValue)
+    {
+        list.resize(size);
+        unsigned int configValueVectorSize = ConfigFileManager::getInstance().getVectorSize(ConfigFileType::JoyStickCalibration, sectionName, valueName);
+        if (configValueVectorSize > size)
+            configValueVectorSize = size;
+
+        for (unsigned int i = 0; i < configValueVectorSize; ++i)
+        {
+            list[i] = multi_cast<int>(ConfigFileManager::getInstance().getValue(
+                ConfigFileType::JoyStickCalibration, sectionName, valueName, i, multi_cast<std::string>(defaultValue), false));
+        }
+
+        // fill the rest with default values
+        for (unsigned int i = configValueVectorSize; i < size; ++i)
+            list[i] = defaultValue;
+    }
+
+    //! Called by InputDevice when calibration mode has started
+    void JoyStick::calibrationStarted()
+    {
+        // Set initial values
+        BOOST_FOREACH(int& minVal, configMinValues_)
+            minVal = INT_MAX;
+        BOOST_FOREACH(int& minVal, configMaxValues_)
+            minVal = INT_MIN;
+        BOOST_FOREACH(int& zeroVal, configZeroValues_)
+            zeroVal = 0;
+    }
+
+    //! Called by InputDevice when calibration mode has stopped
+    void JoyStick::calibrationStopped()
+    {
+        // Get the middle positions now
+        unsigned int iAxis = 0;
+        for (unsigned int i = 0; i < sliderAxes_s/2; ++i)
+        {
+            configZeroValues_[iAxis++] = oisDevice_->getJoyStickState().mSliders[i].abX;
+            configZeroValues_[iAxis++] = oisDevice_->getJoyStickState().mSliders[i].abY;
+        }
+        // Note: joyStickZeroValues_[iJoyStick] was already correctly resised in loadCalibration()
+        assert(oisDevice_->getJoyStickState().mAxes.size() == configZeroValues_.size() - sliderAxes_s);
+        for (unsigned int i = 0; i < configZeroValues_.size() - sliderAxes_s; ++i)
+            configZeroValues_[iAxis++] = oisDevice_->getJoyStickState().mAxes[i].abs;
+
+        for (unsigned int i = 0; i < configMinValues_.size(); ++i)
+        {
+            // Minimum values
+            if (configMinValues_[i] == INT_MAX)
+                configMinValues_[i] = -32768;
+            ConfigFileManager::getInstance().setValue(ConfigFileType::JoyStickCalibration,
+                deviceName_, "MinValue", i, multi_cast<std::string>(configMinValues_[i]), false);
+
+            // Maximum values
+            if (configMaxValues_[i] == INT_MIN)
+                configMaxValues_[i] = 32767;
+            ConfigFileManager::getInstance().setValue(ConfigFileType::JoyStickCalibration,
+                deviceName_, "MaxValue", i, multi_cast<std::string>(configMaxValues_[i]), false);
+
+            // Middle values
+            ConfigFileManager::getInstance().setValue(ConfigFileType::JoyStickCalibration,
+                deviceName_, "ZeroValue", i, multi_cast<std::string>(configZeroValues_[i]), false);
+        }
+
+        this->evaluateCalibration();
+    }
+
+    //! Evaluates the accumulated values during calibration
+    void JoyStick::evaluateCalibration()
+    {
+        for (unsigned int i = 0; i < configMinValues_.size(); i++)
+        {
+            zeroValues_[i] = configZeroValues_[i];
+            negativeCoeffs_[i] = - 1.0f / (configMinValues_[i] - configZeroValues_[i]);
+            positiveCoeffs_[i] =   1.0f / (configMaxValues_[i] - configZeroValues_[i]);
+        }
+    }
+
+    //! Resets the pov states
+    void JoyStick::clearBuffersImpl()
+    {
+        for (int j = 0; j < 4; ++j)
+            povStates_[j] = 0;
+    }
+
+    //! Generic method to forward axis events
+    void JoyStick::fireAxis(int axis, int value)
+    {
+        if (this->isCalibrating())
+        {
+            if (value < configMinValues_[axis])
+                configMinValues_[axis] = value;
+            if (value > configMaxValues_[axis])
+                configMaxValues_[axis] = value;
+        }
+        else
+        {
+            float fValue = static_cast<float>(value - zeroValues_[axis]);
+            if (fValue > 0.0f)
+                fValue *= positiveCoeffs_[axis];
+            else
+                fValue *= negativeCoeffs_[axis];
+
+            BOOST_FOREACH(InputState* state, inputStates_)
+                state->joyStickAxisMoved(this->getDeviceID(), axis, fValue);
+        }
+    }
+
+    //! OIS joy stick axis event handler
+    bool JoyStick::axisMoved(const OIS::JoyStickEvent &arg, int axis)
+    {
+        // keep in mind that the first 8 axes are reserved for the sliders
+        this->fireAxis(axis + sliderAxes_s, arg.state.mAxes[axis].abs);
+
+        return true;
+    }
+
+    //! A Slider always has an X and an Y direction!
+    bool JoyStick::sliderMoved(const OIS::JoyStickEvent &arg, int id)
+    {
+        if (sliderStates_[id][0] != arg.state.mSliders[id].abX)
+            fireAxis(id * 2, arg.state.mSliders[id].abX);
+        else if (sliderStates_[id][1] != arg.state.mSliders[id].abY)
+            fireAxis(id * 2 + 1, arg.state.mSliders[id].abY);
+
+        return true;
+    }
+
+    //! A POV is the big button that can point in all directions (but only in one at once)
+    bool JoyStick::povMoved(const OIS::JoyStickEvent &arg, int id)
+    {
+        // translate the POV into 8 simple buttons
+
+        int lastState = povStates_[id];
+        if (lastState & OIS::Pov::North)
+            buttonReleased(arg, 32 + id * 4 + 0);
+        if (lastState & OIS::Pov::South)
+            buttonReleased(arg, 32 + id * 4 + 1);
+        if (lastState & OIS::Pov::East)
+            buttonReleased(arg, 32 + id * 4 + 2);
+        if (lastState & OIS::Pov::West)
+            buttonReleased(arg, 32 + id * 4 + 3);
+
+        povStates_[id] = arg.state.mPOV[id].direction;
+
+        int currentState = povStates_[id];
+        if (currentState & OIS::Pov::North)
+            buttonPressed(arg, 32 + id * 4 + 0);
+        if (currentState & OIS::Pov::South)
+            buttonPressed(arg, 32 + id * 4 + 1);
+        if (currentState & OIS::Pov::East)
+            buttonPressed(arg, 32 + id * 4 + 2);
+        if (currentState & OIS::Pov::West)
+            buttonPressed(arg, 32 + id * 4 + 3);
+
+        return true;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/JoyStick.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/JoyStick.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/JoyStick.h	(revision 5712)
@@ -0,0 +1,132 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Core_JoyStick_H__
+#define _Core_JoyStick_H__
+
+#include "InputPrereqs.h"
+
+#include <string>
+#include <vector>
+#include "InputDevice.h"
+
+namespace orxonox
+{
+    //! Template parameter collection for the base class
+    struct JoyStickTraits
+    {
+        typedef JoyStick DeviceClass;
+        typedef OIS::JoyStick OISDeviceClass;
+        typedef JoyStickButtonCode::ByEnum ButtonType;
+        typedef JoyStickButtonCode::ByEnum ButtonTypeParam;
+        static const OIS::Type OISDeviceValue = OIS::OISJoyStick;
+    };
+
+    /**
+    @brief
+        Wraps around an OIS::JoyStick and forwards the input events to
+        a list of input states.
+
+        The class also supports joy stick calibration and stores the values
+        in an ini-file.
+    */
+    class _CoreExport JoyStick
+        : public OrxonoxClass
+        , public InputDeviceTemplated<JoyStickTraits>
+        , public OIS::JoyStickListener
+    {
+        friend class InputDeviceTemplated<JoyStickTraits>;
+        //! Super class alias
+        typedef InputDeviceTemplated<JoyStickTraits> super;
+
+    public:
+        //! Assigns a generated ID string and loads the calibration (if present)
+        JoyStick(unsigned int id, OIS::InputManager* oisInputManager);
+        ~JoyStick() { }
+        void setConfigValues();
+
+        //! Returns the name generated from the number of knobs and the device name
+        const std::string& getDeviceName() const { return this->deviceName_; }
+
+    private:
+        void calibrationStarted();
+        void calibrationStopped();
+        void evaluateCalibration();
+
+        void clearBuffersImpl();
+        void calibrationFileCallback();
+        void fireAxis(int axis, int value);
+
+        //! OIS event handler
+        bool buttonPressed (const OIS::JoyStickEvent &arg, int button)
+        {
+            super::buttonPressed(static_cast<JoyStickButtonCode::ByEnum>(button));
+            return true;
+        }
+
+        //! OIS event handler
+        bool buttonReleased(const OIS::JoyStickEvent &arg, int button)
+        {
+            super::buttonReleased(static_cast<JoyStickButtonCode::ByEnum>(button));
+            return true;
+        }
+
+        bool axisMoved     (const OIS::JoyStickEvent &arg, int axis);
+        bool sliderMoved   (const OIS::JoyStickEvent &arg, int id);
+        bool povMoved      (const OIS::JoyStickEvent &arg, int id);
+        //! OIS event handler (don't remove that because of OIS version issues!)
+        bool vector3Moved  (const OIS::JoyStickEvent &arg, int id) { return true; }
+
+        //! Returns the class name as string
+        static std::string getClassNameImpl() { return "JoyStick"; }
+
+        std::string deviceName_;              //!< Name generated by the number of knobs and the device name
+        int povStates_[4];                    //!< Internal states for the POVs
+        int sliderStates_[4][2];              //!< Internal states for the Sliders (each slider has X and Y!)
+
+        // calibration
+        int zeroValues_[24];                  //!< Axes values when the knob is in the middle
+        float positiveCoeffs_[24];            //!< Maps the negative part of an axis to a 0.0 to 1.0 floating range
+        float negativeCoeffs_[24];            //!< Maps the positive part of an axis to a 0.0 to 1.0 floating range
+
+        std::vector<int> configZeroValues_;   //!< Config file stored axis values when the knob is in the middle
+        std::vector<int> configMinValues_;    //!< Config file stored minimum axis values
+        std::vector<int> configMaxValues_;    //!< Config file stored maximum axis values
+
+        // ConfigValues
+        std::string calibrationFilename_;     //!< Joy stick calibration ini filename
+
+        //! Contains a list of all names to avoid duplicates
+        static std::vector<std::string> deviceNames_s;
+
+        //!< Maximum number of slider axes
+        static const unsigned int sliderAxes_s = 8;
+    };
+}
+
+#endif /* _Core_JoyStick_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/JoyStickQuantityListener.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/JoyStickQuantityListener.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/JoyStickQuantityListener.cc	(revision 5712)
@@ -0,0 +1,50 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "JoyStickQuantityListener.h"
+
+#include "core/CoreIncludes.h"
+#include "core/ObjectList.h"
+
+namespace orxonox
+{
+    std::vector<JoyStick*> JoyStickQuantityListener::joyStickList_s;
+
+    JoyStickQuantityListener::JoyStickQuantityListener()
+    {
+        RegisterObject(JoyStickQuantityListener);
+    }
+
+    //! Calls all registered objects and sets the static variable
+    /*static*/ void JoyStickQuantityListener::changeJoyStickQuantity(const std::vector<JoyStick*>& joyStickList)
+    {
+        joyStickList_s = joyStickList;
+        for (ObjectList<JoyStickQuantityListener>::iterator it = ObjectList<JoyStickQuantityListener>::begin(); it; ++it)
+            it->JoyStickQuantityChanged(joyStickList);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/JoyStickQuantityListener.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/JoyStickQuantityListener.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/JoyStickQuantityListener.h	(revision 5712)
@@ -0,0 +1,64 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief 
+*/
+
+#ifndef _JoyStickQuantityListener_H__
+#define _JoyStickQuantityListener_H__
+
+#include "InputPrereqs.h"
+#include "core/OrxonoxClass.h"
+
+namespace orxonox
+{
+    //! Derive from this class to get informed when joy sticks get added/removed
+    class _CoreExport JoyStickQuantityListener : virtual public OrxonoxClass
+    {
+        friend class InputManager;
+    protected:
+        JoyStickQuantityListener();
+        virtual ~JoyStickQuantityListener() { }
+
+        //! Returns a list with all JoySticks currently loaded
+        const std::vector<JoyStick*>& getJoyStickList() const { return joyStickList_s; }
+
+    private:
+        //! Called whenever joy sticks get added/removed
+        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList) = 0;
+
+        static void changeJoyStickQuantity(const std::vector<JoyStick*>& joyStickList);
+
+        //! Static variable that holds the latest distributed information
+        static std::vector<JoyStick*> joyStickList_s;
+    };
+}
+
+#endif /* _JoyStickQuantityListener_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/KeyBinder.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/KeyBinder.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/KeyBinder.cc	(revision 5712)
@@ -0,0 +1,511 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+ @file
+ @brief Implementation of the different input handlers.
+ */
+
+#include "KeyBinder.h"
+
+#include "util/Convert.h"
+#include "util/Debug.h"
+#include "core/ConfigValueIncludes.h"
+#include "core/CoreIncludes.h"
+#include "core/ConfigFileManager.h"
+#include "InputCommands.h"
+#include "JoyStick.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Constructor that does as little as necessary.
+    */
+    KeyBinder::KeyBinder()
+        : deriveTime_(0.0f)
+    {
+        mouseRelative_[0] = 0;
+        mouseRelative_[1] = 0;
+        mousePosition_[0] = 0;
+        mousePosition_[1] = 0;
+
+        RegisterRootObject(KeyBinder);
+
+        // intialise all buttons and half axes to avoid creating everything with 'new'
+        // keys
+        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
+        {
+            std::string keyname = KeyCode::ByString[i];
+            if (!keyname.empty())
+                keys_[i].name_ = std::string("Key") + keyname;
+            else
+                keys_[i].name_ = "";
+            keys_[i].paramCommandBuffer_ = &paramCommandBuffer_;
+            keys_[i].groupName_ = "Keys";
+        }
+        // mouse buttons plus 4 mouse wheel buttons only 'generated' by KeyBinder
+        const char* const mouseWheelNames[] = { "Wheel1Down", "Wheel1Up", "Wheel2Down", "Wheel2Up" };
+        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
+        {
+            std::string nameSuffix;
+            if (i < MouseButtonCode::numberOfButtons)
+                nameSuffix = MouseButtonCode::ByString[i];
+            else
+                nameSuffix = mouseWheelNames[i - MouseButtonCode::numberOfButtons];
+            mouseButtons_[i].name_ = nameSuffix;
+            mouseButtons_[i].paramCommandBuffer_ = &paramCommandBuffer_;
+            mouseButtons_[i].groupName_ = "MouseButtons";
+        }
+        // mouse axes
+        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
+        {
+            mouseAxes_[i].name_ = MouseAxisCode::ByString[i / 2];
+            if (i & 1)
+                mouseAxes_[i].name_ += "Pos";
+            else
+                mouseAxes_[i].name_ += "Neg";
+            mouseAxes_[i].paramCommandBuffer_ = &paramCommandBuffer_;
+            mouseAxes_[i].groupName_ = "MouseAxes";
+        }
+
+        // We might not even load any bindings at all (KeyDetector for instance)
+        this->configFile_ = ConfigFileType::NoType;
+
+        // initialise joy sticks separatly to allow for reloading
+        this->JoyStickQuantityChanged(this->getJoyStickList());
+
+        // set them here to use allHalfAxes_
+        setConfigValues();
+    }
+
+    /**
+    @brief
+        Destructor
+    */
+    KeyBinder::~KeyBinder()
+    {
+        // almost no destructors required because most of the arrays are static.
+        clearBindings(); // does some destruction work
+    }
+
+    /**
+    @brief
+        Loader for the key bindings, managed by config values.
+    */
+    void KeyBinder::setConfigValues()
+    {
+        SetConfigValue(analogThreshold_, 0.05f)
+            .description("Threshold for analog axes until which the state is 0.");
+        SetConfigValue(bFilterAnalogNoise_, false)
+            .description("Specifies whether to filter small analog values like joy stick fluctuations.");
+        SetConfigValue(mouseSensitivity_, 1.0f)
+            .description("Mouse sensitivity.");
+        SetConfigValue(bDeriveMouseInput_, false)
+            .description("Whether or not to derive moues movement for the absolute value.");
+        SetConfigValue(derivePeriod_, 0.05f)
+            .description("Accuracy of the mouse input deriver. The higher the more precise, but laggier.");
+        SetConfigValue(mouseSensitivityDerived_, 1.0f)
+            .description("Mouse sensitivity if mouse input is derived.");
+        SetConfigValue(mouseWheelStepSize_, 120)
+            .description("Equals one step of the mousewheel.");
+        SetConfigValue(buttonThreshold_, 0.80f)
+            .description("Threshold for analog axes until which the button is not pressed.")
+            .callback(this, &KeyBinder::buttonThresholdChanged);
+    }
+
+    void KeyBinder::buttonThresholdChanged()
+    {
+        for (unsigned int i = 0; i < allHalfAxes_.size(); i++)
+            if (!allHalfAxes_[i]->bButtonThresholdUser_)
+                allHalfAxes_[i]->buttonThreshold_ = this->buttonThreshold_;
+    }
+
+    void KeyBinder::JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList)
+    {
+        unsigned int oldValue = joySticks_.size();
+        joySticks_ = joyStickList;
+
+        // initialise joy stick bindings
+        initialiseJoyStickBindings();
+
+        // collect all Buttons and HalfAxes again
+        compilePointerLists();
+
+        // load the bindings if required
+        if (configFile_ != ConfigFileType::NoType)
+        {
+            for (unsigned int iDev = oldValue; iDev < joySticks_.size(); ++iDev)
+            {
+                for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; ++i)
+                    (*joyStickButtons_[iDev])[i].readConfigValue(this->configFile_);
+                for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; ++i)
+                    (*joyStickAxes_[iDev])[i].readConfigValue(this->configFile_);
+            }
+        }
+
+        // Set the button threshold for potential new axes
+        buttonThresholdChanged();
+    }
+
+    void KeyBinder::initialiseJoyStickBindings()
+    {
+        while (joyStickAxes_.size() < joySticks_.size())
+            joyStickAxes_.push_back(shared_ptr<JoyStickAxisVector>(new JoyStickAxisVector()));
+        while (joyStickButtons_.size() < joySticks_.size())
+            joyStickButtons_.push_back(shared_ptr<JoyStickButtonVector>(new JoyStickButtonVector()));
+        // For the case the new size is smaller
+        this->joyStickAxes_.resize(joySticks_.size());
+        this->joyStickButtons_.resize(joySticks_.size());
+
+        // reinitialise all joy stick binings (doesn't overwrite the old ones)
+        for (unsigned int iDev = 0; iDev < joySticks_.size(); iDev++)
+        {
+            std::string deviceName = joySticks_[iDev]->getDeviceName();
+            // joy stick buttons
+            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
+            {
+                (*joyStickButtons_[iDev])[i].name_ = JoyStickButtonCode::ByString[i];
+                (*joyStickButtons_[iDev])[i].paramCommandBuffer_ = &paramCommandBuffer_;
+                (*joyStickButtons_[iDev])[i].groupName_ = "JoyStickButtons_" + deviceName;
+            }
+            // joy stick axes
+            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
+            {
+                (*joyStickAxes_[iDev])[i].name_ = JoyStickAxisCode::ByString[i / 2];
+                if (i & 1)
+                    (*joyStickAxes_[iDev])[i].name_ += "Pos";
+                else
+                    (*joyStickAxes_[iDev])[i].name_ += "Neg";
+                (*joyStickAxes_[iDev])[i].paramCommandBuffer_ = &paramCommandBuffer_;
+                (*joyStickAxes_[iDev])[i].groupName_ = "JoyStickAxes_" + deviceName;
+            }
+        }
+    }
+
+    void KeyBinder::compilePointerLists()
+    {
+        allButtons_.clear();
+        allHalfAxes_.clear();
+
+        // Note: Don't include the dummy keys which don't actually exist in OIS but have a number
+        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
+            if (!keys_[i].name_.empty())
+                allButtons_[keys_[i].groupName_ + "." + keys_[i].name_] = keys_ + i;
+        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
+            allButtons_[mouseButtons_[i].groupName_ + "." + mouseButtons_[i].name_] = mouseButtons_ + i;
+        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
+        {
+            allButtons_[mouseAxes_[i].groupName_ + "." + mouseAxes_[i].name_] = mouseAxes_ + i;
+            allHalfAxes_.push_back(mouseAxes_ + i);
+        }
+        for (unsigned int iDev = 0; iDev < joySticks_.size(); iDev++)
+        {
+            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
+                allButtons_[(*joyStickButtons_[iDev])[i].groupName_ + "." + (*joyStickButtons_[iDev])[i].name_] = &((*joyStickButtons_[iDev])[i]);
+            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
+            {
+                allButtons_[(*joyStickAxes_[iDev])[i].groupName_ + "." + (*joyStickAxes_[iDev])[i].name_] = &((*joyStickAxes_[iDev])[i]);
+                allHalfAxes_.push_back(&((*joyStickAxes_[iDev])[i]));
+            }
+        }
+    }
+
+    /**
+    @brief
+        Loads the key and button bindings.
+    @return
+        True if loading succeeded.
+    */
+    void KeyBinder::loadBindings(const std::string& filename)
+    {
+        COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
+
+        if (filename.empty())
+            return;
+
+        if (this->configFile_ == ConfigFileType::NoType)
+        {
+            // Get a new ConfigFileType from the ConfigFileManager
+            this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
+        }
+
+        ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
+
+        // Parse bindings and create the ConfigValueContainers if necessary
+        clearBindings();
+        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
+            it->second->readConfigValue(this->configFile_);
+
+        COUT(3) << "KeyBinder: Loading key bindings done." << std::endl;
+    }
+
+    bool KeyBinder::setBinding(const std::string& binding, const std::string& name, bool bTemporary)
+    {
+        std::map<std::string, Button*>::iterator it = allButtons_.find(name);
+        if (it != allButtons_.end())
+        {
+            if (bTemporary)
+                it->second->configContainer_->tset(binding);
+            else
+                it->second->configContainer_->set(binding);
+            it->second->configContainer_->getValue(&(it->second->bindingString_), it->second);
+            return true;
+        }
+        else
+        {
+            COUT(2) << "Could not find key/button/axis with name '" << name << "'." << std::endl;
+            return false;
+        }
+    }
+
+    /**
+    @brief
+        Overwrites all bindings with ""
+    */
+    void KeyBinder::clearBindings()
+    {
+        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
+            it->second->clear();
+
+        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
+            delete paramCommandBuffer_[i];
+        paramCommandBuffer_.clear();
+    }
+
+    void KeyBinder::resetJoyStickAxes()
+    {
+        for (unsigned int iDev = 0; iDev < joySticks_.size(); ++iDev)
+        {
+            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
+            {
+                (*joyStickAxes_[iDev])[i].absVal_ = 0.0f;
+                (*joyStickAxes_[iDev])[i].relVal_ = 0.0f;
+            }
+        }
+    }
+
+    void KeyBinder::mouseUpdated(float dt)
+    {
+        if (bDeriveMouseInput_)
+        {
+            // only update when derivation dt has passed
+            if (deriveTime_ > derivePeriod_)
+            {
+                for (int i = 0; i < 2; i++)
+                {
+                    if (mouseRelative_[i] < 0)
+                    {
+                        mouseAxes_[2*i + 0].absVal_
+                            = -mouseRelative_[i] / deriveTime_ * 0.0005f * mouseSensitivityDerived_;
+                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
+                    }
+                    else if (mouseRelative_[i] > 0)
+                    {
+                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
+                        mouseAxes_[2*i + 1].absVal_
+                            =  mouseRelative_[i] / deriveTime_ * 0.0005f * mouseSensitivityDerived_;
+                    }
+                    else
+                    {
+                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
+                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
+                    }
+                    mouseRelative_[i] = 0;
+                    mouseAxes_[2*i + 0].hasChanged_ = true;
+                    mouseAxes_[2*i + 1].hasChanged_ = true;
+                }
+                deriveTime_ = 0.0f;
+            }
+            else
+                deriveTime_ += dt;
+        }
+
+        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
+        {
+            // Why dividing relative value by dt? The reason lies in the simple fact, that when you
+            // press a button that has relative movement, that value has to be multiplied by dt to be
+            // frame rate independent. This can easily (and only) be done in updateInput(float).
+            // Hence we need to divide by dt here for the mouse to compensate, because the relative
+            // move movements have nothing to do with dt.
+            if (dt != 0.0f)
+            {
+                // just ignore if dt == 0.0 because we have multiplied by 0.0 anyway..
+                mouseAxes_[i].relVal_ /= dt;
+            }
+
+            tickHalfAxis(mouseAxes_[i]);
+        }
+    }
+
+    void KeyBinder::joyStickUpdated(unsigned int joyStick, float dt)
+    {
+        for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
+        {
+            tickHalfAxis((*joyStickAxes_[joyStick])[i]);
+        }
+    }
+
+    void KeyBinder::tickHalfAxis(HalfAxis& halfAxis)
+    {
+        // button mode
+        // TODO: optimize out all the half axes that don't act as a button at the moment
+        if (halfAxis.hasChanged_)
+        {
+            if (!halfAxis.pressed_ && halfAxis.absVal_ > halfAxis.buttonThreshold_)
+            {
+                // key pressed event
+                halfAxis.pressed_ = true;
+                if (halfAxis.nCommands_[KeybindMode::OnPress])
+                    halfAxis.execute(KeybindMode::OnPress);
+            }
+            else if (halfAxis.pressed_ && halfAxis.absVal_ < halfAxis.buttonThreshold_)
+            {
+                // key released event
+                halfAxis.pressed_ = false;
+                if (halfAxis.nCommands_[KeybindMode::OnRelease])
+                    halfAxis.execute(KeybindMode::OnRelease);
+            }
+            halfAxis.hasChanged_ = false;
+        }
+
+        if (halfAxis.pressed_)
+        {
+            // key held event
+            if (halfAxis.nCommands_[KeybindMode::OnHold])
+                halfAxis.execute(KeybindMode::OnHold);
+        }
+
+        // these are the actually useful axis bindings for analog input
+        if (!bFilterAnalogNoise_ || halfAxis.relVal_ > analogThreshold_ || halfAxis.absVal_ > analogThreshold_)
+        {
+            halfAxis.execute();
+        }
+    }
+
+    /**
+    @brief
+        Event handler for the mouseMoved Event.
+    @param e
+        Mouse state information
+    */
+    void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
+    {
+        // y axis of mouse input is inverted
+        int rel[] = { rel_.x, -rel_.y };
+
+        if (bDeriveMouseInput_)
+        {
+            mouseRelative_[0] += rel[0];
+            mouseRelative_[1] += rel[1];
+        }
+        else
+        {
+            for (int i = 0; i < 2; i++)
+            {
+                if (rel[i]) // performance opt. for the case that rel[i] == 0
+                {
+                    // write absolute values
+                    mouseAxes_[2*i + 0].hasChanged_ = true;
+                    mouseAxes_[2*i + 1].hasChanged_ = true;
+                    mousePosition_[i] += rel[i];
+
+                    // clip absolute position
+                    if (mousePosition_[i] > mouseClippingSize_)
+                        mousePosition_[i] =  mouseClippingSize_;
+                    if (mousePosition_[i] < -mouseClippingSize_)
+                        mousePosition_[i] = -mouseClippingSize_;
+
+                    if (mousePosition_[i] < 0)
+                    {
+                        mouseAxes_[2*i + 0].absVal_ = -mouseSensitivity_ * mousePosition_[i] / mouseClippingSize_;
+                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
+                    }
+                    else
+                    {
+                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
+                        mouseAxes_[2*i + 1].absVal_ =  mouseSensitivity_ * mousePosition_[i] / mouseClippingSize_;
+                    }
+                }
+            }
+        }
+
+        // relative
+        for (int i = 0; i < 2; i++)
+        {
+            if (rel[i] < 0)
+                mouseAxes_[0 + 2*i].relVal_ = -mouseSensitivity_ * rel[i] / mouseClippingSize_;
+            else
+                mouseAxes_[1 + 2*i].relVal_ =  mouseSensitivity_ * rel[i] / mouseClippingSize_;
+        }
+    }
+
+    /**
+    @brief Event handler for the mouseScrolled Event.
+    @param e Mouse state information
+    */
+    void KeyBinder::mouseScrolled(int abs, int rel)
+    {
+        if (rel < 0)
+            for (int i = 0; i < -rel/mouseWheelStepSize_; i++)
+                mouseButtons_[8].execute(KeybindMode::OnPress, static_cast<float>(abs)/mouseWheelStepSize_);
+        else
+            for (int i = 0; i < rel/mouseWheelStepSize_; i++)
+                mouseButtons_[9].execute(KeybindMode::OnPress, static_cast<float>(abs)/mouseWheelStepSize_);
+    }
+
+    void KeyBinder::axisMoved(unsigned int device, unsigned int axisID, float value)
+    {
+        int i = axisID * 2;
+        JoyStickAxisVector& axis = *joyStickAxes_[device];
+        if (value < 0)
+        {
+            axis[i].absVal_ = -value;
+            axis[i].relVal_ = -value;
+            axis[i].hasChanged_ = true;
+            if (axis[i + 1].absVal_ > 0.0f)
+            {
+                axis[i + 1].absVal_ = -0.0f;
+                axis[i + 1].relVal_ = -0.0f;
+                axis[i + 1].hasChanged_ = true;
+            }
+        }
+        else
+        {
+            axis[i + 1].absVal_ = value;
+            axis[i + 1].relVal_ = value;
+            axis[i + 1].hasChanged_ = true;
+            if (axis[i].absVal_ > 0.0f)
+            {
+                axis[i].absVal_ = -0.0f;
+                axis[i].relVal_ = -0.0f;
+                axis[i].hasChanged_ = true;
+            }
+        }
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/KeyBinder.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/KeyBinder.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/KeyBinder.h	(revision 5712)
@@ -0,0 +1,217 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Different definitions of input processing.
+*/
+
+#ifndef _KeyBinder_H__
+#define _KeyBinder_H__
+
+#include "InputPrereqs.h"
+
+#include <cassert>
+#include <string>
+#include <vector>
+#include <boost/shared_ptr.hpp>
+
+#include "InputHandler.h"
+#include "Button.h"
+#include "HalfAxis.h"
+#include "InputCommands.h"
+#include "JoyStickQuantityListener.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Handles mouse, keyboard and joy stick input while in the actual game mode.
+        Manages the key bindings.
+    */
+    class _CoreExport KeyBinder : public InputHandler, public JoyStickQuantityListener
+    {
+    public:
+        KeyBinder ();
+        virtual ~KeyBinder();
+
+        void loadBindings(const std::string& filename);
+        void clearBindings();
+        bool setBinding(const std::string& binding, const std::string& name, bool bTemporary = false);
+        void setConfigValues();
+        void resetJoyStickAxes();
+
+    protected: // functions
+        void allDevicesUpdated(float dt);
+        void mouseUpdated(float dt);
+        void joyStickUpdated(unsigned int joyStick, float dt);
+        // internal
+        void tickHalfAxis(HalfAxis& halfAxis);
+
+        void buttonThresholdChanged();
+        // from JoyStickQuantityListener interface
+        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+        void initialiseJoyStickBindings();
+        void compilePointerLists();
+
+        void buttonPressed (const KeyEvent& evt);
+        void buttonReleased(const KeyEvent& evt);
+        void buttonHeld    (const KeyEvent& evt);
+
+        void buttonPressed (MouseButtonCode::ByEnum button);
+        void buttonReleased(MouseButtonCode::ByEnum button);
+        void buttonHeld    (MouseButtonCode::ByEnum button);
+        void mouseMoved    (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
+        void mouseScrolled (int abs, int rel);
+
+        void buttonPressed (unsigned int device, JoyStickButtonCode::ByEnum button);
+        void buttonReleased(unsigned int device, JoyStickButtonCode::ByEnum button);
+        void buttonHeld    (unsigned int device, JoyStickButtonCode::ByEnum button);
+        void axisMoved     (unsigned int device, unsigned int axis, float value);
+
+    protected: // variables
+        //! Currently active joy sticks
+        std::vector<JoyStick*>  joySticks_;
+
+        //! Actual key bindings for keys on the keyboard
+        Button keys_            [KeyCode::numberOfKeys];
+        //! Number of mouse buttons in KeyBinder (+4)
+        static const unsigned int numberOfMouseButtons_ = MouseButtonCode::numberOfButtons + 4;
+        //! Actual key bindings for mouse buttons including the wheel(s)
+        Button mouseButtons_    [numberOfMouseButtons_];
+        //! Actual key bindings for mouse axes
+        HalfAxis mouseAxes_     [MouseAxisCode::numberOfAxes * 2];
+
+        //! Helper class to use something like std:vector<Button[64]>
+        struct JoyStickButtonVector
+        {
+            Button& operator[](unsigned int index) { return buttons[index]; }
+            Button buttons[JoyStickButtonCode::numberOfButtons];
+        };
+        //! Actual key bindings for joy stick buttons
+        std::vector<shared_ptr<JoyStickButtonVector> > joyStickButtons_;
+        //! Helper class to use something like std:vector<HalfAxis[48]>
+        struct JoyStickAxisVector
+        {
+            HalfAxis& operator[](unsigned int index) { return halfAxes[index]; }
+            HalfAxis halfAxes[JoyStickAxisCode::numberOfAxes * 2];
+        };
+        //! Actual key bindings for joy stick axes (and sliders)
+        std::vector<shared_ptr<JoyStickAxisVector> > joyStickAxes_;
+
+        //! Pointer map with all Buttons, including half axes
+        std::map<std::string, Button*> allButtons_;
+        //! Pointer list with all half axes
+        std::vector<HalfAxis*> allHalfAxes_;
+
+        /**
+        @brief
+            Commands that have additional parameters (axes) are executed at the end of
+            update() so that all values can be buffered for single execution.
+        */
+        std::vector<BufferedParamCommand*> paramCommandBuffer_;
+
+        //! Keeps track of the absolute mouse value (incl. scroll wheel)
+        int mousePosition_[2];
+        //! Used to derive mouse input if requested
+        int mouseRelative_[2];
+        float deriveTime_;
+
+        //! Config file used. ConfigFileType::NoType in case of KeyDetector. Also indicates whether we've already loaded.
+        ConfigFileType configFile_;
+
+    private:
+        //##### ConfigValues #####
+        //! Whether to filter small value analog input
+        bool bFilterAnalogNoise_;
+        //! Threshold for analog triggers until which the state is 0.
+        float analogThreshold_;
+        //! Threshold for analog triggers until which the button is not pressed.
+        float buttonThreshold_;
+        //! Derive mouse input for absolute values?
+        bool bDeriveMouseInput_;
+        //! Accuracy of the mouse input deriver. The higher the more precise, but laggier.
+        float derivePeriod_;
+        //! mouse sensitivity
+        float mouseSensitivity_;
+        //! mouse sensitivity if mouse input is derived
+        float mouseSensitivityDerived_;
+        //! Equals one step of the mousewheel
+        int mouseWheelStepSize_;
+
+        //##### Constant config variables #####
+        // Use some value at about 1000. This can be configured with mouseSensitivity_ anyway.
+        static const int mouseClippingSize_ = 1024;
+    };
+
+    inline void KeyBinder::buttonPressed (const KeyEvent& evt)
+    { assert(!keys_[evt.getKeyCode()].name_.empty()); keys_[evt.getKeyCode()].execute(KeybindMode::OnPress); }
+
+    inline void KeyBinder::buttonReleased(const KeyEvent& evt)
+    { assert(!keys_[evt.getKeyCode()].name_.empty()); keys_[evt.getKeyCode()].execute(KeybindMode::OnRelease); }
+
+    inline void KeyBinder::buttonHeld    (const KeyEvent& evt)
+    { assert(!keys_[evt.getKeyCode()].name_.empty()); keys_[evt.getKeyCode()].execute(KeybindMode::OnHold); }
+
+
+    inline void KeyBinder::buttonPressed (MouseButtonCode::ByEnum button)
+    { mouseButtons_[button].execute(KeybindMode::OnPress); }
+
+    inline void KeyBinder::buttonReleased(MouseButtonCode::ByEnum button)
+    { mouseButtons_[button].execute(KeybindMode::OnRelease); }
+
+    inline void KeyBinder::buttonHeld    (MouseButtonCode::ByEnum button)
+    { mouseButtons_[button].execute(KeybindMode::OnHold); }
+
+
+    inline void KeyBinder::buttonPressed (unsigned int device, JoyStickButtonCode::ByEnum button)
+    { (*joyStickButtons_[device])[button].execute(KeybindMode::OnPress); }
+
+    inline void KeyBinder::buttonReleased(unsigned int device, JoyStickButtonCode::ByEnum button)
+    { (*joyStickButtons_[device])[button].execute(KeybindMode::OnRelease); }
+
+    inline void KeyBinder::buttonHeld    (unsigned int device, JoyStickButtonCode::ByEnum button)
+    { (*joyStickButtons_[device])[button].execute(KeybindMode::OnHold); }
+
+    inline void KeyBinder::allDevicesUpdated(float dt)
+    {
+        // execute all buffered bindings (additional parameter)
+        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
+        {
+            paramCommandBuffer_[i]->rel_ *= dt;
+            paramCommandBuffer_[i]->execute();
+        }
+
+        // always reset the relative movement of the mouse
+        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
+            mouseAxes_[i].relVal_ = 0.0f;
+    }
+}
+
+#endif /* _KeyBinder_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/KeyDetector.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/KeyDetector.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/KeyDetector.cc	(revision 5712)
@@ -0,0 +1,75 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "KeyDetector.h"
+
+#include "util/Debug.h"
+#include "core/CoreIncludes.h"
+#include "Button.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Constructor
+    */
+    KeyDetector::KeyDetector()
+    {
+        RegisterObject(KeyDetector);
+    }
+
+    /**
+    @brief
+        Destructor
+    */
+    KeyDetector::~KeyDetector()
+    {
+    }
+
+    /**
+    @brief
+        Assigns all the buttons 'command' plus the button's name.
+    */
+    void KeyDetector::setCallbackCommand(const std::string& command)
+    {
+        callbackCommand_ = command;
+        clearBindings();
+        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
+        {
+            it->second->bindingString_ = callbackCommand_ + it->second->groupName_ + "." + it->second->name_;
+            it->second->parse();
+        }
+    }
+
+    void KeyDetector::JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList)
+    {
+        KeyBinder::JoyStickQuantityChanged(joyStickList);
+        if (!callbackCommand_.empty())
+            setCallbackCommand(callbackCommand_);
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/KeyDetector.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/KeyDetector.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/KeyDetector.h	(revision 5712)
@@ -0,0 +1,52 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _KeyDetector_H__
+#define _KeyDetector_H__
+
+#include "InputPrereqs.h"
+
+#include <string>
+#include "KeyBinder.h"
+
+namespace orxonox
+{
+    class _CoreExport KeyDetector : public KeyBinder
+    {
+    public:
+        KeyDetector();
+        ~KeyDetector();
+        void setCallbackCommand(const std::string& command);
+        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+
+    private:
+        std::string callbackCommand_;
+    };
+}
+
+#endif /* _KeyDetector_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/Keyboard.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/Keyboard.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/Keyboard.cc	(revision 5712)
@@ -0,0 +1,65 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Keyboard.h"
+#include "InputState.h"
+
+namespace orxonox
+{
+    //! OIS event handler
+    bool Keyboard::keyPressed(const OIS::KeyEvent& arg)
+    {
+        // update modifiers
+        if(arg.key == OIS::KC_RMENU    || arg.key == OIS::KC_LMENU)
+            modifiers_ |= KeyboardModifier::Alt;   // alt key
+        if(arg.key == OIS::KC_RCONTROL || arg.key == OIS::KC_LCONTROL)
+            modifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
+        if(arg.key == OIS::KC_RSHIFT   || arg.key == OIS::KC_LSHIFT)
+            modifiers_ |= KeyboardModifier::Shift; // shift key
+
+        KeyEvent evt(arg);
+        super::buttonPressed(evt);
+        return true;
+    }
+
+    //! OIS event handler
+    bool Keyboard::keyReleased(const OIS::KeyEvent& arg)
+    {
+        // update modifiers
+        if(arg.key == OIS::KC_RMENU    || arg.key == OIS::KC_LMENU)
+            modifiers_ &= ~KeyboardModifier::Alt;   // alt key
+        if(arg.key == OIS::KC_RCONTROL || arg.key == OIS::KC_LCONTROL)
+            modifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
+        if(arg.key == OIS::KC_RSHIFT   || arg.key == OIS::KC_LSHIFT)
+            modifiers_ &= ~KeyboardModifier::Shift; // shift key
+
+        KeyEvent evt(arg);
+        super::buttonReleased(evt);
+        return true;
+    }
+}
Index: /code/branches/libraries2/src/libraries/core/input/Keyboard.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/Keyboard.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/Keyboard.h	(revision 5712)
@@ -0,0 +1,90 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Core_Keyboard_H__
+#define _Core_Keyboard_H__
+
+#include "InputPrereqs.h"
+
+#include "InputHandler.h"
+#include "InputDevice.h"
+
+namespace orxonox
+{
+    //! Template parameter collection for the base class
+    struct KeyboardTraits
+    {
+        typedef Keyboard DeviceClass;
+        typedef OIS::Keyboard OISDeviceClass;
+        typedef KeyEvent ButtonType;
+        typedef KeyEvent& ButtonTypeParam;
+        static const OIS::Type OISDeviceValue = OIS::OISKeyboard;
+    };
+
+    /**
+    @brief
+        Wraps around an OIS::Mouse and forwards the input events to
+        a list of input states.
+
+        It also saves the state of the keyboard modifiers (like shift, etc.)
+    */
+    class _CoreExport Keyboard
+        : public InputDeviceTemplated<KeyboardTraits>
+        , public OIS::KeyListener
+    {
+        friend class InputDeviceTemplated<KeyboardTraits>;
+        //! Super class alias
+        typedef InputDeviceTemplated<KeyboardTraits> super;
+
+    public:
+        //! Only resets the keyboard modifiers. Initialising is done in the base class.
+        Keyboard(unsigned int id, OIS::InputManager* oisInputManager) : super(id, oisInputManager), modifiers_(0) { }
+        ~Keyboard() { }
+
+    private:
+        //! Resets the keyboard modifiers
+        void clearBuffersImpl() { this->modifiers_ = 0; }
+        //! Translates the KeyHandle to a KeyEvent
+        KeyEvent& getButtonEventArg(KeyEvent& button)
+        {
+            button.setModifiers(modifiers_);
+            return button;
+        }
+
+        bool keyPressed(const OIS::KeyEvent& arg);
+        bool keyReleased(const OIS::KeyEvent& arg);
+
+        //! Returns the class name as string
+        static std::string getClassNameImpl() { return "Keyboard"; }
+
+        //! Bit mask representing keyboard modifiers
+        int modifiers_;
+    };
+}
+
+#endif /* _Core_Keyboard_H__ */
Index: /code/branches/libraries2/src/libraries/core/input/Mouse.cc
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/Mouse.cc	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/Mouse.cc	(revision 5712)
@@ -0,0 +1,109 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "Mouse.h"
+
+#include <ois/OISMouse.h>
+#include "core/ConsoleCommand.h"
+#include "core/CoreIncludes.h"
+#include "InputState.h"
+
+#ifdef ORXONOX_PLATFORM_LINUX
+// include this as last, X11 seems to define some macros...
+#include <ois/linux/LinuxMouse.h>
+#endif
+
+namespace orxonox
+{
+    Mouse::Mouse(unsigned int id, OIS::InputManager* oisInputManager)
+        : super(id, oisInputManager)
+    {
+        RegisterRootObject(Mouse);
+        this->windowResized(this->getWindowWidth(), this->getWindowHeight());
+
+#ifdef ORXONOX_PLATFORM_LINUX
+        {
+            // Mouse grab console command
+            FunctorMember<Mouse>* functor = createFunctor(&Mouse::grab);
+            functor->setObject(this);
+            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "grab"), false);
+        }
+        {
+            // Mouse ungrab console command
+            FunctorMember<Mouse>* functor = createFunctor(&Mouse::ungrab);
+            functor->setObject(this);
+            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "ungrab"), false);
+        }
+#endif
+    }
+
+    //! OIS event handler
+    bool Mouse::mouseMoved(const OIS::MouseEvent &e)
+    {
+        // check for actual moved event
+        if (e.state.X.rel != 0 || e.state.Y.rel != 0)
+        {
+            IntVector2 abs(e.state.X.abs, e.state.Y.abs);
+            IntVector2 rel(e.state.X.rel, e.state.Y.rel);
+            IntVector2 clippingSize(e.state.width, e.state.height);
+            for (unsigned int i = 0; i < inputStates_.size(); ++i)
+                inputStates_[i]->mouseMoved(abs, rel, clippingSize);
+        }
+
+        // check for mouse scrolled event
+        if (e.state.Z.rel != 0)
+        {
+            for (unsigned int i = 0; i < inputStates_.size(); ++i)
+                inputStates_[i]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
+        }
+
+        return true;
+    }
+
+    void Mouse::windowResized(unsigned int newWidth, unsigned int newHeight)
+    {
+        oisDevice_->getMouseState().width  = newWidth;
+        oisDevice_->getMouseState().height = newHeight;
+    }
+
+#ifdef ORXONOX_PLATFORM_LINUX
+    void Mouse::grab()
+    {
+        OIS::LinuxMouse* linuxMouse = dynamic_cast<OIS::LinuxMouse*>(oisDevice_);
+        assert(linuxMouse);
+        linuxMouse->grab(true);
+    }
+
+    void Mouse::ungrab()
+    {
+        OIS::LinuxMouse* linuxMouse = dynamic_cast<OIS::LinuxMouse*>(oisDevice_);
+        assert(linuxMouse);
+        linuxMouse->grab(false);
+    }
+#endif
+}
Index: /code/branches/libraries2/src/libraries/core/input/Mouse.h
===================================================================
--- /code/branches/libraries2/src/libraries/core/input/Mouse.h	(revision 5712)
+++ /code/branches/libraries2/src/libraries/core/input/Mouse.h	(revision 5712)
@@ -0,0 +1,98 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#ifndef _Core_Mouse_H__
+#define _Core_Mouse_H__
+
+#include "InputPrereqs.h"
+
+#include "InputDevice.h"
+#include "core/WindowEventListener.h"
+
+namespace orxonox
+{
+    //! Template parameter collection for the base class
+    struct MouseTraits
+    {
+        typedef Mouse DeviceClass;
+        typedef OIS::Mouse OISDeviceClass;
+        typedef MouseButtonCode::ByEnum ButtonType;
+        typedef MouseButtonCode::ByEnum ButtonTypeParam;
+        static const OIS::Type OISDeviceValue = OIS::OISMouse;
+    };
+
+    /**
+    @brief
+        Wraps around an OIS::Mouse and forwards the input events to
+        a list of input states.
+    */
+    class _CoreExport Mouse
+        : public InputDeviceTemplated<MouseTraits>
+        , public OIS::MouseListener
+        , public WindowEventListener
+    {
+        friend class InputDeviceTemplated<MouseTraits>;
+        //! Super class alias
+        typedef InputDeviceTemplated<MouseTraits> super;
+
+    public:
+        //! Only sets the clipping size. Initialising is done in the base class.
+        Mouse(unsigned int id, OIS::InputManager* oisInputManager);
+        ~Mouse() { }
+
+#ifdef ORXONOX_PLATFORM_LINUX
+        // TODO: Make this a feature rather than a hack
+        void grab();
+        void ungrab();
+#endif
+
+    private:
+        //! OIS event handler
+        bool mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
+        {
+            super::buttonPressed(static_cast<MouseButtonCode::ByEnum>(id));
+            return true;
+        }
+
+        //! OIS event handler
+        bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
+        {
+            super::buttonReleased(static_cast<MouseButtonCode::ByEnum>(id));
+            return true;
+        }
+
+        bool mouseMoved(const OIS::MouseEvent &arg);
+
+        void windowResized(unsigned int newWidth, unsigned int newHeight);
+
+        // Returns the class name as string
+        static std::string getClassNameImpl() { return "Mouse"; }
+    };
+}
+
+#endif /* _Core_Mouse_H__ */
