Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/input/src/orxonox/Orxonox.cc @ 1531

Last change on this file since 1531 was 1531, checked in by rgrieder, 16 years ago
  • added various error code in GraphicsEngine
  • Config values for plugins.cfg, resources.cfg and ogre.log
  • created Settings class for general orxonox settings like dataPath
  • rewrote ArgReader to support any type of argument that converValue can convert
  • There is now a possibility to use boolean arguments (either given or not)
  • Property svn:eol-style set to native
File size: 14.5 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 *      Reto Grieder
24 *   Co-authors:
25 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
26 *
27 */
28
29/**
30 @file
31 @brief Orxonox Main Class
32 */
33
34// Precompiled Headers
35#include "OrxonoxStableHeaders.h"
36#include "Orxonox.h"
37
38//****** STD *******
39#include <deque>
40
41//****** OGRE ******
42#include <OgreFrameListener.h>
43#include <OgreOverlay.h>
44#include <OgreOverlayManager.h>
45#include <OgreRoot.h>
46#include <OgreTimer.h>
47#include <OgreWindowEventUtilities.h>
48
49//***** ORXONOX ****
50// util
51//#include "util/Sleep.h"
52#include "util/ArgReader.h"
53
54// core
55#include "core/ConfigFileManager.h"
56#include "core/ConsoleCommand.h"
57#include "core/Debug.h"
58#include "core/Loader.h"
59#include "core/input/InputManager.h"
60#include "core/TclBind.h"
61#include "core/Core.h"
62
63// audio
64#include "audio/AudioManager.h"
65
66// network
67#include "network/Server.h"
68#include "network/Client.h"
69
70// objects and tools
71#include "hud/HUD.h"
72#include "objects/Tickable.h"
73
74#include "GraphicsEngine.h"
75#include "Settings.h"
76
77// FIXME: is this really file scope?
78// globals for the server or client
79network::Client *client_g = 0;
80network::Server *server_g = 0;
81
82namespace orxonox
83{
84  SetConsoleCommandShortcut(Orxonox, exit).setKeybindMode(KeybindMode::OnPress);
85  SetConsoleCommandShortcut(Orxonox, slomo).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0).setAxisParamIndex(0).setIsAxisRelative(false);
86  SetConsoleCommandShortcut(Orxonox, setTimeFactor).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0);
87
88  /**
89    @brief Reference to the only instance of the class.
90  */
91  Orxonox *Orxonox::singletonRef_s = 0;
92
93  /**
94   * Create a new instance of Orxonox. Avoid doing any actual work here.
95   */
96  Orxonox::Orxonox() :
97    ogre_(0),
98    //auMan_(0),
99    timer_(0),
100    // turn on frame smoothing by setting a value different from 0
101    frameSmoothingTime_(0.0f),
102    orxonoxHUD_(0),
103    bAbort_(false),
104    timefactor_(1.0f),
105    mode_(STANDALONE),
106    serverIp_(""),
107    serverPort_(NETWORK_PORT)
108  {
109  }
110
111  /**
112   * Destruct Orxonox.
113   */
114  Orxonox::~Orxonox()
115  {
116    // keep in mind: the order of deletion is very important!
117//    if (this->orxonoxHUD_)
118//      delete this->orxonoxHUD_;
119    Loader::close();
120    InputManager::destroy();
121    //if (this->auMan_)
122    //  delete this->auMan_;
123    if (this->timer_)
124      delete this->timer_;
125    GraphicsEngine::getSingleton().destroy();
126
127    if (network::Client::getSingleton())
128      network::Client::destroySingleton();
129    if (server_g)
130      delete server_g;
131  }
132
133
134  /**
135    Asks the mainloop nicely to abort.
136  */
137  void Orxonox::abortRequest()
138  {
139    COUT(3) << "Orxonox: Abort requested." << std::endl;
140    bAbort_ = true;
141  }
142
143  /**
144   * @return singleton reference
145   */
146  Orxonox* Orxonox::getSingleton()
147  {
148    if (!singletonRef_s)
149      singletonRef_s = new Orxonox();
150    return singletonRef_s;
151  }
152
153  /**
154    @brief Destroys the Orxonox singleton.
155  */
156  void Orxonox::destroySingleton()
157  {
158    if (singletonRef_s)
159      delete singletonRef_s;
160    singletonRef_s = 0;
161  }
162
163  /**
164   * initialization of Orxonox object
165   * @param argc argument counter
166   * @param argv list of argumenst
167   * @param path path to config (in home dir or something)
168   */
169  bool Orxonox::init(int argc, char **argv)
170  {
171#ifdef _DEBUG
172    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox_d.ini");
173#else
174    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox.ini");
175#endif
176    Factory::createClassHierarchy();
177
178    std::string mode;
179    std::string tempDataPath;
180
181    ArgReader ar(argc, argv);
182    ar.checkArgument("mode", &mode, false);
183    ar.checkArgument("data", &tempDataPath, false);
184    ar.checkArgument("ip",   &serverIp_, false);
185    ar.checkArgument("port", &serverPort_, false);
186    if(ar.errorHandling())
187    {
188      COUT(1) << "Error while parsing command line arguments" << std::endl;
189      COUT(1) << ar.getErrorString();
190      COUT(0) << "Usage:" << std::endl << "orxonox [mode client|server|dedicated|standalone] "
191        << "[--data PATH] [--ip IP] [--port PORT]" << std::endl;
192      return false;
193    }
194
195    if (mode == "client")
196      mode_ = CLIENT;
197    else if (mode == "server")
198      mode_ = SERVER;
199    else if (mode == "dedicated")
200      mode_ = DEDICATED;
201    else
202    {
203      if (mode == "")
204        mode = "standalone";
205      if (mode != "standalone")
206      {
207        COUT(2) << "Warning: mode \"" << mode << "\" doesn't exist. "
208          << "Defaulting to standalone" << std::endl;
209        mode = "standalone";
210      }
211      mode_ = STANDALONE;
212    }
213    COUT(3) << "Orxonox: Mode is " << mode << "." << std::endl;
214
215    if (tempDataPath != "")
216    {
217      if (tempDataPath[tempDataPath.size() - 1] != '/')
218        tempDataPath += "/";
219      Settings::tsetDataPath(tempDataPath);
220    }
221
222    // initialise TCL
223    TclBind::getInstance().setDataPath(Settings::getDataPath());
224
225    //if (mode_ == DEDICATED)
226      // TODO: decide what to do here
227    //else
228
229    // for playable server, client and standalone, the startup
230    // procedure until the GUI is identical
231
232    ogre_ = &GraphicsEngine::getSingleton();
233    if (!ogre_->setup())       // creates ogre root and other essentials
234      return false;
235
236    return true;
237  }
238
239  /**
240   * start modules
241   */
242  bool Orxonox::start()
243  {
244    if (mode_ == DEDICATED)
245    {
246      // do something else
247    }
248    else
249    { // not dedicated server
250      if (!ogre_->loadRenderer())    // creates the render window
251        return false;
252
253      // Calls the InputManager which sets up the input devices.
254      // The render window width and height are used to set up the mouse movement.
255      if (!InputManager::initialise(ogre_->getWindowHandle(),
256            ogre_->getWindowWidth(), ogre_->getWindowHeight(), true, true, true))
257        return false;
258
259      // TODO: Spread this so that this call only initialises things needed for the GUI
260      if (!ogre_->initialiseResources())
261        return false;
262
263      // TOOD: load the GUI here
264      // set InputManager to GUI mode
265      InputManager::setInputState(InputManager::IS_GUI);
266      // TODO: run GUI here
267
268      // The following lines depend very much on the GUI output, so they're probably misplaced here..
269
270      InputManager::setInputState(InputManager::IS_NONE);
271
272      // create Ogre SceneManager
273      ogre_->createNewScene();
274
275      if (!loadPlayground())
276        return false;
277    }
278
279    switch (mode_)
280    {
281    case SERVER:
282      if (!serverLoad())
283        return false;
284      break;
285    case CLIENT:
286      if (!clientLoad())
287        return false;
288      break;
289    case DEDICATED:
290      if (!serverLoad())
291        return false;
292      break;
293    default:
294      if (!standaloneLoad())
295        return false;
296    }
297
298    InputManager::setInputState(InputManager::IS_NORMAL);
299
300    return startRenderLoop();
301  }
302
303  /**
304   * Loads everything in the scene except for the actual objects.
305   * This includes HUD, Console..
306   */
307  bool Orxonox::loadPlayground()
308  {
309    // Init audio
310    //auMan_ = new audio::AudioManager();
311    //auMan_->ambientAdd("a1");
312    //auMan_->ambientAdd("a2");
313    //auMan_->ambientAdd("a3");
314    //auMan->ambientAdd("ambient1");
315    //auMan_->ambientStart();
316
317    // Load the HUD
318    COUT(3) << "Orxonox: Loading HUD..." << std::endl;
319    orxonoxHUD_ = &HUD::getSingleton();
320    return true;
321  }
322
323  /**
324   * Level loading method for server mode.
325   */
326  bool Orxonox::serverLoad()
327  {
328    COUT(2) << "Loading level in server mode" << std::endl;
329
330    server_g = new network::Server(serverPort_);
331
332    if (!loadScene())
333      return false;
334
335    server_g->open();
336
337    return true;
338  }
339
340  /**
341   * Level loading method for client mode.
342   */
343  bool Orxonox::clientLoad()
344  {
345    COUT(2) << "Loading level in client mode" << std::endl;\
346
347    if (serverIp_.compare("") == 0)
348      client_g = network::Client::createSingleton();
349    else
350
351      client_g = network::Client::createSingleton(serverIp_, serverPort_);
352
353    if(!client_g->establishConnection())
354      return false;
355    client_g->tick(0);
356
357    return true;
358  }
359
360  /**
361   * Level loading method for standalone mode.
362   */
363  bool Orxonox::standaloneLoad()
364  {
365    COUT(2) << "Loading level in standalone mode" << std::endl;
366
367    if (!loadScene())
368      return false;
369
370    return true;
371  }
372
373  /**
374   * Helper method to load a level.
375   */
376  bool Orxonox::loadScene()
377  {
378    Level* startlevel = new Level("levels/sample.oxw");
379    Loader::open(startlevel);
380   
381    // HACK: shader stuff for presentation
382    /*Ogre::SceneManager* mSceneMgr = GraphicsEngine::getSingleton().getSceneManager();
383    mSceneMgr->setAmbientLight(ColourValue(0.4,0.4,0.4));
384    Ogre::Light* dirlight = mSceneMgr->createLight("Light1");
385
386    dirlight->setType(Ogre::Light::LT_DIRECTIONAL);
387    dirlight->setDirection(Vector3( 0, 1, 5 ));
388    dirlight->setDiffuseColour(ColourValue(0.6, 0.6, 0.4));
389    dirlight->setSpecularColour(ColourValue(1.0, 1.0, 1.0));*/
390   
391    return true;
392  }
393
394
395  /**
396    Main loop of the orxonox game.
397    About the loop: The design is almost exactly like the one in ogre, so that
398    if any part of ogre registers a framelisteners, it will still behave
399    correctly. Furthermore the time smoothing feature from ogre has been
400    implemented too. If turned on (see orxonox constructor), it will calculate
401    the dt_n by means of the recent most dt_n-1, dt_n-2, etc.
402  */
403  bool Orxonox::startRenderLoop()
404  {
405    // first check whether ogre root object has been created
406    if (Ogre::Root::getSingletonPtr() == 0)
407    {
408      COUT(2) << "Orxonox Error: Could not start rendering. No Ogre root object found" << std::endl;
409      return false;
410    }
411    Ogre::Root& ogreRoot = Ogre::Root::getSingleton();
412
413
414    // Contains the times of recently fired events
415    // eventTimes[4] is the list for the times required for the fps counter
416    std::deque<unsigned long> eventTimes[3];
417    // Clear event times
418    for (int i = 0; i < 3; ++i)
419      eventTimes[i].clear();
420
421    // use the ogre timer class to measure time.
422    if (!timer_)
423      timer_ = new Ogre::Timer();
424    timer_->reset();
425
426    float renderTime = 0.0f;
427    float frameTime = 0.0f;
428    clock_t time = 0;
429
430    //Ogre::SceneManager* mSceneMgr = GraphicsEngine::getSingleton().getSceneManager();
431    //Ogre::Viewport* mViewport = mSceneMgr->getCurrentViewport();
432   
433    //Ogre::CompositorManager::getSingleton().addCompositor(mViewport, "Bloom");
434    //Ogre::CompositorManager::getSingleton().addCompositor(mViewport, "MotionBlur");
435
436    COUT(3) << "Orxonox: Starting the main loop." << std::endl;
437    while (!bAbort_)
438    {
439      // get current time
440      unsigned long now = timer_->getMilliseconds();
441
442      // create an event to pass to the frameStarted method in ogre
443      Ogre::FrameEvent evt;
444      evt.timeSinceLastEvent = calculateEventTime(now, eventTimes[0]);
445      evt.timeSinceLastFrame = calculateEventTime(now, eventTimes[1]);
446      frameTime += evt.timeSinceLastFrame;
447
448      // show the current time in the HUD
449      // HUD::getSingleton().setTime(now);
450      if (mode_ != DEDICATED && frameTime > 0.4f)
451      {
452        HUD::getSingleton().setRenderTimeRatio(renderTime / frameTime);
453        frameTime = 0.0f;
454        renderTime = 0.0f;
455      }
456
457      // tick the core
458      Core::tick((float)evt.timeSinceLastFrame);
459      // Call those objects that need the real time
460      for (Iterator<TickableReal> it = ObjectList<TickableReal>::start(); it; ++it)
461        it->tick((float)evt.timeSinceLastFrame);
462      // Call the scene objects
463      for (Iterator<Tickable> it = ObjectList<Tickable>::start(); it; ++it)
464        it->tick((float)evt.timeSinceLastFrame * this->timefactor_);
465      //AudioManager::tick();
466      if (client_g)
467        client_g->tick((float)evt.timeSinceLastFrame);
468      if (server_g)
469        server_g->tick((float)evt.timeSinceLastFrame);
470
471      // don't forget to call _fireFrameStarted in ogre to make sure
472      // everything goes smoothly
473      ogreRoot._fireFrameStarted(evt);
474
475      // get current time
476      now = timer_->getMilliseconds();
477      calculateEventTime(now, eventTimes[2]);
478
479      if (mode_ != DEDICATED)
480      {
481        // Pump messages in all registered RenderWindows
482        // This calls the WindowEventListener objects.
483        Ogre::WindowEventUtilities::messagePump();
484
485        // render
486        ogreRoot._updateAllRenderTargets();
487      }
488
489      // get current time
490      now = timer_->getMilliseconds();
491
492      // create an event to pass to the frameEnded method in ogre
493      evt.timeSinceLastEvent = calculateEventTime(now, eventTimes[0]);
494      renderTime += calculateEventTime(now, eventTimes[2]);
495
496      // again, just to be sure ogre works fine
497      ogreRoot._fireFrameEnded(evt);
498      //msleep(200);
499    }
500
501    if (mode_ == CLIENT)
502      network::Client::getSingleton()->closeConnection();
503    else if (mode_ == SERVER)
504      server_g->close();
505
506    return true;
507  }
508
509  /**
510    Method for calculating the average time between recently fired events.
511    Code directly taken from OgreRoot.cc
512    @param now The current time in ms.
513    @param type The type of event to be considered.
514  */
515  float Orxonox::calculateEventTime(unsigned long now, std::deque<unsigned long> &times)
516  {
517    // Calculate the average time passed between events of the given type
518    // during the last frameSmoothingTime_ seconds.
519
520    times.push_back(now);
521
522    if(times.size() == 1)
523      return 0;
524
525    // Times up to frameSmoothingTime_ seconds old should be kept
526    unsigned long discardThreshold = (unsigned long)(frameSmoothingTime_ * 1000.0f);
527
528    // Find the oldest time to keep
529    std::deque<unsigned long>::iterator it  = times.begin();
530    // We need at least two times
531    std::deque<unsigned long>::iterator end = times.end() - 2;
532
533    while(it != end)
534    {
535      if (now - *it > discardThreshold)
536        ++it;
537      else
538        break;
539    }
540
541    // Remove old times
542    times.erase(times.begin(), it);
543
544    return (float)(times.back() - times.front()) / ((times.size() - 1) * 1000);
545  }
546}
Note: See TracBrowser for help on using the repository browser.