Exemplo n.º 1
0
void Oculus::setCameras()
{
	Ogre::Camera* camLeft = m_cameras[0] ;
	Ogre::Camera* camRight = m_cameras[1] ; 
	Ogre::RenderTexture* renderTexLeft = mLeftEyeRenderTexture->getBuffer()->getRenderTarget();
	std::cout << "[Rift] Adding viewport to left texture" << std::endl;
	m_viewports[0] = renderTexLeft->addViewport(m_cameras[0]);
	renderTexLeft->getViewport(0)->setOverlaysEnabled(true);

	std::cout << "[Rift] Adding viewport to right texture" << std::endl;
	Ogre::RenderTexture* renderTexRight = mRightEyeRenderTexture->getBuffer()->getRenderTarget();
	m_viewports[1] = renderTexRight->addViewport(m_cameras[1]);

	renderTexRight->getViewport(0)->setOverlaysEnabled(true);

	m_viewports[0]->setBackgroundColour(g_defaultViewportColour);
	m_viewports[1]->setBackgroundColour(g_defaultViewportColour);
	



	ovrFovPort fovLeft = mHMD->DefaultEyeFov[ovrEye_Left];
	ovrFovPort fovRight = mHMD->DefaultEyeFov[ovrEye_Right];

	float combinedTanHalfFovHorizontal = std::max( fovLeft.LeftTan, fovLeft.RightTan );
	float combinedTanHalfFovVertical = std::max( fovLeft.UpTan, fovLeft.DownTan );

	float aspectRatio = combinedTanHalfFovHorizontal / combinedTanHalfFovVertical;

	m_cameras[0]->setAspectRatio( aspectRatio );
	m_cameras[1]->setAspectRatio( aspectRatio );

	ovrMatrix4f projL = ovrMatrix4f_Projection ( fovLeft, g_defaultNearClip, g_defaultFarClip, true );
	ovrMatrix4f projR = ovrMatrix4f_Projection ( fovRight, g_defaultNearClip, g_defaultFarClip, true );

	m_cameras[0]->setCustomProjectionMatrix( true,
			Ogre::Matrix4( 
				projL.M[0][0], projL.M[0][1], projL.M[0][2], projL.M[0][3],
				projL.M[1][0], projL.M[1][1], projL.M[1][2], projL.M[1][3],
				projL.M[2][0], projL.M[2][1], projL.M[2][2], projL.M[2][3],
				projL.M[3][0], projL.M[3][1], projL.M[3][2], projL.M[3][3] ) );
	m_cameras[1]->setCustomProjectionMatrix( true,
			Ogre::Matrix4( 
				projR.M[0][0], projR.M[0][1], projR.M[0][2], projR.M[0][3],
				projR.M[1][0], projR.M[1][1], projR.M[1][2], projR.M[1][3],
				projR.M[2][0], projR.M[2][1], projR.M[2][2], projR.M[2][3],
				projR.M[3][0], projR.M[3][1], projR.M[3][2], projR.M[3][3] ) );
}
Exemplo n.º 2
0
	int EnvironmentCoreApplication::startLoop(std::function<int()> _func) {
		int l_run = 0;
		
		isRunning = true;

		double l_systemTimeIncriment = 0.0;

		int l_frame = 0;
		Ogre::TexturePtr rtt_texture = Ogre::TextureManager::getSingleton().createManual("RttTex", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, m_pRenderWindow->getWidth(), m_pRenderWindow->getHeight(), 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET);
		Ogre::RenderTexture* renderTexture = rtt_texture->getBuffer()->getRenderTarget();

		renderTexture->addViewport(m_pCamera);
		renderTexture->getViewport(0)->setClearEveryFrame(true);
		renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
		renderTexture->getViewport(0)->setOverlaysEnabled(false);

		std::chrono::high_resolution_clock l_time;
		auto l_start = l_time.now();
		auto l_last = l_start;

		while (l_run == 0) {

			try {
				m_pChSystem->DoFrameDynamics((l_systemTimeIncriment / 2.0));
			}
			catch (std::exception e) {

			}
			try {
				m_pChSystem->DoFrameDynamics((l_systemTimeIncriment / 2.0));
			}
			catch (std::exception e) {

			}

			m_pInputManager->update();

			if (m_pInputManager->WindowClose) {
				l_run++;
				break;
			}

			m_pGUIManager->update();

			l_run = _func();

			m_pScene->update();

			m_pViewport->update();

			m_pRenderWindow->update(false);
			m_pRenderWindow->swapBuffers();

			m_pRoot->renderOneFrame();

			m_pCamera->setAspectRatio((((float)(m_pViewport->getActualWidth())) / ((float)(m_pViewport->getActualHeight()))));


			if (!isRealTime) {
				l_systemTimeIncriment += timestep_max;
				timestep = timestep_max;
			}
			else {
				l_systemTimeIncriment = ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(l_time.now() - l_start).count())) / 1000.0; //converts standard library time difference to a double for Chrono

				l_systemTimeIncriment = l_systemTimeIncriment > timestep_max ? l_systemTimeIncriment+=timestep_max : l_systemTimeIncriment;
				l_systemTimeIncriment = l_systemTimeIncriment < timestep_min ? l_systemTimeIncriment+=timestep_min : l_systemTimeIncriment;

				timestep = ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(l_time.now() - l_last).count())) / 1000.0;
				l_last = l_time.now();
			}

			if (WriteToFile) {
				std::string name = "out/frame" + std::to_string(l_frame) + "time" + std::to_string(l_systemTimeIncriment) + ".png";
				renderTexture->update();
				renderTexture->writeContentsToFile(name);
				l_frame++;
			}

			Ogre::WindowEventUtilities::messagePump();

			
		}
		isRunning = false;

		return l_run;
	}
