Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/FICN/src/orxonox/orxonox.cc @ 576

Last change on this file since 576 was 576, checked in by landauf, 16 years ago

added Mesh and Model (doesn't work yet, but i don't want to have merge conflicts all the time :P)

File size: 13.7 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *
4 *
5 *   License notice:
6 *
7 *   This program is free software; you can redistribute it and/or
8 *   modify it under the terms of the GNU General Public License
9 *   as published by the Free Software Foundation; either version 2
10 *   of the License, or (at your option) any later version.
11 *
12 *   This program is distributed in the hope that it will be useful,
13 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 *   GNU General Public License for more details.
16 *
17 *   You should have received a copy of the GNU General Public License
18 *   along with this program; if not, write to the Free Software
19 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 *
21 *   Author:
22 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
23 *   Co-authors:
24 *      ...
25 *
26 */
27
28/**
29 @file  orxonox.cc
30 @brief Orxonox Main Class
31 */
32
33#include "orxonox.h"
34#include "graphicsEngine.h"
35
36//#include <Ogre.h>
37// 40% speed up: (instead of Ogre.h)
38#include <OgreSceneNode.h>
39#include <OgreSceneManager.h>
40#include <OgreRoot.h>
41#include <OgreFrameListener.h>
42#include <OgreConfigFile.h>
43#include <OgreTextureManager.h>
44#include <OgreEntity.h>
45#include <OgreRenderWindow.h>
46
47#include <OIS/OIS.h>
48//#include <CEGUI/CEGUI.h>
49//#include <OgreCEGUIRenderer.h>
50
51#include <string>
52#include <iostream>
53
54#include "objects/Tickable.h"
55#include "objects/Timer.h"
56#include "core/ArgReader.h"
57#include "core/Factory.h"
58#include "core/Debug.h"
59
60#include "../loader/LevelLoader.h"
61#include "../audio/AudioManager.h"
62
63#include "spaceship_steering.h"
64
65#include "particle/ParticleInterface.h"
66
67//network stuff
68#include "../network/Server.h"
69#include "../network/Client.h"
70#include "../network/NetworkFrameListener.h"
71
72#ifdef WIN32
73#include <windows.h>
74#define usleep(x) Sleep((x)/1000)
75#else
76#include <unistd.h>
77#endif
78
79namespace orxonox
80{
81  using namespace Ogre;
82
83   // put this in seperate Class or solve the problem in another fashion
84  class OrxListener : public FrameListener, public OIS::MouseListener
85  {
86    public:
87      OrxListener(OIS::Keyboard *keyboard, OIS::Mouse *mouse, audio::AudioManager*  auMan, SpaceshipSteering* steering)
88      : mKeyboard(keyboard), mMouse(mouse)
89      {
90
91
92
93        speed = 250;
94        loop = 100;
95        rotate = 10;
96        mouseX = 0;
97        mouseY = 0;
98        maxMouseX = 0;
99        minMouseX = 0;
100        moved = false;
101
102        steering_ = steering;
103
104        steering_->brakeRotate(rotate*10);
105        steering_->brakeLoop(loop);
106
107
108        mMouse->setEventCallback(this);
109        auMan_ = auMan;
110      }
111      bool frameStarted(const FrameEvent& evt)
112      {
113
114        auMan_->update();
115
116        mKeyboard->capture();
117        mMouse->capture();
118        if (mKeyboard->isKeyDown(OIS::KC_UP) || mKeyboard->isKeyDown(OIS::KC_W))
119          steering_->moveForward(speed);
120        else
121          steering_->moveForward(0);
122        if(mKeyboard->isKeyDown(OIS::KC_DOWN) || mKeyboard->isKeyDown(OIS::KC_S))
123          steering_->brakeForward(speed);
124        else
125          steering_->brakeForward(speed/10);
126        if (mKeyboard->isKeyDown(OIS::KC_RIGHT) || mKeyboard->isKeyDown(OIS::KC_D))
127          steering_->loopRight(loop);
128        else
129          steering_->loopRight(0);
130        if (mKeyboard->isKeyDown(OIS::KC_LEFT) || mKeyboard->isKeyDown(OIS::KC_A))
131          steering_->loopLeft(loop);
132        else
133          steering_->loopLeft(0);
134
135        if(moved) {
136          if (mouseY<=0)
137            steering_->rotateUp(-mouseY*rotate);
138          if (mouseY>0)
139            steering_->rotateDown(mouseY*rotate);
140          if (mouseX>0)
141            steering_->rotateRight(mouseX*rotate);
142          if (mouseX<=0)
143            steering_->rotateLeft(-mouseX*rotate);
144          mouseY = 0;
145          mouseX = 0;
146          moved = false;
147        }
148        else {
149          steering_->rotateUp(0);
150          steering_->rotateDown(0);
151          steering_->rotateRight(0);
152          steering_->rotateLeft(0);
153        }
154
155                steering_->tick(evt.timeSinceLastFrame);
156
157
158
159//      scenemanager->spacehip->tick(evt.timesincelastframe);
160        //if(mKeyboard->isKeyDown(OIS::KC_ESCAPE))
161          //cout << "maximal MouseX: " << maxMouseX << "\tminMouseX: " << minMouseX << endl;
162        usleep(10);
163        return !mKeyboard->isKeyDown(OIS::KC_ESCAPE);
164      }
165
166      bool mouseMoved(const OIS::MouseEvent &e)
167      {
168        mouseX += e.state.X.rel;
169        mouseY += e.state.Y.rel;
170        if(mouseX>maxMouseX) maxMouseX = mouseX;
171        if(mouseX<minMouseX) minMouseX = mouseX;
172        //cout << "mouseX: " << mouseX << "\tmouseY: " << mouseY << endl;
173        moved = true;
174        return true;
175      }
176
177      bool mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id) { return true; }
178      bool mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id) { return true; }
179
180    private:
181      float speed;
182      float rotate;
183      float loop;
184      float mouseY;
185      float mouseX;
186      float maxMouseX;
187      float minMouseX;
188      bool moved;
189      OIS::Keyboard *mKeyboard;
190      OIS::Mouse *mMouse;
191      audio::AudioManager*  auMan_;
192      SpaceshipSteering* steering_;
193  };
194  // init static singleton reference of Orxonox
195  Orxonox* Orxonox::singletonRef_ = NULL;
196
197  /**
198   * create a new instance of Orxonox
199   */
200  Orxonox::Orxonox()
201  {
202    ogre_ = new GraphicsEngine();
203    dataPath_ = "";
204  }
205
206  /**
207   * destruct Orxonox
208   */
209  Orxonox::~Orxonox()
210  {
211    // nothing to delete as for now
212  }
213
214  /**
215   * initialization of Orxonox object
216   * @param argc argument counter
217   * @param argv list of arguments
218   * @param path path to config (in home dir or something)
219   */
220  void Orxonox::init(int argc, char **argv, std::string path)
221  {
222    //TODO: find config file (assuming executable directory)
223    //TODO: read config file
224    //TODO: give config file to Ogre
225    std::string mode;
226    if(argc>=2)
227      mode = std::string(argv[1]);
228    else
229      mode = "";
230    ArgReader ar = ArgReader(argc, argv);
231    ar.checkArgument("mode", mode, false);
232    ar.checkArgument("data", this->dataPath_, false);
233    if(ar.errorHandling()) die();
234
235    if(mode == std::string("server"))
236    {
237      serverInit(path);
238      mode = SERVER;
239    }
240    else if(mode == std::string("client"))
241    {
242      clientInit(path);
243      mode = CLIENT;
244    }
245    else if(mode == std::string("presentation"))
246    {
247      serverInit(path);
248      mode = PRESENTATION;
249    }
250    else{
251      standaloneInit(path);
252      mode = STANDALONE;
253    }
254  }
255
256  /**
257   * start modules
258   */
259  void Orxonox::start()
260  {
261    //TODO: start modules
262    ogre_->startRender();
263    //TODO: run engine
264    createScene();
265    setupScene();
266    setupInputSystem();
267    createFrameListener();
268    Factory::createClassHierarchy();
269    switch(mode_){
270    case PRESENTATION:
271      server_g->open();
272      break;
273    case SERVER:
274    case CLIENT:
275    case STANDALONE:
276    default:
277      break;
278    }
279    startRenderLoop();
280  }
281
282  /**
283   * @return singleton object
284   */
285  Orxonox* Orxonox::getSingleton()
286  {
287    if (!singletonRef_)
288      singletonRef_ = new Orxonox();
289    return singletonRef_;
290  }
291
292  /**
293   * error kills orxonox
294   */
295  void Orxonox::die(/* some error code */)
296  {
297    //TODO: destroy and destruct everything and print nice error msg
298    delete this;
299  }
300
301  void Orxonox::standaloneInit(std::string path)
302  {
303    ogre_->setConfigPath(path);
304    ogre_->setup();
305    root_ = ogre_->getRoot();
306    if(!ogre_->load()) die(/* unable to load */);
307
308    //defineResources();
309    //setupRenderSystem();
310    //createRenderWindow();
311    //initializeResourceGroups();
312    /*createScene();
313    setupScene();
314    setupInputSystem();
315    createFrameListener();
316    Factory::createClassHierarchy();
317    startRenderLoop();*/
318  }
319
320  void Orxonox::playableServer(std::string path)
321  {
322    ogre_->setConfigPath(path);
323    ogre_->setup();
324    root_ = ogre_->getRoot();
325    defineResources();
326    setupRenderSystem();
327    createRenderWindow();
328    initializeResourceGroups();
329    createScene();
330    setupScene();
331    setupInputSystem();
332    Factory::createClassHierarchy();
333    createFrameListener();
334    try{
335      server_g = new network::Server(); // add port and bindadress
336      server_g->open(); // open server and create listener thread
337      if(ogre_ && ogre_->getRoot())
338        ogre_->getRoot()->addFrameListener(new network::ServerFrameListener()); // adds a framelistener for the server
339      COUT(3) << "Info: network framelistener added" << std::endl;
340    }
341    catch(exception &e)
342    {
343      COUT(1) << "Error: There was a problem initialising the server :(" << std::endl;
344    }
345    startRenderLoop();
346  }
347
348  void Orxonox::standalone(){
349
350
351
352  }
353
354  void Orxonox::serverInit(std::string path)
355  {
356    ogre_->setConfigPath(path);
357    ogre_->setup();
358    server_g = new network::Server(); // add some settings if wanted
359    if(!ogre_->load()) die(/* unable to load */);
360    // add network framelistener
361    ogre_->getRoot()->addFrameListener(new network::ServerFrameListener());
362  }
363
364  void Orxonox::clientInit(std::string path)
365  {
366    ogre_->setConfigPath(path);
367    ogre_->setup();
368    client_g = new network::Client(); // address here
369    if(!ogre_->load()) die(/* unable to load */);
370    ogre_->getRoot()->addFrameListener(new network::ClientFrameListener());
371  }
372
373  void Orxonox::defineResources()
374  {
375    Ogre::String secName, typeName, archName;
376    Ogre::ConfigFile cf;
377#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
378    cf.load(macBundlePath() + "/Contents/Resources/resources.cfg");
379#else
380    cf.load(dataPath_ + "resources.cfg");
381#endif
382
383    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
384    while (seci.hasMoreElements())
385    {
386      secName = seci.peekNextKey();
387      Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
388      Ogre::ConfigFile::SettingsMultiMap::iterator i;
389      for (i = settings->begin(); i != settings->end(); ++i)
390      {
391        typeName = i->first;
392        archName = i->second;
393#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
394        Ogre::ResourceGroupManager::getSingleton().addResourceLocation( String(macBundlePath() + "/" + archName), typeName, secName);
395#else
396        Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName);
397#endif
398      }
399    }
400  }
401
402  void Orxonox::setupRenderSystem()
403  {
404    if (/*!root_->restoreConfig() &&*/ !root_->showConfigDialog())
405      throw Exception(52, "User canceled the config dialog!", "OrxApplication::setupRenderSystem()");
406  }
407
408  void Orxonox::createRenderWindow()
409  {
410    root_->initialise(true, "OrxonoxV2");
411  }
412
413  void Orxonox::initializeResourceGroups()
414  {
415    TextureManager::getSingleton().setDefaultNumMipmaps(5);
416    ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
417  }
418
419  /**
420   *
421   * @param
422   */
423  void Orxonox::createScene(void)
424  {
425        // Init audio
426    auMan_ = new audio::AudioManager();
427
428    // load this file from config
429    loader_ = new loader::LevelLoader("sample.oxw");
430    loader_->loadLevel();
431
432        /*
433    auMan_->ambientAdd("a1");
434    auMan_->ambientAdd("a2");
435    auMan_->ambientAdd("a3");
436                                //auMan->ambientAdd("ambient1");
437    auMan_->ambientStart();
438        */
439  }
440
441
442  /**
443   *
444   */
445  void Orxonox::setupScene()
446  {
447    SceneManager *mgr = ogre_->getSceneManager();
448
449
450    SceneNode* node = (SceneNode*)mgr->getRootSceneNode()->getChild("OgreHeadNode");
451//     SceneNode *node = mgr->getRootSceneNode()->createChildSceneNode("OgreHeadNode", Vector3(0,0,0));
452
453
454    steering_ = new SpaceshipSteering(500, 200, 200, 200);
455    steering_->addNode(node);
456
457
458    particle::ParticleInterface *e = new particle::ParticleInterface(mgr,"engine","Orxonox/strahl");
459    e->particleSystem_->setParameter("local_space","true");
460    e->setPositionOfEmitter(0, Vector3(0,-10,200));
461    e->setDirection(Vector3(0,0,-1));
462    e->addToSceneNode(node);
463
464    particle::ParticleInterface *w = new particle::ParticleInterface(mgr,"schuss","Orxonox/schuss");
465    w->particleSystem_->setParameter("local_space","true");
466    w->newEmitter();
467    w->setDirection(Vector3(0,0,1));
468    w->setPositionOfEmitter(0, Vector3(10,10,0));
469    w->setPositionOfEmitter(1, Vector3(-10,10,0));
470    w->addToSceneNode(node);
471  }
472
473
474  void Orxonox::setupInputSystem()
475  {
476    size_t windowHnd = 0;
477    std::ostringstream windowHndStr;
478    OIS::ParamList pl;
479    Ogre::RenderWindow *win = ogre_->getRoot()->getAutoCreatedWindow();
480
481    win->getCustomAttribute("WINDOW", &windowHnd);
482    windowHndStr << windowHnd;
483    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
484    inputManager_ = OIS::InputManager::createInputSystem(pl);
485
486    try
487    {
488      keyboard_ = static_cast<OIS::Keyboard*>(inputManager_->createInputObject(OIS::OISKeyboard, false));
489      mouse_ = static_cast<OIS::Mouse*>(inputManager_->createInputObject(OIS::OISMouse, true));
490    }
491    catch (const OIS::Exception &e)
492    {
493      throw new Ogre::Exception(42, e.eText, "OrxApplication::setupInputSystem");
494    }
495  }
496
497  // we actually want to do this differently...
498  void Orxonox::createFrameListener()
499  {
500    TickFrameListener* TickFL = new TickFrameListener();
501    ogre_->getRoot()->addFrameListener(TickFL);
502
503    TimerFrameListener* TimerFL = new TimerFrameListener();
504    ogre_->getRoot()->addFrameListener(TimerFL);
505
506    frameListener_ = new OrxListener(keyboard_, mouse_, auMan_, steering_);
507    ogre_->getRoot()->addFrameListener(frameListener_);
508  }
509
510  void Orxonox::startRenderLoop()
511  {
512    // this is a hack!!!
513    // the call to reset the mouse clipping size should probably be somewhere
514    // else, however this works for the moment.
515    unsigned int width, height, depth;
516    int left, top;
517    ogre_->getRoot()->getAutoCreatedWindow()->getMetrics(width, height, depth, left, top);
518
519    const OIS::MouseState &ms = mouse_->getMouseState();
520    ms.width = width;
521    ms.height = height;
522
523    ogre_->getRoot()->startRendering();
524  }
525}
Note: See TracBrowser for help on using the repository browser.