Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/main_reto/src/RunManager.cpp @ 128

Last change on this file since 128 was 128, checked in by rgrieder, 17 years ago
File size: 10.8 KB
Line 
1#include "RunManager.h"
2
3
4// Constructor takes a RenderWindow because it uses that to determine input context
5RunManager::RunManager(OgreControl * mOgre, bool bufferedKeys, bool bufferedMouse,
6                                           bool bufferedJoy ) :
7mOgre(mOgre), mWindow(mOgre->getRenderWindow()),
8mTranslateVector(Vector3::ZERO), mStatsOn(true), mNumScreenShots(0),
9mMoveScale(0.0f), mRotScale(0.0f), mTimeUntilNextToggle(0), mFiltering(TFO_BILINEAR),
10mAniso(1), mSceneDetailIndex(0), mMoveSpeed(300), mRotateSpeed(36), mDebugOverlay(0),
11mInputManager(0), mMouse(0), mKeyboard(0), mJoy(0)
12{
13        // create new SceneManger
14        mSceneMgr = mOgre->getRoot()->createSceneManager(ST_GENERIC,"mScene");
15
16
17        // create various objects
18        // background scene
19        mScene = new OrxonoxScene(mSceneMgr);
20
21        // create a steerable SceneNode for the spaceship to be attached to
22        mShipNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("ShipNode", Vector3(20, 20, 20));
23
24        // spaceship
25        mShip = new OrxonoxShip(mSceneMgr, mShipNode);
26
27        // load all resources and create the entities
28        mScene->initialise();
29        mShip->initialise();
30
31        // create camera and viewport
32        createCamera();
33        createViewports();
34
35        // Set default mipmap level (NB some APIs ignore this)
36        TextureManager::getSingleton().setDefaultNumMipmaps(5);
37
38        using namespace OIS;
39
40        mDebugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay");
41
42        LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
43        ParamList pl;
44        size_t windowHnd = 0;
45        std::ostringstream windowHndStr;
46
47        mWindow->getCustomAttribute("WINDOW", &windowHnd);
48        windowHndStr << windowHnd;
49        pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
50
51        mInputManager = InputManager::createInputSystem( pl );
52
53        //Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
54        mKeyboard = static_cast<Keyboard*>(mInputManager->createInputObject( OISKeyboard, bufferedKeys ));
55        mMouse = static_cast<Mouse*>(mInputManager->createInputObject( OISMouse, bufferedMouse ));
56        try {
57                mJoy = static_cast<JoyStick*>(mInputManager->createInputObject( OISJoyStick, bufferedJoy ));
58        }
59        catch(...) {
60                mJoy = 0;
61        }
62
63        //Set initial mouse clipping size
64        windowResized(mWindow);
65
66        showDebugOverlay(true);
67
68        //Register as a Window listener
69        WindowEventUtilities::addWindowEventListener(mWindow, this);
70}
71
72
73RunManager::~RunManager()
74{
75        //Remove ourself as a Window listener
76        WindowEventUtilities::removeWindowEventListener(mWindow, this);
77        windowClosed(mWindow);
78
79        if (mScene)
80                delete mScene;
81}
82
83
84// Override frameStarted event to process that (don't care about frameEnded)
85bool RunManager::tick(unsigned long time, float deltaTime)
86{
87        mTime = time;
88
89        updateStats();
90       
91        mScene->tick(time, deltaTime);
92
93        using namespace OIS;
94
95        if(mWindow->isClosed()) return false;
96
97        //Need to capture/update each device
98        mKeyboard->capture();
99        mMouse->capture();
100        if( mJoy ) mJoy->capture();
101
102        bool buffJ = (mJoy) ? mJoy->buffered() : true;
103
104        //Check if one of the devices is not buffered
105        if( !mMouse->buffered() || !mKeyboard->buffered() || !buffJ )
106        {
107                // one of the input modes is immediate, so setup what is needed for immediate movement
108                if (mTimeUntilNextToggle >= 0)
109                        mTimeUntilNextToggle -= deltaTime;
110
111                // If this is the first frame, pick a speed
112                if (deltaTime == 0)
113                {
114                        mMoveScale = 1;
115                        mRotScale = 0.1;
116                }
117                // Otherwise scale movement units by time passed since last frame
118                else
119                {
120                        // Move about 100 units per second,
121                        mMoveScale = mMoveSpeed * deltaTime;
122                        // Take about 10 seconds for full rotation
123                        mRotScale = mRotateSpeed * deltaTime;
124                }
125                mRotX = 0;
126                mRotY = 0;
127                mTranslateVector = Ogre::Vector3::ZERO;
128        }
129
130        //Check to see which device is not buffered, and handle it
131        if( !mKeyboard->buffered() )
132                if( processUnbufferedKeyInput() == false )
133                        return false;
134        if( !mMouse->buffered() )
135                if( processUnbufferedMouseInput() == false )
136                        return false;
137
138        if( !mMouse->buffered() || !mKeyboard->buffered() || !buffJ )
139                moveCamera();
140
141        return true;
142}
143
144
145//Adjust mouse clipping area
146void RunManager::windowResized(RenderWindow* rw)
147{
148        unsigned int width, height, depth;
149        int left, top;
150        rw->getMetrics(width, height, depth, left, top);
151
152        const OIS::MouseState &ms = mMouse->getMouseState();
153        ms.width = width;
154        ms.height = height;
155}
156
157
158//Unattach OIS before window shutdown (very important under Linux)
159void RunManager::windowClosed(RenderWindow* rw)
160{
161        //Only close for window that created OIS (the main window in these demos)
162        if( rw == mWindow )
163        {
164                if( mInputManager )
165                {
166                        mInputManager->destroyInputObject( mMouse );
167                        mInputManager->destroyInputObject( mKeyboard );
168                        mInputManager->destroyInputObject( mJoy );
169
170                        OIS::InputManager::destroyInputSystem(mInputManager);
171                        mInputManager = 0;
172                }
173        }
174}
175
176
177bool RunManager::processUnbufferedKeyInput()
178{
179        using namespace OIS;
180
181        if(mKeyboard->isKeyDown(KC_A))
182                mTranslateVector.x = -mMoveScale;       // Move camera left
183
184        if(mKeyboard->isKeyDown(KC_D))
185                mTranslateVector.x = mMoveScale;        // Move camera RIGHT
186
187        if(mKeyboard->isKeyDown(KC_UP) || mKeyboard->isKeyDown(KC_W) )
188                mTranslateVector.z = -mMoveScale;       // Move camera forward
189
190        if(mKeyboard->isKeyDown(KC_DOWN) || mKeyboard->isKeyDown(KC_S) )
191                mTranslateVector.z = mMoveScale;        // Move camera backward
192
193        if(mKeyboard->isKeyDown(KC_PGUP))
194                mTranslateVector.y = mMoveScale;        // Move camera up
195
196        if(mKeyboard->isKeyDown(KC_PGDOWN))
197                mTranslateVector.y = -mMoveScale;       // Move camera down
198
199        if(mKeyboard->isKeyDown(KC_RIGHT))
200                mCamera->yaw(-mRotScale);
201
202        if(mKeyboard->isKeyDown(KC_LEFT))
203                mCamera->yaw(mRotScale);
204
205        if( mKeyboard->isKeyDown(KC_ESCAPE) || mKeyboard->isKeyDown(KC_Q) )
206                return false;
207
208        if( mKeyboard->isKeyDown(KC_F) && mTimeUntilNextToggle <= 0 )
209        {
210                mStatsOn = !mStatsOn;
211                showDebugOverlay(mStatsOn);
212                mTimeUntilNextToggle = 1;
213        }
214
215        if( mKeyboard->isKeyDown(KC_T) && mTimeUntilNextToggle <= 0 )
216        {
217                switch(mFiltering)
218                {
219                case TFO_BILINEAR:
220                        mFiltering = TFO_TRILINEAR;
221                        mAniso = 1;
222                        break;
223                case TFO_TRILINEAR:
224                        mFiltering = TFO_ANISOTROPIC;
225                        mAniso = 8;
226                        break;
227                case TFO_ANISOTROPIC:
228                        mFiltering = TFO_BILINEAR;
229                        mAniso = 1;
230                        break;
231                default: break;
232                }
233                MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering);
234                MaterialManager::getSingleton().setDefaultAnisotropy(mAniso);
235
236                showDebugOverlay(mStatsOn);
237                mTimeUntilNextToggle = 1;
238        }
239
240        if(mKeyboard->isKeyDown(KC_SYSRQ) && mTimeUntilNextToggle <= 0)
241        {
242                std::ostringstream ss;
243                ss << "screenshot_" << ++mNumScreenShots << ".png";
244                mWindow->writeContentsToFile(ss.str());
245                mTimeUntilNextToggle = 0.5;
246                mDebugText = "Saved: " + ss.str();
247        }
248
249        if(mKeyboard->isKeyDown(KC_R) && mTimeUntilNextToggle <=0)
250        {
251                mSceneDetailIndex = (mSceneDetailIndex+1)%3 ;
252                switch(mSceneDetailIndex) {
253                                case 0 : mCamera->setPolygonMode(PM_SOLID); break;
254                                case 1 : mCamera->setPolygonMode(PM_WIREFRAME); break;
255                                case 2 : mCamera->setPolygonMode(PM_POINTS); break;
256                }
257                mTimeUntilNextToggle = 0.5;
258        }
259
260        static bool displayCameraDetails = false;
261        if(mKeyboard->isKeyDown(KC_P) && mTimeUntilNextToggle <= 0)
262        {
263                displayCameraDetails = !displayCameraDetails;
264                mTimeUntilNextToggle = 0.5;
265                if (!displayCameraDetails)
266                        mDebugText = "";
267        }
268
269        // Print camera details
270        if(displayCameraDetails)
271                mDebugText = "P: " + StringConverter::toString(mCamera->getDerivedPosition()) +
272                " " + "O: " + StringConverter::toString(mCamera->getDerivedOrientation());
273
274        // Return true to continue rendering
275        return true;
276}
277
278
279bool RunManager::processUnbufferedMouseInput()
280{
281        using namespace OIS;
282
283        // Rotation factors, may not be used if the second mouse button is pressed
284        // 2nd mouse button - slide, otherwise rotate
285        const MouseState &ms = mMouse->getMouseState();
286        mRotX = Degree(-ms.X.rel * 0.13);
287        mRotY = Degree(-ms.Y.rel * 0.13);
288
289        mShip->setYaw(mRotX);
290        mShip->setPitch(mRotY);
291
292        return true;
293}
294
295
296void RunManager::moveCamera()
297{
298        // Make all the changes to the camera
299        // Note that YAW direction is around a fixed axis (freelook style) rather than a natural YAW
300        //(e.g. airplane)
301        //mCamera->yaw(mRotX);
302        //mCamera->pitch(mRotY);
303        //mCamera->moveRelative(mTranslateVector);
304
305        mShipNode->translate(mShipNode->getLocalAxes() * mTranslateVector);
306}
307
308
309void RunManager::showDebugOverlay(bool show)
310{
311        if (mDebugOverlay)
312        {
313                if (show)
314                        mDebugOverlay->show();
315                else
316                        mDebugOverlay->hide();
317        }
318}
319
320
321
322void RunManager::updateStats(void)
323{
324        static String currFps = "Current FPS: ";
325        static String avgFps = "Average FPS: ";
326        static String bestFps = "Best FPS: ";
327        static String worstFps = "Worst FPS: ";
328        static String tris = "Triangle Count: ";
329        static String batches = "Batch Count: ";
330
331        // update stats when necessary
332        try {
333                OverlayElement* guiAvg = OverlayManager::getSingleton().getOverlayElement("Core/AverageFps");
334                OverlayElement* guiCurr = OverlayManager::getSingleton().getOverlayElement("Core/CurrFps");
335                OverlayElement* guiBest = OverlayManager::getSingleton().getOverlayElement("Core/BestFps");
336                OverlayElement* guiWorst = OverlayManager::getSingleton().getOverlayElement("Core/WorstFps");
337                //OverlayElement* asfd = OverlayManager::getSingleton().getOverlayElement(
338
339                const RenderTarget::FrameStats& stats = mWindow->getStatistics();
340                guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
341                guiCurr->setCaption(currFps + StringConverter::toString(stats.lastFPS));
342                guiBest->setCaption(bestFps + StringConverter::toString(stats.bestFPS)
343                        +" "+StringConverter::toString(stats.bestFrameTime)+" ms");
344                guiWorst->setCaption(worstFps + StringConverter::toString(stats.worstFPS)
345                        +" "+StringConverter::toString(stats.worstFrameTime)+" ms");
346
347                OverlayElement* guiTris = OverlayManager::getSingleton().getOverlayElement("Core/NumTris");
348                guiTris->setCaption(tris + StringConverter::toString(stats.triangleCount));
349
350                OverlayElement* guiBatches = OverlayManager::getSingleton().getOverlayElement("Core/NumBatches");
351                guiBatches->setCaption(batches + StringConverter::toString(stats.batchCount));
352
353                OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText");
354                guiDbg->setCaption(mDebugText);
355        }
356        catch(...) { /* ignore */ }
357}
358
359
360
361// create camera
362void RunManager::createCamera(void)
363{
364        mCamera = mSceneMgr->createCamera("PlayerCam");
365        mShipNode->attachObject(mCamera);
366        mCamera->setNearClipDistance(5);
367        mCamera->setPosition(Vector3(0,10,500));
368        mCamera->lookAt(Vector3(0,0,0));
369}
370
371
372void RunManager::createViewports(void)
373{
374        // Create one viewport, entire window
375        Viewport* vp = mWindow->addViewport(mCamera);
376        vp->setBackgroundColour(ColourValue(0,0,0));
377
378        // Alter the camera aspect ratio to match the viewport
379        mCamera->setAspectRatio(
380                Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
381}
382
383
Note: See TracBrowser for help on using the repository browser.