OgreFrameWork

来源:互联网 发布:JS在图片上录入文字 编辑:程序博客网 时间:2024/06/05 18:45

//mygame.h

#include "Ogre.h"
#include "OgreConfigFile.h"
#include "OIS/OIS.h"
using namespace Ogre;
class mygame : public FrameListener
{
public:
    /// Standard constructor
    mygame()
    {
       
        mRoot = 0;
   mResourcePath = "";

    }
    /// Standard destructor
    virtual ~mygame()
    {

        if (mRoot)
            delete mRoot;
    }

    /// Start the example
    virtual void go(void)
    {
        if (!setup())
            return;

        mRoot->startRendering();

        // clean up
        destroyScene();
    }

protected:
    Root *mRoot;
    Camera* mCamera;
    SceneManager* mSceneMgr;

    RenderWindow* mWindow;
Ogre::String mResourcePath;


   //OIS Input devices
OIS::InputManager* mInputManager;
OIS::Mouse*    mMouse;
OIS::Keyboard* mKeyboard;


//
Vector3 mTranslateVector;
float mMoveScale;
Degree mRotScale;

// just to stop toggles flipping too fast
Real mTimeUntilNextToggle ;
Radian mRotX, mRotY;
TextureFilterOptions mFiltering;
int mAniso;


bool mStatsOn;

std::string mDebugText;
int mSceneDetailIndex ;
Overlay* mDebugOverlay;
Real mMoveSpeed;
Degree mRotateSpeed;

