Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/orxonox/Scene.cc @ 10555

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

renamed SmartPtr to StrongPtr (now we have weak and strong pointers)

  • Property svn:eol-style set to native
File size: 15.7 KB
RevLine 
[2072]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
[2662]24 *      Reto Grieder (physics)
[2072]25 *   Co-authors:
26 *      ...
27 *
28 */
29
30#include "Scene.h"
31
32#include <OgreRoot.h>
[3196]33#include <OgreSceneManager.h>
[2072]34#include <OgreSceneManagerEnumerator.h>
35#include <OgreSceneNode.h>
36
[3196]37#include <BulletCollision/BroadphaseCollision/btAxisSweep3.h>
38#include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h>
39#include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h>
40#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
[2662]41
[2072]42#include "core/CoreIncludes.h"
[2896]43#include "core/GameMode.h"
[5929]44#include "core/GUIManager.h"
[2072]45#include "core/XMLPort.h"
[10347]46#include "core/command/ConsoleCommandIncludes.h"
[2662]47#include "tools/BulletConversions.h"
[10196]48#include "tools/BulletDebugDrawer.h"
49#include "tools/DebugDrawer.h"
[5929]50#include "Radar.h"
[5735]51#include "worldentities/WorldEntity.h"
[7163]52#include "Level.h"
[2072]53
54namespace orxonox
55{
[9667]56    RegisterClass(Scene);
[2072]57
[10196]58    SetConsoleCommand("Scene", "debugDrawPhysics", &Scene::consoleCommand_debugDrawPhysics).addShortcut().defaultValue(1, true).defaultValue(2, 0.5f);
59
[9667]60    Scene::Scene(Context* context) : BaseObject(context), Synchronisable(context), Context(context)
[2072]61    {
62        RegisterObject(Scene);
63
[10555]64        this->setScene(StrongPtr<Scene>(this, false), OBJECTID_UNKNOWN);
[2662]65        this->bShadows_ = true;
[10196]66        this->bDebugDrawPhysics_ = false;
67        this->debugDrawer_ = NULL;
[6417]68        this->soundReferenceDistance_ = 20.0;
[10415]69        this->bIsUpdatingPhysics_ = false;
[2072]70
[2896]71        if (GameMode::showsGraphics())
[2072]72        {
[3196]73            assert(Ogre::Root::getSingletonPtr());
74            this->sceneManager_ = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC);
75            this->rootSceneNode_ = this->sceneManager_->getRootSceneNode();
[5929]76
77            this->radar_ = new Radar();
[2072]78        }
79        else
80        {
81            // create a dummy SceneManager of our own since we don't have Ogre::Root.
82            this->sceneManager_ = new Ogre::DefaultSceneManager("");
83            this->rootSceneNode_ = this->sceneManager_->getRootSceneNode();
[5929]84
85            this->radar_ = 0;
[2072]86        }
87
[2662]88        // No physics yet, XMLPort will do that.
89        const int defaultMaxWorldSize = 100000;
90        this->negativeWorldRange_ = Vector3::UNIT_SCALE * -defaultMaxWorldSize;
91        this->positiveWorldRange_ = Vector3::UNIT_SCALE *  defaultMaxWorldSize;
92        this->gravity_ = Vector3::ZERO;
93        this->physicalWorld_   = 0;
94        this->solver_          = 0;
95        this->dispatcher_      = 0;
96        this->collisionConfig_ = 0;
97        this->broadphase_      = 0;
[2072]98
99        this->registerVariables();
100    }
101
102    Scene::~Scene()
103    {
104        if (this->isInitialized())
105        {
[10192]106            this->setPhysicalWorld(false);
107
108            if (this->radar_)
109                this->radar_->destroy();
110
[3196]111            if (GameMode::showsGraphics())
[2072]112                Ogre::Root::getSingleton().destroySceneManager(this->sceneManager_);
[3196]113            else
[2072]114                delete this->sceneManager_;
115        }
116    }
117
118    void Scene::XMLPort(Element& xmlelement, XMLPort::Mode mode)
119    {
120        SUPER(Scene, XMLPort, xmlelement, mode);
121
122        XMLPortParam(Scene, "skybox", setSkybox, getSkybox, xmlelement, mode);
[3196]123        XMLPortParam(Scene, "ambientlight", setAmbientLight, getAmbientLight, xmlelement, mode).defaultValues(ColourValue(0.2f, 0.2f, 0.2f, 1.0f));
[2072]124        XMLPortParam(Scene, "shadow", setShadow, getShadow, xmlelement, mode).defaultValues(true);
[6417]125        XMLPortParam(Scene, "soundReferenceDistance", setSoundReferenceDistance, getSoundReferenceDistance, xmlelement, mode);
[2072]126
[2662]127        XMLPortParam(Scene, "gravity", setGravity, getGravity, xmlelement, mode);
128        XMLPortParam(Scene, "negativeWorldRange", setNegativeWorldRange, getNegativeWorldRange, xmlelement, mode);
129        XMLPortParam(Scene, "positiveWorldRange", setPositiveWorldRange, getPositiveWorldRange, xmlelement, mode);
130        XMLPortParam(Scene, "hasPhysics", setPhysicalWorld, hasPhysics, xmlelement, mode).defaultValues(true);
131
[2072]132        XMLPortObjectExtended(Scene, BaseObject, "", addObject, getObject, xmlelement, mode, true, false);
133    }
134
135    void Scene::registerVariables()
136    {
[3280]137        registerVariable(this->skybox_,             VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applySkybox));
138        registerVariable(this->ambientLight_,       VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyAmbientLight));
139        registerVariable(this->negativeWorldRange_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_negativeWorldRange));
140        registerVariable(this->positiveWorldRange_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_positiveWorldRange));
141        registerVariable(this->gravity_,            VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_gravity));
142        registerVariable(this->bHasPhysics_,        VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_hasPhysics));
143        registerVariable(this->bShadows_,           VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyShadows));
[7163]144        registerVariable(this->getLevel(),          VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::changedLevel));
[2072]145    }
146
[2662]147    void Scene::setNegativeWorldRange(const Vector3& range)
148    {
149        if (range.length() < 10.0f)
150        {
[8858]151            orxout(internal_warning) << "Setting the negative world range to a very small value: "
152                                     << multi_cast<std::string>(range) << endl;
[2662]153        }
154        if (this->hasPhysics())
155        {
[8858]156            orxout(internal_warning) << "Attempting to set the physical world range at run time. "
157                                     << "This causes a complete physical reload which might take some time." << endl;
[2662]158            this->setPhysicalWorld(false);
159            this->negativeWorldRange_ = range;
160            this->setPhysicalWorld(true);
161        }
162        else
163            this->negativeWorldRange_ = range;
164    }
165
166    void Scene::setPositiveWorldRange(const Vector3& range)
167    {
168        if (range.length() < 10.0f)
169        {
[8858]170            orxout(internal_warning) << "Setting the positive world range to a very small value: "
171                                     << multi_cast<std::string>(range) << endl;
[2662]172        }
173        if (this->hasPhysics())
174        {
[8858]175            orxout(internal_warning) << "Attempting to set the physical world range at run time. "
176                                     << "This causes a complete physical reload which might take some time." << endl;
[2662]177            this->setPhysicalWorld(false);
178            this->positiveWorldRange_ = range;
179            this->setPhysicalWorld(true);
180        }
181        else
182            this->positiveWorldRange_ = range;
183    }
184
185    void Scene::setGravity(const Vector3& gravity)
186    {
187        this->gravity_ = gravity;
188        if (this->hasPhysics())
[3196]189            this->physicalWorld_->setGravity(multi_cast<btVector3>(this->gravity_));
[2662]190    }
191
192    void Scene::setPhysicalWorld(bool wantPhysics)
193    {
194        this->bHasPhysics_ = wantPhysics;
195        if (wantPhysics && !hasPhysics())
196        {
197            // Note: These are all little known default classes and values.
198            //       It would require further investigation to properly dertermine the right choices.
199            this->broadphase_      = new bt32BitAxisSweep3(
[3196]200                multi_cast<btVector3>(this->negativeWorldRange_), multi_cast<btVector3>(this->positiveWorldRange_));
[2662]201            this->collisionConfig_ = new btDefaultCollisionConfiguration();
202            this->dispatcher_      = new btCollisionDispatcher(this->collisionConfig_);
203            this->solver_          = new btSequentialImpulseConstraintSolver();
204
205            this->physicalWorld_   = new btDiscreteDynamicsWorld(this->dispatcher_, this->broadphase_, this->solver_, this->collisionConfig_);
[3196]206            this->physicalWorld_->setGravity(multi_cast<btVector3>(this->gravity_));
[2662]207
[10316]208            if (GameMode::showsGraphics() && this->sceneManager_)
209            {
210                this->debugDrawer_ = new BulletDebugDrawer(this->sceneManager_);
211                this->physicalWorld_->setDebugDrawer(this->debugDrawer_);
212            }
[10196]213
[2662]214            // also set the collision callback variable.
215            // Note: This is a global variable which we assign a static function.
216            // TODO: Check whether this (or anything about Bullet) works with multiple physics engine instances.
217            gContactAddedCallback = &Scene::collisionCallback;
218        }
219        else if (!wantPhysics && hasPhysics())
220        {
221            // Remove all WorldEntities and shove them to the queue since they would still like to be in a physical world.
222            for (std::set<WorldEntity*>::const_iterator it = this->physicalObjects_.begin();
223                it != this->physicalObjects_.end(); ++it)
224            {
225                this->physicalWorld_->removeRigidBody((*it)->physicalBody_);
226                this->physicalObjectQueue_.insert(*it);
227            }
228            this->physicalObjects_.clear();
229
[10196]230            delete this->debugDrawer_;
[2662]231            delete this->physicalWorld_;
232            delete this->solver_;
233            delete this->dispatcher_;
234            delete this->collisionConfig_;
235            delete this->broadphase_;
236            this->physicalWorld_   = 0;
237            this->solver_          = 0;
238            this->dispatcher_      = 0;
239            this->collisionConfig_ = 0;
240            this->broadphase_      = 0;
241        }
242    }
243
244    void Scene::tick(float dt)
245    {
[2896]246        if (!GameMode::showsGraphics())
[2662]247        {
248            // We need to update the scene nodes if we don't render
249            this->rootSceneNode_->_update(true, false);
250        }
251        if (this->hasPhysics())
252        {
253            // TODO: This here is bad practice! It will slow down the first tick() by ages.
254            //       Rather have an initialise() method as well, called by the Level after everything has been loaded.
255            if (this->physicalObjectQueue_.size() > 0)
256            {
257                // Add all scheduled WorldEntities
258                for (std::set<WorldEntity*>::const_iterator it = this->physicalObjectQueue_.begin();
259                    it != this->physicalObjectQueue_.end(); ++it)
260                {
261                    this->physicalWorld_->addRigidBody((*it)->physicalBody_);
262                    this->physicalObjects_.insert(*it);
263                }
264                this->physicalObjectQueue_.clear();
265            }
266
267            // Note: 60 means that Bullet will do physics correctly down to 1 frames per seconds.
268            //       Under that mark, the simulation will "loose time" and get unusable.
[10415]269            this->bIsUpdatingPhysics_ = true;
270            this->physicalWorld_->stepSimulation(dt, 60);
271            this->bIsUpdatingPhysics_ = false;
[10196]272
273            if (this->bDebugDrawPhysics_)
[10415]274                this->physicalWorld_->debugDrawWorld();
[2662]275        }
276    }
277
[2072]278    void Scene::setSkybox(const std::string& skybox)
279    {
[9348]280        try
281        {
282            if (GameMode::showsGraphics() && this->sceneManager_)
283                this->sceneManager_->setSkyBox(true, skybox);
284        }
285        catch (const Ogre::Exception&)
286        {
287            orxout(internal_error) << "Could not load skybox '" << skybox << "':" << endl;
288            orxout(internal_error) << Exception::handleMessage() << endl;
289        }
[2072]290
291        this->skybox_ = skybox;
292    }
293
294    void Scene::setAmbientLight(const ColourValue& colour)
295    {
[2896]296        if (GameMode::showsGraphics() && this->sceneManager_)
[2072]297            this->sceneManager_->setAmbientLight(colour);
298
299        this->ambientLight_ = colour;
300    }
301
302    void Scene::setShadow(bool bShadow)
303    {
[2896]304        if (GameMode::showsGraphics() && this->sceneManager_)
[2072]305        {
306            if (bShadow)
307                this->sceneManager_->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
308            else
309                this->sceneManager_->setShadowTechnique(Ogre::SHADOWTYPE_NONE);
310        }
311
312        this->bShadows_ = bShadow;
313    }
314
315    void Scene::addObject(BaseObject* object)
316    {
317        this->objects_.push_back(object);
[5929]318        object->setScene(this, this->getObjectID());
[2072]319    }
320
321    BaseObject* Scene::getObject(unsigned int index) const
322    {
323        unsigned int i = 0;
324        for (std::list<BaseObject*>::const_iterator it = this->objects_.begin(); it != this->objects_.end(); ++it)
325        {
326            if (i == index)
327                return (*it);
328            ++i;
329        }
330        return 0;
331    }
[2171]332
[2662]333    void Scene::addPhysicalObject(WorldEntity* object)
[2171]334    {
[2662]335        if (object)
[2171]336        {
[2662]337            std::set<WorldEntity*>::iterator it = this->physicalObjects_.find(object);
338            if (it != this->physicalObjects_.end())
339                return;
340
341            this->physicalObjectQueue_.insert(object);
[2171]342        }
343    }
[2662]344
345    void Scene::removePhysicalObject(WorldEntity* object)
346    {
347        // check queue first
348        std::set<WorldEntity*>::iterator it = this->physicalObjectQueue_.find(object);
349        if (it != this->physicalObjectQueue_.end())
350        {
351            this->physicalObjectQueue_.erase(it);
352            return;
353        }
354
355        it = this->physicalObjects_.find(object);
356        if (it == this->physicalObjects_.end())
357            return;
358        this->physicalObjects_.erase(it);
359
360        if (this->hasPhysics())
361            this->physicalWorld_->removeRigidBody(object->physicalBody_);
362    }
363
364    /*static*/ bool Scene::collisionCallback(btManifoldPoint& cp, const btCollisionObject* colObj0, int partId0,
365                                             int index0, const btCollisionObject* colObj1, int partId1, int index1)
366    {
367        // get the WorldEntity pointers
[10555]368        StrongPtr<WorldEntity> object0 = static_cast<WorldEntity*>(colObj0->getUserPointer());
369        StrongPtr<WorldEntity> object1 = static_cast<WorldEntity*>(colObj1->getUserPointer());
[2662]370
[10216]371        // get the CollisionShape pointers
372        const btCollisionShape* cs0 = colObj0->getCollisionShape();
373        const btCollisionShape* cs1 = colObj1->getCollisionShape();
374
[2662]375        // false means that bullet will assume we didn't modify the contact
376        bool modified = false;
377        if (object0->isCollisionCallbackActive())
[10216]378            modified |= object0->collidesAgainst(object1, cs1, cp);
[6064]379        if (object1->isCollisionCallbackActive())
[10216]380            modified |= object1->collidesAgainst(object0, cs0, cp);
[2662]381
382        return modified;
383    }
[10196]384
385    void Scene::setDebugDrawPhysics(bool bDraw, bool bFill, float fillAlpha)
386    {
387        this->bDebugDrawPhysics_ = bDraw;
388        if (this->debugDrawer_)
389            this->debugDrawer_->configure(bFill, fillAlpha);
390    }
391
392    /*static*/ void Scene::consoleCommand_debugDrawPhysics(bool bDraw, bool bFill, float fillAlpha)
393    {
394        for (ObjectListIterator<Scene> it = ObjectList<Scene>::begin(); it != ObjectList<Scene>::end(); ++it)
395            it->setDebugDrawPhysics(bDraw, bFill, fillAlpha);
396    }
[2072]397}
Note: See TracBrowser for help on using the repository browser.