BaseApplication.h
- #ifndef __BaseApplication_h_
- #define __BaseApplication_h_
- #include <OgreCamera.h>
- #include <OgreEntity.h>
- #include <OgreLogManager.h>
- #include <OgreRoot.h>
- #include <OgreViewport.h>
- #include <OgreSceneManager.h>
- #include <OgreRenderWindow.h>
- #include <OgreConfigFile.h>
- #include <OISEvents.h>
- #include <OISInputManager.h>
- #include <OISKeyboard.h>
- #include <OISMouse.h>
- #include <SdkTrays.h>
- #include <SdkCameraMan.h>
- /* If you wanna a static linked product. then please define OGRE_STATIC_LIB in advance.
- Then you should manully include necessary files and load the plugins. */
- #ifdef OGRE_STATIC_LIB
- # include "OgreOggSoundPlugin.h"
- # include "RenderSystems/Direct3D9/OgreD3D9Plugin.h"
- # include "Plugins/ParticleFX/OgreParticleFXPlugin.h"
- # include "Plugins/OctreeSceneManager/OgreOctreePlugin.h"
- #endif
- class BaseApplication : public Ogre::FrameListener, public Ogre::WindowEventListener, public OIS::KeyListener, public OIS::MouseListener, OgreBites::SdkTrayListener
- {
- public:
- BaseApplication(void);
- virtual ~BaseApplication(void);
- virtual void go(void);
- protected:
- // some basic frame fuctions
- virtual bool setup();
- virtual bool configure(void);
- virtual void chooseSceneManager(void);
- virtual void createCamera(void);
- virtual void createFrameListener(void);
- virtual void createScene(void) = 0; // Override me!
- virtual void destroyScene(void);
- virtual void createViewports(void);
- virtual void setupResources(void);
- virtual void createResourceListener(void);
- virtual void loadResources(void);
- virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt);
- // functions to deal with inputs, include keyboard and mouse input.
- virtual bool keyPressed( const OIS::KeyEvent &arg );
- virtual bool keyReleased( const OIS::KeyEvent &arg );
- virtual bool mouseMoved( const OIS::MouseEvent &arg );
- virtual bool mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id );
- virtual bool mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id );
- //Adjust mouse clipping area
- virtual void windowResized(Ogre::RenderWindow* rw);
- //Unattach OIS before window shutdown (very important under Linux)
- virtual void windowClosed(Ogre::RenderWindow* rw);
- Ogre::Root *mRoot;
- Ogre::Camera* mCamera;
- Ogre::SceneManager* mSceneMgr;
- Ogre::RenderWindow* mWindow;
- Ogre::String mResourcesCfg;
- Ogre::String mPluginsCfg;
- // OgreBites
- OgreBites::SdkTrayManager* mTrayMgr;
- OgreBites::SdkCameraMan* mCameraMan; // basic camera controller
- OgreBites::ParamsPanel* mDetailsPanel; // sample details panel
- bool mCursorWasVisible; // was cursor visible before dialog appeared
- bool mShutDown;
- //OIS Input devices
- OIS::InputManager* mInputManager;
- OIS::Mouse* mMouse;
- OIS::Keyboard* mKeyboard;
- /* If static link is used, we should use some variables in order to load plugins ourself. */
- #ifdef OGRE_STATIC_LIB
- Ogre::ParticleFXPlugin* mParticleFXPlugin;
- Ogre::D3D9Plugin* mD3D9Plugin;
- Ogre::OctreePlugin* mOctreePlugin;
- #if defined __OGREOGGSOUNG__
- OgreOggSound::OgreOggSoundPlugin* mOgreOggSoundPlugin;
- #endif
- #endif
- };
- #endif // #ifndef __BaseApplication_h_
TutorialApplication.h
- /*
- -----------------------------------------------------------------------------
- Filename: TutorialApplication.h
- -----------------------------------------------------------------------------
- This source file is part of the
- ___ __ __ _ _ _
- /___/__ _ _ __ ___ / / // / (_) | _(_)
- // // _` | '__/ _ / / // // / | |/ / |
- / /_// (_| | | | __/ / // /| | <| |
- /___/ /__, |_| /___| // // |_|_|/_/_|
- |___/
- Tutorial Framework
- http://www.ogre3d.org/tikiwiki/
- -----------------------------------------------------------------------------
- */
- #ifndef __TutorialApplication_h_
- #define __TutorialApplication_h_
- #include "BaseApplication.h"
- /* If we use OgreOggSound libs to provides sound support for the programe. */
- #if defined __OGREOGGSOUNG__
- #include "OgreOggSound.h"
- #endif
- /* Use CEGUI system to render independent GUI and deal with some graphic inputs. */
- #if defined __CEGUIOGRE__
- #include <CEGUISystem.h>
- #include <RendererModules/Ogre/CEGUIOgreRenderer.h>
- #include <CEGUISchemeManager.h>
- /* A cool wobbly effect of windows which has been implenmented in CEGUI samples SampleDemo7.
- But it somehow did not work in this system. I think it's becase of here I use CEGUIOgreRenderer.
- Maybe it is a bug in the renderer of CEGUIOgreRenderer. Just leave these codes here.
- */
- #ifdef __WOBBLLY_EFFECT__
- #include <CEGUIRenderEffect.h>
- #include <CEGUIVertex.h>
- // Sample subclass for CEGUI::RenderEffect. This particluar implementation
- // provides a basic 'wobbly window' type effect.
- class MyEffect : public CEGUI::RenderEffect
- {
- public:
- MyEffect();
- // implement required functions from RenderEffect interface.
- int getPassCount() const;
- void performPreRenderFunctions(const int pass);
- void performPostRenderFunctions();
- bool realiseGeometry(CEGUI::RenderingWindow& window, CEGUI::GeometryBuffer& geometry);
- bool update(const float elapsed, CEGUI::RenderingWindow& window);
- protected:
- static const float tess_x;
- static const float tess_y;
- // tess_x * tess_y * vertex_per_quad
- static const int buffsize = (8 * 8 * 6);
- bool initialised;
- float lastX, lastY;
- float dragX, dragY;
- float elasX, elasY;
- CEGUI::Vertex vb[buffsize];
- };
- #endif
- #endif
- // STL dqeue to manage the path of the robot.
- #include <deque>
- //#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
- //#include "../res/resource.h"
- //#endif
- class ITutorial01 : public BaseApplication
- {
- public:
- ITutorial01(void);
- virtual ~ITutorial01(void);
- protected:
- virtual void createScene(void);
- virtual void createFrameListener(void);
- // find the next location for the robot to walk to.
- virtual bool nextLocation(void);
- virtual bool frameRenderingQueued(const Ogre::FrameEvent &evt);
- // Cause we need to query terrain, so choose sceneManager of type ST_EXTERIOR_CLOSE
- virtual void chooseSceneManager(void);
- //mouse listener
- virtual bool mouseMoved(const OIS::MouseEvent &arg);
- virtual bool mousePressed(const OIS::MouseEvent &arg,OIS::MouseButtonID id);
- virtual bool mouseReleased(const OIS::MouseEvent &arg,OIS::MouseButtonID id);
- #if defined __CEGUIOGRE__
- virtual bool handleSlider(const CEGUI::EventArgs&); // slider the voice control
- virtual bool overlayHandler(const CEGUI::EventArgs&); // handler to the logo overlay
- #ifdef __WOBBLLY_EFFECT__
- virtual bool updateRTT(const CEGUI::EventArgs&);
- virtual bool handleRTTResize(const CEGUI::EventArgs&);
- virtual void initialiseRTTViewport(CEGUI::RenderingSurface* const);
- #endif
- CEGUI::OgreRenderer *mGUIRenderer; // CEGUI renderer
- CEGUI::GeometryBuffer* d_logo_geometry;
- #endif
- Ogre::RaySceneQuery *mRaySceneQuery; // The ray scene query pointer
- bool mLMouseDown, mRMouseDown; // True if the mouse buttons are down
- float mRotateSpeed;
- Ogre::Real mDistance; // The distance the object has left to travel
- Ogre::Vector3 mDirection; // The direction the object is moving
- Ogre::Vector3 mDestination; // The destination the object is moving towards
- Ogre::AnimationState *mAnimationState; // The current animation state of the object
- Ogre::Entity *mEntity; // The Entity we are animating
- Ogre::SceneNode *mNode,*mSoundNode; // The SceneNode that the Entity is attached to
- std::deque<Ogre::Vector3> mWalkList; // The list of points we are walking to
- Ogre::Real mWalkSpeed; // The speed at which the object is moving
- Ogre::RenderTexture *rtex;
- #if defined __OGREOGGSOUNG__
- bool mReplay; // If the sound is playing now
- OgreOggSound::OgreOggSoundManager * mSoundManager; // Pointer to sound manager
- OgreOggSound::OgreOggISound *sound; // pointer to sound
- #endif
- char exFlag; // Flag to distinguish different states
- Ogre::ParticleSystem* thrusters; // Pointer of ParticleSystem, our boomb.
- Ogre::Camera *rttCam; // Pointer of RTT camera
- };
- #endif // #ifndef __TutorialApplication_h_
- #include "BaseApplication.h"
- //-------------------------------------------------------------------------------------
- BaseApplication::BaseApplication(void)
- : mRoot(0),
- mCamera(0),
- mSceneMgr(0),
- mWindow(0),
- mResourcesCfg(Ogre::StringUtil::BLANK),
- mPluginsCfg(Ogre::StringUtil::BLANK),
- mTrayMgr(0),
- mCameraMan(0),
- mDetailsPanel(0),
- mCursorWasVisible(false),
- mShutDown(false),
- mInputManager(0),
- mMouse(0),
- mKeyboard(0)
- {
- }
- //-------------------------------------------------------------------------------------
- BaseApplication::~BaseApplication(void)
- {
- if (mTrayMgr) delete mTrayMgr;
- if (mCameraMan) delete mCameraMan;
- /* If you want to unload plugins early, you can do so by calling Root::uninstallPlugin
- although you don't have to do this since when Root shuts down, it automatically safely
- terminates and removes the plugins. Doing it manually has to be done carefully in case
- there are cross-plugin dependencies, e.g. one plugin creating rendersystem resources
- from another plugin.*/
- #ifdef OGRE_STATIC_LIB
- mRoot->uninstallPlugin(mOgreOggSoundPlugin);
- #endif
- //Remove ourself as a Window listener
- Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
- windowClosed(mWindow);
- delete mRoot;
- /* In static link, we created the plugins manully with new method
- so we should free them with delete method, manully too.
- Delete your plugin instances at some point after Root has been shut down,
- or after you manually uninstalled the plugin.
- */
- #ifdef OGRE_STATIC_LIB
- OGRE_DELETE mParticleFXPlugin;
- OGRE_DELETE mD3D9Plugin;
- OGRE_DELETE mOctreePlugin;
- #if defined __OGREOGGSOUNG__
- OGRE_DELETE mOgreOggSoundPlugin;
- #endif
- #endif
- }
- //-------------------------------------------------------------------------------------
- bool BaseApplication::configure(void)
- {
- // Show the configuration dialog and initialise the system
- // You can skip this and use root.restoreConfig() to load configuration
- // settings if you were sure there are valid ones saved in ogre.cfg
- if(mRoot->showConfigDialog())
- {
- // If returned true, user clicked OK so initialise
- // Here we choose to let the system create a default rendering window by passing 'true'
- mWindow = mRoot->initialise(true, "TutorialApplication Render Window");
- return true;
- }
- else
- {
- return false;
- }
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::chooseSceneManager(void)
- {
- // Get the SceneManager, in this case a generic one
- mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::createCamera(void)
- {
- // Create the camera
- mCamera = mSceneMgr->createCamera("PlayerCam");
- // Position it at 80 in Z direction
- mCamera->setPosition(Ogre::Vector3(0,0,80));
- // Look back along -Z
- mCamera->lookAt(Ogre::Vector3(0,0,-300));
- mCamera->setNearClipDistance(5);
- mCameraMan = new OgreBites::SdkCameraMan(mCamera); // create a default camera controller
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::createFrameListener(void)
- {
- Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
- OIS::ParamList pl;
- size_t windowHnd = 0;
- std::ostringstream windowHndStr;
- mWindow->getCustomAttribute("WINDOW", &windowHnd);
- windowHndStr << windowHnd;
- pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
- mInputManager = OIS::InputManager::createInputSystem( pl );
- mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
- mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));
- mMouse->setEventCallback(this);
- mKeyboard->setEventCallback(this);
- //Set initial mouse clipping size
- windowResized(mWindow);
- //Register as a Window listener
- Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
- mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", mWindow, mMouse, this);
- mTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
- mTrayMgr->toggleAdvancedFrameStats();
- mTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT);
- mTrayMgr->hideCursor();
- // create a params panel for displaying sample details
- Ogre::StringVector items;
- items.push_back("cam.pX");
- items.push_back("cam.pY");
- items.push_back("cam.pZ");
- items.push_back("");
- items.push_back("cam.oW");
- items.push_back("cam.oX");
- items.push_back("cam.oY");
- items.push_back("cam.oZ");
- items.push_back("");
- items.push_back("Filtering");
- items.push_back("Poly Mode");
- mDetailsPanel = mTrayMgr->createParamsPanel(OgreBites::TL_NONE, "DetailsPanel", 200, items);
- mDetailsPanel->setParamValue(9, "Bilinear");
- mDetailsPanel->setParamValue(10, "Solid");
- mDetailsPanel->hide();
- mRoot->addFrameListener(this);
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::destroyScene(void)
- {
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::createViewports(void)
- {
- // Create one viewport, entire window
- Ogre::Viewport* vp = mWindow->addViewport(mCamera);
- vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
- // Alter the camera aspect ratio to match the viewport
- mCamera->setAspectRatio(
- Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::setupResources(void)
- {
- // Load resource paths from config file
- Ogre::ConfigFile cf;
- cf.load(mResourcesCfg);
- // Go through all sections & settings in the file
- Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
- Ogre::String secName, typeName, archName;
- while (seci.hasMoreElements())
- {
- secName = seci.peekNextKey();
- Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
- Ogre::ConfigFile::SettingsMultiMap::iterator i;
- for (i = settings->begin(); i != settings->end(); ++i)
- {
- typeName = i->first;
- archName = i->second;
- Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
- archName, typeName, secName);
- }
- }
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::createResourceListener(void)
- {
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::loadResources(void)
- {
- Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
- }
- //-------------------------------------------------------------------------------------
- void BaseApplication::go(void)
- {
- #ifdef _DEBUG
- mResourcesCfg = "resources_d.cfg";
- mPluginsCfg = "plugins_d.cfg";
- #else
- mResourcesCfg = "resources.cfg";
- mPluginsCfg = "plugins.cfg";
- #endif
- if (!setup())
- return;
- mRoot->startRendering();
- // clean up
- destroyScene();
- }
- //-------------------------------------------------------------------------------------
- bool BaseApplication::setup(void)
- {
- /*
- If we need to give a static link, then we should manully new an object of
- the plugins and install them. And since we create them with new method,
- do not forget to delete them before the programe exit.
- */
- #ifdef OGRE_STATIC_LIB
- mRoot = OGRE_NEW Ogre::Root("", "ogre.cfg", "ogre.log");
- mParticleFXPlugin = OGRE_NEW Ogre::ParticleFXPlugin();
- mRoot->installPlugin(mParticleFXPlugin);
- mD3D9Plugin = OGRE_NEW Ogre::D3D9Plugin();
- mRoot->installPlugin(mD3D9Plugin);
- mOctreePlugin = OGRE_NEW Ogre::OctreePlugin();
- mRoot->installPlugin(mOctreePlugin);
- #if defined __OGREOGGSOUNG__
- mOgreOggSoundPlugin = OGRE_NEW OgreOggSound::OgreOggSoundPlugin();
- mRoot->installPlugin(mOgreOggSoundPlugin);
- #endif
- #else
- mRoot = new Ogre::Root(mPluginsCfg);
- #endif
- setupResources();
- bool carryOn = configure();
- if (!carryOn) return false;
- chooseSceneManager();
- createCamera();
- createViewports();
- // Set default mipmap level (NB some APIs ignore this)
- Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
- // Create any resource listeners (for loading screens)
- createResourceListener();
- // Load resources
- loadResources();
- // Create the scene
- createScene();
- createFrameListener();
- return true;
- };
- //-------------------------------------------------------------------------------------
- bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)
- {
- if(mWindow->isClosed())
- return false;
- if(mShutDown)
- return false;
- //Need to capture/update each device
- mKeyboard->capture();
- mMouse->capture();
- mTrayMgr->frameRenderingQueued(evt);
- if (!mTrayMgr->isDialogVisible())
- {
- mCameraMan->frameRenderingQueued(evt); // if dialog isn't up, then update the camera
- if (mDetailsPanel->isVisible()) // if details panel is visible, then update its contents
- {
- mDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(mCamera->getDerivedPosition().x));
- mDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(mCamera->getDerivedPosition().y));
- mDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(mCamera->getDerivedPosition().z));
- mDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().w));
- mDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().x));
- mDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().y));
- mDetailsPanel->setParamValue(7, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().z));
- }
- }
- return true;
- }
- //-------------------------------------------------------------------------------------
- bool BaseApplication::keyPressed( const OIS::KeyEvent &arg )
- {
- if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up
- if (arg.key == OIS::KC_F) // toggle visibility of advanced frame stats
- {
- mTrayMgr->toggleAdvancedFrameStats();
- }
- else if (arg.key == OIS::KC_G) // toggle visibility of even rarer debugging details
- {
- if (mDetailsPanel->getTrayLocation() == OgreBites::TL_NONE)
- {
- mTrayMgr->moveWidgetToTray(mDetailsPanel, OgreBites::TL_TOPRIGHT, 0);
- mDetailsPanel->show();
- }
- else
- {
- mTrayMgr->removeWidgetFromTray(mDetailsPanel);
- mDetailsPanel->hide();
- }
- }
- else if (arg.key == OIS::KC_T) // cycle polygon rendering mode
- {
- Ogre::String newVal;
- Ogre::TextureFilterOptions tfo;
- unsigned int aniso;
- switch (mDetailsPanel->getParamValue(9).asUTF8()[0])
- {
- case 'B':
- newVal = "Trilinear";
- tfo = Ogre::TFO_TRILINEAR;
- aniso = 1;
- break;
- case 'T':
- newVal = "Anisotropic";
- tfo = Ogre::TFO_ANISOTROPIC;
- aniso = 8;
- break;
- case 'A':
- newVal = "None";
- tfo = Ogre::TFO_NONE;
- aniso = 1;
- break;
- default:
- newVal = "Bilinear";
- tfo = Ogre::TFO_BILINEAR;
- aniso = 1;
- }
- Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(tfo);
- Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(aniso);
- mDetailsPanel->setParamValue(9, newVal);
- }
- else if (arg.key == OIS::KC_R) // cycle polygon rendering mode
- {
- Ogre::String newVal;
- Ogre::PolygonMode pm;
- switch (mCamera->getPolygonMode())
- {
- case Ogre::PM_SOLID:
- newVal = "Wireframe";
- pm = Ogre::PM_WIREFRAME;
- break;
- case Ogre::PM_WIREFRAME:
- newVal = "Points";
- pm = Ogre::PM_POINTS;
- break;
- default:
- newVal = "Solid";
- pm = Ogre::PM_SOLID;
- }
- mCamera->setPolygonMode(pm);
- mDetailsPanel->setParamValue(10, newVal);
- }
- else if(arg.key == OIS::KC_F5) // refresh all textures
- {
- Ogre::TextureManager::getSingleton().reloadAll();
- }
- else if (arg.key == OIS::KC_SYSRQ) // take a screenshot
- {
- mWindow->writeContentsToTimestampedFile("screenshot", ".jpg");
- }
- else if (arg.key == OIS::KC_ESCAPE)
- {
- mShutDown = true;
- }
- mCameraMan->injectKeyDown(arg);
- return true;
- }
- bool BaseApplication::keyReleased( const OIS::KeyEvent &arg )
- {
- mCameraMan->injectKeyUp(arg);
- return true;
- }
- bool BaseApplication::mouseMoved( const OIS::MouseEvent &arg )
- {
- if (mTrayMgr->injectMouseMove(arg)) return true;
- mCameraMan->injectMouseMove(arg);
- return true;
- }
- bool BaseApplication::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
- {
- if (mTrayMgr->injectMouseDown(arg, id)) return true;
- mCameraMan->injectMouseDown(arg, id);
- return true;
- }
- bool BaseApplication::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
- {
- if (mTrayMgr->injectMouseUp(arg, id)) return true;
- mCameraMan->injectMouseUp(arg, id);
- return true;
- }
- //Adjust mouse clipping area
- void BaseApplication::windowResized(Ogre::RenderWindow* rw)
- {
- unsigned int width, height, depth;
- int left, top;
- rw->getMetrics(width, height, depth, left, top);
- const OIS::MouseState &ms = mMouse->getMouseState();
- ms.width = width;
- ms.height = height;
- }
- //Unattach OIS before window shutdown (very important under Linux)
- void BaseApplication::windowClosed(Ogre::RenderWindow* rw)
- {
- //Only close for window that created OIS (the main window in these demos)
- if( rw == mWindow )
- {
- if( mInputManager )
- {
- mInputManager->destroyInputObject( mMouse );
- mInputManager->destroyInputObject( mKeyboard );
- OIS::InputManager::destroyInputSystem(mInputManager);
- mInputManager = 0;
- }
- }
- }
TutorialApplication.cpp
- #include "TutorialApplication.h"
- #include "OgreParticleAffector.h"
- #include "OgreParticleEmitter.h"
- #include "OgreParticleSystemManager.h"
- #if defined __CEGUIOGRE__
- #include "CEGUI.h"
- #include <RendererModules/Ogre/CEGUIOgreTexture.h>
- #include <RendererModules/Ogre/CEGUIOgreTextureTarget.h>
- CEGUI::MouseButton convertButton(OIS::MouseButtonID buttonID)
- {
- switch (buttonID)
- {
- case OIS::MB_Left:
- return CEGUI::LeftButton;
- case OIS::MB_Right:
- return CEGUI::RightButton;
- case OIS::MB_Middle:
- return CEGUI::MiddleButton;
- default:
- return CEGUI::LeftButton;
- }
- }
- #ifdef __WOBBLLY_EFFECT__
- //----------------------------------------------------------------------------//
- // The following are related to the RenderEffect
- //
- // Note: This be the land of magic numbers and compound hacks upon hacks :-p
- // Any final version of this we might provide will likely be cleaned up
- // considerably.
- //----------------------------------------------------------------------------//
- const float MyEffect::tess_x = 8;
- const float MyEffect::tess_y = 8;
- //----------------------------------------------------------------------------//
- MyEffect::MyEffect() :
- initialised(false),
- dragX(0), dragY(0),
- elasX(0), elasY(0)
- {
- }
- //----------------------------------------------------------------------------//
- int MyEffect::getPassCount() const
- {
- return 1;
- }
- //----------------------------------------------------------------------------//
- void MyEffect::performPreRenderFunctions(const int /*pass*/)
- {
- // nothing we need here
- }
- //----------------------------------------------------------------------------//
- void MyEffect::performPostRenderFunctions()
- {
- // nothing we need here
- }
- //----------------------------------------------------------------------------//
- bool MyEffect::realiseGeometry(CEGUI::RenderingWindow& window,
- CEGUI::GeometryBuffer& geometry)
- {
- using namespace CEGUI;
- Texture& tex = window.getTextureTarget().getTexture();
- static const CEGUI::colour c(1, 1, 1, 1);
- const float qw = window.getSize().d_width / tess_x;
- const float qh = window.getSize().d_height / tess_y;
- const float tcx = qw * tex.getTexelScaling().d_x;
- const float tcy =
- (window.getTextureTarget().isRenderingInverted() ? -qh : qh) *
- tex.getTexelScaling().d_y;
- for (int j = 0; j < tess_y; ++j)
- {
- for (int i = 0; i < tess_x; ++i)
- {
- int idx = (j * tess_x + i) * 6;
- float top_adj = dragX * ((1.0f / tess_x) * j);
- float bot_adj = dragX * ((1.0f / tess_x) * (j+1));
- top_adj = ((top_adj*top_adj) / 3) * (dragX < 0 ? -1 : 1);
- bot_adj = ((bot_adj*bot_adj) / 3) * (dragX < 0 ? -1 : 1);
- float lef_adj = dragY * ((1.0f / tess_y) * i);
- float rig_adj = dragY * ((1.0f / tess_y) * (i+1));
- lef_adj = ((lef_adj*lef_adj) / 3) * (dragY < 0 ? -1 : 1);
- rig_adj = ((rig_adj*rig_adj) / 3) * (dragY < 0 ? -1 : 1);
- // vertex 0
- vb[idx + 0].position = Vector3(i * qw - top_adj, j * qh - lef_adj, 0.0f);
- vb[idx + 0].colour_val = c;
- vb[idx + 0].tex_coords = Vector2(i * tcx, j*tcy);
- // vertex 1
- vb[idx + 1].position = Vector3(i * qw - bot_adj, j * qh + qh - lef_adj, 0.0f);
- vb[idx + 1].colour_val = c;
- vb[idx + 1].tex_coords = Vector2(i*tcx, j*tcy+tcy);
- // vertex 2
- vb[idx + 2].position = Vector3(i * qw + qw - bot_adj, j * qh + qh - rig_adj, 0.0f);
- vb[idx + 2].colour_val = c;
- vb[idx + 2].tex_coords = Vector2(i*tcx+tcx, j*tcy+tcy);
- // vertex 3
- vb[idx + 3].position = Vector3(i * qw + qw - bot_adj, j * qh + qh - rig_adj, 0.0f);
- vb[idx + 3].colour_val = c;
- vb[idx + 3].tex_coords = Vector2(i*tcx+tcx, j*tcy+tcy);
- // vertex 4
- vb[idx + 4].position = Vector3(i * qw + qw - top_adj, j * qh - rig_adj, 0.0f);
- vb[idx + 4].colour_val = c;
- vb[idx + 4].tex_coords = Vector2(i*tcx+tcx, j*tcy);
- // vertex 5
- vb[idx + 5].position = Vector3(i * qw - top_adj, j * qh - lef_adj, 0.0f);
- vb[idx + 5].colour_val = c;
- vb[idx + 5].tex_coords = Vector2(i * tcx, j*tcy);
- }
- }
- geometry.setActiveTexture(&tex);
- geometry.appendGeometry(vb, buffsize);
- // false, because we do not want the default geometry added!
- return false;
- }
- //----------------------------------------------------------------------------//
- bool MyEffect::update(const float elapsed, CEGUI::RenderingWindow& window)
- {
- using namespace CEGUI;
- // initialise ourself upon the first update call.
- if (!initialised)
- {
- initialised=true;
- lastX = window.getPosition().d_x;
- lastY = window.getPosition().d_y;
- return true;
- }
- const Vector2 pos(window.getPosition());
- //
- // Set up for X axis animation.
- //
- if (pos.d_x != lastX)
- {
- dragX += (pos.d_x - lastX) * 0.2;
- elasX = 0.05f;
- lastX = pos.d_x;
- if (dragX > 25)
- dragX = 25;
- else if (dragX < -25)
- dragX = -25;
- }
- //
- // Set up for y axis animation
- //
- if (pos.d_y != lastY)
- {
- dragY += (pos.d_y - lastY) * 0.2f;
- elasY = 0.05f;
- lastY = pos.d_y;
- if (dragY > 25)
- dragY = 25;
- else if (dragY < -25)
- dragY = -25;
- }
- //
- // Perform required animation steps
- //
- if ((dragX != 0) || (dragY != 0))
- {
- if (dragX < 0)
- {
- dragX += (elasX * 800 * elapsed);
- elasX += 0.075 * elapsed;
- if (dragX >0)
- dragX = 0;
- }
- else
- {
- dragX -= (elasX * 800 * elapsed);
- elasX += 0.075 * elapsed;
- if (dragX < 0)
- dragX = 0;
- }
- if (dragY < 0)
- {
- dragY += elasY * 800 * elapsed;
- elasY += 0.075 * elapsed;
- if (dragY >0)
- dragY = 0;
- }
- else
- {
- dragY -= elasY * 800 * elapsed;
- elasY += 0.075 * elapsed;
- if (dragY < 0)
- dragY = 0;
- }
- // note we just need system to redraw the geometry; we do not need a
- // full redraw of all window/widget content - which is unchanged.
- System::getSingleton().signalRedraw();
- return false;
- }
- return true;
- }
- #endif
- #endif
- ITutorial01::ITutorial01(void):mRaySceneQuery(0),exFlag(0),mReplay(false)
- {
- }
- ITutorial01::~ITutorial01(void)
- {
- mWalkList.clear();
- // We created the query, and we are also responsible for deleting it.
- if(mRaySceneQuery)
- {
- mSceneMgr->destroyQuery(mRaySceneQuery);
- }
- }
- void ITutorial01::createScene(void)
- {
- // Set ambient light
- mSceneMgr->setAmbientLight(Ogre::ColourValue(0.2f, 0.2f, 0.2f));
- mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000); // set our skybox
- // World geometry
- mSceneMgr->setWorldGeometry("terrain.cfg");
- // Set camera look point
- mCamera->setPosition(Ogre::Vector3(2500, 30, 3980));
- //mCamera->setDirection(0,-1,0);
- mCamera->lookAt(Ogre::Vector3(2600, 100, 3615));
- mCamera->setNearClipDistance(0.5);
- // Create the entity
- mEntity = mSceneMgr->createEntity("Robot", "robot.mesh");
- // Create the scene node
- mNode = mSceneMgr->getRootSceneNode()->
- createChildSceneNode("RobotNode", Ogre::Vector3(2680, 30, 4030));
- mNode->attachObject(mEntity);
- mNode->setScale(0.3f,0.3f,0.3f);
- // Create the walking list
- mWalkList.push_back(Ogre::Vector3(2300, 0, 3760));
- mWalkList.push_back(Ogre::Vector3(2700, 0, 3250));
- rttCam = mSceneMgr->createCamera("RTTCam");
- rttCam->setNearClipDistance(1);
- //RTT
- Ogre::TexturePtr tex = mRoot->getTextureManager()->createManual("RTT",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
- Ogre::TEX_TYPE_2D,512,512,0,Ogre::PF_R8G8B8,Ogre::TU_RENDERTARGET);
- rtex = tex->getBuffer()->getRenderTarget();
- Ogre::Viewport *v = rtex->addViewport(mSceneMgr->getCamera("RTTCam"));
- v->setOverlaysEnabled(false);
- v->setClearEveryFrame(true);
- v->setBackgroundColour(Ogre::ColourValue::Black);
- // create a particle system with 200 quota, then set its material and dimensions
- thrusters = mSceneMgr->createParticleSystem("thrusters",25);
- thrusters ->setMaterialName("Examples/Flare");
- thrusters ->setDefaultDimensions(15, 15);
- // create emitter for our thruster particle system
- Ogre::ParticleEmitter* emitter = thrusters ->addEmitter("Point"); // add a point emitter
- Ogre::Vector3 direct = mCamera->getDirection();
- // set the emitter properties
- emitter->setAngle(Ogre::Degree(5));
- emitter->setTimeToLive(0.5);
- emitter->setEmissionRate(20);
- emitter->setParticleVelocity(10);
- emitter->setDirection(Ogre::Vector3::ZERO);
- emitter->setColour(Ogre::ColourValue::White, Ogre::ColourValue::Red);
- emitter->setPosition(Ogre::Vector3(0,0,0));
- // attach our thruster particles to the rear of the ship
- mSceneMgr->getRootSceneNode()->createChildSceneNode("emitter")->attachObject(thrusters);
- rttCam->detachFromParent();
- mSceneMgr->getSceneNode("emitter")->attachObject(rttCam);
- mSceneMgr->getSceneNode("emitter")->setPosition(mCamera->getPosition()+15*direct-Ogre::Vector3(0,10,0));
- // Create objects so we can see movement
- Ogre::Entity *ent;
- Ogre::SceneNode *node;
- ent = mSceneMgr->createEntity("Sphere1", "sphere.mesh");
- node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Sphere0Node");
- node->attachObject(ent);
- node->setScale(0.02f, 0.02f, 0.02f);
- ent = mSceneMgr->createEntity("Sphere2", "sphere.mesh");
- node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Sphere1Node");
- node->attachObject(ent);
- node->setScale(0.02f, 0.02f, 0.02f);
- ent = mSceneMgr->createEntity("Sphere3", "sphere.mesh");
- node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Sphere2Node");
- node->attachObject(ent);
- node->setScale(0.02f, 0.02f, 0.02f);
- #if defined __OGREMINISCREEN__
- //Ogre miniScreen render to texture
- Ogre::Rectangle2D *mMiniScreen = new Ogre::Rectangle2D(true);
- mMiniScreen->setCorners(0.5f, -0.5f, 1.0f, -1.0f);
- mMiniScreen->setBoundingBox(Ogre::AxisAlignedBox(-100000.0f * Ogre::Vector3::UNIT_SCALE, 100000.0f * Ogre::Vector3::UNIT_SCALE));
- Ogre::SceneNode* miniScreenNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("MiniScreenNode");
- miniScreenNode->attachObject(mMiniScreen);
- Ogre::MaterialPtr renderMaterial = Ogre::MaterialManager::getSingleton().create("RttMat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
- Ogre::Technique* matTechnique = renderMaterial->createTechnique();
- matTechnique->createPass();
- renderMaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
- renderMaterial->getTechnique(0)->getPass(0)->createTextureUnitState("RTT");
- mMiniScreen->setMaterial("RttMat");
- #endif
- #if defined __CEGUIOGRE__
- // CEGUI setup
- mGUIRenderer = &CEGUI::OgreRenderer::bootstrapSystem();
- #ifdef __WOBBLLY_EFFECT__
- // Register our effect with the system
- CEGUI::RenderEffectManager::getSingleton().addEffect<MyEffect>("WobblyWindow");
- // Now we make a Falagard mapping for a frame window that uses this effect.
- // We create a type "TaharezLook/WobblyFrameWindow", which is subsequently
- // referenced in the layout file loaded below. Note that it wold be more
- // usual for this mapping to be specified in the scheme xml file, though
- // here we are doing in manually to save from needing either multiple
- // versions of the schemes or from having demo specific definitions in
- // the schemes.
- CEGUI::WindowFactoryManager::getSingleton().addFalagardWindowMapping(
- "TaharezLook/WobblyFrameWindow", // type to create
- "CEGUI/FrameWindow", // 'base' widget type
- "TaharezLook/FrameWindow", // WidgetLook to use.
- "Falagard/FrameWindow", // WindowRenderer to use.
- "WobblyWindow"); // effect to use.
- #endif
- // Mouse
- CEGUI::SchemeManager::getSingleton().create((CEGUI::utf8*)"TaharezLook.scheme");
- CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
- CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseArrow");
- /// CEGUI logo render //
- // setup required to do direct rendering
- const CEGUI::Size hsz = mGUIRenderer->getDisplaySize() * 0.5f;
- const CEGUI::Rect scrn(CEGUI::Vector2(0, 0), hsz * 2);
- // setup for logo
- CEGUI::ImagesetManager::getSingleton().createFromImageFile("cegui_logo", "logo.png", "Imagesets");
- d_logo_geometry = &mGUIRenderer->createGeometryBuffer();
- d_logo_geometry->setClippingRegion(scrn);
- d_logo_geometry->setPivot(CEGUI::Vector3(hsz.d_width, 34.75f, 0));
- d_logo_geometry->setTranslation(CEGUI::Vector3(0, hsz.d_height * 2 - 80, 0));
- CEGUI::ImagesetManager::getSingleton().get("cegui_logo").getImage("full_image").draw(*d_logo_geometry,
- CEGUI::Rect(hsz.d_width - 50, 0, hsz.d_width + 50, 69.5f), 0);
- // clearing this queue actually makes sure it's created(!)
- mGUIRenderer->getDefaultRenderingRoot().clearGeometry(CEGUI::RQ_OVERLAY);
- // subscribe handler to render overlay items
- mGUIRenderer->getDefaultRenderingRoot().subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
- CEGUI::Event::Subscriber(&ITutorial01::overlayHandler,this));
- ///
- CEGUI::Texture &guiTex = mGUIRenderer->createTexture(tex);
- CEGUI::Imageset &imageSet = CEGUI::ImagesetManager::getSingleton().create("RTTImageset", guiTex);
- imageSet.defineImage("RTTImage",CEGUI::Point(0.0f, 0.0f),CEGUI::Size(guiTex.getSize().d_width,
- guiTex.getSize().d_height), CEGUI::Point(0.0f, 0.0f));
- // CEGUI GUI sheet setup
- CEGUI::Window * sheet = CEGUI::WindowManager::getSingleton().createWindow("DefaultWindow", "Root");
- CEGUI::System::getSingleton().setGUISheet(sheet);
- // RTTFrameWindow
- #ifdef __WOBBLLY_EFFECT__
- CEGUI::Window *si = CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/WobblyFrameWindow", "RTTFrameWindow");
- #else
- CEGUI::Window *si = CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/FrameWindow", "RTTFrameWindow");
- #endif
- sheet->addChildWindow(si);
- si->setPosition(CEGUI::UVector2(CEGUI::UDim(0.0f, 0), CEGUI::UDim(0.0f, 0)));
- si->setProperty("CloseButtonEnabled","False");
- si->setProperty("Text","Sound");
- si->setProperty("ClientAreaColour","7F141B38");
- si = CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/Slider", "slider");
- CEGUI::WindowManager::getSingleton().getWindow("RTTFrameWindow")->addChildWindow(si);
- si->setSize(CEGUI::UVector2(CEGUI::UDim(0.2f, 0), CEGUI::UDim(1.0f, 0)));
- si->setPosition(CEGUI::UVector2(CEGUI::UDim(0.4f, 0), CEGUI::UDim(0.0f, 0)));
- si->setProperty("MaximumValue", "1");
- si->setProperty("CurrentValue", "0.7");
- si->subscribeEvent(CEGUI::Slider::EventValueChanged, CEGUI::Event::Subscriber(&ITutorial01::handleSlider,this));
- si = CEGUI::WindowManager::getSingleton().getWindow("RTTFrameWindow");
- si->setSize(CEGUI::UVector2(CEGUI::UDim(0.15f, 0), CEGUI::UDim(0.5f, 0)));
- ((CEGUI::FrameWindow*)si)->toggleRollup();
- si = CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/StaticImage", "RTTWindow");
- si->setProperty("BackgroundEnabled","False");
- si->setSize(CEGUI::UVector2(CEGUI::UDim(0.5f, 0), CEGUI::UDim(0.4f, 0)));
- si->setPosition(CEGUI::UVector2(CEGUI::UDim(0.5f, 0), CEGUI::UDim(0.0f, 0)));
- si->setProperty("Image", CEGUI::PropertyHelper::imageToString(&imageSet.getImage("RTTImage")));
- sheet->addChildWindow(si);
- si->setVisible(false);
- #ifdef __CEGUI_RTT__
- // get rendering surface used by FrameWindow.
- CEGUI::RenderingSurface* surface = &si->getTargetRenderingSurface();
- // if there's no surface, skip the RTT setup parts!
- if (surface)
- {
- initialiseRTTViewport(surface);
- // Since we set the Ogre RTT above to not be auto updated, we'll use an
- // event subscription to decide when to render that content manually.
- // Basically this needs to be done after other UI content is drawn but
- // before anything gets put on screen. We need to use an appropriate
- // RenderingSurface for this - not the surface used for the window we
- // will render directly to - but something higher up. For this demo
- // (and many other scenarios) the RenderingRoot will suffice. We use
- // the EventRenderQueueStarted because we want to update the content
- // /before/ it's drawn to the surface (here that would be the screen).
- mGUIRenderer->getDefaultRenderingRoot().subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueEnded,
- CEGUI::Event::Subscriber(&ITutorial01::updateRTT, this));
- // subscribe to hear about resize events. This is needed because
- // when the underlying texture gets resized, all the associated objects
- // must be assumed to be lost also
- si->subscribeEvent(CEGUI::Window::EventSized,CEGUI::Event::Subscriber(&ITutorial01::handleRTTResize, this));
- }
- #endif
- #endif
- #if defined __OGREOGGSOUNG__
- //OgreOggSound setup
- mSoundNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("soundNode",mCamera->getPosition());
- if(mSoundManager->init())
- {
- mSoundNode->attachObject(mSoundManager->getListener());
- /** prebuffered, streamed, looping */
- // but I've changed it here
- sound = 0;
- if ( sound = mSoundManager->createSound("PointSound", "WA121.wav") )
- {
- sound->disable3D(true);
- }
- /** streamed, looping, EFX Direct filter */
- sound = 0;
- sound = mSoundManager->createSound("background", "p42.ogg", true, true);
- if ( sound )
- {
- sound->disable3D(true);
- sound->play();
- }
- sound = 0;
- sound = mSoundManager->createSound("Fire", "WD366.wav", false, false, true);
- if ( sound )
- {
- sound->disable3D(true);
- }
- /** prebuffered, streamed, looping */
- sound = 0;
- if ( sound = sound = mSoundManager->createSound("Explosion","WD309.wav", false, false, true) )
- {
- sound->setMaxDistance(3000);
- sound->setReferenceDistance(1000);
- mSceneMgr->getSceneNode("emitter")->attachObject(sound);
- }
- /** prebuffered, streamed, looping */
- sound = 0;
- if ( sound = mSoundManager->createSound("Emitter", "WD299.wav", true, true) )
- {
- sound->setMaxDistance(150);
- sound->setReferenceDistance(50);
- mSceneMgr->getSceneNode("emitter")->attachObject(sound);
- sound->play();
- sound->setLoopOffset(5.f);
- }
- sound = 0;
- if ( sound = mSoundManager->createSound("StepSound", "WF038.wav", false, true) )
- {
- sound->setMaxDistance(300);
- sound->setReferenceDistance(100);
- mNode->attachObject(sound);
- }
- mSoundManager->setMasterVolume(0.7f);
- }
- #endif
- }
- #if defined __CEGUIOGRE__
- #ifdef __CEGUI_RTT__
- void ITutorial01::initialiseRTTViewport(CEGUI::RenderingSurface* const surface)
- {
- const Ogre::RenderTexture* const old_rtt = rtex;
- // extract the Ogre render target at for the surface
- rtex = dynamic_cast<CEGUI::OgreTexture&>(dynamic_cast<CEGUI::OgreTextureTarget&>(
- surface->getRenderTarget()).getTexture()).getOgreTexture()->getBuffer()->getRenderTarget();
- // only do set up if target is changed.
- if (old_rtt != rtex)
- {
- // tell Ogre not to draw this target automatically (else you get
- // visible flickering).
- //rtex->setAutoUpdated(false);
- // setup viewport.
- Ogre::Viewport *v = rtex->addViewport(mSceneMgr->getCamera("RTTCam"));
- v->setOverlaysEnabled(false);
- v->setClearEveryFrame(true);
- v->setBackgroundColour(Ogre::ColourValue::Black);
- }
- }
- bool ITutorial01::updateRTT(const CEGUI::EventArgs& args)
- {
- // There are many rendering queues that may (or may not) be present for
- // a RenderingSurface. For our purposes, we can hook the 'default' of
- // RQ_BASE. - and we need to do our rendering /before/ this queue
- if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_BASE)
- return false;
- // get the target to draw itself.
- rtex->update();
- // Reset the initial CEGUI rendering states.
- mGUIRenderer->initialiseRenderStateSettings();
- // (Re)Activate the appropriate CEGUI render target.
- mGUIRenderer->getDefaultRenderingRoot().getRenderTarget().activate();
- return true;
- }
- bool ITutorial01::handleRTTResize(const CEGUI::EventArgs& args)
- {
- // get rendering surface used by FrameWindow.
- CEGUI::RenderingSurface* surface = static_cast<const CEGUI::WindowEventArgs&>(args).window
- ->getRenderingSurface();
- // if there's no surface, skip the RTT setup parts!
- if (surface)
- {
- initialiseRTTViewport(surface);
- }
- return true;
- }
- #endif
- bool ITutorial01::overlayHandler(const CEGUI::EventArgs& args)
- {
- if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
- return false;
- d_logo_geometry->draw();
- return true;
- }
- bool ITutorial01::handleSlider(const CEGUI::EventArgs& args)
- {
- float val = static_cast<CEGUI::Slider*>(static_cast<const CEGUI::WindowEventArgs&>(args).window)->getCurrentValue();
- mSoundManager->setMasterVolume(val);
- return true;
- }
- #endif
- void ITutorial01::createFrameListener(void)
- {
- // Set idle animation
- mAnimationState = mEntity->getAnimationState("Idle");
- mAnimationState->setLoop(true);
- mAnimationState->setEnabled(true);
- // Set default values for variables
- mWalkSpeed = 50.0f;
- mDirection = Ogre::Vector3::ZERO;
- // Setup default variables
- mLMouseDown = false;
- mRMouseDown = false;
- // Reduce rotate speed
- mRotateSpeed =.1f;
- // Create RaySceneQuery
- mRaySceneQuery = mSceneMgr->createRayQuery(Ogre::Ray());
- BaseApplication::createFrameListener();
- }
- bool ITutorial01::nextLocation(void)
- {
- if (mWalkList.empty())
- return false;
- mDestination = mWalkList.front(); // this gets the front of the deque
- mWalkList.pop_front(); // this removes the front of the deque
- // in order to just rotate the robot in XZ plane, we make the Y axis be the same
- mDirection = mDestination - mNode->getPosition();
- mDirection.y = 0;
- mDistance = mDirection.normalise();
- return true;
- }
- bool ITutorial01::frameRenderingQueued(const Ogre::FrameEvent &evt)
- {
- #if defined __CEGUIOGRE__
- // update logo rotation
- static float rot = 0.0f;
- d_logo_geometry->setRotation(CEGUI::Vector3(rot, 0, 0));
- rot += 180.0f * (evt.timeSinceLastFrame);
- if (rot > 360.0f)
- rot -= 360.0f;
- #endif
- #if defined __OGREOGGSOUNG__
- //update the listener's postion
- mSoundNode->setPosition(mCamera->getPosition());
- mSoundManager->update(evt.timeSinceLastFrame);
- #endif
- // Setup the scene query
- Ogre::Vector3 nodePos = mNode->getPosition();
- Ogre::Ray nodeRay(Ogre::Vector3(nodePos.x, 5000.0f, nodePos.z), Ogre::Vector3::NEGATIVE_UNIT_Y);
- mRaySceneQuery->setRay(nodeRay);
- // Perform the scene query
- Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
- Ogre::RaySceneQueryResult::iterator itr = result.begin();
- // Get the results, set the RobotNode height
- if (itr != result.end() && itr->worldFragment)
- {
- Ogre::Real terrainHeight = itr->worldFragment->singleIntersection.y;
- if ((terrainHeight) != nodePos.y)
- mNode->setPosition( nodePos.x, terrainHeight, nodePos.z );
- }
- // Setup the scene query. For the camera
- nodePos = mCamera->getPosition();
- nodeRay.setOrigin(Ogre::Vector3(nodePos.x, 5000.0f, nodePos.z));
- mRaySceneQuery->setRay(nodeRay);
- // Perform the scene query
- result = mRaySceneQuery->execute();
- itr = result.begin();
- // Get the results, set the camera height
- if (itr != result.end() && itr->worldFragment)
- {
- Ogre::Real terrainHeight = itr->worldFragment->singleIntersection.y;
- if ((terrainHeight + 10.0f) >= nodePos.y)
- mCamera->setPosition( nodePos.x, terrainHeight + 10.0f, nodePos.z );
- }
- // Here nodePos is just a vector of direction
- nodePos = thrusters->getEmitter(0)->getDirection();
- if(!nodePos.isZeroLength())
- {
- mSceneMgr->getSceneNode("emitter")->translate(nodePos * 150 * evt.timeSinceLastFrame);
- if(!(exFlag & 0x01))
- {
- nodePos = mSceneMgr->getSceneNode("emitter")->getPosition();
- if((nodePos - mCamera->getPosition()).squaredLength() > 25000000)
- {
- thrusters->getEmitter(0)->setDirection(Ogre::Vector3::ZERO);
- exFlag |= 0x01;
- }
- else
- {
- nodeRay.setOrigin(nodePos);
- nodeRay.setDirection(thrusters->getEmitter(0)->getDirection());
- mRaySceneQuery->setRay(nodeRay);
- // Execute query
- result = mRaySceneQuery->execute();
- // And I think it is more intelligent to use query mask here.
- for(itr = result.begin();itr != result.end();++itr)
- {
- if(itr->distance < 0.5f && itr->movable && !itr->movable->getName().compare("Robot"))
- {
- thrusters->getEmitter(0)->setDirection(Ogre::Vector3::ZERO);
- exFlag |= 0x01;
- exFlag |= 0x02;
- break;
- }
- if (itr->distance < 3.0f && itr->worldFragment)
- {
- thrusters->getEmitter(0)->setDirection(Ogre::Vector3::ZERO);
- exFlag |= 0x01;
- break;
- } // if
- }
- }
- }
- }
- static float size = 15.0f;
- #if defined __CEGUIOGRE__
- if(exFlag & 0x04)
- {
- size += evt.timeSinceLastFrame;
- if(size > 15.7f)
- {
- CEGUI::WindowManager::getSingleton().getWindow("RTTWindow")->setVisible(false);
- size = 15.0f;
- exFlag &= ~0x04;
- }
- }
- else
- #endif
- if(exFlag & 0x01)
- {
- #if defined __OGREOGGSOUNG__
- if(size < 15.001f)
- {
- mSoundManager->getSound("Emitter")->pause();
- mSoundManager->getSound("Explosion")->play();
- }
- #endif
- // when it goes into an explosion, we just let its size increase rapidly
- // but I can guarantee that's not a exponential growth.
- size *= (1 + 2.5f * evt.timeSinceLastFrame);
- thrusters->setDefaultDimensions(size,size);
- if(thrusters->getDefaultHeight() >= 900)
- {
- thrusters->setDefaultDimensions(15,15);
- size = 15.0f;
- thrusters->getEmitter(0)->setEnabled(false);
- if(exFlag & 0x02)
- {
- mNode->setVisible(false);
- mDistance = 0.0f;
- exFlag &= ~0x02;
- }
- exFlag &= ~0x01;
- exFlag |= 0x04;
- }
- }
- if (mDirection == Ogre::Vector3::ZERO)
- {
- if (nextLocation())
- {
- #if defined __OGREOGGSOUNG__
- mSoundManager->getSound("StepSound")->play();
- #endif
- // Set walking animation
- mAnimationState = mEntity->getAnimationState("Walk");
- mAnimationState->setLoop(true);
- mAnimationState->setEnabled(true);
- // Rotation Code will go here
- Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_X;
- if ((1.0f + src.dotProduct(mDirection)) < 0.0001f)
- {
- mNode->yaw(Ogre::Degree(180));
- }
- else
- {
- Ogre::Quaternion quat = src.getRotationTo(mDirection);
- mNode->rotate(quat);
- } // else
- }
- }
- else
- {
- Ogre::Real move = mWalkSpeed * evt.timeSinceLastFrame;
- mDistance -= move;
- if (mDistance <= 0.0f)
- {
- mNode->setPosition(mDestination);
- mDirection = Ogre::Vector3::ZERO;
- // Set animation based on if the robot has another point to walk to.
- if (! nextLocation())
- {
- #if defined __OGREOGGSOUNG__
- mSoundManager->getSound("StepSound")->stop();
- #endif
- // Set Idle animation
- mAnimationState = mEntity->getAnimationState("Idle");
- mAnimationState->setLoop(true);
- mAnimationState->setEnabled(true);
- }
- else
- {
- // Rotation Code will go here later
- Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_X;
- if ((1.0f + src.dotProduct(mDirection)) < 0.0001f)
- {
- mNode->yaw(Ogre::Degree(180));
- }
- else
- {
- Ogre::Quaternion quat = src.getRotationTo(mDirection);
- mNode->rotate(quat);
- } // else
- }
- }
- else if(!(exFlag & 0x02))
- {
- mNode->translate(mDirection * move);
- } // else
- } // if
- mAnimationState->addTime(evt.timeSinceLastFrame);
- return BaseApplication::frameRenderingQueued(evt);
- }
- void ITutorial01::chooseSceneManager(void)
- {
- // Use the terrain scene manager.
- // Not this method always success, sometimes it isn't a good situation
- mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE);
- #if defined __OGREOGGSOUNG__
- mSoundManager = OgreOggSound::OgreOggSoundManager::getSingletonPtr();
- #endif
- }
- bool ITutorial01::mouseMoved(const OIS::MouseEvent &arg)
- {
- if (mRMouseDown)
- {
- mCamera->yaw(Ogre::Degree(-arg.state.X.rel * mRotateSpeed));
- mCamera->pitch(Ogre::Degree(-arg.state.Y.rel * mRotateSpeed));
- } // else if
- #if defined __CEGUIOGRE__
- else
- {
- // Update CEGUI with the mouse motion
- if (arg.state.Z.rel)
- {
- CEGUI::System::getSingleton().injectMouseWheelChange(arg.state.Z.rel / 120.0f);
- }
- CEGUI::System::getSingleton().injectMouseMove(arg.state.X.rel, arg.state.Y.rel);
- }
- #endif
- return true;
- }
- bool ITutorial01::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
- {
- if (id == OIS::MB_Right)
- {
- #if defined __CEGUIOGRE__
- CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseTarget");
- CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseTarget");
- CEGUI::MouseCursor::getSingleton().setPosition(CEGUI::Point(arg.state.width*0.5,arg.state.height*0.5));
- #endif
- mRMouseDown = true;
- }
- else
- {
- #if defined __CEGUIOGRE__
- CEGUI::System::getSingleton().injectMouseButtonDown(convertButton(id));
- #endif
- // Left mouse button down
- if (id == OIS::MB_Left && !(exFlag & 0x05))
- {
- if(mRMouseDown)
- {
- #if defined __CEGUIOGRE__
- CEGUI::WindowManager::getSingleton().getWindow("RTTWindow")->setVisible(true);
- #endif
- #if defined __OGREOGGSOUNG__
- sound = mSoundManager->getSound("Fire");
- if(sound->isPlaying()) sound->stop();
- sound->play();
- mSoundManager->getSound("Emitter")->play();
- #endif
- Ogre::Vector3 tor = mCamera->getDirection();
- //here we get the boomb flying
- mSceneMgr->getSceneNode("emitter")->setPosition(mCamera->getPosition());
- thrusters->getEmitter(0)->setDirection(tor);
- thrusters->getEmitter(0)->setEnabled(true);
- tor.y = 0.0f;
- // we use a cross product to got a right look of RTTcam
- tor = tor.crossProduct(Ogre::Vector3::UNIT_Y).normalisedCopy();
- //tor.y = 0.4f;
- // we've let the CamraNode move with the emitter
- // so we just set relative position of the rttcam
- // Note: here the emitter have the same position with mCamera
- tor *= 5;
- tor -= mCamera->getDirection() * 55;
- rttCam->setPosition(tor);
- rttCam->lookAt(mCamera->getPosition());
- }
- else
- {
- #if defined __CEGUIOGRE__
- // Setup the ray scene query, use CEGUI's mouse position
- CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
- Ogre::Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
- #else
- Ogre::Ray mouseRay = mCamera->getCameraToViewportRay(0.5,0.5);
- #endif
- mRaySceneQuery->setRay(mouseRay);
- // Execute query
- Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
- Ogre::RaySceneQueryResult::iterator itr = result.begin( );
- // Get results, create a node/entity on the position
- if (itr != result.end() && itr->worldFragment)
- {
- #if defined __OGREOGGSOUNG__
- sound = mSoundManager->getSound("PointSound");
- if(sound->isPlaying()) sound->stop();
- sound->play();
- #endif
- if(mNode->getAttachedObject(0)->isVisible())
- {
- char name[16] = {0};
- static size_t i=0;
- sprintf_s(name,sizeof(name)-1,"Sphere%dNode",i++%3);
- mSceneMgr->getSceneNode(name)->setPosition(itr->worldFragment->singleIntersection + Ogre::Vector3(0,2,0));
- mWalkList.push_back(itr->worldFragment->singleIntersection);
- }
- else
- {
- mWalkList.clear();
- #if defined __OGREOGGSOUNG__
- mSoundManager->getSound("StepSound")->stop();
- #endif
- // Set Idle animation
- mAnimationState = mEntity->getAnimationState("Idle");
- mAnimationState->setLoop(true);
- mAnimationState->setEnabled(true);
- mNode->setPosition(itr->worldFragment->singleIntersection);
- mNode->setVisible(true);
- }
- } // if
- }
- } // if
- }
- return true;
- }
- bool ITutorial01::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
- {
- if (id == OIS::MB_Right)
- {
- #if defined __CEGUIOGRE__
- CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
- CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseArrow");
- #endif
- mRMouseDown = false;
- } // else if
- #if defined __CEGUIOGRE__
- else
- {
- CEGUI::System::getSingleton().injectMouseButtonUp(convertButton(id));
- }
- #endif
- return true;
- }
- #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
- #define WIN32_LEAN_AND_MEAN
- #include "windows.h"
- #endif
- #ifdef __cplusplus
- extern "C" {
- #endif
- #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
- #else
- int main(int argc, char *argv[])
- #endif
- {
- // Create application object
- ITutorial01 app;
- try {
- app.go();
- } catch( Ogre::Exception& e ) {
- #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
- MessageBoxA( NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
- #else
- std::cerr << "An exception has occurred: " <<
- e.getFullDescription().c_str() << std::endl;
- #endif
- }
- return 0;
- }
- #ifdef __cplusplus
- }
- #endif
资源文件:
resource.h
- //{{NO_DEPENDENCIES}}
- // Microsoft Visual C++ generated include file.
- // Used by OgreWin32Resources.rc
- //
- #define IDD_DLG_VIDEO 101
- #define IDD_DLG_CONFIG 101
- #define IDI_ICON1 103
- #define IDB_SPLASH 106
- #define IDD_DLG_ERROR 107
- #define IDI_OGREICON 111
- #define IDC_CBO_VIDEO 1001
- #define IDC_VIDEO_MODE 1002
- #define ID_LBL_RES 1003
- #define IDC_CBO_RESOLUTION 1004
- #define IDC_CBO_VIDEOMODE 1004
- #define IDC_COLOUR_DEPTH 1005
- #define IDC_CBO_COLOUR_DEPTH 1006
- #define IDC_CHK_FULLSCREEN 1007
- #define IDC_CBO_RENDERSYSTEM 1009
- #define IDC_OPTFRAME 1010
- #define IDC_CBO_OPTION 1011
- #define IDC_LST_OPTIONS 1013
- #define IDC_LBL_OPTION 1014
- #define IDC_ERRMSG 1018
- #define IDC_SELECT_VIDEO -1
- // Next default values for new objects
- //
- #ifdef APSTUDIO_INVOKED
- #ifndef APSTUDIO_READONLY_SYMBOLS
- #define _APS_NEXT_RESOURCE_VALUE 115
- #define _APS_NEXT_COMMAND_VALUE 40001
- #define _APS_NEXT_CONTROL_VALUE 1020
- #define _APS_NEXT_SYMED_VALUE 101
- #endif
- #endif
winresrc.h
- #include <winresrc.h>
- #ifdef IDC_STATIC
- #undef IDC_STATIC
- #endif
- #define IDC_STATIC (-1)