Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/Samples/OceanDemo/src/OceanDemo.cpp @ 3

Last change on this file since 3 was 3, checked in by anonymous, 17 years ago

=update

File size: 45.8 KB
Line 
1/*
2-----------------------------------------------------------------------------
3This source file is part of OGRE
4    (Object-oriented Graphics Rendering Engine)
5For the latest info, see http://www.ogre3d.org/
6
7Copyright (c) 2000-2006 Torus Knot Software Ltd
8Also see acknowledgements in Readme.html
9
10You may use this sample code for anything you like, it is not covered by the
11LGPL like the rest of the engine.
12-----------------------------------------------------------------------------
13*/
14
15#include "OceanDemo.h"
16#include "Ogre.h"
17
18#include <cstdlib>
19
20
21/**********************************************************************
22OS X Specific Resource Location Finding
23**********************************************************************/
24#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
25
26Ogre::String bundlePath()
27{
28    char path[1024];
29    CFBundleRef mainBundle = CFBundleGetMainBundle();
30    assert( mainBundle );
31
32    CFURLRef mainBundleURL = CFBundleCopyBundleURL( mainBundle);
33    assert( mainBundleURL);
34
35    CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);
36    assert( cfStringRef);
37
38    CFStringGetCString( cfStringRef, path, 1024, kCFStringEncodingASCII);
39
40    CFRelease( mainBundleURL);
41    CFRelease( cfStringRef);
42
43    return Ogre::String( path);
44}
45
46#endif
47
48/**********************************************************************
49  Static declarations
50**********************************************************************/
51// Lights
52#define NUM_LIGHTS 1
53
54// the light
55Ogre::Light* mLights[NUM_LIGHTS];
56// billboards for lights
57Ogre::BillboardSet* mLightFlareSets[NUM_LIGHTS];
58Ogre::Billboard* mLightFlares[NUM_LIGHTS];
59// Positions for lights
60Ogre::Vector3 mLightPositions[NUM_LIGHTS] =
61{
62        Ogre::Vector3(00, 400, 00)
63};
64// Base orientations of the lights
65Ogre::Real mLightRotationAngles[NUM_LIGHTS] = { 35 };
66Ogre::Vector3 mLightRotationAxes[NUM_LIGHTS] = {
67    Ogre::Vector3::UNIT_X
68};
69// Rotation speed for lights, degrees per second
70Ogre::Real mLightSpeeds[NUM_LIGHTS] = { 30};
71
72// Colours for the lights
73Ogre::ColourValue mDiffuseLightColours[NUM_LIGHTS] =
74{
75        Ogre::ColourValue(0.6, 0.6, 0.6)
76};
77
78Ogre::ColourValue mSpecularLightColours[NUM_LIGHTS] =
79{
80        Ogre::ColourValue(0.5, 0.5, 0.5)
81};
82
83// Which lights are enabled
84bool mLightState[NUM_LIGHTS] =
85{
86        true
87};
88
89// the light nodes
90Ogre::SceneNode* mLightNodes[NUM_LIGHTS];
91// the light node pivots
92Ogre::SceneNode* mLightPivots[NUM_LIGHTS];
93
94#define UVECTOR2(x, y) UVector2(cegui_reldim(x), cegui_reldim(y))
95#define TEXTWIDGET_SIZE UVECTOR2(0.19, 0.06)
96#define NUMBERWIDGET_SIZE UVECTOR2(0.065, 0.06)
97#define SCROLLWIDGET_SIZE UVECTOR2(0.21, 0.02)
98
99#define TEXTWIDGET_XPOS 0.01
100#define NUMBERWIDGET_XPOS 0.37
101#define SCROLLWIDGET_XPOS 0.50
102
103#define TEXTWIDGET_YADJUST (-0.05f)
104#define WIDGET_YSTART 0.2f
105#define WIDGET_YOFFSET 0.15f
106
107/*************************************************************************
108        sub-class for ListboxTextItem that auto-sets the selection brush
109        image.
110*************************************************************************/
111class MyListItem : public CEGUI::ListboxTextItem
112{
113public:
114    MyListItem(const CEGUI::String& text, CEGUI::uint id) : CEGUI::ListboxTextItem(text, id)
115        {
116                setSelectionBrushImage("TaharezLook", "MultiListSelectionBrush");
117        }
118};
119
120
121
122/*********************************************************************
123    Main Program Entry Point
124***********************************************************************/
125#ifdef __cplusplus
126extern "C" {
127#endif
128
129#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
130#define WIN32_LEAN_AND_MEAN
131#include "windows.h"
132
133INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
134#else
135int main(int argc, char *argv[])
136#endif
137{
138        // Create application object
139        OceanDemo app;
140
141        try {
142                app.go();
143
144        } catch( Ogre::Exception& e ) {
145#if OGRE_PLATFORM == PLATFORM_WIN32
146        MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
147#else
148        std::cerr << "An exception has occured: " <<
149            e.getFullDescription().c_str() << std::endl;
150#endif
151    }
152
153    return 0;
154}
155
156#ifdef __cplusplus
157}
158#endif
159
160/*************************************************************************
161                            OceanDemo Methods
162*************************************************************************/
163OceanDemo::~OceanDemo()
164{
165        delete mGUISystem;
166        delete mGUIRenderer;
167    delete mFrameListener;
168
169    // get rid of the shared pointers before shutting down ogre or exceptions occure
170    mActiveFragmentProgram.setNull();
171    mActiveFragmentParameters.setNull();
172    mActiveVertexProgram.setNull();
173    mActiveVertexParameters.setNull();
174    mActiveMaterial.setNull();
175
176    delete mRoot;
177}
178
179//--------------------------------------------------------------------------
180void OceanDemo::go(void)
181{
182    if (!setup())
183        return;
184
185    mRoot->startRendering();
186}
187
188//--------------------------------------------------------------------------
189bool OceanDemo::setup(void)
190{
191        bool setupCompleted = false;
192
193        #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
194        Ogre::String mResourcePath;
195        mResourcePath = bundlePath() + "/Contents/Resources/";
196        mRoot = new Ogre::Root(mResourcePath + "plugins.cfg",
197                         mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");
198    #else
199
200        mRoot = new Ogre::Root();
201
202    #endif
203
204    setupResources();
205
206    if (configure())
207    {
208        chooseSceneManager();
209        createCamera();
210        createViewports();
211
212        // Set default mipmap level (NB some APIs ignore this)
213        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
214        loadResources();
215
216
217        if (setupGUI())
218        {
219            // Create the scene
220            createScene();
221
222            createFrameListener();
223
224            // load some GUI stuff for demo.
225            loadAllMaterialControlFiles(mMaterialControlsContainer);
226            initDemoEventWiring();
227            initComboBoxes();
228            setupCompleted = true;
229        }
230    }
231
232        return setupCompleted;
233}
234
235//--------------------------------------------------------------------------
236bool OceanDemo::configure(void)
237{
238    // Show the configuration dialog and initialise the system
239    // You can skip this and use root.restoreConfig() to load configuration
240    // settings if you were sure there are valid ones saved in ogre.cfg
241    if(mRoot->showConfigDialog())
242    {
243        // If returned true, user clicked OK so initialise
244        // Here we choose to let the system create a default rendering window by passing 'true'
245        mWindow = mRoot->initialise(true);
246        return true;
247    }
248    else
249    {
250        return false;
251    }
252}
253
254//--------------------------------------------------------------------------
255void OceanDemo::chooseSceneManager(void)
256{
257    // Get the SceneManager, in this case a generic one
258    mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC, "ExampleSMInstance");
259}
260
261//--------------------------------------------------------------------------
262void OceanDemo::createCamera(void)
263{
264    // Create the camera
265    mCamera = mSceneMgr->createCamera("PlayerCam");
266
267    // Position it at 500 in Z direction
268    mCamera->setPosition(Ogre::Vector3(0,0,0));
269    // Look back along -Z
270    mCamera->lookAt(Ogre::Vector3(0,0,-300));
271    mCamera->setNearClipDistance(1);
272
273}
274
275//--------------------------------------------------------------------------
276void OceanDemo::createViewports(void)
277{
278    // Create one viewport, entire window
279    Ogre::Viewport* vp = mWindow->addViewport(mCamera);
280    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
281
282    // Alter the camera aspect ratio to match the viewport
283    mCamera->setAspectRatio(
284        Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
285}
286
287//--------------------------------------------------------------------------
288void OceanDemo::setupResources(void)
289{
290    // Load resource paths from config file
291    Ogre::ConfigFile cf;
292
293    #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
294        Ogre::String mResourcePath;
295        mResourcePath = bundlePath() + "/Contents/Resources/";
296        cf.load(mResourcePath + "resources.cfg");
297    #else
298        cf.load("resources.cfg");
299    #endif
300
301    // Go through all sections & settings in the file
302    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
303
304    Ogre::String secName, typeName, archName;
305    while (seci.hasMoreElements())
306    {
307        secName = seci.peekNextKey();
308        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
309        Ogre::ConfigFile::SettingsMultiMap::iterator i;
310        for (i = settings->begin(); i != settings->end(); ++i)
311        {
312            typeName = i->first;
313            archName = i->second;
314#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
315                // OS X does not set the working directory relative to the app,
316                // In order to make things portable on OS X we need to provide
317                // the loading with it's own bundle path location
318                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
319                    Ogre::String(bundlePath() + "/" + archName), typeName, secName);
320#else
321                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
322                    archName, typeName, secName);
323#endif
324        }
325    }
326
327        Ogre::LogManager::getSingleton().logMessage( "Resource directories setup" );
328
329}
330
331//-----------------------------------------------------------------------------------
332        void OceanDemo::loadResources(void)
333        {
334                // Initialise, parse scripts etc
335        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
336
337        }
338
339//--------------------------------------------------------------------------
340bool OceanDemo::setupGUI(void)
341{
342    bool setupGUICompleted = false;
343        // setup GUI system
344        try
345        {
346        mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY, false, 0, mSceneMgr);
347        // load scheme and set up defaults
348
349        mGUISystem = new CEGUI::System(mGUIRenderer, 0, 0, 0, (CEGUI::utf8*)"OceanDemoCegui.config");
350        CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
351        setupGUICompleted = true;
352        }
353        catch(...)
354        {
355
356        }
357
358        return setupGUICompleted;
359}
360//--------------------------------------------------------------------------
361void OceanDemo::createScene(void)
362{
363    // Set ambient light
364    mSceneMgr->setAmbientLight(Ogre::ColourValue(0.3, 0.3, 0.3));
365        mSceneMgr->setSkyBox(true, "SkyBox", 1000);
366
367    mMainNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
368
369
370    for (unsigned int i = 0; i < NUM_LIGHTS; ++i)
371    {
372        mLightPivots[i] = mSceneMgr->getRootSceneNode()->createChildSceneNode();
373        mLightPivots[i]->rotate(mLightRotationAxes[i], Ogre::Angle(mLightRotationAngles[i]));
374        // Create a light, use default parameters
375        mLights[i] = mSceneMgr->createLight("Light" + Ogre::StringConverter::toString(i));
376                mLights[i]->setPosition(mLightPositions[i]);
377                mLights[i]->setDiffuseColour(mDiffuseLightColours[i]);
378                mLights[i]->setSpecularColour(mSpecularLightColours[i]);
379                mLights[i]->setVisible(mLightState[i]);
380                //mLights[i]->setAttenuation(400, 0.1 , 1 , 0);
381        // Attach light
382        mLightPivots[i]->attachObject(mLights[i]);
383                // Create billboard for light
384        mLightFlareSets[i] = mSceneMgr->createBillboardSet("Flare" + Ogre::StringConverter::toString(i));
385                mLightFlareSets[i]->setMaterialName("LightFlare");
386                mLightPivots[i]->attachObject(mLightFlareSets[i]);
387                mLightFlares[i] = mLightFlareSets[i]->createBillboard(mLightPositions[i]);
388                mLightFlares[i]->setColour(mDiffuseLightColours[i]);
389                mLightFlareSets[i]->setVisible(mLightState[i]);
390    }
391
392    // move the camera a bit right and make it look at the knot
393        mCamera->moveRelative(Ogre::Vector3(50, 0, 100));
394        mCamera->lookAt(0, 0, 0);
395
396    // Define a plane mesh that will be used for the ocean surface
397    Ogre::Plane oceanSurface;
398    oceanSurface.normal = Ogre::Vector3::UNIT_Y;
399    oceanSurface.d = 20;
400    Ogre::MeshManager::getSingleton().createPlane("OceanSurface",
401        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
402        oceanSurface,
403        1000, 1000, 50, 50, true, 1, 1, 1, Ogre::Vector3::UNIT_Z);
404
405    mOceanSurfaceEnt = mSceneMgr->createEntity( "OceanSurface", "OceanSurface" );
406    mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mOceanSurfaceEnt);
407
408}
409
410
411//--------------------------------------------------------------------------
412void OceanDemo::initComboBoxes(void)
413{
414        using namespace CEGUI;
415
416
417        Combobox* cbobox = (Combobox*)WindowManager::getSingleton().getWindow("ShaderCombos");
418
419    for(size_t idx = 0; idx < mMaterialControlsContainer.size(); ++idx  )
420        {
421        cbobox->addItem(new MyListItem( mMaterialControlsContainer[idx].getDisplayName().c_str(), static_cast<CEGUI::uint>(idx)));
422        }
423
424        // make first item visible
425    if (cbobox->getItemCount() > 0)
426            cbobox->setItemSelectState((size_t)0, true);
427
428    Editbox* eb;
429    // set text in combobox
430    if (!mMaterialControlsContainer.empty())
431    {
432        eb = (Editbox*)WindowManager::getSingleton().getWindow(cbobox->getName() + "__auto_editbox__");
433        eb->setText(mMaterialControlsContainer[0].getDisplayName().c_str());
434        handleShaderComboChanged(CEGUI::WindowEventArgs(cbobox));
435    }
436
437        cbobox = (Combobox*)WindowManager::getSingleton().getWindow("ModelCombos");
438    Ogre::StringVectorPtr meshStringVector = Ogre::ResourceGroupManager::getSingleton().findResourceNames( Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "*.mesh" );
439    std::vector<Ogre::String>::iterator meshFileNameIterator = meshStringVector->begin();
440
441    while ( meshFileNameIterator != meshStringVector->end() )
442        {
443        cbobox->addItem(new MyListItem( (*meshFileNameIterator).c_str(), 0 ));
444        ++meshFileNameIterator;
445        }
446
447        // make first item visible
448        //cbobox->setItemSelectState((CEGUI::uint)0, true);
449 //   eb = (Editbox*)WindowManager::getSingleton().getWindow(cbobox->getName() + "__auto_editbox__");
450 //   if (meshStringVector->begin() != meshStringVector->end())
451 //   {
452 //       eb->setText((*meshStringVector->begin()).c_str());
453 //       handleModelComboChanged(CEGUI::WindowEventArgs(cbobox));
454 //   }
455
456}
457
458
459//--------------------------------------------------------------------------
460void OceanDemo::initDemoEventWiring(void)
461{
462        using namespace CEGUI;
463
464        WindowManager::getSingleton().getWindow("ExitDemoBtn")->
465                subscribeEvent(PushButton::EventClicked, CEGUI::Event::Subscriber(&OceanDemo::handleQuit, this));
466
467        WindowManager::getSingleton().getWindow("ModelCombos")->
468        subscribeEvent(Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&OceanDemo::handleModelComboChanged, this));
469
470        WindowManager::getSingleton().getWindow("ShaderCombos")->
471                subscribeEvent(Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&OceanDemo::handleShaderComboChanged, this));
472
473        Window* wndw = WindowManager::getSingleton().getWindow("root");
474
475        wndw->subscribeEvent(Window::EventMouseMove, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handleMouseMove, mFrameListener));
476
477        wndw->subscribeEvent(Window::EventMouseButtonUp, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handleMouseButtonUp, mFrameListener));
478
479        wndw->subscribeEvent(Window::EventMouseButtonDown, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handleMouseButtonDown, mFrameListener));
480
481        wndw->subscribeEvent(Window::EventMouseWheel, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handleMouseWheelEvent, mFrameListener));
482        wndw->subscribeEvent(Window::EventKeyDown, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handleKeyDownEvent, mFrameListener ));
483        wndw->subscribeEvent(Window::EventKeyUp, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handleKeyUpEvent, mFrameListener ));
484
485        wndw = WindowManager::getSingleton().getWindow("ModelSpinCB");
486        wndw->subscribeEvent(Checkbox::EventCheckStateChanged, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handelModelSpinChange, mFrameListener ));
487
488        wndw = WindowManager::getSingleton().getWindow("LightSpinCB");
489        wndw->subscribeEvent(Checkbox::EventCheckStateChanged, CEGUI::Event::Subscriber(&OceanDemo_FrameListener::handelLightSpinChange, mFrameListener ));
490
491        wndw = WindowManager::getSingleton().getWindow("CameraRBtn");
492        wndw->subscribeEvent(RadioButton::EventSelectStateChanged, CEGUI::Event::Subscriber(&OceanDemo::handleMovementTypeChange, this ));
493
494        wndw = WindowManager::getSingleton().getWindow("ModelRBtn");
495        wndw->subscribeEvent(RadioButton::EventSelectStateChanged, CEGUI::Event::Subscriber(&OceanDemo::handleMovementTypeChange, this ));
496
497        mVertScroll = (Scrollbar*)WindowManager::getSingleton().getWindow("VerticalScroll");
498        mVertScroll->subscribeEvent(Scrollbar::EventScrollPositionChanged, CEGUI::Event::Subscriber(&OceanDemo::handleScrollControlsWindow, this ));
499
500}
501
502
503//--------------------------------------------------------------------------
504void OceanDemo::doErrorBox(const char* text)
505{
506        using namespace CEGUI;
507
508        WindowManager& winMgr = WindowManager::getSingleton();
509        Window* root = winMgr.getWindow("root_wnd");
510
511        FrameWindow* errbox;
512
513        try
514        {
515                errbox = (FrameWindow*)winMgr.getWindow("ErrorBox");
516        }
517        catch(UnknownObjectException x)
518        {
519                // create frame window for box
520                FrameWindow* fwnd = (FrameWindow*)winMgr.createWindow("TaharezLook/FrameWindow", "ErrorBox");
521                root->addChildWindow(fwnd);
522                fwnd->setPosition(UVECTOR2(0.25, 0.25f));
523                fwnd->setMaxSize(UVECTOR2(1.0f, 1.0f));
524                fwnd->setSize(UVECTOR2(0.5f, 0.5f));
525                fwnd->setText("CEGUI Demo - Error!");
526                fwnd->setDragMovingEnabled(false);
527                fwnd->setSizingEnabled(false);
528                fwnd->setAlwaysOnTop(true);
529                fwnd->setCloseButtonEnabled(false);
530
531                // create error text message
532                Window* wnd = winMgr.createWindow("TaharezLook/StaticText", "ErrorBox/Message");
533                fwnd->addChildWindow(wnd);
534                wnd->setPosition(UVECTOR2(0.1f, 0.1f));
535                wnd->setSize(UVECTOR2(0.8f, 0.5f));
536                wnd->setProperty("VertFormatting", "VertCentred");
537                wnd->setProperty("HorzFormatting", "HorzCentred");
538                wnd->setProperty("BackgroundEnabled", "false");
539                wnd->setProperty("FrameEnabled", "false");
540
541                // create ok button
542                wnd = (PushButton*)winMgr.createWindow("TaharezLook/Button", "ErrorBox/OkButton");
543                fwnd->addChildWindow(wnd);
544                wnd->setPosition(UVECTOR2(0.3f, 0.80f));
545                wnd->setSize(UVECTOR2(0.4f, 0.1f));
546                wnd->setText("Okay!");
547
548                // subscribe event
549                wnd->subscribeEvent(PushButton::EventClicked, CEGUI::Event::Subscriber(&OceanDemo::handleErrorBox, this ));
550
551                errbox = fwnd;
552        }
553
554        errbox->getChild("ErrorBox/Message")->setText(text);
555        errbox->show();
556        errbox->activate();
557}
558
559
560//--------------------------------------------------------------------------
561bool OceanDemo::handleQuit(const CEGUI::EventArgs& e)
562{
563        mRoot->queueEndRendering();
564    return true;
565}
566
567//--------------------------------------------------------------------------
568void OceanDemo::setShaderControlVal(const float val, const size_t index)
569{
570        char valTxtBuf[20];
571
572        // set the text of the value
573        sprintf(valTxtBuf, "%3.3f", val );
574        mShaderControlContainer[index].NumberWidget->setText(valTxtBuf);
575}
576
577//--------------------------------------------------------------------------
578bool OceanDemo::handleShaderControl(const CEGUI::EventArgs& e)
579{
580        using namespace CEGUI;
581        using namespace Ogre;
582
583
584        size_t index = ((Scrollbar*)((const WindowEventArgs&)e).window)->getID();
585    const ShaderControl& ActiveShaderDef = mMaterialControlsContainer[mCurrentMaterial].getShaderControl(index);
586
587        float val = ((Scrollbar*)((const WindowEventArgs&)e).window)->getScrollPosition();
588        val = ActiveShaderDef.convertScrollPositionToParam(val);
589        setShaderControlVal( val, index );
590
591        if(mActivePass)
592        {
593                switch(ActiveShaderDef.ValType)
594                {
595                        case GPU_VERTEX:
596                        case GPU_FRAGMENT:
597                                {
598                                        GpuProgramParametersSharedPtr activeParameters =
599                                                (ActiveShaderDef.ValType == GPU_VERTEX) ?
600                                                        mActiveVertexParameters : mActiveFragmentParameters;
601
602                                        if(!activeParameters.isNull())
603                                        {
604                                                activeParameters->_writeRawConstant(
605                                                        ActiveShaderDef.PhysicalIndex + ActiveShaderDef.ElementIndex, val);
606                                        }
607                                }
608                                break;
609
610                        case MAT_SPECULAR:
611                                {
612                                        // get the specular values from the material pass
613                                        ColourValue OldSpec(mActivePass->getSpecular());
614                                        OldSpec[ActiveShaderDef.ElementIndex] = val;
615                                        mActivePass->setSpecular( OldSpec );
616                                }
617
618                                break;
619
620                        case MAT_DIFFUSE:
621                                {
622                                        // get the specular values from the material pass
623                                        ColourValue OldSpec(mActivePass->getDiffuse());
624                                        OldSpec[ActiveShaderDef.ElementIndex] = val;
625                                        mActivePass->setDiffuse( OldSpec );
626                                }
627                                break;
628
629                        case MAT_AMBIENT:
630                                {
631                                        // get the specular values from the material pass
632                                        ColourValue OldSpec(mActivePass->getAmbient());
633                                        OldSpec[ActiveShaderDef.ElementIndex] = val;
634                                        mActivePass->setAmbient( OldSpec );
635                                }
636                                break;
637
638                        case MAT_SHININESS:
639                                // get the specular values from the material pass
640                                mActivePass->setShininess( val );
641                                break;
642                }
643        }
644
645    return true;
646}
647
648//--------------------------------------------------------------------------
649void OceanDemo::configureShaderControls(void)
650{
651        using namespace CEGUI;
652
653    if (mMaterialControlsContainer.empty()) return;
654
655    mActiveMaterial = Ogre::MaterialManager::getSingleton().getByName( mMaterialControlsContainer[mCurrentMaterial].getMaterialName() );
656    if(!mActiveMaterial.isNull() && mActiveMaterial->getNumSupportedTechniques())
657        {
658        Ogre::Technique* currentTechnique = mActiveMaterial->getSupportedTechnique(0);
659                if(currentTechnique)
660                {
661                        mActivePass = currentTechnique->getPass(0);
662                        if(mActivePass)
663                        {
664                if (mActivePass->hasFragmentProgram())
665                {
666                                    mActiveFragmentProgram = mActivePass->getFragmentProgram();
667                                mActiveFragmentParameters = mActivePass->getFragmentProgramParameters();
668                }
669                if (mActivePass->hasVertexProgram())
670                {
671                                    mActiveVertexProgram = mActivePass->getVertexProgram();
672                                    mActiveVertexParameters = mActivePass->getVertexProgramParameters();
673                }
674
675                size_t activeControlCount = mMaterialControlsContainer[mCurrentMaterial].getShaderControlCount();
676                                mVertScroll->setDocumentSize( activeControlCount / 5.0f );
677                                mVertScroll->setScrollPosition(0.0f);
678
679                                // init the GUI controls
680                                // check the material entry for Params GUI list
681                if(mMaterialControlsContainer[mCurrentMaterial].getShaderControlCount() > 0)
682                                {
683                                        // if mShaderControlContainer size < Params list
684                                        if( activeControlCount > mShaderControlContainer.size())
685                                        {
686                                                // resize container
687                                                mShaderControlContainer.resize( activeControlCount );
688                                        }
689                                        Window* controlWindow = WindowManager::getSingleton().getWindow("ShaderControlsWin");
690                                        // initialize each widget based on control data
691                                        // iterate through the params GUI list
692                                        for( size_t i=0; i < activeControlCount; ++i )
693                                        {
694                                                const ShaderControl& ActiveShaderDef = mMaterialControlsContainer[mCurrentMaterial].getShaderControl(i);
695
696                                                // if TextWidget is NULL
697                                                Window* activeTextWidget = mShaderControlContainer[i].TextWidget;
698                                                if(activeTextWidget == NULL)
699                                                {
700                                                        // create TextWidget
701
702                                                        mShaderControlContainer[i].TextWidget = activeTextWidget =
703                                                                WindowManager::getSingleton().createWindow("TaharezLook/StaticText",
704                                ( ("UniformTxt" + Ogre::StringConverter::toString(i)).c_str() ));
705                                                        // add to Shader control window
706                                                        controlWindow->addChildWindow( activeTextWidget );
707                                                        // set position based on its index
708                                                        activeTextWidget->setPosition(UVECTOR2(TEXTWIDGET_XPOS, WIDGET_YSTART + TEXTWIDGET_YADJUST + WIDGET_YOFFSET * float(i)));
709                                                        activeTextWidget->setProperty("VertFormatting", "TopAligned");
710                                                        activeTextWidget->setProperty("HorzFormatting", "RightAligned");
711                                                        activeTextWidget->setProperty("FrameEnabled", "false");
712                                                        activeTextWidget->setInheritsAlpha(false);
713                                                        activeTextWidget->setProperty("BackgroundEnabled", "false");
714                                                        activeTextWidget->setMaxSize( TEXTWIDGET_SIZE );
715                                                        activeTextWidget->setMinSize( TEXTWIDGET_SIZE );
716                                                        activeTextWidget->setSize( TEXTWIDGET_SIZE );
717                                                }
718
719                                                // set TextWidget text to control name
720                        activeTextWidget->setText( ActiveShaderDef.Name.c_str() );
721                                                // make TextWidget visible
722                                                activeTextWidget->show();
723
724                                                // if NumberWidget is NULL
725                                                Window* activeNumberWidget = mShaderControlContainer[i].NumberWidget;
726                                                if(activeNumberWidget == NULL)
727                                                {
728                                                        // create NumberWidget
729
730                                                        mShaderControlContainer[i].NumberWidget = activeNumberWidget =
731                                                                WindowManager::getSingleton().createWindow("TaharezLook/StaticText",
732                                ( ("UniformNumTxt" + Ogre::StringConverter::toString(i)).c_str() ));
733                                                        // add to Shader control window
734                                                        controlWindow->addChildWindow( activeNumberWidget );
735                                                        // set position based on its index
736                                                        activeNumberWidget->setPosition(UVECTOR2(NUMBERWIDGET_XPOS, WIDGET_YSTART + TEXTWIDGET_YADJUST + WIDGET_YOFFSET * float(i)));
737                                                        activeNumberWidget->setProperty("HorzFormatting", "RightAligned");
738                                                        activeNumberWidget->setProperty("VertFormatting", "TopAligned");
739                                                        activeNumberWidget->setProperty("FrameEnabled", "false");
740                                                        activeNumberWidget->setInheritsAlpha(false);
741                                                        activeNumberWidget->setProperty("BackgroundEnabled", "false");
742                                                        activeNumberWidget->setMaxSize( NUMBERWIDGET_SIZE );
743                                                        activeNumberWidget->setMinSize( NUMBERWIDGET_SIZE );
744                                                        activeNumberWidget->setSize( NUMBERWIDGET_SIZE );
745                                                }
746                                                // make TextWidget visible
747                                                activeNumberWidget->show();
748
749                                                Scrollbar* activeScrollWidget = mShaderControlContainer[i].ScrollWidget;
750                                                // if ScrollWidget is NULL
751                                                if( activeScrollWidget == NULL )
752                                                {
753                                                        // create ScrollWidget
754                                                        mShaderControlContainer[i].ScrollWidget = activeScrollWidget =
755                                                                (Scrollbar*)WindowManager::getSingleton().createWindow("TaharezLook/HorizontalScrollbar",
756                                ( ("UniformSB" + Ogre::StringConverter::toString(i)).c_str() ));
757                                                        // add to Shader control window
758                                                        controlWindow->addChildWindow( activeScrollWidget );
759                                                        // set position based on its index
760                                                        activeScrollWidget->setPosition(UVECTOR2(SCROLLWIDGET_XPOS, WIDGET_YSTART + WIDGET_YOFFSET * float(i)));
761                                                        activeScrollWidget->setInheritsAlpha(false);
762                                                        activeScrollWidget->setMaxSize( SCROLLWIDGET_SIZE );
763                                                        activeScrollWidget->setMinSize( SCROLLWIDGET_SIZE );
764                                                        activeScrollWidget->setSize( SCROLLWIDGET_SIZE );
765                            activeScrollWidget->setID( static_cast<CEGUI::uint>(i) );
766                                                        activeScrollWidget->setOverlapSize(0);
767                                                        // wire up ScrollWidget position changed event to handleShaderControl
768                                                        activeScrollWidget->subscribeEvent(Scrollbar::EventScrollPositionChanged, CEGUI::Event::Subscriber(&OceanDemo::handleShaderControl, this ));                                            }
769                                                // set max value of ScrollWidget
770                                                float maxval = ActiveShaderDef.getRange();
771                                                activeScrollWidget->setDocumentSize(maxval);
772                                                activeScrollWidget->setPageSize(0.000);
773                                                activeScrollWidget->setStepSize(maxval/20);
774                                                // get current value of param
775
776                                                float uniformVal = 0.0;
777
778                                                switch(ActiveShaderDef.ValType)
779                                                {
780                                                        case GPU_VERTEX:
781                                                        case GPU_FRAGMENT:
782                                                                {
783                                                                        Ogre::GpuProgramParametersSharedPtr activeParameters =
784                                                                                (ActiveShaderDef.ValType == Ogre::GPT_VERTEX_PROGRAM) ?
785                                                                                        mActiveVertexParameters : mActiveFragmentParameters;
786                                                                        if(!activeParameters.isNull())
787                                                                        {
788                                                                                // use param name to get index : use appropiate paramters ptr
789                                                                                const Ogre::GpuConstantDefinition& def = 
790                                                                                        activeParameters->getConstantDefinition(ActiveShaderDef.ParamName);
791                                                                                ActiveShaderDef.PhysicalIndex = def.physicalIndex;
792                                                                                // use index to get RealConstantEntry
793                                                                                const float* pFloat = activeParameters->getFloatPointer(ActiveShaderDef.PhysicalIndex);
794                                                                                // set position of ScrollWidget as param value
795                                                                                uniformVal = pFloat[ActiveShaderDef.ElementIndex];
796                                                                                activeScrollWidget->setScrollPosition( ActiveShaderDef.convertParamToScrollPosition(uniformVal) );
797                                                                        }
798                                                                }
799                                                                break;
800
801                                                        case MAT_SPECULAR:
802                                                                {
803                                                                        // get the specular values from the material pass
804
805                                                                        Ogre::ColourValue OldSpec(mActivePass->getSpecular());
806                                                                        uniformVal = OldSpec[ActiveShaderDef.ElementIndex];
807                                                                        activeScrollWidget->setScrollPosition( ActiveShaderDef.convertParamToScrollPosition(uniformVal) );
808                                                                }
809                                                                break;
810
811                                                        case MAT_DIFFUSE:
812                                                                {
813                                                                        // get the diffuse values from the material pass
814
815                                                                        Ogre::ColourValue OldSpec(mActivePass->getDiffuse());
816                                                                        uniformVal = OldSpec[ActiveShaderDef.ElementIndex];
817                                                                        activeScrollWidget->setScrollPosition( ActiveShaderDef.convertParamToScrollPosition(uniformVal) );
818                                                                }
819                                                                break;
820
821                                                        case MAT_AMBIENT:
822                                                                {
823                                                                        // get the ambient values from the material pass
824
825                                                                        Ogre::ColourValue OldSpec(mActivePass->getAmbient());
826                                                                        uniformVal = OldSpec[ActiveShaderDef.ElementIndex];
827                                                                        activeScrollWidget->setScrollPosition( ActiveShaderDef.convertParamToScrollPosition(uniformVal) );
828                                                                }
829                                                                break;
830
831                                                        case MAT_SHININESS:
832                                                                {
833                                                                        // get the ambient values from the material pass
834
835                                                                        uniformVal = mActivePass->getShininess();
836                                                                        activeScrollWidget->setScrollPosition( ActiveShaderDef.convertParamToScrollPosition(uniformVal) );
837                                                                }
838
839                                                                break;
840
841                                                        case MAT_EMISSIVE:
842                                                                {
843                                                                        // get the ambient values from the material pass
844
845                                                                        //ColourValue OldSpec(mActivePass->gete());
846                                                                        //activeScrollWidget->setScrollPosition( OldSpec.val[ActiveShaderDef->ElementIndex] );
847                                                                }
848                                                                break;
849                                                }
850
851                                                setShaderControlVal( uniformVal, i );
852                                                activeScrollWidget->show();
853                                        } // end of iterate
854                                }
855
856                                // turn off extra GUI widgets
857                                // iterate from 1 + active widgets to end
858                                for( size_t i = activeControlCount; i < mShaderControlContainer.size(); i++ )
859                                {
860                                        // hide widget
861                                        if( mShaderControlContainer[i].TextWidget != NULL )
862                                        {
863                                                mShaderControlContainer[i].TextWidget->hide();
864                                        }
865
866                                        if( mShaderControlContainer[i].NumberWidget != NULL )
867                                        {
868                                                mShaderControlContainer[i].NumberWidget->hide();
869                                        }
870
871                                        {
872                                                mShaderControlContainer[i].ScrollWidget->hide();
873                                        }
874
875                                }// end of iterate
876
877                        }
878                }
879        }
880
881}
882
883//--------------------------------------------------------------------------
884bool OceanDemo::handleModelComboChanged(const CEGUI::EventArgs& e)
885{
886        using namespace CEGUI;
887
888    // get the selected mesh filename from the combo box
889        CEGUI::ListboxItem* item = ((Combobox*)((const WindowEventArgs&)e).window)->getSelectedItem();
890
891    // convert from CEGUI::String to Ogre::String
892    Ogre::String meshName(item->getText().c_str());
893
894    // hide the current entity
895    if (mCurrentEntity)
896    {
897        mCurrentEntity->setVisible(false);
898        // disconnect the entity from the scenenode
899        mMainNode->detachObject(mCurrentEntity->getName());
900    }
901
902    // find the entity selected in combo box
903    // an exception is raised by getEntity if it doesn't exist
904    // so trap the exception if entity not found and load it
905    try
906    {
907        mCurrentEntity = mSceneMgr->getEntity( meshName );
908    }
909    catch (Ogre::Exception e)
910    // if not found create it
911    {
912        Ogre::MeshPtr pMesh = Ogre::MeshManager::getSingleton().load(meshName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
913            //Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY,
914                        //Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY,
915                        //true, true
916            ); //so we can still read it
917        // Build tangent vectors, all our meshes use only 1 texture coordset
918        //pMesh->buildTangentVectors(0, 1);
919        // Create entity
920        mCurrentEntity = mSceneMgr->createEntity(meshName, meshName);
921    }
922
923    // make the entity visible and attach it to our main scenenode
924    mCurrentEntity->setVisible(true);
925    mMainNode->attachObject(mCurrentEntity);
926
927    // set the the entity's material to the current material
928    //mCurrentEntity->setMaterialName(mMaterialControlsContainer[mCurrentMaterial].getMaterialName());
929        configureShaderControls();
930    return true;
931}
932
933//--------------------------------------------------------------------------
934bool OceanDemo::handleShaderComboChanged(const CEGUI::EventArgs& e)
935{
936        using namespace CEGUI;
937
938        CEGUI::ListboxItem* item = ((Combobox*)((const WindowEventArgs&)e).window)->getSelectedItem();
939
940        mCurrentMaterial = item->getID();
941    if (mOceanSurfaceEnt)
942            mOceanSurfaceEnt->setMaterialName(mMaterialControlsContainer[mCurrentMaterial].getMaterialName());
943        configureShaderControls();
944
945    return true;
946}
947
948
949//--------------------------------------------------------------------------
950bool OceanDemo::handleScrollControlsWindow(const CEGUI::EventArgs& e)
951{
952        using namespace CEGUI;
953
954        size_t controlCount = mShaderControlContainer.size();
955        float scrollval = ((Scrollbar*)((const WindowEventArgs&)e).window)->getScrollPosition();
956
957        for (size_t i = 0; i < controlCount; i++)
958        {
959                float ypos = WIDGET_YSTART + WIDGET_YOFFSET * float(i) - scrollval;
960                mShaderControlContainer[i].TextWidget->setPosition(UVECTOR2( TEXTWIDGET_XPOS, ypos + TEXTWIDGET_YADJUST));
961                mShaderControlContainer[i].NumberWidget->setPosition(UVECTOR2( NUMBERWIDGET_XPOS, ypos + TEXTWIDGET_YADJUST));
962                mShaderControlContainer[i].ScrollWidget->setPosition(UVECTOR2( SCROLLWIDGET_XPOS, ypos ));
963        }
964
965    return true;
966}
967
968//--------------------------------------------------------------------------
969bool OceanDemo::handleMovementTypeChange(const CEGUI::EventArgs& e)
970{
971        using namespace CEGUI;
972        CEGUI::uint id = ((RadioButton*)((const WindowEventArgs&)e).window)->getSelectedButtonInGroup()->getID();
973        if (id == 0)
974        {
975                mMouseMovement = mv_CAMERA;
976        }
977        else
978        {
979                mMouseMovement = mv_MODEL;
980        }
981
982    return true;
983}
984
985
986//--------------------------------------------------------------------------
987bool OceanDemo::handleErrorBox(const CEGUI::EventArgs& e)
988{
989        CEGUI::WindowManager::getSingleton().getWindow((CEGUI::utf8*)"ErrorBox")->hide();
990    return true;
991}
992
993//--------------------------------------------------------------------------
994void OceanDemo::createFrameListener(void)
995{
996        mFrameListener= new OceanDemo_FrameListener(this);
997        mRoot->addFrameListener(mFrameListener);
998}
999
1000
1001/*************************************************************************
1002        OceanDemo_FrameListener methods that handle all input for this GLSL demo.
1003*************************************************************************/
1004
1005OceanDemo_FrameListener::OceanDemo_FrameListener(OceanDemo* main)
1006    : mMain(main)
1007    , mStatsOn(true)
1008    , mWriteToFile(false)
1009    , mLastMousePositionSet(false)
1010    , mSpinModel(true)
1011    , mSpinLight(false)
1012        , mMouse(0)
1013        , mKeyboard(0)
1014    , mLMBDown(false)
1015    , mRMBDown(false)
1016    , mProcessMovement(false)
1017    , mUpdateMovement(false)
1018    , mMoveFwd(false)
1019    , mMoveBck(false)
1020    , mMoveLeft(false)
1021    , mMoveRight(false)
1022
1023{
1024    mRotateSpeed = 0;
1025    mMoveSpeed = 100;
1026
1027        mNumScreenShots = 0;
1028        mTimeUntilNextToggle = 0;
1029    mSceneDetailIndex = 0;
1030    mMoveScale = 0.0f;
1031        mSpeed = MINSPEED;
1032        mRotX = 0;
1033        mRotY = 0;
1034    mRotScale = 0.0f;
1035        mTranslateVector = Ogre::Vector3::ZERO;
1036    mAniso = 1;
1037    mFiltering = Ogre::TFO_BILINEAR;
1038        mAvgFrameTime = 0.1;
1039
1040        // using buffered input
1041        OIS::ParamList pl;
1042        size_t windowHnd = 0;
1043        std::ostringstream windowHndStr;
1044        mMain->getRenderWindow()->getCustomAttribute("WINDOW", &windowHnd);
1045        windowHndStr << windowHnd;
1046        pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
1047
1048        mInputManager = OIS::InputManager::createInputSystem( pl );
1049        //Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
1050        mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
1051        mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));
1052
1053        unsigned int width, height, depth;
1054        int left, top;
1055        mMain->getRenderWindow()->getMetrics(width, height, depth, left, top);
1056
1057        //Set Mouse Region.. if window resizes, we should alter this to reflect as well
1058        const OIS::MouseState &ms = mMouse->getMouseState();
1059        ms.width = width;
1060        ms.height = height;
1061
1062        mMouse->setEventCallback(this);
1063        mKeyboard->setEventCallback(this);
1064
1065        mQuit = false;
1066        mSkipCount = 0;
1067        mUpdateFreq = 50;
1068
1069        mGuiRenderer = CEGUI::System::getSingleton().getRenderer();
1070
1071        mGuiAvg   = CEGUI::WindowManager::getSingleton().getWindow("OPAverageFPS");
1072        mGuiCurr  = CEGUI::WindowManager::getSingleton().getWindow("OPCurrentFPS");
1073        mGuiBest  = CEGUI::WindowManager::getSingleton().getWindow("OPBestFPS");
1074        mGuiWorst = CEGUI::WindowManager::getSingleton().getWindow("OPWorstFPS");
1075        mGuiTris  = CEGUI::WindowManager::getSingleton().getWindow("OPTriCount");
1076        mGuiDbg   = CEGUI::WindowManager::getSingleton().getWindow("OPDebugMsg");
1077        mRoot     = CEGUI::WindowManager::getSingleton().getWindow("root");
1078}
1079
1080//--------------------------------------------------------------------------
1081OceanDemo_FrameListener::~OceanDemo_FrameListener()
1082{
1083        if(mInputManager)
1084        {
1085                mInputManager->destroyInputObject(mMouse);
1086                mInputManager->destroyInputObject(mKeyboard);
1087                OIS::InputManager::destroyInputSystem(mInputManager);
1088                mInputManager = 0;
1089        }
1090}
1091
1092
1093//--------------------------------------------------------------------------
1094bool OceanDemo_FrameListener::frameStarted(const Ogre::FrameEvent& evt)
1095{
1096        mMouse->capture();
1097        mKeyboard->capture();
1098
1099        if (mQuit)
1100                return false;
1101        else
1102        {
1103                mSkipCount++;
1104                if (mSkipCount >= mUpdateFreq)
1105                {
1106                        mSkipCount = 0;
1107                        updateStats();
1108                }
1109                // update movement process
1110                if(mProcessMovement || mUpdateMovement)
1111                {
1112                        mTranslateVector.x += mMoveLeft ? mAvgFrameTime * -MOVESPEED : 0;
1113                        mTranslateVector.x += mMoveRight ? mAvgFrameTime * MOVESPEED : 0;
1114                        mTranslateVector.z += mMoveFwd ? mAvgFrameTime * -MOVESPEED : 0;
1115                        mTranslateVector.z += mMoveBck ? mAvgFrameTime * MOVESPEED : 0;
1116                        switch(mMain->getMouseMovement())
1117                        {
1118                                case mv_CAMERA:
1119                    mMain->getCamera()->yaw(Ogre::Angle(mRotX));
1120                                        mMain->getCamera()->pitch(Ogre::Angle(mRotY));
1121                                        mMain->getCamera()->moveRelative(mTranslateVector);
1122                                        break;
1123
1124                                case mv_MODEL:
1125                                        mMain->getMainNode()->yaw(Ogre::Angle(mRotX));
1126                                        //mMain->getMainNode()->pitch(mRotY);
1127                                        mMain->getMainNode()->translate(mTranslateVector);
1128                                        break;
1129                default:
1130                    break;
1131                        }
1132
1133                        mUpdateMovement = false;
1134                        mRotX = 0;
1135                        mRotY = 0;
1136                        mTranslateVector = Ogre::Vector3::ZERO;
1137                }
1138
1139                if(mSpinModel)
1140                {
1141                        mRotateSpeed = mAvgFrameTime * 20;
1142                        mMain->getMainNode()->yaw( Ogre::Angle(mRotateSpeed) );
1143                }
1144                if(mSpinLight)
1145                {
1146                mLightPivots[0]->rotate(mLightRotationAxes[0], Ogre::Angle(mRotateSpeed * 2.0f));
1147                }
1148                if(mWriteToFile)
1149                {
1150                        char tmp[20];
1151                        sprintf(tmp, "frame_%d.png", ++mNumScreenShots);
1152                        mMain->getRenderWindow()->writeContentsToFile(tmp);
1153                }
1154                return true;
1155        }
1156}
1157
1158//--------------------------------------------------------------------------
1159bool OceanDemo_FrameListener::mouseMoved (const OIS::MouseEvent &e)
1160{
1161        CEGUI::System::getSingleton().injectMouseMove( e.state.X.rel, e.state.Y.rel );
1162        CEGUI::System::getSingleton().injectMouseWheelChange(e.state.Z.rel);
1163        return true;
1164}
1165
1166//--------------------------------------------------------------------------
1167bool OceanDemo_FrameListener::keyPressed (const OIS::KeyEvent &e)
1168{
1169    // give 'quitting' priority
1170        if (e.key == OIS::KC_ESCAPE)
1171    {
1172        mQuit = true;
1173        return false;
1174    }
1175
1176    if (e.key == OIS::KC_SYSRQ )
1177    {
1178                std::ostringstream ss;
1179        ss << "screenshot_" << ++mNumScreenShots << ".png";
1180        mMain->getRenderWindow()->writeContentsToFile(ss.str());
1181        //mTimeUntilNextToggle = 0.5;
1182                mDebugText = "Saved: " + ss.str();
1183    }
1184
1185    // do event injection
1186    CEGUI::System& cegui = CEGUI::System::getSingleton();
1187    cegui.injectKeyDown(e.key);
1188        cegui.injectChar(e.text);
1189        return true;
1190}
1191
1192//--------------------------------------------------------------------------
1193bool OceanDemo_FrameListener::keyReleased (const OIS::KeyEvent &e)
1194{
1195        CEGUI::System::getSingleton().injectKeyUp(e.key);
1196        return true;
1197}
1198
1199//--------------------------------------------------------------------------
1200bool OceanDemo_FrameListener::mousePressed (const OIS::MouseEvent &e, OIS::MouseButtonID id)
1201{
1202        CEGUI::System::getSingleton().injectMouseButtonDown(convertOISButtonToCegui(id));
1203        return true;
1204}
1205
1206//--------------------------------------------------------------------------
1207bool OceanDemo_FrameListener::mouseReleased (const OIS::MouseEvent &e, OIS::MouseButtonID id)
1208{
1209        CEGUI::System::getSingleton().injectMouseButtonUp(convertOISButtonToCegui(id));
1210        return true;
1211}
1212
1213//--------------------------------------------------------------------------
1214CEGUI::MouseButton OceanDemo_FrameListener::convertOISButtonToCegui(int ois_button_id)
1215{
1216    switch (ois_button_id)
1217    {
1218        case 0: return CEGUI::LeftButton;
1219        case 1: return CEGUI::RightButton;
1220        case 2: return CEGUI::MiddleButton;
1221        case 3: return CEGUI::X1Button;
1222        default: return CEGUI::LeftButton;
1223    }
1224}
1225//--------------------------------------------------------------------------
1226void OceanDemo_FrameListener::updateStats(void)
1227{
1228        static CEGUI::String currFps = "Current FPS: ";
1229        static CEGUI::String avgFps = "Average FPS: ";
1230        static CEGUI::String bestFps = "Best FPS: ";
1231        static CEGUI::String worstFps = "Worst FPS: ";
1232        static CEGUI::String tris = "Triangle Count: ";
1233
1234
1235        const Ogre::RenderTarget::FrameStats& stats = mMain->getRenderWindow()->getStatistics();
1236
1237        mGuiAvg->setText(avgFps + Ogre::StringConverter::toString(stats.avgFPS));
1238        mGuiCurr->setText(currFps + Ogre::StringConverter::toString(stats.lastFPS));
1239        mGuiBest->setText(bestFps + Ogre::StringConverter::toString(stats.bestFPS)
1240                + " " + Ogre::StringConverter::toString(stats.bestFrameTime)+" ms");
1241        mGuiWorst->setText(worstFps + Ogre::StringConverter::toString(stats.worstFPS)
1242                + " " + Ogre::StringConverter::toString(stats.worstFrameTime)+" ms");
1243
1244        mGuiTris->setText(tris + Ogre::StringConverter::toString(stats.triangleCount));
1245        mGuiDbg->setText(mDebugText);
1246        mAvgFrameTime = 1.0f/(stats.avgFPS + 1.0f);
1247        if (mAvgFrameTime > 0.1f) mAvgFrameTime = 0.1f;
1248
1249}
1250
1251
1252//--------------------------------------------------------------------------
1253bool OceanDemo_FrameListener::handleMouseMove(const CEGUI::EventArgs& e)
1254{
1255        using namespace CEGUI;
1256
1257        if( mLMBDown && !mRMBDown)
1258        {
1259                // rotate camera
1260                mRotX += -((const MouseEventArgs&)e).moveDelta.d_x * mAvgFrameTime * 10.0;
1261                mRotY += -((const MouseEventArgs&)e).moveDelta.d_y * mAvgFrameTime * 10.0;
1262                MouseCursor::getSingleton().setPosition( mLastMousePosition );
1263                mUpdateMovement = true;
1264        }
1265        else
1266        {
1267                if( mRMBDown && !mLMBDown)
1268                {
1269                        // translate camera
1270                        mTranslateVector.x += ((const MouseEventArgs&)e).moveDelta.d_x * mAvgFrameTime * MOVESPEED;
1271                        mTranslateVector.y += -((const MouseEventArgs&)e).moveDelta.d_y * mAvgFrameTime * MOVESPEED;
1272                        //mTranslateVector.z = 0;
1273                        MouseCursor::getSingleton().setPosition( mLastMousePosition );
1274                        mUpdateMovement = true;
1275                }
1276                else
1277                {
1278                        if( mRMBDown && mLMBDown)
1279                        {
1280                                mTranslateVector.z += (((const MouseEventArgs&)e).moveDelta.d_x + ((const MouseEventArgs&)e).moveDelta.d_y) * mAvgFrameTime * MOVESPEED;
1281                                MouseCursor::getSingleton().setPosition( mLastMousePosition );
1282                                mUpdateMovement = true;
1283                        }
1284
1285                }
1286        }
1287
1288    return true;
1289}
1290
1291//--------------------------------------------------------------------------
1292bool OceanDemo_FrameListener::handleMouseButtonUp(const CEGUI::EventArgs& e)
1293{
1294        using namespace CEGUI;
1295
1296        //Window* wndw = ((const WindowEventArgs&)e).window;
1297        if( ((const MouseEventArgs&)e).button == LeftButton )
1298        {
1299                mLMBDown = false;
1300        }
1301
1302        if( ((const MouseEventArgs&)e).button == RightButton )
1303        {
1304                mRMBDown = false;
1305        }
1306        if( !mLMBDown && !mRMBDown )
1307        {
1308                MouseCursor::getSingleton().show();
1309                if(mLastMousePositionSet)
1310                {
1311                        MouseCursor::getSingleton().setPosition( mLastMousePosition );
1312                        mLastMousePositionSet = false;
1313                }
1314                mRoot->releaseInput();
1315        }
1316
1317    return true;
1318}
1319
1320//--------------------------------------------------------------------------
1321bool OceanDemo_FrameListener::handleMouseButtonDown(const CEGUI::EventArgs& e)
1322{
1323        using namespace CEGUI;
1324
1325        //Window* wndw = ((const WindowEventArgs&)e).window;
1326        if( ((const MouseEventArgs&)e).button == LeftButton )
1327        {
1328                mLMBDown = true;
1329        }
1330
1331        if( ((const MouseEventArgs&)e).button == RightButton )
1332        {
1333                mRMBDown = true;
1334        }
1335
1336        if( mLMBDown || mRMBDown )
1337        {
1338                MouseCursor::getSingleton().hide();
1339                if (!mLastMousePositionSet)
1340                {
1341                        mLastMousePosition = MouseCursor::getSingleton().getPosition();
1342                        mLastMousePositionSet = true;
1343                }
1344                mRoot->captureInput();
1345        }
1346
1347    return true;
1348}
1349
1350//--------------------------------------------------------------------------
1351bool OceanDemo_FrameListener::handleMouseWheelEvent(const CEGUI::EventArgs& e)
1352{
1353        using namespace CEGUI;
1354        mTranslateVector.z += ((const MouseEventArgs&)e).wheelChange * -5.0;
1355        mUpdateMovement = true;
1356
1357    return true;
1358}
1359
1360//--------------------------------------------------------------------------
1361bool OceanDemo_FrameListener::handleKeyDownEvent(const CEGUI::EventArgs& e)
1362{
1363        using namespace CEGUI;
1364
1365        CheckMovementKeys( ((const KeyEventArgs&)e).scancode , true);
1366
1367    return true;
1368}
1369
1370//--------------------------------------------------------------------------
1371bool OceanDemo_FrameListener::handleKeyUpEvent(const CEGUI::EventArgs& e)
1372{
1373        using namespace CEGUI;
1374        CheckMovementKeys( ((const KeyEventArgs&)e).scancode, false );
1375
1376    return true;
1377}
1378
1379
1380//--------------------------------------------------------------------------
1381bool OceanDemo_FrameListener::handelModelSpinChange(const CEGUI::EventArgs& e)
1382{
1383        using namespace CEGUI;
1384        mSpinModel = ((Checkbox*)((const WindowEventArgs&)e).window)->isSelected();
1385
1386    return true;
1387}
1388
1389//--------------------------------------------------------------------------
1390bool OceanDemo_FrameListener::handelLightSpinChange(const CEGUI::EventArgs& e)
1391{
1392        using namespace CEGUI;
1393        mSpinLight = ((Checkbox*)((const WindowEventArgs&)e).window)->isSelected();
1394
1395    return true;
1396}
1397
1398//--------------------------------------------------------------------------
1399void OceanDemo_FrameListener::CheckMovementKeys( CEGUI::Key::Scan scancode, bool state )
1400{
1401        using namespace CEGUI;
1402
1403        switch ( scancode )
1404        {
1405                case Key::A:
1406                        mMoveLeft = state;
1407                        break;
1408
1409                case Key::D:
1410                        mMoveRight = state;
1411                        break;
1412
1413                case Key::S:
1414                        mMoveBck = state;
1415                        break;
1416
1417                case Key::W:
1418                        mMoveFwd = state;
1419                        break;
1420
1421        default:
1422            break;
1423
1424        }
1425
1426        mProcessMovement = mMoveLeft || mMoveRight || mMoveFwd || mMoveBck;
1427
1428}
Note: See TracBrowser for help on using the repository browser.