    // These internal methods package up the stages in the startup process
    /** Sets up the application - returns false if the user chooses to abandon configuration. */
    virtual bool setup(void)
    {

   String pluginsPath;
   // only use plugins.cfg if not static
#ifndef OGRE_STATIC_LIB
   pluginsPath = mResourcePath + "plugins.cfg";
#endif
  
        mRoot = new Root(pluginsPath,
            mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");

        setupResources();

        bool carryOn = configure();
        if (!carryOn) return false;

        chooseSceneManager();
        createCamera();
        createViewports();

        // Set default mipmap level (NB some APIs ignore this)
        TextureManager::getSingleton().setDefaultNumMipmaps(5);

   // Create any resource listeners (for loading screens)
   createResourceListener();
   // Load resources
   loadResources();

   // Create the scene
        createScene();

        createFrameListener();

        return true;

    }
    /** Configures the application - returns false if the user chooses to abandon configuration. */
    virtual bool 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);
            return true;
        }
        else
        {
            return false;
        }
    }

    virtual void chooseSceneManager(void)
    {
        // Create the SceneManager, in this case a generic one
        mSceneMgr = mRoot->createSceneManager(ST_GENERIC, "mygameInstance");
    }
    virtual void createCamera(void)
    {
        // Create the camera
        mCamera = mSceneMgr->createCamera("PlayerCam");

        // Position it at 500 in Z direction
        mCamera->setPosition(Vector3(0,0,500));
        // Look back along -Z
        mCamera->lookAt(Vector3(0,0,-300));
        mCamera->setNearClipDistance(5);

    }
    virtual void createFrameListener(void)
    {
using namespace OIS;

mRotateSpeed = 36;
mMoveSpeed = 100;


   mDebugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay");

   LogManager::getSingletonPtr()->logMessage("*** Initializing 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 = InputManager::createInputSystem( pl );

   //Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
   mKeyboard = static_cast<Keyboard*>(mInputManager->createInputObject( OISKeyboard, false));
   mMouse = static_cast<Mouse*>(mInputManager->createInputObject( OISMouse, false ));
  

        this->showDebugOverlay(true);
        mRoot->addFrameListener((Ogre::FrameListener *)this);
    }

    virtual void createScene(void) ;    // pure virtual - this has to be overridden

    virtual void destroyScene(void){}    // Optional to override this

    virtual void createViewports(void)
    {
        // Create one viewport, entire window
        Viewport* vp = mWindow->addViewport(mCamera);
        vp->setBackgroundColour(ColourValue(0,0,0));

        // Alter the camera aspect ratio to match the viewport
        mCamera->setAspectRatio(
            Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
    }

    /// Method which will define the source of resources (other than current folder)
    virtual void setupResources(void)
    {
        // Load resource paths from config file
        ConfigFile cf;
        cf.load(mResourcePath + "resources.cfg");

        // Go through all sections & settings in the file
        ConfigFile::SectionIterator seci = cf.getSectionIterator();

        String secName, typeName, archName;
        while (seci.hasMoreElements())
        {
            secName = seci.peekNextKey();
            ConfigFile::SettingsMultiMap *settings = seci.getNext();
            ConfigFile::SettingsMultiMap::iterator i;
            for (i = settings->begin(); i != settings->end(); ++i)
            {
                typeName = i->first;
                archName = i->second;

                ResourceGroupManager::getSingleton().addResourceLocation(
                    archName, typeName, secName);

            }
        }
    }

/// Optional override method where you can create resource listeners (e.g. for loading screens)
virtual void createResourceListener(void)
{

}

/// Optional override method where you can perform resource group loading
/// Must at least do ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
virtual void loadResources(void)
{
   // Initialise, parse scripts etc
   ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

}

 

virtual bool processUnbufferedKeyInput(const FrameEvent& evt)
{
   using namespace OIS;

   if(mKeyboard->isKeyDown(KC_A))
    mTranslateVector.x = -mMoveScale; // Move camera left

   if(mKeyboard->isKeyDown(KC_D))
    mTranslateVector.x = mMoveScale; // Move camera RIGHT

   if(mKeyboard->isKeyDown(KC_UP) || mKeyboard->isKeyDown(KC_W) )
    mTranslateVector.z = -mMoveScale; // Move camera forward

   if(mKeyboard->isKeyDown(KC_DOWN) || mKeyboard->isKeyDown(KC_S) )
    mTranslateVector.z = mMoveScale; // Move camera backward

   if(mKeyboard->isKeyDown(KC_PGUP))
    mTranslateVector.y = mMoveScale; // Move camera up

   if(mKeyboard->isKeyDown(KC_PGDOWN))
    mTranslateVector.y = -mMoveScale; // Move camera down

   if(mKeyboard->isKeyDown(KC_RIGHT))
    mCamera->yaw(-mRotScale);

   if(mKeyboard->isKeyDown(KC_LEFT))
    mCamera->yaw(mRotScale);

   if( mKeyboard->isKeyDown(KC_ESCAPE) || mKeyboard->isKeyDown(KC_Q) )
    return false;

       if( mKeyboard->isKeyDown(KC_F) && mTimeUntilNextToggle <= 0 )
   {
    mStatsOn = !mStatsOn;
    showDebugOverlay(mStatsOn);
    mTimeUntilNextToggle = 1;
   }

   if( mKeyboard->isKeyDown(KC_T) && mTimeUntilNextToggle <= 0 )
   {
    switch(mFiltering)
    {
    case TFO_BILINEAR:
     mFiltering = TFO_TRILINEAR;
     mAniso = 1;
     break;
    case TFO_TRILINEAR:
     mFiltering = TFO_ANISOTROPIC;
     mAniso = 8;
     break;
    case TFO_ANISOTROPIC:
     mFiltering = TFO_BILINEAR;
     mAniso = 1;
     break;
    default: break;
    }
    MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering);
    MaterialManager::getSingleton().setDefaultAnisotropy(mAniso);

    showDebugOverlay(mStatsOn);
    mTimeUntilNextToggle = 1;
   }

 

   if(mKeyboard->isKeyDown(KC_R) && mTimeUntilNextToggle <=0)
   {
    mSceneDetailIndex = (mSceneDetailIndex+1)%3 ;
    switch(mSceneDetailIndex) {
     case 0 : mCamera->setPolygonMode(PM_SOLID); break;
     case 1 : mCamera->setPolygonMode(PM_WIREFRAME); break;
     case 2 : mCamera->setPolygonMode(PM_POINTS); break;
    }
    mTimeUntilNextToggle = 0.5;
   }

   static bool displayCameraDetails = false;
   if(mKeyboard->isKeyDown(KC_P) && mTimeUntilNextToggle <= 0)
   {
    displayCameraDetails = !displayCameraDetails;
    mTimeUntilNextToggle = 0.5;
    if (!displayCameraDetails)
     mDebugText = "";
   }

   // Print camera details
   if(displayCameraDetails)
    mDebugText = "P: " + StringConverter::toString(mCamera->getDerivedPosition()) +
       " " + "O: " + StringConverter::toString(mCamera->getDerivedOrientation());

   // Return true to continue rendering
   return true;
}

virtual bool processUnbufferedMouseInput(const FrameEvent& evt)
{
   using namespace OIS;

   // Rotation factors, may not be used if the second mouse button is pressed
   // 2nd mouse button - slide, otherwise rotate
   const MouseState &ms = mMouse->getMouseState();
   if( ms.buttonDown( MB_Right ) )
   {
    mTranslateVector.x += ms.X.rel * 0.13;
    mTranslateVector.y -= ms.Y.rel * 0.13;
   }
   else
   {
    mRotX = Degree(-ms.X.rel * 0.13);
    mRotY = Degree(-ms.Y.rel * 0.13);
   }

   return true;
}

virtual void moveCamera()
{
   // Make all the changes to the camera
   // Note that YAW direction is around a fixed axis (freelook style) rather than a natural YAW
   //(e.g. airplane)
   mCamera->yaw(mRotX);
   mCamera->pitch(mRotY);
   mCamera->moveRelative(mTranslateVector);
}

virtual void showDebugOverlay(bool show)
{
   if (mDebugOverlay)
   {
    if (show)
     mDebugOverlay->show();
    else
     mDebugOverlay->hide();
   }
}


virtual bool frameRenderingQueued(const FrameEvent& evt)
{


   using namespace OIS;

  

   //Need to capture/update each device
   mKeyboard->capture();
   mMouse->capture();

 

   //Check if one of the devices is not buffered
   if( !mMouse->buffered() || !mKeyboard->buffered() )
   {
    // one of the input modes is immediate, so setup what is needed for immediate movement
    if (mTimeUntilNextToggle >= 0)
     mTimeUntilNextToggle -= evt.timeSinceLastFrame;

    // Move about 100 units per second
    mMoveScale = mMoveSpeed * evt.timeSinceLastFrame;
    // Take about 10 seconds for full rotation
    mRotScale = mRotateSpeed * evt.timeSinceLastFrame;

    mRotX = 0;
    mRotY = 0;
    mTranslateVector = Ogre::Vector3::ZERO;
   }

   //Check to see which device is not buffered, and handle it
   if( !mKeyboard->buffered() )
    if( processUnbufferedKeyInput(evt) == false )
     return false;
   if( !mMouse->buffered() )
    if( processUnbufferedMouseInput(evt) == false )
     return false;

   if( !mMouse->buffered() || !mKeyboard->buffered() )
    moveCamera();

   return true;
}

virtual bool frameEnded(const FrameEvent& evt)
{

   return true;
}

virtual bool frameStarted(const FrameEvent& evt) { return true; }
};

 