Exemplo n.º 3
0
/*!
  Initialisation of Ogre.

  Load the plugins that are specified in the plugins.cfg or
  plugins_d.cfg files. These files are located in
  VISP_HAVE_OGRE_PLUGINS_PATH folder that is defined in vpConfig.h.
  Note that plugins.cfg file is always considered under Unix
  platforms. The file plugins_d.cfg is only considered under Windows
  when the build type is Debug.

  Load also the resources that are defined in the resources.cfg
  file. This file is located in VISP_HAVE_OGRE_RESOURCES_PATH folder
  that is defined in vpConfig.h.

  \param bufferedKeys : If true, use of buffered input for the keyboard (see
  Ogre documentation). Note that this parameter is only useful if OIS is used.

  \param hidden : If true, the created window will be hidden.
  Note that this functionnality requires Ogre3D 1.8.1 at least.

  \exception vpException::ioError : If the required plugins.cfg /
  plugins_d.cfg or resources.cfg files are not accessible.

*/
void vpAROgre::init(bool
#ifdef VISP_HAVE_OIS
		    bufferedKeys
#endif
        ,bool hidden
		    )
{
  // Create the root
  // mPluginsPath may contain more than one folder location separated by ";"
  bool pluginsFileExists = false;
  std::string pluginFile;
  std::vector<std::string> plugingsPaths = vpIoTools::splitChain(std::string(mPluginsPath), std::string(";"));
  for (size_t i=0; i<plugingsPaths.size(); i++) {
#if defined(NDEBUG) || !defined(_WIN32)
    pluginFile = plugingsPaths[i]+"/plugins.cfg";
#else
    pluginFile = plugingsPaths[i]+"/plugins_d.cfg";
#endif

    if(vpIoTools::checkFilename(pluginFile)) {
      pluginsFileExists = true;
      break;
    }
  }
  if (! pluginsFileExists) {
    std::string errorMsg = std::string("Error: the requested plugins file \"")
#if defined(NDEBUG) || !defined(_WIN32)
        + std::string("plugins.cfg")
#else
        + std::string("plugins_d.cfg")
#endif
    + std::string("\" doesn't exist in ")
    + std::string(mPluginsPath);
    std::cout << errorMsg << std::endl;

    throw (vpException(vpException::ioError, errorMsg));
  }
  std::cout << "######################### Load plugin file: " << pluginFile << std::endl;

  if(Ogre::Root::getSingletonPtr() == NULL)
    mRoot = new Ogre::Root(pluginFile, "ogre.cfg", "Ogre.log");
  else
    mRoot = Ogre::Root::getSingletonPtr();

  // Load resource paths from config file

  // File format is:
  //  [ResourceGroupName]
  //  ArchiveType=Path
  //  .. repeat
  // For example:
  //  [General]
  //  FileSystem=media/
  //  Zip=packages/level1.zip

  // mResourcePath may contain more than one folder location separated by ";"
  bool resourcesFileExists = false;
  std::string resourceFile;
  std::vector<std::string> resourcesPaths = vpIoTools::splitChain(std::string(mResourcePath), std::string(";"));
  for (size_t i=0; i<resourcesPaths.size(); i++) {
    resourceFile = resourcesPaths[i]+"/resources.cfg";
    if(vpIoTools::checkFilename(resourceFile)) {
      resourcesFileExists = true;
      break;
    }
  }
  if (! resourcesFileExists) {
    std::string errorMsg = std::string("Error: the requested resource file \"resources.cfg\"")
        + std::string("doesn't exist in ")
        + std::string(mResourcePath);

    std::cout << errorMsg << std::endl;

    throw (vpException(vpException::ioError, errorMsg));
  }
  std::cout << "######################### Load resource file: " << resourceFile << std::endl;
  Ogre::ConfigFile cf;
  cf.load(resourceFile);

  // 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);
	}
    }
    std::cout << "##################### add resources" << std::endl;
  //Add optionnal resources (given by the user).
  for(std::list<std::string>::const_iterator iter = mOptionnalResourceLocation.begin(); iter != mOptionnalResourceLocation.end(); ++iter){
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(*iter, "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
  }

  // Create the window
  bool canInit = true;
  if(mshowConfigDialog){
    mRoot->restoreConfig();
    if(!mRoot->showConfigDialog())
      canInit = false;
  }
  else{
    if(!mRoot->restoreConfig())
      canInit = false;
  }

  if(!mRoot->isInitialised()){
    if(!canInit){ //We set the default renderer system
      const Ogre::RenderSystemList& lRenderSystemList = mRoot->getAvailableRenderers();
      if( lRenderSystemList.size() == 0 )
        throw "ConfigDialog aborted"; // Exit the application on cancel

      Ogre::RenderSystem *lRenderSystem = lRenderSystemList.at(0);
      std::cout << "Using " << lRenderSystem->getName() << " as renderer." << std::endl;
      mRoot->setRenderSystem(lRenderSystem);
    }

    mRoot->initialise(false);
  }

  bool fullscreen = false;
  Ogre::NameValuePairList misc;
  Ogre::ConfigOptionMap config = mRoot->getRenderSystem()->getConfigOptions();
  Ogre::ConfigOptionMap::const_iterator it = config.begin();

  while( it != config.end() ){
    Ogre::String leftconf = (*it).first;
    Ogre::String rightconf = (*it).second.currentValue;

    if(leftconf == "Video Mode"){
      if(canInit) {
        int ret = sscanf(rightconf.c_str(), "%d %*s %d", &mWindowWidth, &mWindowHeight);
        if (ret == 0)
          std::cout << "Cannot read Ogre video mode" << std::endl;
      }
      else{
        if(mWindowWidth == 0 && mWindowHeight == 0){
          mWindowWidth = mBackgroundWidth;
          mWindowHeight = mBackgroundHeight;
        }
      }
    }
    else if( leftconf == "Full Screen" ){
      if(canInit){
        if(rightconf == "Yes") fullscreen = true;
      }
    }
    else
      misc[leftconf] = rightconf;

    it++;
  }

  // With Ogre version >= 1.8.1 we hide the window
  if( hidden ){
#if ( OGRE_VERSION >= (1 << 16 | 8 << 8 | 1) )
    misc["hidden"] = "true";
    windowHidden = true;
#endif
  }
  mWindow = mRoot->createRenderWindow(name, mWindowWidth, mWindowHeight, fullscreen, &misc);

  // Initialise resources
  Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
  //-----------------------------------------------------
  // 4 Create the SceneManager
  //
  //		ST_GENERIC = octree
  //		ST_EXTERIOR_CLOSE = simple terrain
  //		ST_EXTERIOR_FAR = nature terrain (depreciated)
  //		ST_EXTERIOR_REAL_FAR = paging landscape
  //		ST_INTERIOR = Quake3 BSP
  //-----------------------------------------------------

  mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);

  // Create the camera
  createCamera();

  // Create a viewport
  Ogre::Viewport* viewPort = mWindow->addViewport(mCamera);
