Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/usability/src/orxonox/worldentities/WorldEntity.cc @ 8974

Last change on this file since 8974 was 7936, checked in by landauf, 14 years ago

trying to fix a crash

  • Property svn:eol-style set to native
File size: 37.8 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *      Reto Grieder (physics)
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30#include "WorldEntity.h"
31
32#include <OgreBillboardSet.h>
33#include <OgreCamera.h>
34#include <OgreEntity.h>
35#include <OgreParticleSystem.h>
36#include <OgreSceneManager.h>
37#include <OgreSceneNode.h>
38#include <BulletDynamics/Dynamics/btRigidBody.h>
39#include <boost/static_assert.hpp>
40
41#include "util/OrxAssert.h"
42#include "util/Convert.h"
43#include "util/Exception.h"
44#include "core/CoreIncludes.h"
45#include "core/XMLPort.h"
46#include "Scene.h"
47#include "collisionshapes/WorldEntityCollisionShape.h"
48
49namespace orxonox
50{
51    const Vector3 WorldEntity::FRONT = Vector3::NEGATIVE_UNIT_Z;
52    const Vector3 WorldEntity::BACK  = Vector3::UNIT_Z;
53    const Vector3 WorldEntity::LEFT  = Vector3::NEGATIVE_UNIT_X;
54    const Vector3 WorldEntity::RIGHT = Vector3::UNIT_X;
55    const Vector3 WorldEntity::DOWN  = Vector3::NEGATIVE_UNIT_Y;
56    const Vector3 WorldEntity::UP    = Vector3::UNIT_Y;
57
58    // Be sure we don't do bad conversions
59    BOOST_STATIC_ASSERT((int)Ogre::Node::TS_LOCAL  == (int)WorldEntity::Local);
60    BOOST_STATIC_ASSERT((int)Ogre::Node::TS_PARENT == (int)WorldEntity::Parent);
61    BOOST_STATIC_ASSERT((int)Ogre::Node::TS_WORLD  == (int)WorldEntity::World);
62
63    /**
64    @brief
65        Creates a new WorldEntity that may immediately be used.
66        All the default values are being set here.
67    */
68    WorldEntity::WorldEntity(BaseObject* creator) : BaseObject(creator), Synchronisable(creator)
69    {
70        RegisterObject(WorldEntity);
71
72        if (!this->getScene() || !this->getScene()->getRootSceneNode())
73            ThrowException(AbortLoading, "Can't create WorldEntity, no scene or no root-scenenode given.");
74
75        this->node_ = this->getScene()->getRootSceneNode()->createChildSceneNode();
76
77        this->parent_ = 0;
78        this->parentID_ = OBJECTID_UNKNOWN;
79        this->bDeleteWithParent_ = true;
80
81        this->node_->setPosition(Vector3::ZERO);
82        this->node_->setOrientation(Quaternion::IDENTITY);
83
84        // Activity and visibility memory.
85        this->bActiveMem_ = true;
86        this->bVisibleMem_ = true;
87
88
89        // Default behaviour does not include physics
90        this->physicalBody_   = 0;
91        this->bPhysicsActive_ = false;
92        this->bPhysicsActiveSynchronised_    = false;
93        this->bPhysicsActiveBeforeAttaching_ = false;
94        this->collisionShape_ = new WorldEntityCollisionShape(this);
95        this->collisionType_             = None;
96        this->collisionTypeSynchronised_ = None;
97        this->mass_           = 0;
98        this->childrenMass_   = 0;
99        // Using bullet default values
100        this->restitution_    = 0;
101        this->angularFactor_  = 1;
102        this->linearDamping_  = 0;
103        this->angularDamping_ = 0;
104        this->friction_       = 0.5;
105        this->bCollisionCallbackActive_ = false;
106        this->bCollisionResponseActive_ = true;
107
108        this->registerVariables();
109    }
110
111    /**
112    @brief
113        Destroys the WorldEntity AND ALL its children with it.
114    */
115    WorldEntity::~WorldEntity()
116    {
117        if (this->isInitialized())
118        {
119            if (this->parent_)
120                this->detachFromParent();
121
122            std::set<WorldEntity*>::iterator it;
123            while ((it = this->children_.begin()) != this->children_.end())
124            {
125                WorldEntity* entity = *it;
126
127                // do this for all children, because even if getDeleteWithParent() returns true a child might still stay active due to smart pointers pointing to it
128                entity->setPosition(entity->getWorldPosition());
129                this->detach(entity); // detach also erases the element from the children set
130
131                if (entity->getDeleteWithParent())
132                    entity->destroy();
133            }
134
135            if (this->physicalBody_)
136            {
137                this->deactivatePhysics();
138                delete this->physicalBody_;
139            }
140            this->collisionShape_->destroy();
141
142            this->node_->detachAllObjects();
143            this->node_->removeAllChildren();
144
145            OrxAssert(this->getScene()->getSceneManager(), "No SceneManager defined in a WorldEntity.");
146            this->getScene()->getSceneManager()->destroySceneNode(this->node_->getName());
147        }
148    }
149
150    void WorldEntity::XMLPort(Element& xmlelement, XMLPort::Mode mode)
151    {
152        SUPER(WorldEntity, XMLPort, xmlelement, mode);
153
154        XMLPortParamTemplate(WorldEntity, "position",    setPosition,    getPosition,    xmlelement, mode, const Vector3&);
155        XMLPortParamTemplate(WorldEntity, "orientation", setOrientation, getOrientation, xmlelement, mode, const Quaternion&);
156        XMLPortParamTemplate(WorldEntity, "scale3D",     setScale3D,     getScale3D,     xmlelement, mode, const Vector3&);
157        XMLPortParam        (WorldEntity, "scale",       setScale,       getScale,       xmlelement, mode);
158        XMLPortParamLoadOnly(WorldEntity, "lookat",      lookAt_xmlport,       xmlelement, mode);
159        XMLPortParamLoadOnly(WorldEntity, "direction",   setDirection_xmlport, xmlelement, mode);
160        XMLPortParamLoadOnly(WorldEntity, "yaw",         yaw_xmlport,          xmlelement, mode);
161        XMLPortParamLoadOnly(WorldEntity, "pitch",       pitch_xmlport,        xmlelement, mode);
162        XMLPortParamLoadOnly(WorldEntity, "roll",        roll_xmlport,         xmlelement, mode);
163        XMLPortParam        (WorldEntity, "deletewithparent", setDeleteWithParent, getDeleteWithParent, xmlelement, mode);
164
165        // Physics
166        XMLPortParam(WorldEntity, "collisionType",     setCollisionTypeStr,  getCollisionTypeStr,  xmlelement, mode);
167        XMLPortParam(WorldEntity, "collisionResponse", setCollisionResponse, hasCollisionResponse, xmlelement, mode);
168        XMLPortParam(WorldEntity, "mass",              setMass,              getMass,              xmlelement, mode);
169        XMLPortParam(WorldEntity, "restitution",       setRestitution,       getRestitution,       xmlelement, mode);
170        XMLPortParam(WorldEntity, "angularFactor",     setAngularFactor,     getAngularFactor,     xmlelement, mode);
171        XMLPortParam(WorldEntity, "linearDamping",     setLinearDamping,     getLinearDamping,     xmlelement, mode);
172        XMLPortParam(WorldEntity, "angularDamping",    setAngularDamping,    getAngularDamping,    xmlelement, mode);
173        XMLPortParam(WorldEntity, "friction",          setFriction,          getFriction,          xmlelement, mode);
174
175        // Other attached WorldEntities
176        XMLPortObject(WorldEntity, WorldEntity, "attached", attach, getAttachedObject, xmlelement, mode);
177        // Attached collision shapes
178        XMLPortObject(WorldEntity, CollisionShape, "collisionShapes", attachCollisionShape, getAttachedCollisionShape, xmlelement, mode);
179    }
180
181    void WorldEntity::registerVariables()
182    {
183        registerVariable(this->mainStateName_,  VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedMainStateName));
184
185        registerVariable(this->bActive_,        VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedActivity));
186        registerVariable(this->bVisible_,       VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedVisibility));
187
188        registerVariable(this->getScale3D(),    VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::scaleChanged));
189
190        // Physics stuff
191        registerVariable(this->mass_,           VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::massChanged));
192        registerVariable(this->restitution_,    VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::restitutionChanged));
193        registerVariable(this->angularFactor_,  VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::angularFactorChanged));
194        registerVariable(this->linearDamping_,  VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::linearDampingChanged));
195        registerVariable(this->angularDamping_, VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::angularDampingChanged));
196        registerVariable(this->friction_,       VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::frictionChanged));
197        registerVariable(this->bCollisionCallbackActive_,
198                                                VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::collisionCallbackActivityChanged));
199        registerVariable(this->bCollisionResponseActive_,
200                                                VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::collisionResponseActivityChanged));
201        registerVariable((int&)this->collisionTypeSynchronised_,
202                                                VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::collisionTypeChanged));
203        registerVariable(this->bPhysicsActiveSynchronised_,
204                                                VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::physicsActivityChanged));
205
206        // Attach to parent if necessary
207        registerVariable(this->parentID_,       VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::networkcallback_parentChanged));
208    }
209
210    /**
211    @brief
212        When the activity is changed, it is changed for all attached objects as well.
213    */
214    void WorldEntity::changedActivity(void)
215    {
216        SUPER(WorldEntity, changedActivity);
217
218        if(GameMode::isMaster())
219        {
220            for (std::set<WorldEntity*>::const_iterator it = this->getAttachedObjects().begin(); it != this->getAttachedObjects().end(); it++)
221            {
222                if(!this->isActive())
223                {
224                    (*it)->bActiveMem_ = (*it)->isActive();
225                    (*it)->setActive(this->isActive());
226                }
227                else
228                {
229                    (*it)->setActive((*it)->bActiveMem_);
230                }
231            }
232        }
233    }
234
235    /**
236    @brief
237        When the visibility is changed, it is changed for all attached objects as well.
238    */
239    void WorldEntity::changedVisibility(void)
240    {
241        SUPER(WorldEntity, changedVisibility);
242
243        if(GameMode::isMaster())
244        {
245            for (std::set<WorldEntity*>::const_iterator it = this->getAttachedObjects().begin(); it != this->getAttachedObjects().end(); it++)
246            {
247                if(!this->isVisible())
248                {
249                    (*it)->bVisibleMem_ = (*it)->isVisible();
250                    (*it)->setVisible(this->isVisible());
251                }
252                else
253                {
254                    (*it)->setVisible((*it)->bVisibleMem_);
255                }
256            }
257        }
258    }
259
260    /**
261    @brief
262        Network function that object this instance to its correct parent.
263    */
264    void WorldEntity::networkcallback_parentChanged()
265    {
266        if (this->parentID_ != OBJECTID_UNKNOWN)
267        {
268            WorldEntity* parent = orxonox_cast<WorldEntity*>(Synchronisable::getSynchronisable(this->parentID_));
269            if (parent)
270                this->attachToParent(parent);
271        }
272    }
273
274    /**
275    @brief
276        Attaches this object to a parent SceneNode.
277    @remarks
278        Only use this method if you know exactly what you're doing!
279        Normally, attaching works internally by attaching WE's.
280    */
281    void WorldEntity::attachToNode(Ogre::SceneNode* node)
282    {
283        Ogre::Node* parent = this->node_->getParent();
284        if (parent)
285            parent->removeChild(this->node_);
286        node->addChild(this->node_);
287    }
288
289    /**
290    @brief
291        Detaches this object from a parent SceneNode.
292    @remarks
293        Only use this method if you know exactly what you're doing!
294        Normally, attaching works internally by attaching WE's.
295    */
296    void WorldEntity::detachFromNode(Ogre::SceneNode* node)
297    {
298        node->removeChild(this->node_);
299//        this->getScene()->getRootSceneNode()->addChild(this->node_);
300    }
301
302    /**
303    @brief
304        Network callback for the collision type. Only change the type if it was valid.
305    */
306    void WorldEntity::collisionTypeChanged()
307    {
308        if (this->collisionTypeSynchronised_ != Dynamic &&
309            this->collisionTypeSynchronised_ != Kinematic &&
310            this->collisionTypeSynchronised_ != Static &&
311            this->collisionTypeSynchronised_ != None)
312        {
313            CCOUT(1) << "Error when collsion Type was received over network. Unknown enum value:" << this->collisionTypeSynchronised_ << std::endl;
314        }
315        else if (this->collisionTypeSynchronised_ != collisionType_)
316        {
317            if (this->parent_)
318                CCOUT(2) << "Warning: Network connection tried to set the collision type of an attached WE. Ignoring." << std::endl;
319            else
320                this->setCollisionType(this->collisionTypeSynchronised_);
321        }
322    }
323
324    //! Network callback for this->bPhysicsActive_
325    void WorldEntity::physicsActivityChanged()
326    {
327        if (this->bPhysicsActiveSynchronised_)
328            this->activatePhysics();
329        else
330            this->deactivatePhysics();
331    }
332
333    //! Function sets whether Bullet should issue a callback on collisions
334    void WorldEntity::collisionCallbackActivityChanged()
335    {
336        if (this->hasPhysics())
337        {
338            if (this->bCollisionCallbackActive_)
339                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() |
340                    btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
341            else
342                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() &
343                    ~btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
344        }
345    }
346
347    //! Function sets whether Bullet should react itself to a collision
348    void WorldEntity::collisionResponseActivityChanged()
349    {
350        if (this->hasPhysics())
351        {
352            if (this->bCollisionResponseActive_)
353                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() &
354                    ~btCollisionObject::CF_NO_CONTACT_RESPONSE);
355            else
356                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() |
357                    btCollisionObject::CF_NO_CONTACT_RESPONSE);
358        }
359    }
360
361    /**
362    @brief
363        Attaches a child WorldEntity to this object. This calls notifyBeingAttached()
364        of the child WE.
365    @note
366        The collision shape of the child object gets attached nevertheless. That also means
367        that you can change the collision shape of the child and it correctly cascadeds the changes to this instance.
368        Be aware of this implication: When implementing attaching of kinematic objects to others, you have to change
369        this behaviour because you then might not want to merge the collision shapes.
370    */
371    void WorldEntity::attach(WorldEntity* object)
372    {
373        if (object == this)
374        {
375            COUT(2) << "Warning: Can't attach a WorldEntity to itself." << std::endl;
376            return;
377        }
378
379        if (!object->notifyBeingAttached(this))
380            return;
381
382        this->attachNode(object->node_);
383        this->children_.insert(object);
384
385        this->attachCollisionShape(object->collisionShape_);
386        // mass
387        this->childrenMass_ += object->getMass();
388        recalculateMassProps();
389    }
390
391    /**
392    @brief
393        Function gets called when this object is being attached to a new parent.
394
395        This operation is only allowed if the collision types "like" each other.
396        - You cannot a attach a non physical object to a physical one.
397        - Dynamic object can NOT be attached at all.
398        - It is also not possible to attach a kinematic to a dynamic one.
399        - Attaching of kinematic objects otherwise is not yet supported.
400    */
401    bool WorldEntity::notifyBeingAttached(WorldEntity* newParent)
402    {
403        // check first whether attaching is even allowed
404        if (this->hasPhysics())
405        {
406            if (!newParent->hasPhysics())
407            {
408                COUT(2) << "Warning: Cannot attach a physical object to a non physical one." << std::endl;
409                return false;
410            }
411            else if (this->isDynamic())
412            {
413                COUT(2) << "Warning: Cannot attach a dynamic object to a WorldEntity." << std::endl;
414                return false;
415            }
416            else if (this->isKinematic() && newParent->isDynamic())
417            {
418                COUT(2) << "Warning: Cannot attach a kinematic object to a dynamic one." << std::endl;
419                return false;
420            }
421            else if (this->isKinematic())
422            {
423                COUT(2) << "Warning: Cannot attach a kinematic object to a static or kinematic one: Not yet implemented." << std::endl;
424                return false;
425            }
426        }
427
428        if (this->isPhysicsActive())
429            this->bPhysicsActiveBeforeAttaching_ = true;
430        this->deactivatePhysics();
431
432        if (this->parent_)
433            this->detachFromParent();
434
435        this->parent_ = newParent;
436        this->parentID_ = newParent->getObjectID();
437
438        this->parentChanged();
439
440        // apply transform to collision shape
441        this->collisionShape_->setPosition(this->getPosition());
442        this->collisionShape_->setOrientation(this->getOrientation());
443        // TODO: Scale
444
445        return true;
446    }
447
448    /**
449    @brief
450        Detaches a child WorldEntity from this instance.
451    */
452    void WorldEntity::detach(WorldEntity* object)
453    {
454        std::set<WorldEntity*>::iterator it = this->children_.find(object);
455        if (it == this->children_.end())
456        {
457            CCOUT(2) << "Warning: Cannot detach an object that is not a child." << std::endl;
458            return;
459        }
460
461        // collision shapes
462        this->detachCollisionShape(object->collisionShape_);
463
464        // mass
465        if (object->getMass() > 0.0f)
466        {
467            this->childrenMass_ -= object->getMass();
468            recalculateMassProps();
469        }
470
471        this->detachNode(object->node_);
472        this->children_.erase(it);
473
474        object->notifyDetached();
475    }
476
477    /**
478    @brief
479        Function gets called when the object has been detached from its parent.
480    */
481    void WorldEntity::notifyDetached()
482    {
483        this->parent_ = 0;
484        this->parentID_ = OBJECTID_UNKNOWN;
485
486        this->parentChanged();
487
488        // reset orientation of the collisionShape (cannot be set within a WE usually)
489        this->collisionShape_->setPosition(Vector3::ZERO);
490        this->collisionShape_->setOrientation(Quaternion::IDENTITY);
491        // TODO: Scale
492
493        if (this->bPhysicsActiveBeforeAttaching_)
494        {
495            this->activatePhysics();
496            this->bPhysicsActiveBeforeAttaching_ = false;
497        }
498    }
499
500    //! Returns an attached object (merely for XMLPort).
501    WorldEntity* WorldEntity::getAttachedObject(unsigned int index)
502    {
503        unsigned int i = 0;
504        for (std::set<WorldEntity*>::const_iterator it = this->children_.begin(); it != this->children_.end(); ++it)
505        {
506            if (i == index)
507                return (*it);
508            ++i;
509        }
510        return 0;
511    }
512
513    //! Attaches an Ogre::SceneNode to this WorldEntity.
514    void WorldEntity::attachNode(Ogre::SceneNode* node)
515    {
516        Ogre::Node* parent = node->getParent();
517        if (parent)
518            parent->removeChild(node);
519        this->node_->addChild(node);
520    }
521
522    //! Detaches an Ogre::SceneNode from this WorldEntity.
523    void WorldEntity::detachNode(Ogre::SceneNode* node)
524    {
525        this->node_->removeChild(node);
526//        this->getScene()->getRootSceneNode()->addChild(node);
527    }
528
529    //! Attaches an Ogre::MovableObject to this WorldEntity.
530    void WorldEntity::attachOgreObject(Ogre::MovableObject* object)
531    {
532        this->node_->attachObject(object);
533        object->setUserAny(Ogre::Any(static_cast<OrxonoxClass*>(this)));
534    }
535
536    void WorldEntity::attachOgreObject(Ogre::BillboardSet* object)
537        { this->attachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
538    void WorldEntity::attachOgreObject(Ogre::Camera* object)
539        { this->attachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
540    void WorldEntity::attachOgreObject(Ogre::Entity* object)
541        { this->attachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
542    void WorldEntity::attachOgreObject(Ogre::ParticleSystem* object)
543        { this->attachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
544
545    //! Detaches an Ogre::MovableObject from this WorldEntity.
546    void WorldEntity::detachOgreObject(Ogre::MovableObject* object)
547    {
548        object->setUserAny(Ogre::Any(static_cast<OrxonoxClass*>(NULL)));
549        this->node_->detachObject(object);
550    }
551
552    void WorldEntity::detachOgreObject(Ogre::BillboardSet* object)
553        { this->detachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
554    void WorldEntity::detachOgreObject(Ogre::Camera* object)
555        { this->detachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
556    void WorldEntity::detachOgreObject(Ogre::Entity* object)
557        { this->detachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
558    void WorldEntity::detachOgreObject(Ogre::ParticleSystem* object)
559        { this->detachOgreObject(static_cast<Ogre::MovableObject*>(object)); }
560
561    //! Detaches an Ogre::MovableObject (by string) from this WorldEntity.
562    Ogre::MovableObject* WorldEntity::detachOgreObject(const Ogre::String& name)
563    {
564        return this->node_->detachObject(name);
565    }
566
567    //! Attaches a collision Shape to this object (delegated to the internal CompoundCollisionShape)
568    void WorldEntity::attachCollisionShape(CollisionShape* shape)
569    {
570        this->collisionShape_->attach(shape);
571        // Note: this->collisionShape_ already notifies us of any changes.
572    }
573
574    //! Detaches a collision Shape from this object (delegated to the internal CompoundCollisionShape)
575    void WorldEntity::detachCollisionShape(CollisionShape* shape)
576    {
577        // Note: The collision shapes may not be detached with this function!
578        this->collisionShape_->detach(shape);
579        // Note: this->collisionShape_ already notifies us of any changes.
580    }
581
582    //! Returns an attached collision Shape of this object (delegated to the internal CompoundCollisionShape)
583    CollisionShape* WorldEntity::getAttachedCollisionShape(unsigned int index)
584    {
585        return this->collisionShape_->getAttachedShape(index);
586    }
587
588    // Note: These functions are placed in WorldEntity.h as inline functions for the release build.
589#ifndef ORXONOX_RELEASE
590    const Vector3& WorldEntity::getPosition() const
591    {
592        return this->node_->getPosition();
593    }
594
595    const Quaternion& WorldEntity::getOrientation() const
596    {
597        return this->node_->getOrientation();
598    }
599
600    const Vector3& WorldEntity::getScale3D() const
601    {
602        return this->node_->getScale();
603    }
604#endif
605
606    //! Returns the position relative to the root space
607    const Vector3& WorldEntity::getWorldPosition() const
608    {
609        return this->node_->_getDerivedPosition();
610    }
611
612    //! Returns the orientation relative to the root space
613    const Quaternion& WorldEntity::getWorldOrientation() const
614    {
615        return this->node_->_getDerivedOrientation();
616    }
617
618    //! Returns the scaling applied relative to the root space in 3 coordinates
619    const Vector3& WorldEntity::getWorldScale3D() const
620    {
621        return this->node_->_getDerivedScale();
622    }
623
624    /**
625    @brief
626        Returns the scaling applied relative to the root space in 3 coordinates
627    @return
628        Returns the scaling if it is uniform, 1.0f otherwise.
629    */
630    float WorldEntity::getWorldScale() const
631    {
632        Vector3 scale = this->getWorldScale3D();
633        return (scale.x == scale.y && scale.x == scale.z) ? scale.x : 1;
634    }
635
636    /**
637    @brief
638        Sets the three dimensional scaling of this object.
639    @note
640        Scaling physical objects has not yet been implemented and is therefore forbidden.
641    */
642    void WorldEntity::setScale3D(const Vector3& scale)
643    {
644/*
645HACK HACK HACK
646        if (bScalePhysics && this->hasPhysics() && scale != Vector3::UNIT_SCALE)
647        {
648            CCOUT(2) << "Warning: Cannot set the scale of a physical object: Not yet implemented. Ignoring scaling." << std::endl;
649            return;
650        }
651HACK HACK HACK
652*/
653        this->node_->setScale(scale);
654
655        this->changedScale();
656    }
657
658    /**
659    @brief
660        Translates this WorldEntity by a vector.
661    @param distance
662        The relative distance of the translation
663    @param relativeTo
664        The TransformSpace of this translation
665    */
666    void WorldEntity::translate(const Vector3& distance, TransformSpace relativeTo)
667    {
668        switch (relativeTo)
669        {
670        case WorldEntity::Local:
671            // position is relative to parent so transform downwards
672            this->setPosition(this->getPosition() + this->getOrientation() * distance);
673            break;
674        case WorldEntity::Parent:
675            this->setPosition(this->getPosition() + distance);
676            break;
677        case WorldEntity::World:
678            // position is relative to parent so transform upwards
679            if (this->node_->getParent())
680                setPosition(getPosition() + (node_->getParent()->_getDerivedOrientation().Inverse() * distance)
681                    / node_->getParent()->_getDerivedScale());
682            else
683                this->setPosition(this->getPosition() + distance);
684            break;
685        }
686    }
687
688    /**
689    @brief
690        Rotates this WorldEntity by a quaternion.
691    @param rotation
692        The desired relative rotation
693    @param relativeTo
694        The TransformSpace of this translation
695    */
696    void WorldEntity::rotate(const Quaternion& rotation, TransformSpace relativeTo)
697    {
698        switch(relativeTo)
699        {
700        case WorldEntity::Local:
701            this->setOrientation(this->getOrientation() * rotation);
702            break;
703        case WorldEntity::Parent:
704            // Rotations are normally relative to local axes, transform up
705            this->setOrientation(rotation * this->getOrientation());
706            break;
707        case WorldEntity::World:
708            // Rotations are normally relative to local axes, transform up
709            this->setOrientation(this->getOrientation() * this->getWorldOrientation().Inverse()
710                * rotation * this->getWorldOrientation());
711            break;
712        }
713    }
714
715    /**
716    @brief
717        Makes this WorldEntity look at a specific target location.
718    @param target
719        An absolute point in the space which defines the direction of the entity
720    @param relativeTo
721        The TransformSpace of this translation
722    @param localDirectionVector
723        The vector which normally describes the natural direction of the object, usually -Z.
724    */
725    void WorldEntity::lookAt(const Vector3& target, TransformSpace relativeTo, const Vector3& localDirectionVector)
726    {
727        Vector3 origin(0, 0, 0);
728        switch (relativeTo)
729        {
730        case WorldEntity::Local:
731            origin = Vector3::ZERO;
732            break;
733        case WorldEntity::Parent:
734            origin = this->getPosition();
735            break;
736        case WorldEntity::World:
737            origin = this->getWorldPosition();
738            break;
739        }
740        this->setDirection(target - origin, relativeTo, localDirectionVector);
741    }
742
743    /**
744    @brief
745        Makes this WorldEntity look in specific direction.
746    @param direction
747        A point relative to the position of the WorldEntity which defines its orientation
748    @param relativeTo
749        The TransformSpace of this translation
750    @param localDirectionVector
751        The vector which normally describes the natural direction of the object, usually -Z.
752    */
753    void WorldEntity::setDirection(const Vector3& direction, TransformSpace relativeTo, const Vector3& localDirectionVector)
754    {
755        Quaternion savedOrientation(this->getOrientation());
756        this->node_->setDirection(direction, static_cast<Ogre::Node::TransformSpace>(relativeTo), localDirectionVector);
757        Quaternion newOrientation(this->node_->getOrientation());
758        this->node_->setOrientation(savedOrientation);
759        this->setOrientation(newOrientation);
760    }
761
762    //! Activates physics if the CollisionType is not None.
763    void WorldEntity::activatePhysics()
764    {
765        if (this->isActive() && this->hasPhysics() && !this->isPhysicsActive() && !this->parent_)
766        {
767            this->getScene()->addPhysicalObject(this);
768            this->bPhysicsActive_ = true;
769            this->bPhysicsActiveSynchronised_ = true;
770        }
771    }
772
773    //! Deactivates physics but the CollisionType does not change.
774    void WorldEntity::deactivatePhysics()
775    {
776        if (this->isPhysicsActive())
777        {
778            this->getScene()->removePhysicalObject(this);
779            this->bPhysicsActive_ = false;
780            this->bPhysicsActiveSynchronised_ = false;
781        }
782    }
783
784    //! Tells whether the object has already been added to the Bullet physics World.
785    bool WorldEntity::addedToPhysicalWorld() const
786    {
787        return this->physicalBody_ && this->physicalBody_->isInWorld();
788    }
789
790    /**
791    @brief
792        Sets the CollisionType. This alters the object significantly!
793    @note
794        Operation does not work on attached WorldEntities.
795    */
796    void WorldEntity::setCollisionType(CollisionType type)
797    {
798        if (this->collisionType_ == type)
799            return;
800
801        // If we are already attached to a parent, this would be a bad idea..
802        if (this->parent_)
803        {
804            CCOUT(2) << "Warning: Cannot set the collision type of a WorldEntity with a parent." << std::endl;
805            return;
806        }
807
808        // Check for type legality. Could be StaticEntity or MobileEntity.
809        if (!this->isCollisionTypeLegal(type))
810            return;
811
812        if (this->isPhysicsActive())
813            this->deactivatePhysics();
814
815        bool bReactivatePhysics = true;
816        if (this->hasPhysics() && !this->isPhysicsActive())
817            bReactivatePhysics = false;
818
819        // Check whether we have to create or destroy.
820        if (type != None && this->collisionType_ == None)
821        {
822/*
823HACK HACK HACK
824            // Check whether there was some scaling applied.
825            if (!this->node_->getScale().positionEquals(Vector3(1, 1, 1), 0.001))
826            {
827                CCOUT(2) << "Warning: Cannot create a physical body if there is scaling applied to the node: Not yet implemented." << std::endl;
828                return;
829            }
830HACK HACK HACK
831*/
832            // Create new rigid body
833            btRigidBody::btRigidBodyConstructionInfo bodyConstructionInfo(0, this, this->collisionShape_->getCollisionShape());
834            this->physicalBody_ = new btRigidBody(bodyConstructionInfo);
835            this->physicalBody_->setUserPointer(this);
836            this->physicalBody_->setActivationState(DISABLE_DEACTIVATION);
837        }
838        else if (type == None && this->collisionType_ != None)
839        {
840            // Destroy rigid body
841            assert(this->physicalBody_);
842            deactivatePhysics();
843            delete this->physicalBody_;
844            this->physicalBody_ = 0;
845            this->collisionType_ = None;
846            this->collisionTypeSynchronised_ = None;
847            return;
848        }
849
850        // Change type
851        switch (type)
852        {
853        case Dynamic:
854            this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() & !btCollisionObject::CF_STATIC_OBJECT & !btCollisionObject::CF_KINEMATIC_OBJECT);
855            break;
856        case Kinematic:
857            this->physicalBody_->setCollisionFlags((this->physicalBody_->getCollisionFlags() & !btCollisionObject::CF_STATIC_OBJECT) | btCollisionObject::CF_KINEMATIC_OBJECT);
858            break;
859        case Static:
860            this->physicalBody_->setCollisionFlags((this->physicalBody_->getCollisionFlags() & !btCollisionObject::CF_KINEMATIC_OBJECT) | btCollisionObject::CF_STATIC_OBJECT);
861            break;
862        case None:
863            assert(false); // Doesn't happen
864            return;
865        }
866        this->collisionType_ = type;
867        this->collisionTypeSynchronised_ = type;
868
869        // update mass and inertia tensor
870        recalculateMassProps();
871        internalSetPhysicsProps();
872        collisionCallbackActivityChanged();
873        collisionResponseActivityChanged();
874        if (bReactivatePhysics)
875            activatePhysics();
876    }
877
878    //! Sets the CollisionType by string (used for the XMLPort)
879    void WorldEntity::setCollisionTypeStr(const std::string& typeStr)
880    {
881        const std::string& typeStrLower = getLowercase(typeStr);
882        CollisionType type;
883        if (typeStrLower == "dynamic")
884            type = Dynamic;
885        else if (typeStrLower == "static")
886            type = Static;
887        else if (typeStrLower == "kinematic")
888            type = Kinematic;
889        else if (typeStrLower == "none")
890            type = None;
891        else
892            ThrowException(ParseError, std::string("Attempting to set an unknown collision type: '") + typeStr + "'.");
893        this->setCollisionType(type);
894    }
895
896    //! Gets the CollisionType by string (used for the XMLPort)
897    std::string WorldEntity::getCollisionTypeStr() const
898    {
899        switch (this->getCollisionType())
900        {
901            case Dynamic:
902                return "dynamic";
903            case Kinematic:
904                return "kinematic";
905            case Static:
906                return "static";
907            case None:
908                return "none";
909            default:
910                assert(false);
911                return "";
912        }
913    }
914
915    /**
916    @brief
917        Recalculates the accumulated child mass and calls recalculateMassProps()
918        and notifies the parent of the change.
919    @note
920        Called by a child WE
921    */
922    void WorldEntity::notifyChildMassChanged()
923    {
924        // Note: CollisionShape changes of a child get handled over the internal CompoundCollisionShape already
925        // Recalculate mass
926        this->childrenMass_ = 0.0f;
927        for (std::set<WorldEntity*>::const_iterator it = this->children_.begin(); it != this->children_.end(); ++it)
928            this->childrenMass_ += (*it)->getMass();
929        recalculateMassProps();
930        // Notify parent WE
931        if (this->parent_)
932            parent_->notifyChildMassChanged();
933    }
934
935    /**
936    @brief
937        Undertakes the necessary steps to change the collision shape in Bullet, even at runtime.
938    @note
939        - called by this->collisionShape_
940        - May have a REALLY big overhead when called continuously at runtime, because then we need
941          to remove the physical body from Bullet and add it again.
942    */
943    void WorldEntity::notifyCollisionShapeChanged()
944    {
945        if (hasPhysics())
946        {
947            // Bullet doesn't like sudden changes of the collision shape, so we remove and add it again
948            if (this->addedToPhysicalWorld())
949            {
950                this->deactivatePhysics();
951                this->physicalBody_->setCollisionShape(this->collisionShape_->getCollisionShape());
952                this->activatePhysics();
953            }
954            else
955                this->physicalBody_->setCollisionShape(this->collisionShape_->getCollisionShape());
956        }
957        recalculateMassProps();
958    }
959
960    //! Updates all mass dependent parameters (mass, inertia tensor and child mass)
961    void WorldEntity::recalculateMassProps()
962    {
963        // Store local inertia for faster access. Evaluates to (0,0,0) if there is no collision shape.
964        float totalMass = this->mass_ + this->childrenMass_;
965        this->collisionShape_->calculateLocalInertia(totalMass, this->localInertia_);
966        if (this->hasPhysics())
967        {
968            if (this->isStatic())
969            {
970                // Just set everything to zero
971                this->physicalBody_->setMassProps(0.0f, btVector3(0, 0, 0));
972            }
973            else if ((this->mass_ + this->childrenMass_) == 0.0f)
974            {
975                // Use default values to avoid very large or very small values
976                CCOUT(4) << "Warning: Setting the internal physical mass to 1.0 because mass_ is 0.0" << std::endl;
977                btVector3 inertia(0, 0, 0);
978                this->collisionShape_->calculateLocalInertia(1.0f, inertia);
979                this->physicalBody_->setMassProps(1.0f, inertia);
980            }
981            else
982            {
983                this->physicalBody_->setMassProps(totalMass, this->localInertia_);
984            }
985        }
986    }
987
988    //! Copies our own parameters for restitution, angular factor, damping and friction to the bullet rigid body.
989    void WorldEntity::internalSetPhysicsProps()
990    {
991        if (this->hasPhysics())
992        {
993            this->physicalBody_->setRestitution(this->restitution_);
994            this->physicalBody_->setAngularFactor(this->angularFactor_);
995            this->physicalBody_->setDamping(this->linearDamping_, this->angularDamping_);
996            this->physicalBody_->setFriction(this->friction_);
997        }
998    }
999}
Note: See TracBrowser for help on using the repository browser.