//mygame.cpp

#include "Ogre.h"
#include "OgreConfigFile.h"
#include "OIS/OIS.h"
using namespace Ogre;
class mygame : public FrameListener
{
public:
    /// Standard constructor
    mygame()
    {
       
        mRoot = 0;
   mResourcePath = "";

    }
    /// Standard destructor
    virtual ~mygame()
    {

        if (mRoot)
            delete mRoot;
    }

    /// Start the example
    virtual void go(void)
    {
        if (!setup())
            return;

        mRoot->startRendering();

        // clean up
        destroyScene();
    }

protected:
    Root *mRoot;
    Camera* mCamera;
    SceneManager* mSceneMgr;

    RenderWindow* mWindow;
Ogre::String mResourcePath;


   //OIS Input devices
OIS::InputManager* mInputManager;
OIS::Mouse*    mMouse;
OIS::Keyboard* mKeyboard;


//
Vector3 mTranslateVector;
float mMoveScale;
Degree mRotScale;

// just to stop toggles flipping too fast
Real mTimeUntilNextToggle ;
Radian mRotX, mRotY;
TextureFilterOptions mFiltering;
int mAniso;


bool mStatsOn;

std::string mDebugText;
int mSceneDetailIndex ;
Overlay* mDebugOverlay;
Real mMoveSpeed;
Degree mRotateSpeed;