//   Ogre::Viewport* viewPort = mCamera->getViewport();
  viewPort->setClearEveryFrame(true);
  // Set the projection parameters to match the camera intrinsic parameters
  updateCameraProjection();

  // Create the 3D scene
  createScene();

  // Initialise and register event handlers
  mRoot->addFrameListener(this);

  // Register as a Window listener
  Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

#ifdef VISP_HAVE_OIS
  // Initialise OIS
  Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
  OIS::ParamList pl;

  size_t windowHnd = 0;
  std::ostringstream windowHndStr;
  // Initialise window
  mWindow->getCustomAttribute("WINDOW", &windowHnd);
  windowHndStr << windowHnd;
  pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
  // Let the user use the keyboard elsewhere
#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
  pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false")));
#endif

  mInputManager = OIS::InputManager::createInputSystem( pl );

  //Create all devices
  // Here we only consider the keyboard input
  mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, bufferedKeys ));
  if ( !bufferedKeys ) mKeyboard->setEventCallback ( this);
#endif

  // Initialise a render to texture to be able to retrieve a screenshot
  Ogre::TexturePtr Texture = Ogre::TextureManager::getSingleton().createManual("rtf", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,Ogre::TEX_TYPE_2D,
                                                                               mWindow->getWidth(),mWindow->getHeight(), 0, Ogre::PF_R8G8B8A8, Ogre::TU_RENDERTARGET);



//   Ogre::TexturePtr Texture = Ogre::TextureManager::getSingleton().createManual("rtf", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,Ogre::TEX_TYPE_2D,
//                                                                                640,480, 0, Ogre::PF_R8G8B8A8, Ogre::TU_RENDERTARGET);
  Ogre::RenderTexture* RTarget = Texture->getBuffer()->getRenderTarget();
  /*Ogre::Viewport* Viewport =*/ RTarget->addViewport(mCamera);
  RTarget->getViewport(0)->setClearEveryFrame(true);
  RTarget->getViewport(0)->setOverlaysEnabled(false);
}