    // These internal methods package up the stages in the startup process
    /** Sets up the application - returns false if the user chooses to abandon configuration. */
    virtual bool setup(void)
    {

   String pluginsPath;
   // only use plugins.cfg if not static
#ifndef OGRE_STATIC_LIB
   pluginsPath = mResourcePath + "plugins.cfg";
#endif
  
        mRoot = new Root(pluginsPath,
            mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");

        setupResources();

        bool carryOn = configure();
        if (!carryOn) return false;

        chooseSceneManager();
        createCamera();
        createViewports();

        // Set default mipmap level (NB some APIs ignore this)
        TextureManager::getSingleton().setDefaultNumMipmaps(5);

   // Create any resource listeners (for loading screens)
   createResourceListener();
   // Load resources
   loadResources();

   // Create the scene
        createScene();

        createFrameListener();

        return true;

    }
    /** Configures the application - returns false if the user chooses to abandon configuration. */
    virtual bool 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);
            return true;
        }
        else
        {
            return false;
        }
    }

    virtual void chooseSceneManager(void)
    {
        // Create the SceneManager, in this case a generic one
        mSceneMgr = mRoot->createSceneManager(ST_GENERIC, "mygameInstance");
    }
    virtual void createCamera(void)
    {
        // Create the camera
        mCamera = mSceneMgr->createCamera("PlayerCam");

        // Position it at 500 in Z direction
        mCamera->setPosition(Vector3(0,0,500));
        // Look back along -Z
        mCamera->lookAt(Vector3(0,0,-300));
        mCamera->setNearClipDistance(5);

    }
    virtual void createFrameListener(void)
    {
using namespace OIS;

mRotateSpeed = 36;
mMoveSpeed = 100;


   mDebugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay");

   LogManager::getSingletonPtr()->logMessage("*** Initializing 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 = InputManager::createInputSystem( pl );

   //Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
   mKeyboard = static_cast<Keyboard*>(mInputManager->createInputObject( OISKeyboard, false));
   mMouse = static_cast<Mouse*>(mInputManager->createInputObject( OISMouse, false ));
  

        this->showDebugOverlay(true);
        mRoot->addFrameListener((Ogre::FrameListener *)this);
    }

    virtual void createScene(void) ;    // pure virtual - this has to be overridden

    virtual void destroyScene(void){}    // Optional to override this

    virtual void createViewports(void)
    {
        // Create one viewport, entire window
        Viewport* vp = mWindow->addViewport(mCamera);
        vp->setBackgroundColour(ColourValue(0,0,0));

        // Alter the camera aspect ratio to match the viewport
        mCamera->setAspectRatio(
            Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
    }

    /// Method which will define the source of resources (other than current folder)
    virtual void setupResources(void)
    {
        // Load resource paths from config file
        ConfigFile cf;
        cf.load(mResourcePath + "resources.cfg");

        // Go through all sections & settings in the file
        ConfigFile::SectionIterator seci = cf.getSectionIterator();

        String secName, typeName, archName;
        while (seci.hasMoreElements())
        {
            secName = seci.peekNextKey();
            ConfigFile::SettingsMultiMap *settings = seci.getNext();
            ConfigFile::SettingsMultiMap::iterator i;
            for (i = settings->begin(); i != settings->end(); ++i)
            {
                typeName = i->first;
                archName = i->second;

                ResourceGroupManager::getSingleton().addResourceLocation(
                    archName, typeName, secName);

            }
        }
    }

/// Optional override method where you can create resource listeners (e.g. for loading screens)
virtual void createResourceListener(void)
{

}

/// Optional override method where you can perform resource group loading
/// Must at least do ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
virtual void loadResources(void)
{
   // Initialise, parse scripts etc
   ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

}

 

virtual bool processUnbufferedKeyInput(const FrameEvent& evt)
{
   using namespace OIS;

   if(mKeyboard->isKeyDown(KC_A))
    mTranslateVector.x = -mMoveScale; // Move camera left

   if(mKeyboard->isKeyDown(KC_D))
    mTranslateVector.x = mMoveScale; // Move camera RIGHT

   if(mKeyboard->isKeyDown(KC_UP) || mKeyboard->isKeyDown(KC_W) )
    mTranslateVector.z = -mMoveScale; // Move camera forward

   if(mKeyboard->isKeyDown(KC_DOWN) || mKeyboard->isKeyDown(KC_S) )
    mTranslateVector.z = mMoveScale; // Move camera backward

   if(mKeyboard->isKeyDown(KC_PGUP))
    mTranslateVector.y = mMoveScale; // Move camera up

   if(mKeyboard->isKeyDown(KC_PGDOWN))
    mTranslateVector.y = -mMoveScale; // Move camera down

   if(mKeyboard->isKeyDown(KC_RIGHT))
    mCamera->yaw(-mRotScale);

   if(mKeyboard->isKeyDown(KC_LEFT))
    mCamera->yaw(mRotScale);

   if( mKeyboard->isKeyDown(KC_ESCAPE) || mKeyboard->isKeyDown(KC_Q) )
    return false;

       if( mKeyboard->isKeyDown(KC_F) && mTimeUntilNextToggle <= 0 )
   {
    mStatsOn = !mStatsOn;
    showDebugOverlay(mStatsOn);
    mTimeUntilNextToggle = 1;
   }

   if( mKeyboard->isKeyDown(KC_T) && mTimeUntilNextToggle <= 0 )
   {
    switch(mFiltering)
    {
    case TFO_BILINEAR:
     mFiltering = TFO_TRILINEAR;
     mAniso = 1;
     break;
    case TFO_TRILINEAR:
     mFiltering = TFO_ANISOTROPIC;
     mAniso = 8;
     break;
    case TFO_ANISOTROPIC:
     mFiltering = TFO_BILINEAR;
     mAniso = 1;
     break;
    default: break;
    }
    MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering);
    MaterialManager::getSingleton().setDefaultAnisotropy(mAniso);

    showDebugOverlay(mStatsOn);
    mTimeUntilNextToggle = 1;
   }

 

   if(mKeyboard->isKeyDown(KC_R) && mTimeUntilNextToggle <=0)
   {
    mSceneDetailIndex = (mSceneDetailIndex+1)%3 ;
    switch(mSceneDetailIndex) {
     case 0 : mCamera->setPolygonMode(PM_SOLID); break;
     case 1 : mCamera->setPolygonMode(PM_WIREFRAME); break;
     case 2 : mCamera->setPolygonMode(PM_POINTS); break;
    }
    mTimeUntilNextToggle = 0.5;
   }

   static bool displayCameraDetails = false;
   if(mKeyboard->isKeyDown(KC_P) && mTimeUntilNextToggle <= 0)
   {
    displayCameraDetails = !displayCameraDetails;
    mTimeUntilNextToggle = 0.5;
    if (!displayCameraDetails)
     mDebugText = "";
   }

   // Print camera details
   if(displayCameraDetails)
    mDebugText = "P: " + StringConverter::toString(mCamera->getDerivedPosition()) +
       " " + "O: " + StringConverter::toString(mCamera->getDerivedOrientation());

   // Return true to continue rendering
   return true;
}

virtual bool processUnbufferedMouseInput(const FrameEvent& evt)
{
   using namespace OIS;

   // Rotation factors, may not be used if the second mouse button is pressed
   // 2nd mouse button - slide, otherwise rotate
   const MouseState &ms = mMouse->getMouseState();
   if( ms.buttonDown( MB_Right ) )
   {
    mTranslateVector.x += ms.X.rel * 0.13;
    mTranslateVector.y -= ms.Y.rel * 0.13;
   }
   else
   {
    mRotX = Degree(-ms.X.rel * 0.13);
    mRotY = Degree(-ms.Y.rel * 0.13);
   }

   return true;
}

virtual void moveCamera()
{
   // Make all the changes to the camera
   // Note that YAW direction is around a fixed axis (freelook style) rather than a natural YAW
   //(e.g. airplane)
   mCamera->yaw(mRotX);
   mCamera->pitch(mRotY);
   mCamera->moveRelative(mTranslateVector);
}

virtual void showDebugOverlay(bool show)
{
   if (mDebugOverlay)
   {
    if (show)
     mDebugOverlay->show();
    else
     mDebugOverlay->hide();
   }
}


virtual bool frameRenderingQueued(const FrameEvent& evt)
{


   using namespace OIS;

  

   //Need to capture/update each device
   mKeyboard->capture();
   mMouse->capture();

 

   //Check if one of the devices is not buffered
   if( !mMouse->buffered() || !mKeyboard->buffered() )
   {
    // one of the input modes is immediate, so setup what is needed for immediate movement
    if (mTimeUntilNextToggle >= 0)
     mTimeUntilNextToggle -= evt.timeSinceLastFrame;

    // Move about 100 units per second
    mMoveScale = mMoveSpeed * evt.timeSinceLastFrame;
    // Take about 10 seconds for full rotation
    mRotScale = mRotateSpeed * evt.timeSinceLastFrame;

    mRotX = 0;
    mRotY = 0;
    mTranslateVector = Ogre::Vector3::ZERO;
   }

   //Check to see which device is not buffered, and handle it
   if( !mKeyboard->buffered() )
    if( processUnbufferedKeyInput(evt) == false )
     return false;
   if( !mMouse->buffered() )
    if( processUnbufferedMouseInput(evt) == false )
     return false;

   if( !mMouse->buffered() || !mKeyboard->buffered() )
    moveCamera();

   return true;
}

virtual bool frameEnded(const FrameEvent& evt)
{

   return true;
}

virtual bool frameStarted(const FrameEvent& evt) { return true; }
};

只是个粗略的框架 输入方式默认为 非缓冲的

以后慢慢再对这个框架做修改

原创粉丝点击