Exemple #1
0
void GameMain::CreateRenderer()
{

	m_pkRoot = new Ogre::Root();

	mD3D9Plugin = new Ogre::D3D9Plugin();
	m_pkRoot->installPlugin(mD3D9Plugin);
	mOctreePlugin = new Ogre::OctreePlugin();
	m_pkRoot->installPlugin(mOctreePlugin);
	mBSPPlugin = new BspSceneManagerPlugin();
	m_pkRoot->installPlugin(mBSPPlugin);
	mCgPlugin = new CgPlugin();
	m_pkRoot->installPlugin(mCgPlugin);
	mParticleFXPlugin = new ParticleFXPlugin();
	m_pkRoot->installPlugin(mParticleFXPlugin);

	//	Initialize window
	Ogre::RenderSystem *selectedRenderSystem = m_pkRoot->getRenderSystemByName("Direct3D9 Rendering Subsystem");
	m_pkRoot->setRenderSystem(selectedRenderSystem);
	selectedRenderSystem->setConfigOption("Full Screen", "No");
	selectedRenderSystem->setConfigOption("VSync","Yes");
	char value[128];
	sprintf(value, "%d x %d @ %d-bit colour", Chapter::ms_nWidth, Chapter::ms_nHeight, 32);
	selectedRenderSystem->setConfigOption("Video Mode", value);



	m_pkWindow = m_pkRoot->initialise(false, "Test Bullet");

	Ogre::NameValuePairList parms;
	parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);

	m_pkWindow = m_pkRoot->createRenderWindow("Test Bullet", Chapter::ms_nWidth, Chapter::ms_nHeight, !Chapter::ms_bWindowed, &parms);

	Chapter::ms_hWnd = m_hWnd;
	Chapter::m_pkRoot = m_pkRoot;
	Chapter::m_pkWindow = m_pkWindow;

	m_pkRoot->addFrameListener( this );

	m_pkWindow->setActive(true);
	m_pkWindow->update();


	//	Add media path
	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);


	m_fCurrentTime =  GetTickCount();
}
bool OgreApplication::initStart(void)
{

    mPluginsCfg = "../configs/plugins.cfg";
    mResourcesCfg = "../configs/resources.cfg";

    Ogre::LogManager * lm = new Ogre::LogManager();
    lm->createLog("OgreLogfile.log", true, false, false);

    // construct Ogre::Root
    mRoot = new Ogre::Root(mPluginsCfg, "", "");

    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);
        }
    }

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../assets/", "FileSystem");

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../assets/particles", "FileSystem");

    // Do not add this to the application
    Ogre::RenderSystem *rs = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    mRoot->setRenderSystem(rs);
    rs->setConfigOption("Full Screen", "No");
    rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
    rs->setStencilCheckEnabled(true);

    mRoot->initialise(false);

    running = true;
    return true;
}
Exemple #3
0
/**
 * @brief init the object
 * @author kito berg-taylor
 */
void OgreWidget::init()
{
  // create the main ogre object
  mOgreRoot = new Ogre::Root;

  mOgreRoot->loadPlugin("RenderSystem_GL");
  Ogre::String rName("OpenGL Rendering Subsystem");
  Ogre::RenderSystemList rList = mOgreRoot->getAvailableRenderers();
  Ogre::RenderSystemList::iterator it = rList.begin();
  Ogre::RenderSystem *rSys = 0;
  while(it != rList.end())
  {
    rSys = * (it++);
    Ogre::String strx=rSys->getName();
    if(strx == rName)
    {
      mOgreRoot->setRenderSystem(rSys);
      break;
    }
  }
   QString dimensions = QString( "%1x%2" )
                    .arg(this->width())
                    .arg(this->height());
 
  rSys->setConfigOption( "Video Mode", dimensions.toStdString() );
 
  // initialize without creating window
  mOgreRoot->getRenderSystem()->setConfigOption( "Full Screen", "No" );
  mOgreRoot->saveConfig();
  mOgreRoot->initialise(false); // don't create a window
}
void ApplicationContext::reconfigure(const Ogre::String &renderer, Ogre::NameValuePairList &options)
{
    mNextRenderer = renderer;
    Ogre::RenderSystem* rs = mRoot->getRenderSystemByName(renderer);

    // set all given render system options
    for (Ogre::NameValuePairList::iterator it = options.begin(); it != options.end(); it++)
    {
        rs->setConfigOption(it->first, it->second);

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
        // Change the viewport orientation on the fly if requested
        if(it->first == "Orientation")
        {
            if (it->second == "Landscape Left")
                mWindow->getViewport(0)->setOrientationMode(Ogre::OR_LANDSCAPELEFT, true);
            else if (it->second == "Landscape Right")
                mWindow->getViewport(0)->setOrientationMode(Ogre::OR_LANDSCAPERIGHT, true);
            else if (it->second == "Portrait")
                mWindow->getViewport(0)->setOrientationMode(Ogre::OR_PORTRAIT, true);
        }
#endif
    }

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
    // Need to save the config on iOS to make sure that changes are kept on disk
    mRoot->saveConfig();
#endif
    mRoot->queueEndRendering();   // break from render loop
}
Exemple #5
0
	void OgreWidget::init(std::string const& plugins_file, std::string const& ogre_cfg_file, std::string const& ogre_log)
	{
		// create the main ogre object
		_mOgreRoot = new Ogre::Root(plugins_file, ogre_cfg_file, ogre_log);

		// setup a renderer
		Ogre::RenderSystemList::const_iterator renderers = _mOgreRoot->getAvailableRenderers().begin();
		while(renderers != _mOgreRoot->getAvailableRenderers().end())
		{
			Ogre::String rName = (*renderers)->getName();
			if (rName == "OpenGL Rendering Subsystem")
				break;
			renderers++;
		}

		Ogre::RenderSystem *renderSystem = *renderers;

		_mOgreRoot->setRenderSystem(renderSystem);
		QString dimensions = QString("%1x%2")
											.arg(this->width())
											.arg(this->height());

		renderSystem->setConfigOption("Video Mode", dimensions.toStdString());

		// initialize without creating window
		_mOgreRoot->getRenderSystem()->setConfigOption("Full Screen", "No");
		_mOgreRoot->saveConfig();
		_mOgreRoot->initialise(false); // don't create a window
	}
Exemple #6
0
/** Sets up the application - returns false if the user chooses to abandon configuration. */
bool OgreApp::setup(void){
	String cfgPath = mResourcePath + resource_cfg_file;

	mRoot = new Root();

#if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
	Ogre::GLES2Plugin* plugin = new Ogre::GLES2Plugin();
#else
	Ogre::GLPlugin* plugin = new Ogre::GLPlugin();
	//Ogre::GLES2Plugin* plugin = new Ogre::GLES2Plugin();
#endif

	mRoot->installPlugin(plugin);
	Ogre::RenderSystem* rs = mRoot->getRenderSystemByName( "OpenGL Rendering Subsystem" );
	assert( rs );

//    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCSize frameSize = CCDirector::sharedDirector()->getWinSize();
	char buff[256]; memset( buff, 0x00, sizeof(buff) );
	sprintf( buff, "%dx%d", (int)frameSize.width, (int)frameSize.height );
//	sprintf( buff, "%dx%d", 200, 200 );
	rs->setConfigOption( "Video Mode", buff );
	rs->setConfigOption( "Full Screen", "No" );

	mRoot->setRenderSystem( rs );
	mWindow = mRoot->initialise(true);

	setupResources();

	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

#if( CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID )
	//android 不需要?
	loadResources();
#endif
	return true;
}
void RenderSystem::setupRenderSystem()
{
    Ogre::RenderSystem *renderSys;
    const Ogre::RenderSystemList *rsList;

    // Get the list of available renderers.
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
    rsList = ogre_root_->getAvailableRenderers();
#else
    rsList = &(ogre_root_->getAvailableRenderers());
#endif

    // Look for the OpenGL one, which we require.
    renderSys = NULL;
    for( unsigned int i = 0; i < rsList->size(); i++ )
    {
        renderSys = rsList->at( i );
        if( renderSys->getName().compare("OpenGL Rendering Subsystem")== 0 )
        {
            break;
        }
    }

    if( renderSys == NULL )
    {
        throw std::runtime_error( "Could not find the opengl rendering subsystem!\n" );
    }

    // We operate in windowed mode
    renderSys->setConfigOption("Full Screen","No");

    /// We used to allow the user to set the RTT mode to PBuffer, FBO, or Copy.
    ///   Copy is slow, and there doesn't seem to be a good reason to use it
    ///   PBuffer limits the size of the renderable area of the RTT to the
    ///           size of the first window created.
    ///   FBO seem to be the only good option
    //  renderSys->setConfigOption("RTT Preferred Mode", "FBO");

    // Set the Full Screen Anti-Aliasing factor.
    renderSys->setConfigOption("FSAA", "2");

    ogre_root_->setRenderSystem(renderSys);
}
Exemple #8
0
void GameMain::CreateRenderer()
{

	m_pkRoot = new Ogre::Root();

	m_pkPluginLoader = new Ogre::StaticPluginLoader();
	m_pkPluginLoader->load( *m_pkRoot );

	//	Initialize window
	Ogre::RenderSystem *selectedRenderSystem = m_pkRoot->getRenderSystemByName("Direct3D9 Rendering Subsystem");
	m_pkRoot->setRenderSystem(selectedRenderSystem);
	selectedRenderSystem->setConfigOption("Full Screen", "No");
	selectedRenderSystem->setConfigOption("VSync","Yes");
	char value[128];
	sprintf(value, "%d x %d @ %d-bit colour", Chapter::ms_nWidth, Chapter::ms_nHeight, 32);
	selectedRenderSystem->setConfigOption("Video Mode", value);



	m_pkWindow = m_pkRoot->initialise(false, "ETM");

	Ogre::NameValuePairList parms;
	parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);

	m_pkWindow = m_pkRoot->createRenderWindow("ETM", Chapter::ms_nWidth, Chapter::ms_nHeight, !Chapter::ms_bWindowed, &parms);

	Chapter::ms_hWnd = m_hWnd;
	Chapter::m_pkRoot = m_pkRoot;
	Chapter::m_pkWindow = m_pkWindow;

	m_pkRoot->addFrameListener( this );

	m_pkWindow->setActive(true);
	m_pkWindow->update();




	m_fCurrentTime =  GetTickCount();
}
Exemple #9
0
void OgreWidget::init( std::string plugins_file,  std::string ogre_cfg_file, std::string ogre_log )
{
  mOgreRoot = new Ogre::Root( plugins_file, ogre_cfg_file, ogre_log );
  Ogre::RenderSystemList renderers = mOgreRoot->getAvailableRenderers();
  assert( !renderers.empty() );
  Ogre::RenderSystem *renderSystem = chooseRenderer(& renderers );
  assert( renderSystem );
  mOgreRoot->setRenderSystem( renderSystem );
  QString dimensions = QString( "%1x%2" ).arg(this->width()).arg(this->height());
  renderSystem->setConfigOption( "Video Mode", dimensions.toStdString() );
  mOgreRoot->getRenderSystem()->setConfigOption( "Full Screen", "No" );
  mOgreRoot->saveConfig();
  mOgreRoot->initialise(false);
  initResourses();
}
Exemple #10
0
//-------------------------------------------------------------------------------------
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

	Ogre::RenderSystem *rs = mRoot->getRenderSystemByName("Direct3D9 Rendering Subsystem");
	mRoot->setRenderSystem(rs);
	if(FullscreenMode){
		rs->setConfigOption("Full Screen", "Yes");
		rs->setConfigOption("Video Mode", "1280 x 720 @ 32-bit colour");
	}
	else{
		rs->setConfigOption("Full Screen", "No");
		rs->setConfigOption("Video Mode", "1024 x 768 @ 32-bit colour");
	}
	rs->setConfigOption("Multi device memory hint", "Auto hardware buffers management");
	mWindow = mRoot->initialise(true, "SIGViewer");

	mWindow->setDeactivateOnFocusChange(false);

	return true;

#ifdef _OLD_VERSION
	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, "SIGViewer");
        return true;

    } else {
        return false;
    }
#endif

}
Exemple #11
0
//-------------------------------------------------------------------------------------
bool THIS::configure(void)
{

    cout << "<TRACE><LOG><SceneManager><configure> Start" << endl;
    // 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
    //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;
    //}

    // setup a renderer
    Ogre::RenderSystemList::const_iterator renderers = mRoot->getAvailableRenderers().begin();
    while(renderers != mRoot->getAvailableRenderers().end())
    {
        Ogre::String rName = (*renderers)->getName();
        if (rName == "OpenGL Rendering Subsystem")
            break;
        renderers++;
    }

    Ogre::RenderSystem *renderSystem = *renderers;

    mRoot->setRenderSystem( renderSystem );
    QString dimensions = QString( "%1x%2" )
            .arg(this->width())
            .arg(this->height());

    renderSystem->setConfigOption( "Video Mode", dimensions.toStdString() );

    // initialize without creating window
    mRoot->getRenderSystem()->setConfigOption( "Full Screen", "No" );
    mRoot->saveConfig();

    cout << "<TRACE><LOG><SceneManager><configure> initialize" << endl;
    mRoot->initialise(false); // don't create a window

}
/**
 * Setup application configuration options
 */
bool Robot::Application::configure()
{
	// Always load the GL render system
	this->mRoot->loadPlugin("./RenderSystem_GL");

	// Get the GL Render system and set it on the root
	Ogre::RenderSystem* RS = this->mRoot->getAvailableRenderers()[0];
	this->mRoot->setRenderSystem(RS);

	// Dont use full-screen
	RS->setConfigOption("Full Screen", "no");

	// Setup the root window
	this->mWindow = this->mRoot->initialise(true, "CG - Project 4");

	return true;
}
Exemple #13
0
	printf("\n");
}

void Game::InitializeGame()
{
	InitializeRootResourcesAndPlugins();
	//Manually set the Rendering System
	Ogre::RenderSystem *rs = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
	rs->setConfigOption("Full Screen","No");
	rs->setConfigOption("Video Mode","1024 x 768 @ 32-bit colour");
	rs->setConfigOption("FSAA","16");
	rs->setConfigOption("Fixed Pipeline Enabled","Yes");
	rs->setConfigOption("RTT Preferred Mode","FBO");
	rs->setConfigOption("VSync","Yes");
	rs->setConfigOption("sRGB Gamma Conversion","No");

	mRoot->setRenderSystem(rs);

	CreateOgreWindow("Probending");
	///https://github.com/oysteinkrog/gpusphsim/tree/master/SPHSimOgreApp
	// Set default mipmap level (note: some APIs ignore this)
	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

	InitializeOIS(true);
void QOgreWindow::initialize()
{
    // Initialize Ogre like normal
#ifdef _MSC_VER
    oRoot = new Ogre::Root(Ogre::String("plugins" OGRE_BUILD_SUFFIX ".cfg"));
#else
    oRoot = new Ogre::Root(Ogre::String("plugins.cfg"));
#endif
    Ogre::ConfigFile oConf;

    oConf.load(resConfig);

    Ogre::ConfigFile::SectionIterator seci = oConf.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);
        }
    }

    /*Ogre::String name, locType;
    Ogre::ConfigFile::SectionIterator secIt = oConf.getSectionIterator();

    while(secIt.hasMoreElements())
    {
        Ogre::ConfigFile::SettingsMultiMap* _settings = secIt.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator it;

        for (it = _settings->begin(); it != _settings->end(); ++it)
        {
            locType = it->first;
            name    = it->second;
        }

        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(name,locType);
    }*/

    //if (!oRoot->restoreConfig() || oRoot->showConfigDialog()) return;

    const Ogre::RenderSystemList& rsList = oRoot->getAvailableRenderers();

    Ogre::RenderSystem* rs = rsList[0];

    // This list setup search order for used render system
    Ogre::StringVector renderOrder;
    renderOrder.push_back("OpenGL");
#if PONY_PLATFORM == PLAT_WIN32 || PONY_PLATFORM == PLAT_WIN64
    renderOrder.push_back("Direct3D9");
    renderOrder.push_back("Direct3D11");
#endif
    //renderOrder.push_back("OpenGL 3+");

    for (Ogre::StringVector::iterator iter = renderOrder.begin(); iter != renderOrder.end(); iter++)
    {
        for (Ogre::RenderSystemList::const_iterator it = rsList.begin(); it != rsList.end(); it++)
        {
            if ((*it)->getName().find(*iter) != Ogre::String::npos)
            {
                rs = *it;
                break;
            }
        }
        if (rs != NULL) break;
    }
    if (rs == NULL)
    {
        if (!oRoot->restoreConfig())
        {
            if (!oRoot->showConfigDialog())
            {
                OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "[PoneNgine][Ogre3D] Abort render system configuration.","QOgreWindow::initialize");
            }
        }
    }

    // Settings size on windows will solve a lot of problems
    // VSync... why is this praised by developers again? Becuase I hate it in games.
    // Soon, I'll make a settings class for the in-game settings.
    QString dimensions = QString("%1 x %2").arg(this->width()).arg(this->height());
    rs->setConfigOption("Video Mode", dimensions.toStdString());
    rs->setConfigOption("Full Screen", "No");
    rs->setConfigOption("VSync", "No");
    oRoot->setRenderSystem(rs);
    oRoot->initialise(false);

    Ogre::NameValuePairList parameters;

    if (rs->getName().find("GL") <= rs->getName().size())
        parameters["currentGLContext"] = Ogre::String("false");

#if PONY_PLATFORM == PLAT_WIN32 || PONY_PLATFORM == PLAT_WIN64 || PONY_PLATFORM == PLAT_MACOSX
    parameters["externalWindowHandle"] = Ogre::StringConverter::toString((size_t)(this->winId()));
    parameters["parentWindowHandle"]   = Ogre::StringConverter::toString((size_t)(this->winId()));
#else
    parameters["externalWindowHandle"] = Ogre::StringConverter::toString((unsigned long)(this->winId()));
    parameters["parentWindowHandle"] = Ogre::StringConverter::toString((unsigned long)(this->winId()));
#endif

#if PONY_PLATFORM == PLAT_MACOSX
    parameters["macAPI"] = "cocoa";
    parameters["macAPICocoaUseNSView"] = "true";
#endif

    oWin = oRoot->createRenderWindow("QOgreWindow Test | PoneNgine Version "+Ogre::String(PONENGINE_VERSION)+" Build "+Ogre::String(PONENGINE_BUILD), this->width(), this->height(), false, &parameters);
    oWin->setVisible(true);

    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

#if OGRE_VERSION >= ((2 << 16) | (0 << 8) | 0)
    const size_t numThreads = std::max<int>(1, Ogre::PlatformInformation::getNumLogicalCores());
    Ogre::InstancingTheadedCullingMethod threadedCullingMethod = Ogre::INSTANCING_CULLING_SINGLETHREAD;
    if (numThreads > 1)threadedCullingMethod = Ogre::INSTANCING_CULLING_THREADED;
    oSceneMgr = oRoot->createSceneManager(Ogre::ST_GENERIC, numThreads, threadedCullingMethod);
#else
    oSceneMgr = oRoot->createSceneManager(Ogre::ST_GENERIC);
#endif

    oCam = oSceneMgr->createCamera("MainCamera");
    oCam->setPosition(Ogre::Vector3(0.0f,0.0f,10.0f));
    oCam->lookAt(Ogre::Vector3(0.0f,0.0f,-300.0f));
    oCam->setNearClipDistance(0.1f);
    oCam->setFarClipDistance(200.0f);
    camMan = new OgreQtBites::QtOgreSdkCameraMan(oCam);

#if OGRE_VERSION >= ((2 << 16) | (0 << 8) | 0)
    createCompositor();
#else
    Ogre::Viewport* oViewPort = oWin->addViewport(oCam);
    oViewPort->setBackgroundColour(oBgColor);
#endif

    oCam->setAspectRatio(Ogre::Real(oWin->getWidth()) / Ogre::Real(oWin->getHeight()));
    oCam->setAutoAspectRatio(true);

    createScene();

    oRoot->addFrameListener(this);
}
Exemple #15
0
BOOL InitOgre()
{
	using namespace Ogre;

#ifdef _DEBUG
	mOgreRoot = new Ogre::Root("plugins_d.cfg", "OgreMFC.cfg", "OgreMFC.log"); 
#else
	mOgreRoot = new Ogre::Root("plugins.cfg", "OgreMFC.cfg", "OgreMFC.log"); 
#endif

	//
	// Setup paths to all resources
	//

	Ogre::ConfigFile cf;
	cf.load("resources_d.cfg");

	// Go through all sections & settings in the file
	Ogre::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);
		}
	}

	const RenderSystemList& render =  mOgreRoot->getAvailableRenderers();

	RenderSystemList::const_iterator pRend = render.begin();

	while (pRend != render.end())
	{
		Ogre::String rName = (*pRend)->getName();
		//if (rName == "OpenGL Rendering Subsystem") //
		if (rName == "Direct3D9 Rendering Subsystem") //Direct3D9 Rendering Subsystem
			break;
		pRend++;
	}

	if (pRend == render.end())
	{
		// Unrecognised render system
		//MessageBox("Unable to locate OpenGL rendering system.  Application is terminating");
		return FALSE;
	}

	Ogre::RenderSystem *rsys = *pRend;
	rsys->setConfigOption("Full Screen", "No");
	rsys->setConfigOption("VSync", "Yes");

	// Set the rendering system.
	mOgreRoot->setRenderSystem(rsys);

	//
	// Initialize the system, but don't create a render window.
	//
	mOgreRoot->initialise(false);

	return TRUE;
}
void MaterialEditorFrame::createOgrePane()
{
	mRoot = new Ogre::Root();

	// Find Render Systems
	// Testing only, this will be deleted once Projects can tell us
	// which rendering system they want used
	mDirectXRenderSystem = NULL;
	mOpenGLRenderSystem = NULL;
	const RenderSystemList &rl = mRoot.getAvailableRenderers();
	if (rl->empty()) 
	{
		wxMessageBox("No render systems found", "Error");
		return;
	}
	for(RenderSystemList::const_iterator it = rl.begin(); it != rl.end(); ++it)
	{
		Ogre::RenderSystem *rs = (*it);
		rs->setConfigOption("Full Screen", "No");
		rs->setConfigOption("VSync", "No");
		rs->setConfigOption("Video Mode", "512 x 512 @ 32-bit");
		
		if(rs->getName() == "OpenGL Rendering Subsystem") 
			mOpenGLRenderSystem = *it;
		else if(rs->getName() == "Direct3D9 Rendering Subsystem")
			mDirectXRenderSystem = *it;
	}

	// We'll see if there is already and Ogre.cfg, if not we'll
	// default to OpenGL since we know that will work on all
	// platforms
	if(!mRoot->restoreConfig())
	{
		mRoot->setRenderSystem(mOpenGLRenderSystem);
	}

	mOgreControl = new wxOgre(this);

	ConfigFile cf;
	cf.load("resources.cfg");

	ConfigFile::SectionIterator seci = cf.getSectionIterator();

	Ogre::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;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
		}
	}

	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	wxString caption;
	String rs = mRoot->getRenderSystem()->getName();
	if(rs == "OpenGL Rendering Subsystem") caption = "OGRE - OpenGL";
	else caption = "OGRE - DirectX";

	wxAuiPaneInfo info;
	info.Caption(caption);
	info.MaximizeButton(true);
	info.MinimizeButton(true);
	info.Floatable(true);
	info.BestSize(512, 512);
	info.Left();

	mAuiManager->AddPane(mOgreControl, info);
}
Exemple #17
0
bool Game::init()
{
  try
  {
    // Read config first
    config.read("./config.cfg");

    // Init SDL
    SDL_Init(SDL_INIT_VIDEO);
    SDL_putenv((char*)"SDL_VIDEO_CENTERED=true");
    int flags = SDL_OPENGL;
    if (config.getFullscreen())
      flags |= SDL_FULLSCREEN;
    SDL_SetVideoMode(config.getCanvasWidth(), config.getCanvasHeight(), config.getBits(), flags);
    SDL_WM_SetCaption("Yet Another Rubik's Cube", NULL);

    // Ogre
    root = new Ogre::Root();
    #ifdef _WINDOWS
      root->loadPlugin("./RenderSystem_GL.dll");
    #else
      root->loadPlugin("./RenderSystem_GL.so");
    #endif
    Ogre::RenderSystem *rs = root->getRenderSystemByName("OpenGL Rendering Subsystem");
    root->setRenderSystem(rs);
    rs->setConfigOption("Full Screen", config.getFullscreenStr());
    rs->setConfigOption("Video Mode", config.getVideoModeStr());
    root->initialise(false);

    // Window
    Ogre::NameValuePairList params;
    #ifdef _WINDOWS
      SDL_SysWMinfo info;
      SDL_VERSION(&info.version);
      SDL_GetWMInfo(&info);
      params["externalWindowHandle"] = Ogre::StringConverter::toString(reinterpret_cast<size_t>(info.window));
      params["externalGLContent"] = Ogre::StringConverter::toString(reinterpret_cast<size_t>(info.hglrc));
      params["externalGLControl"] = Ogre::String("True");
    #else
      params["currentGLContext"] = Ogre::String("True");
    #endif
    wnd = root->createRenderWindow("Main window", config.getCanvasWidth(), config.getCanvasHeight(),
        config.getFullscreen(), &params);
    wnd->setVisible(true);

    // Input
    imgr = new InputManager();

    // Hard-code res location
    Ogre::ResourceGroupManager *rgm = Ogre::ResourceGroupManager::getSingletonPtr();
    rgm->addResourceLocation("res.gdat", "Zip", "General");
    rgm->initialiseAllResourceGroups();

    // Window and rendering events listener
    root->addFrameListener(this);
    imgr->regEventListener(this);
    imgr->regKeyboardListener(this);
  }
  catch (std::exception &e)
  {
    #ifdef _WINDOWS
      MessageBoxA(NULL, e.what(), "Exception occured", MB_OK | MB_ICONERROR);
    #else
      std::cout << e.what();
    #endif
    return false;
  }
  return true;
}
Exemple #18
0
/** Configures the application - returns false if the user chooses to abandon configuration. */
Ogre::Root* OgreSetup::configure(void)
{

	ConfigService& configService(EmberServices::getSingleton().getConfigService());
	createOgreSystem();
#ifndef BUILD_WEBEMBER
	bool success = false;
	bool suppressConfig = false;
	if (configService.itemExists("ogre", "suppressconfigdialog")) {
		suppressConfig = static_cast<bool>(configService.getValue("ogre", "suppressconfigdialog"));
	}
	try {
		success = mRoot->restoreConfig();
		if (!success || !suppressConfig) {
			success = showConfigurationDialog();
		}

	} catch (const std::exception& ex) {
		S_LOG_WARNING("Error when showing config dialog. Will try to remove ogre.cfg file and retry." << ex);
		unlink((EmberServices::getSingleton().getConfigService().getHomeDirectory() + "/ogre.cfg").c_str());
		try {
			success = mRoot->showConfigDialog();
		} catch (const std::exception& ex) {
			S_LOG_CRITICAL("Could not configure Ogre. Will shut down." << ex);
		}
	}
	if (!success) {
		return false;
	}

	mRenderWindow = mRoot->initialise(true, "Ember");

#else //BUILD_WEBEMBER == true
	//In webember we will disable the config dialog.
	//Also we will use fixed resolution and windowed mode.
	try {
		mRoot->restoreConfig();
	} catch (const std::exception& ex) {
		//this isn't a problem, we will set the needed functions manually.
	}
	Ogre::RenderSystem* renderer = mRoot->getRenderSystem();
#ifdef _WIN32
	//on windows, the default renderer is directX, we will force OpenGL.
	renderer = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
	if (renderer != NULL) {
		mRoot->setRenderSystem(renderer);
	} else {
		S_LOG_WARNING("OpenGL RenderSystem not found. Starting with default RenderSystem.");
		renderer = mRoot->getRenderSystem();
	}
#endif // _WIN32
	renderer->setConfigOption("Video Mode", "800 x 600");
	renderer->setConfigOption("Full Screen", "no");

	mRoot->initialise(false, "Ember");

	Ogre::NameValuePairList options;

	if (configService.itemExists("ogre", "windowhandle")) {
		//set the owner window
		std::string windowhandle = configService.getValue("ogre", "windowhandle");
		options["parentWindowHandle"] = windowhandle;

		//put it in the top left corner
		options["top"] = "0";
		options["left"] = "0";
	}

	mRenderWindow = mRoot->createRenderWindow("Ember",800,600,false,&options);

#endif // BUILD_WEBEMBER
#ifdef _WIN32
	//do some FPU fiddling, since we need the correct settings for stuff like mercator (which uses fractals etc.) to work
	_fpreset();
	_controlfp(_PC_64, _MCW_PC);
	_controlfp(_RC_NEAR , _MCW_RC);
#endif

	mRenderWindow->setActive(true);
	mRenderWindow->setAutoUpdated(true);
	mRenderWindow->setVisible(true);

	setStandardValues();

	// Create new scene manager factory
	mSceneManagerFactory = new EmberPagingSceneManagerFactory();

	// Register our factory
	mRoot->addSceneManagerFactory(mSceneManagerFactory);

	return mRoot;
}
Exemple #19
0
void App::initOgre()
{
	// Config file class is an utility that parses and stores values from a .cfg file
	Ogre::ConfigFile cf;
	std::string configFilePathPrefix = "cfg/";			// configuration files default location when app is installed
#ifdef _DEBUG
	std::string pluginsFileName = "plugins_d.cfg";		// plugins config file name (Debug mode)
#else
	std::string pluginsFileName = "plugins.cfg";		// plugins config file name (Release mode)
#endif
	std::string resourcesFileName = "resources.cfg";	// resources config file name (Debug/Release mode)


	// LOAD OGRE PLUGINS
	// Try to load load up a valid config file (and don't start the program if none is found)
	try
	{
		//This will work ONLY when application is installed (only Release application)!
		cf.load(configFilePathPrefix + pluginsFileName);
	}
	catch (Ogre::FileNotFoundException &e)
	{
		try
		{
			// if no existing config, or could not restore it, try to load from a different location
			configFilePathPrefix = "../cfg/";

			//This will work ONLY when application is in development (Debug/Release configuration)
			cf.load(configFilePathPrefix + pluginsFileName);			
		}
		catch (Ogre::FileNotFoundException &e)
		{
			// launch exception if no valid config file is found! - PROGRAM WON'T START!
			throw e;
		}
	}


	// INSTANCIATE OGRE ROOT (IT INSTANCIATES ALSO ALL OTHER OGRE COMPONENTS)
	// In Ogre, the singletons are instanciated explicitly (with new) the first time,
	// then it can be accessed with Ogre::Root::getSingleton()
	// Plugins are passed as argument to the "Root" constructor
	mRoot = new Ogre::Root(configFilePathPrefix + pluginsFileName, configFilePathPrefix + "ogre.cfg", "ogre.log");
	// No Ogre::FileNotFoundException is thrown by this, that's why we tried to open it first with ConfigFile::load()

	
	// LOAD OGRE RESOURCES
	// Load up resources according to resources.cfg ("cf" variable is reused)
	try
	{
		//This will work ONLY when application is installed!
		cf.load("cfg/resources.cfg");
	}
	catch (Ogre::FileNotFoundException &e)	// It works, no need to change anything
	{
		try
		{
			//This will work ONLY when application is in development (Debug/Release configuration)
			cf.load("../cfg/resources.cfg");
		}
		catch (Ogre::FileNotFoundException &e)
		{
			// launch exception if no valid config file is found! - PROGRAM WON'T START!
			throw e;
		}
	}

    // 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;
			//For each section/key-value, add a resource to ResourceGroupManager
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                archName, typeName, secName);
        }
	}


	// Then setup THIS CLASS INSTANCE as a frame listener
	// This means that Ogre will call frameStarted(), frameRenderingQueued() and frameEnded()
	// automatically and periodically if defined in this class
	mRoot->addFrameListener(this);


	// SELECT AND CUSTOMIZE OGRE RENDERING (OpenGL)
	// Get a reference of the RenderSystem in Ogre that I want to customize
	Ogre::RenderSystem* pRS = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
	// Get current config RenderSystem options in a ConfigOptionMap
	Ogre::ConfigOptionMap cfgMap = pRS->getConfigOptions();
	// Modify them
	cfgMap["Full Screen"].currentValue = "No";
	cfgMap["VSync"].currentValue = "Yes";
	#ifdef _DEBUG
		cfgMap["FSAA"].currentValue = "0";
	#else
		cfgMap["FSAA"].currentValue = "8";
	#endif
	cfgMap["Video Mode"].currentValue = "1200 x 800";
	// Set them back into the RenderSystem
	for(Ogre::ConfigOptionMap::iterator iter = cfgMap.begin(); iter != cfgMap.end(); iter++) pRS->setConfigOption(iter->first, iter->second.currentValue);
	// Set this RenderSystem as the one I want to use
	mRoot->setRenderSystem(pRS);
	// Initialize it: "false" is DO NOT CREATE A WINDOW FOR ME
	mRoot->initialise(false, "Oculus Rift Visualization");


	// CREATE WINDOWS
	/* REMOVED: Rift class creates the window if no null is passed to its constructor
	// Options for Window 1 (rendering window)
	Ogre::NameValuePairList miscParams;
	if( NO_RIFT )
		miscParams["monitorIndex"] = Ogre::StringConverter::toString(0);
	else
		miscParams["monitorIndex"] = Ogre::StringConverter::toString(1);
	miscParams["border "] = "none";
	*/

	/*
	// Create Window 1
	if( !ROTATE_VIEW )
	mWindow = mRoot->createRenderWindow("Oculus Rift Liver Visualization", 1280, 800, true, &miscParams);
	//mWindow = mRoot->createRenderWindow("Oculus Rift Liver Visualization", 1920*0.5, 1080*0.5, false, &miscParams);
	else
	mWindow = mRoot->createRenderWindow("Oculus Rift Liver Visualization", 1080, 1920, true, &miscParams);
	*/

	// Options for Window 2 (debug window)
	// This window will simply show what the two cameras see in two different viewports
	Ogre::NameValuePairList miscParamsSmall;
	miscParamsSmall["monitorIndex"] = Ogre::StringConverter::toString(0);

	// Create Window 2
	if( DEBUG_WINDOW )
		mSmallWindow = mRoot->createRenderWindow("DEBUG Oculus Rift Liver Visualization", 1920*debugWindowSize, 1080*debugWindowSize, false, &miscParamsSmall);   

	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
Exemple #20
0
//-------------------------------------------------------------------------------------
void setupOgre(Ogre::String plugins, Ogre::String config, Ogre::String log)
{
    // create the main ogre object
    mOgreRoot = OGRE_NEW Ogre::Root( plugins);

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
    // load additional plugins
    const Ogre::String& pluginPathDepends = "../../Dependencies/lib/";
    mOgreRoot->loadPlugin(pluginPathDepends + "libCaelum.so");
#endif

    Ogre::LogManager::getSingleton().setLogDetail(Ogre::LL_NORMAL);

    Ogre::ConfigFile cf;
    std::string cfPath = resourcePath();
    cfPath.append("resources.cfg");
    cf.load(cfPath);

    // 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 = resourcePath() + i->second;
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
        }
    }

#if ((OGRE_VERSION_MAJOR * 10) + OGRE_VERSION_MINOR) >= 17
    Ogre::RenderSystemList::const_iterator pRend = mOgreRoot->getAvailableRenderers().begin();
    while (pRend != mOgreRoot->getAvailableRenderers().end())
#else
    Ogre::RenderSystemList::const_iterator pRend = mOgreRoot->getAvailableRenderers()->begin();
    while (pRend != mOgreRoot->getAvailableRenderers()->end())
#endif
    {
        Ogre::String rName = (*pRend)->getName();
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        if (rName == "Direct3D9 Rendering Subsystem")
#else
        if (rName == "OpenGL Rendering Subsystem")
#endif
            break;
        pRend++;
    }

    Ogre::RenderSystem *rsys = *pRend;

    QSettings settings;

    settings.beginGroup("preferences");

    int antialias = settings.value("antiAliasing", 0).toInt();
    bool vsync = settings.value("useVSync", false).toBool();


    // Some standard rendering system configurations
    if(vsync)
        rsys->setConfigOption("VSync", "Yes");
    else
        rsys->setConfigOption("VSync", "No");

    rsys->setConfigOption("FSAA", Ogre::StringConverter::toString(antialias));

    // Set the rendering system and Initialise OGRE
    mOgreRoot->setRenderSystem(rsys);

    // initialize without creating window
    mOgreRoot->getRenderSystem()->setConfigOption( "Full Screen", "No" );
    //mOgreRoot->saveConfig();
    mOgreRoot->initialise(false); // don't create a window

    Ogitors::OgitorsSpecialKeys keys;
    /* Shortcuts class was created only with getInstance() and because of this it's destructor never ran */
    shortCuts = new Shortcuts();//Shortcuts::getInstance();
    shortCuts->load();
    //tmp->add(QKeySequence(Qt::Key_W).toString(), QString("Move Forward"), "SPK_FORWARD", Qt::Key_W);
    //tmp->add(QKeySequence(Qt::Key_A).toString(), QString("Move Left"), "SPK_LEFT", Qt::Key_A);
    //tmp->add(QKeySequence(Qt::Key_S).toString(), QString("Move Backward"), "SPK_BACKWARD", Qt::Key_S);
    //tmp->add(QKeySequence(Qt::Key_D).toString(), QString("Move Right"), "SPK_RIGHT", Qt::Key_D);

    // normal keys
    keys.SPK_LEFT = Qt::Key_A;
    keys.SPK_RIGHT = Qt::Key_D;
    keys.SPK_FORWARD = Qt::Key_W;
    keys.SPK_BACKWARD = Qt::Key_S;
    keys.SPK_UP = Qt::Key_E;
    keys.SPK_DOWN = Qt::Key_Q;
    keys.SPK_FOCUS_OBJECT = Qt::Key_F;
    // special keys
    keys.SPK_DELETE = (Qt::Key_Delete & 0xFFF) + 0xFF; 
    keys.SPK_SWITCH_AXIS = (Qt::Key_End & 0xFFF) + 0xFF;
    // modifiers
    // space
    keys.SPK_SNAP_GROUND = Qt::Key_Space;
    // shift
    keys.SPK_CLONE = (Qt::Key_Shift & 0xFFF) + 0xFF;
    keys.SPK_REVERSE_UPDATE = (Qt::Key_Shift & 0xFFF) + 0xFF;
    keys.SPK_ADD_TO_SELECTION = (Qt::Key_Shift & 0xFFF) + 0xFF;
    // control
    keys.SPK_SNAP = (Qt::Key_Control & 0xFFF) + 0xFF;;
    keys.SPK_SUBTRACT_FROM_SELECTION = (Qt::Key_Control & 0xFFF) + 0xFF;
    // alt
    keys.SPK_OBJECT_CENTERED_MOVEMENT = (Qt::Key_Alt & 0xFFF) + 0xFF;
    keys.SPK_ALWAYS_SELECT = (Qt::Key_Alt & 0xFFF) + 0xFF;

    Ogitors::CViewportEditor::SetKeyboard(ViewKeyboard, keys);

    mSystem = OGRE_NEW QtOgitorSystem();
    mOgitorsRoot = OGRE_NEW Ogitors::OgitorsRoot();
}
//---------------------------------------------------------------------
bool OgreInit::startOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener , OIS::MouseListener *pMouseListener)
{
    // Initialisation du monde virtuel utilisé par Bullet
    m_broadphase = new btDbvtBroadphase();
    m_collisionConfiguration = new btDefaultCollisionConfiguration();
    m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
    m_solver = new btSequentialImpulseConstraintSolver;
    m_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
    m_world->setGravity(btVector3(0,-25,0));

    pLogMgr = new Ogre::LogManager();
    pLog = pLogMgr->createLog("LogFile.log", true, true, false);
    pLog->setDebugOutputEnabled(true);

    pRoot = new Ogre::Root();
//    if(!pRoot->showConfigDialog()) return false;

// variante : configuration sans boite de dialogue
//*
//Ogre::RenderSystem *rs = pRoot->getRenderSystemByName("OpenGL Rendering Subsystem");//"Direct3D9 Rendering Subsystem"); // Pour OpenGL : "OpenGL Rendering Subsystem"

   //    pRoot->loadPlugin("RenderSystem_GL.dll");

//        pRoot->setRenderSystem((*(pRoot->getAvailableRenderers()))[0]);

       Ogre::RenderSystem *mRenderSystem = pRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
        pRoot->setRenderSystem(mRenderSystem);
       // OpenGL Parameters
       mRenderSystem->setConfigOption( "Colour Depth", "32" );
       mRenderSystem->setConfigOption( "Display Frequency", "N/A" );
       mRenderSystem->setConfigOption( "FSAA", "0" );
       mRenderSystem->setConfigOption( "Full Screen", "No" );
       mRenderSystem->setConfigOption( "RTT Preferred Mode", "FBO" );
       mRenderSystem->setConfigOption( "VSync", "Yes" );
       mRenderSystem->setConfigOption( "Video Mode", "800 x 600" );

//*/
    pRenderWnd = pRoot->initialise(true, wndTitle);
    //Initialisation du SceneManager
    pSceneMgr = pRoot->createSceneManager(ST_GENERIC, "SceneManager");
    pSceneMgr->setAmbientLight(Ogre::ColourValue(0.3f, 0.3f, 0.4f));

    //Initialisation de la camera
    pCamera=pSceneMgr->createCamera("MainCamera");
    pCamera->setPosition(Vector3(0,60,120));
    pCamera->lookAt(Vector3(0,0,0));
    pCamera->setNearClipDistance(1);
    //Initialisation du viewport
    pViewport=pRenderWnd->addViewport(pCamera);
    pViewport->setBackgroundColour(ColourValue(0.3f,0.3f,0.3f,1.0f));
    pCamera->setAspectRatio(Real(pViewport->getActualWidth()) / Real(pViewport->getActualHeight()));
    pViewport->setCamera(pCamera);
    //Initialisation de OIS
    unsigned long hwnd=0;
    OIS::ParamList paramList;
    pRenderWnd->getCustomAttribute("WINDOW",&hwnd);
    paramList.insert(OIS::ParamList::value_type("WINDOW",Ogre::StringConverter::toString(hwnd)));

    pInputMgr=OIS::InputManager::createInputSystem(paramList);
    pKeyboard=static_cast<OIS::Keyboard*>(pInputMgr->createInputObject(OIS::OISKeyboard,true));
    pMouse=static_cast<OIS::Mouse*>(pInputMgr->createInputObject(OIS::OISMouse, true));
    pMouse->getMouseState().height = pRenderWnd->getHeight();
    pMouse->getMouseState().width = pRenderWnd->getWidth();

    if(pKeyListener == 0)
        pKeyboard->setEventCallback(this);
    else
        pKeyboard->setEventCallback(pKeyListener);

    if(pMouseListener == 0)
        pMouse->setEventCallback(this);
    else
        pMouse->setEventCallback(pMouseListener);

    //Definition des ressources
    Ogre::String secName, typeName, archName;
    Ogre::ConfigFile cf;
    cf.load("resources.cfg");

    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
    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);
        }
    }

    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    pTimer = new Ogre::Timer();
    pTimer->reset();

    pTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", pRenderWnd , pMouse, this);
    pTrayMgr->hideLogo();
    pTrayMgr->hideFrameStats();
    pTrayMgr->hideCursor();

    pRenderWnd->setActive(true);
    return true;
}//startOgre
/****************************************************************************
**
** Copyright (C) 2016 - 2017
**
** This file is generated by the Magus toolkit
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE go (ODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/

#include "ogre3_renderman.h"
#include "OgreConfigFile.h"
#include "OgreArchiveManager.h"
#include "OgreHlms.h"
#include "OgreHlmsUnlit.h"
#include "OgreHlmsPbs.h"
#include "OgreHlmsManager.h"
#include "OgreHlmsCommon.h"
#include "OgreLogManager.h"
#include "OgreFrameStats.h"

namespace Magus
{
    //****************************************************************************/
    OgreManager::OgreManager(void)
    {
        mGlContext = 0;
        mCompositorPassProvider = 0;
        mPause = true;

        #if _DEBUG || DEBUG
            mResourcesCfg = "resources_d.cfg";
            mPluginsCfg = "plugins_d.cfg";
        #else
            mResourcesCfg = "resources.cfg";
            mPluginsCfg = "plugins.cfg";
        #endif

        // Create Ogre tt and initialize
        mRoot = new Ogre::Root(mPluginsCfg);

        // Setup renderer
        mCurrentRenderSystem = 0;
        const Ogre::RenderSystemList& rsList = mRoot->getAvailableRenderers();
        Ogre::RenderSystem* renderSystem = rsList[0];
        std::vector<Ogre::String> renderOrder;
        #if defined(Q_OS_WIN)
            renderOrder.push_back("Direct3D11");
        #endif
            renderOrder.push_back("OpenGL 3+");
        for (std::vector<Ogre::String>::iterator iter = renderOrder.begin(); iter != renderOrder.end(); iter++)
        {
            for (Ogre::RenderSystemList::const_iterator it = rsList.begin(); it != rsList.end(); it++)
            {
                if ((*it)->getName().find(*iter) != Ogre::String::npos)
                {
                    renderSystem = *it;
                    break;
                }
            }
            if (renderSystem != 0) break;
        }

        if (renderSystem == 0)
        {
            if (!mRoot->restoreConfig())
            {
                if (!mRoot->showConfigDialog())
                    OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "Abort render system configuration", "OgreManager::OgreManager");
            }
        }

        renderSystem->setConfigOption("Full Screen", "No");
        renderSystem->setConfigOption("VSync", "Yes");
        mRoot->setRenderSystem(renderSystem);
        mCurrentRenderSystem = renderSystem;

        // Uncomment next line to show dialog
        //if(mRoot->restoreConfig() || mRoot->showConfigDialog())
        //{
            mRoot->initialise(false);
        //}


        // Initialize resources
        setupResources();

        // Start timer
        mTimer = new Ogre::Timer();
        mTimer->reset();
    }
Exemple #23
0
bool GameManager::configure(void)
{
    //// load config settings from ogre.cfg
    //if (!mRoot->restoreConfig())
    //{
    //    // if there is no config file, show the configuration dialog
    //    if (!mRoot->showConfigDialog())
    //    {
    //        return false;
    //    }
    //}
 
    //// initialise and create a default rendering window
    //mRenderWindow = mRoot->initialise(true);
 
    //ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	// -- NEW --

	// A list of required plugins
    Ogre::StringVector required_plugins;
    required_plugins.push_back("GL RenderSystem");
   // required_plugins.push_back("Octree & Terrain Scene Manager");
 
    // List of plugins to load
    Ogre::StringVector plugins_toLoad;
    plugins_toLoad.push_back("RenderSystem_GL");
    //plugins_toLoad.push_back("Plugin_OctreeSceneManager");
 
    // Load the OpenGL RenderSystem and the Octree SceneManager plugins
    for (Ogre::StringVector::iterator j = plugins_toLoad.begin(); j != plugins_toLoad.end(); j++)
    {
#ifdef _DEBUG
        mRoot->loadPlugin(*j + Ogre::String("_d"));
#else
        mRoot->loadPlugin(*j);
#endif;
    }
 
    // Check if the required plugins are installed and ready for use
    // If not: exit the application
    Ogre::Root::PluginInstanceList ip = mRoot->getInstalledPlugins();
    for (Ogre::StringVector::iterator j = required_plugins.begin(); j != required_plugins.end(); j++)
    {
        bool found = false;
        // try to find the required plugin in the current installed plugins
        for (Ogre::Root::PluginInstanceList::iterator k = ip.begin(); k != ip.end(); k++) {
            if ((*k)->getName() == *j) {
                found = true;
                break;
            }
        }
        if (!found)  // return false because a required plugin is not available
        {
            return false;
        }
    }
 
////-------------------------------------------------------------------------------------
//    // setup resources
//    // Only add the minimally required resource locations to load up the Ogre head mesh
//    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../../media/materials/programs", "FileSystem", "General");
//    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../../media/materials/scripts", "FileSystem", "General");
//    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../../media/materials/textures", "FileSystem", "General");
//    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../../media/models", "FileSystem", "General");
// 
//-------------------------------------------------------------------------------------
    // configure
    // Grab the OpenGL RenderSystem, or exit
    Ogre::RenderSystem* rs = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    if(!(rs->getName() == "OpenGL Rendering Subsystem"))
    {
        return false; //No RenderSystem found
    }
    // configure our RenderSystem
    rs->setConfigOption("Full Screen", "No");
    rs->setConfigOption("VSync", "No");
    rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit");
 
    mRoot->setRenderSystem(rs);
 
    mRenderWindow = mRoot->initialise(true, "LowLevelOgre Render Window");
 
    return true;
}
Exemple #24
0
void App::initOgre()
{
#ifdef _DEBUG
    mRoot = new Ogre::Root("plugins_d.cfg");
#else
    mRoot = new Ogre::Root("plugins.cfg");
#endif
    mRoot->addFrameListener(this);

    // Load up resources according to resources.cfg:
    Ogre::ConfigFile cf;
    cf.load("resources.cfg");

    // 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);
        }
    }

    Ogre::RenderSystem* pRS = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    Ogre::ConfigOptionMap cfgMap = pRS->getConfigOptions();
    cfgMap["Full Screen"].currentValue = "No";
    cfgMap["VSync"].currentValue = "Yes";
#ifdef _DEBUG
    cfgMap["FSAA"].currentValue = "0";
#else
    cfgMap["FSAA"].currentValue = "8";
#endif
    cfgMap["Video Mode"].currentValue = "1200 x 800";
    for(Ogre::ConfigOptionMap::iterator iter = cfgMap.begin(); iter != cfgMap.end(); iter++) pRS->setConfigOption(iter->first, iter->second.currentValue);
    mRoot->setRenderSystem(pRS);
    mRoot->initialise(false, "Oculus Rift Visualization");

    // Create the Windows:
    Ogre::NameValuePairList miscParams;
    if( NO_RIFT )
        miscParams["monitorIndex"] = Ogre::StringConverter::toString(0);
    else
        miscParams["monitorIndex"] = Ogre::StringConverter::toString(1);
    miscParams["border "] = "none";

    Ogre::NameValuePairList miscParamsSmall;
    miscParamsSmall["monitorIndex"] = Ogre::StringConverter::toString(0);

    if( !ROTATE_VIEW )
        mWindow = mRoot->createRenderWindow("ShowARoom", WIDTH, HEIGHT, FULL_SCREEN, &miscParams);
    //mWindow = mRoot->createRenderWindow("Oculus Rift Liver Visualization", 1920*0.5, 1080*0.5, false, &miscParams);
    else
        mWindow = mRoot->createRenderWindow("ShowARoom", HEIGHT, WIDTH, FULL_SCREEN, &miscParams);

    if( DEBUG_WINDOW )
        mSmallWindow = mRoot->createRenderWindow("DEBUG ShowARoom", 1920*debugWindowSize, 1080*debugWindowSize, false, &miscParamsSmall);

    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
void setupOgre(Ogre::String plugins, Ogre::String config, Ogre::String log)
{
    // create the main ogre object
    mOgreRoot = new Ogre::Root( plugins);

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
    // load additional plugins
    const Ogre::String& pluginPathDepends = "../../Dependencies/lib/";
    mOgreRoot->loadPlugin(pluginPathDepends + "libCaelum.so");
#endif

    Ogre::LogManager::getSingleton().setLogDetail(Ogre::LL_BOREME);

    Ogre::ConfigFile cf;
    std::string cfPath = resourcePath();
    cfPath.append("resources.cfg");
    cf.load(cfPath);

    // 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 = resourcePath() + i->second;
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
        }
    }

#if ((OGRE_VERSION_MAJOR * 10) + OGRE_VERSION_MINOR) >= 17
    Ogre::RenderSystemList::const_iterator pRend = mOgreRoot->getAvailableRenderers().begin();
    while (pRend != mOgreRoot->getAvailableRenderers().end())
#else
        Ogre::RenderSystemList::const_iterator pRend = mOgreRoot->getAvailableRenderers()->begin();
    while (pRend != mOgreRoot->getAvailableRenderers()->end())
#endif
    {
        Ogre::String rName = (*pRend)->getName();
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        if (rName == "Direct3D9 Rendering Subsystem")
#else
        if (rName == "OpenGL Rendering Subsystem")
#endif
            break;
        pRend++;
    }

    Ogre::RenderSystem *rsys = *pRend;

    // Some standard rendering system configurations
    rsys->setConfigOption("VSync", "No"); // -> Why not?

    // Set the rendering system and Initialise OGRE
    mOgreRoot->setRenderSystem(rsys);

    // initialize without creating window
    mOgreRoot->getRenderSystem()->setConfigOption( "Full Screen", "No" );
    //mOgreRoot->saveConfig();
    mOgreRoot->initialise(false); // don't create a window

}
void CLASS::SaveSettings()
{
	//Get combo boxes values first
	//Check boxes and sliders values are updated as they are being used
	GameSettingsMap["GearboxMode"] = m_gearbox_mode->getCaption();
	OgreSettingsMap["Render System"] = m_render_sys->getCaption(); //This one is special 
	OgreSettingsMap["Video Mode"] = m_resolution->getCaption(); //This one is special 
	OgreSettingsMap["FSAA"] = m_fsaa->getCaption(); //This one is special 
	GameSettingsMap["FOV External"] = m_fovexternal->getCaption();
	GameSettingsMap["FOV Internal"] = m_fovinternal->getCaption();
	GameSettingsMap["Texture Filtering"] = m_tex_filter->getCaption();
	GameSettingsMap["Sky effects"] = m_sky_type->getCaption();
	GameSettingsMap["Shadow technique"] = m_shadow_type->getCaption();
	GameSettingsMap["Water effects"] = m_water_type->getCaption();
	GameSettingsMap["Vegetation"] = m_vegetation->getCaption();
	GameSettingsMap["Lights"] = m_light_source_effects->getCaption(); 
	GameSettingsMap["AudioDevice"] = m_audio_dev->getCaption();
	GameSettingsMap["SpeedUnit"] = m_speed_unit->getCaption();
	//That's it i think

	//Not sure if these settings really need a restart, temporary.
	if (GameSettingsMap["AudioDevice"] != ExGameSettingsMap["AudioDevice"])
		ShowRestartNotice = true;
	else if (GameSettingsMap["FOV External"] != ExGameSettingsMap["FOV External"] || GameSettingsMap["FOV Internal"] != ExGameSettingsMap["FOV Internal"])
		ShowRestartNotice = true;
	else if (OgreSettingsMap["Render System"] != ExOgreSettingsMap["Render System"])
		ShowRestartNotice = true;
	else if (OgreSettingsMap["Video Mode"] != ExOgreSettingsMap["Video Mode"])
		ShowRestartNotice = true;
	else if (OgreSettingsMap["FSAA"] != ExOgreSettingsMap["FSAA"])
		ShowRestartNotice = true;


	if (GameSettingsMap["Water effects"] == "Hydrax")
		GameSettingsMap["SightRange"] = "5000";

	if (isKeyMapLoaded)
	{
		Application::GetInputEngine()->saveMapping("input.map", RoR::Application::GetOgreSubsystem()->GetMainHWND());
	}

	//Something used by both saves
	std::map<std::string, std::string>::iterator it;

	//Save ogre's settings
	Ogre::RenderSystem* rs = Ogre::Root::getSingleton().getRenderSystem();
	for (it = OgreSettingsMap.begin(); it != OgreSettingsMap.end(); it++)
	{
		try
		{
			rs->setConfigOption(it->first.c_str(), it->second.c_str());
		}
		catch (...)
		{
			LOG("Error setting Ogre Values");
		}
	}
	Ogre::String err = rs->validateConfigOptions();
	if (err.length() > 0)
	{
		LOG("Ogre config validation error");
	}
	else
	{
		Ogre::Root::getSingleton().saveConfig();
	}

	// now save the GameSettingsMap
	for (it = GameSettingsMap.begin(); it != GameSettingsMap.end(); it++)
	{
		if (it->first.c_str() == "User Token" || it->first.c_str() == "User Token Hash" || it->first.c_str() == "Config Root" || it->first.c_str() == "Cache Path" || it->first.c_str() == "Log Path" || it->first.c_str() == "Resources Path" || it->first.c_str() == "Program Path")
			return;

		Settings::getSingleton().setSetting(it->first.c_str(), it->second.c_str()); //Avoid restarting the game in few cases.
		Settings::getSingleton().saveSettings();
	}

	//Apply fullscreen
	//Not working correctly
	/*
	if (BSETTING("DevMode", false)) //let's disable this for now
	{
		if (OgreSettingsMap["Full Screen"].c_str() != ExOgreSettingsMap["Full Screen"].c_str())
		{
			Ogre::StringVector args = Ogre::StringUtil::split(OgreSettingsMap["Video Mode"], " ");

			static int org_width = -1, org_height = -1;
			int width = RoR::Application::GetOgreSubsystem()->GetRenderWindow()->getWidth();
			int height = RoR::Application::GetOgreSubsystem()->GetRenderWindow()->getHeight();
			if (org_width == -1)
				org_width = width;
			if (org_height == -1)
				org_height = height;
			bool mode = RoR::Application::GetOgreSubsystem()->GetRenderWindow()->isFullScreen();
			if (!mode)
			{
				RoR::Application::GetOgreSubsystem()->GetRenderWindow()->setFullscreen(true, (int)args[0].c_str(), (int)args[2].c_str());
				LOG(" ** switched to fullscreen: " + TOSTRING(width) + "x" + TOSTRING(height));
			}
			else
			{
				RoR::Application::GetOgreSubsystem()->GetRenderWindow()->setFullscreen(false, 640, 480);
				RoR::Application::GetOgreSubsystem()->GetRenderWindow()->setFullscreen(false, org_width, org_height);
				LOG(" ** switched to windowed mode: ");
			}
			ShowRestartNotice = false;
		}
	}*/

} 
int _tmain(int argc, _TCHAR* argv[])
{
	// ------------------------- Check for command line argument -------------------------------------------

	if (! argv[1])
	{
		printf("\n");
		printf("Missing argument.\nExample: \"Converter.exe job1.cfg\"");		
		return 0;	
	}

	// ------------------------- Basic Ogre Engine initialization -------------------------------------------

	Ogre::Root* root = new Ogre::Root;	
	Ogre::RenderSystem* rendersys = root->getRenderSystemByName("Direct3D9 Rendering Subsystem");
	
	rendersys->setConfigOption("Full Screen", "No");
	rendersys->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
	
	root->setRenderSystem(rendersys);		
	
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	root->initialise(false);

	Ogre::RenderWindow* window = root->createRenderWindow("RAW2OGT", 800, 600, false);		
	Ogre::SceneManager* scenemgr = root->createSceneManager(Ogre::SceneType::ST_GENERIC);
	Ogre::Camera* camera = scenemgr->createCamera("camera");
	Ogre::Viewport* viewport = window->addViewport(camera);
	/*Ogre::Vector3 lightdir(0, -0.3, 0.75);
	lightdir.normalise();

	Ogre::Light* l = scenemgr->createLight("tstLight");
	l->setType(Ogre::Light::LT_DIRECTIONAL);
	l->setDirection(lightdir);
	l->setDiffuseColour(Ogre::ColourValue(1.0, 1.0, 1.0));
	l->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));*/

	scenemgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7));
	
	// --------------------------------- Start convert ----------------------------------------------------

	// Load job config
	Ogre::ConfigFile* terrainconfig = OGRE_NEW Ogre::ConfigFile();
	terrainconfig->loadDirect(argv[1]);
		
	// Load info from [general] block
	Ogre::String heightmapfile = terrainconfig->getSetting("heightmap", "general");
	Ogre::Real heightmapscale = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapscale", "general"));
	Ogre::Real heightmapoffset = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapoffset", "general"));
	Ogre::uint16 terrainsize = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("terrainsize", "general"));
	Ogre::Real worldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", "general"));
	Ogre::uint16 layercount = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("layercount", "general"));

	// initialise stream to heightmapfile
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(heightmapfile, "General");
	size_t size = stream.get()->size();
		
	// verify size
	if(size != terrainsize * terrainsize * 4)
		OGRE_EXCEPT( Ogre::Exception::ERR_INTERNAL_ERROR, "Size of stream does not match terrainsize!", "TerrainPage" );
					
	// load to buffer
	float* buffer = OGRE_ALLOC_T(float, size, Ogre::MEMCATEGORY_GENERAL);
	stream->read(buffer, size);

	// apply scale and offset 
	for(int i=0;i<terrainsize*terrainsize;i++)
	{
		buffer[i]  = (buffer[i] + heightmapoffset) * heightmapscale;
	}

	// Terrain initialization
	Ogre::TerrainGlobalOptions* terrainglobals = OGRE_NEW Ogre::TerrainGlobalOptions();
	terrainglobals->setMaxPixelError(1);
	//terrainglobals->setCompositeMapDistance(30000);
	//terrainglobals->setLightMapDirection(lightdir);
    //terrainglobals->setCompositeMapAmbient(scenemgr->getAmbientLight());
    //terrainglobals->setCompositeMapDiffuse(l->getDiffuseColour());
	
	Ogre::TerrainMaterialGeneratorA::SM2Profile* pMatProfile = 
      static_cast<Ogre::TerrainMaterialGeneratorA::SM2Profile*>(terrainglobals->getDefaultMaterialGenerator()->getActiveProfile());
	
	pMatProfile->setLightmapEnabled(false);
	pMatProfile->setCompositeMapEnabled(false);
	
	Ogre::TerrainGroup* terraingroup = OGRE_NEW Ogre::TerrainGroup(scenemgr, Ogre::Terrain::ALIGN_X_Z, terrainsize, worldsize);
    terraingroup->setFilenameConvention(Ogre::String("terrain"), Ogre::String("ogt"));
    terraingroup->setOrigin(Ogre::Vector3::ZERO);
		
	Ogre::Terrain* terrain = OGRE_NEW Ogre::Terrain(scenemgr);

	// terrainsettings							
	Ogre::Terrain::ImportData& imp = terraingroup->getDefaultImportSettings();	
	imp.terrainSize = terrainsize;
	imp.worldSize = worldsize;
	imp.minBatchSize = 33;
	imp.maxBatchSize = 65;

	// use float RAW heightmap as input
	imp.inputFloat = buffer;
	
	// process texture layers
	imp.layerList.resize(layercount);
	Ogre::StringVector blendmaps(layercount);
	for(int i=0;i<layercount;i++)
	{
		// load layer info
		Ogre::String sectionStr = Ogre::StringConverter::toString(i);
		Ogre::Real layerworldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", sectionStr));
		
		if (i==0)
		{			
			// no blendmap at layer 0 (baselayer)
			Ogre::String specular = terrainconfig->getSetting("specular", sectionStr);
			Ogre::String normal = terrainconfig->getSetting("normal", sectionStr);

			// add layer		
			imp.layerList[i].textureNames.push_back(specular);
			imp.layerList[i].textureNames.push_back(normal);
			imp.layerList[i].worldSize = layerworldsize;			
		}
		else
		{
			Ogre::String specular = terrainconfig->getSetting("specular", sectionStr);
			Ogre::String normal = terrainconfig->getSetting("normal", sectionStr);
			Ogre::String blend = terrainconfig->getSetting("blend", sectionStr);
		
			// add layer		
			imp.layerList[i].textureNames.push_back(specular);
			imp.layerList[i].textureNames.push_back(normal);	
			imp.layerList[i].worldSize = layerworldsize;

			blendmaps[i] = blend; 
		}
	}

	// load the terrain
	terrain->prepare(imp);
	terrain->load();	
	
	// load those blendmaps into the layers
	for(int j = 1;j < terrain->getLayerCount();j++)
	{
		Ogre::TerrainLayerBlendMap *blendmap = terrain->getLayerBlendMap(j);
		Ogre::Image img;
		img.load(blendmaps[j],"General");
		int blendmapsize = terrain->getLayerBlendMapSize();
		if(img.getWidth() != blendmapsize)
			img.resize(blendmapsize, blendmapsize);

		float *ptr = blendmap->getBlendPointer();
		Ogre::uint8 *data = static_cast<Ogre::uint8*>(img.getPixelBox().data);

		for(int bp = 0;bp < blendmapsize * blendmapsize;bp++)
			ptr[bp] = static_cast<float>(data[bp]) / 255.0f;

		blendmap->dirty();
		blendmap->update();
	}

	// create filename for writing
	int pos = heightmapfile.find_last_of('.');
	if (pos < 0)	
		heightmapfile = heightmapfile + ".ogt";
	else	
		heightmapfile = heightmapfile.substr(0, pos) + ".ogt";
			
	// save as Ogre .OGT
	terrain->save(heightmapfile);	
	Ogre::LogManager::getSingletonPtr()->logMessage(Ogre::LogMessageLevel::LML_NORMAL, heightmapfile + " successfully written.");
	
	// debug viewing (exit with CTRL+C)
	camera->setPosition(-terrainsize, 7000, -terrainsize);
	camera->lookAt(terrainsize/2,0,terrainsize/2);	
	root->startRendering();

	return 0;
}
Exemple #28
0
/** Configures the application - returns false if the user chooses to abandon configuration. */
Ogre::Root* OgreSetup::configure() {
	delete mConfigListenerContainer;
	mConfigListenerContainer = new ConfigListenerContainer();
	mConfigListenerContainer->registerConfigListener("ogre", "loglevel", sigc::mem_fun(*this, &OgreSetup::Config_ogreLogChanged), true);

	ConfigService& configService(EmberServices::getSingleton().getConfigService());
	createOgreSystem();
#ifndef BUILD_WEBEMBER
	bool success = false;
	bool suppressConfig = false;
	if (configService.itemExists("ogre", "suppressconfigdialog")) {
		suppressConfig = static_cast<bool>(configService.getValue("ogre", "suppressconfigdialog"));
	}
	try {
		success = mRoot->restoreConfig();
		if (!success || !suppressConfig) {
			success = showConfigurationDialog();
		}

	} catch (const std::exception& ex) {
		S_LOG_WARNING("Error when showing config dialog. Will try to remove ogre.cfg file and retry." << ex);
		unlink((EmberServices::getSingleton().getConfigService().getHomeDirectory(BaseDirType_CONFIG) + "ogre.cfg").c_str());
		try {
			Ogre::ConfigDialog* dlg = OGRE_NEW Ogre::ConfigDialog();
			success = mRoot->showConfigDialog(dlg);
			OGRE_DELETE dlg;
		} catch (const std::exception& ex) {
			S_LOG_CRITICAL("Could not configure Ogre. Will shut down." << ex);
		}
	}
	if (!success) {
		return nullptr;
	}

	// we start by trying to figure out what kind of resolution the user has selected, and whether full screen should be used or not
	unsigned int height = 768, width = 1024;
	bool fullscreen = false;

	parseWindowGeometry(mRoot->getRenderSystem()->getConfigOptions(), width, height, fullscreen);

	bool handleOpenGL = false;
#ifdef __APPLE__
	handleOpenGL = true;
#endif

	std::string windowId = Input::getSingleton().createWindow(width, height, fullscreen, true, true, handleOpenGL);

	mRoot->initialise(false, "Ember");
	Ogre::NameValuePairList misc;
#ifdef __APPLE__
	misc["currentGLContext"] = Ogre::String("true");
	misc["macAPI"] = Ogre::String("cocoa");
#else
//We should use "externalWindowHandle" on Windows, and "parentWindowHandle" on Linux.
#ifdef _WIN32
	misc["externalWindowHandle"] = windowId;
#else
	misc["parentWindowHandle"] = windowId;
#endif
#endif

	mRenderWindow = mRoot->createRenderWindow("MainWindow", width, height, fullscreen, &misc);

	Input::getSingleton().EventSizeChanged.connect(sigc::mem_fun(*this, &OgreSetup::input_SizeChanged));

	registerOpenGLContextFix();

	if (mSaveShadersToCache) {
		Ogre::GpuProgramManager::getSingleton().setSaveMicrocodesToCache(true);

		std::string cacheFilePath = configService.getHomeDirectory(BaseDirType_CACHE) + "/gpu-" VERSION ".cache";
		if (std::ifstream(cacheFilePath).good()) {
			try {
				auto cacheStream = mRoot->openFileStream(cacheFilePath);
				if (cacheStream) {
					Ogre::GpuProgramManager::getSingleton().loadMicrocodeCache(cacheStream);
				}
			} catch (...) {
				S_LOG_WARNING("Error when trying to open GPU cache file.");
			}
		}
	}

#else //BUILD_WEBEMBER == true
	//In webember we will disable the config dialog.
	//Also we will use fixed resolution and windowed mode.
	try {
		mRoot->restoreConfig();
	} catch (const std::exception& ex) {
		//this isn't a problem, we will set the needed functions manually.
	}
	Ogre::RenderSystem* renderer = mRoot->getRenderSystem();
#ifdef _WIN32
	//on windows, the default renderer is directX, we will force OpenGL.
	Ogre::RenderSystem* renderer = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
	if(renderer != nullptr) {
		mRoot->setRenderSystem(renderer);
	} else {
		S_LOG_WARNING("OpenGL RenderSystem not found. Starting with default RenderSystem.");
		renderer = mRoot->getRenderSystem();
	}
#endif // _WIN32
	renderer->setConfigOption("Video Mode", "800 x 600");
	renderer->setConfigOption("Full Screen", "no");

	mRoot->initialise(false, "Ember");

	Ogre::NameValuePairList options;

	if (configService.itemExists("ogre", "windowhandle")) {
		//set the owner window
		std::string windowhandle = configService.getValue("ogre", "windowhandle");
		options["parentWindowHandle"] = windowhandle;

		//put it in the top left corner
		options["top"] = "0";
		options["left"] = "0";
	}

	mRenderWindow = mRoot->createRenderWindow("Ember",800,600,false,&options);
	mOgreWindowProvider = new OgreWindowProvider(*mRenderWindow);
	Input::getSingleton().attach(mOgreWindowProvider);

#endif // BUILD_WEBEMBER

	mRenderWindow->setActive(true);
	mRenderWindow->setAutoUpdated(true);
	mRenderWindow->setVisible(true);

	setStandardValues();


	mConfigListenerContainer->registerConfigListener("ogre", "profiler", [&](const std::string& section, const std::string& key, varconf::Variable& variable) {
		if (variable.is_bool()) {
			auto* profiler = Ogre::Profiler::getSingletonPtr();
			if (profiler) {
				if ((bool) variable) {
					auto& resourceGroupMgr = Ogre::ResourceGroupManager::getSingleton();
					if (!resourceGroupMgr.resourceGroupExists("Profiler")) {
						resourceGroupMgr.addResourceLocation(OGRE_MEDIA_DIR"/packs/profiler.zip", "Zip", "Profiler", true);
						resourceGroupMgr.addResourceLocation(OGRE_MEDIA_DIR"/packs/SdkTrays.zip", "Zip", "Profiler", true);
						resourceGroupMgr.initialiseResourceGroup("Profiler");
					}
				}

				if (profiler->getEnabled() != (bool) variable) {
					profiler->reset();
					profiler->setEnabled((bool) variable);
				}
			}
		}
	});

	// Create new scene manager factory
	//mSceneManagerFactory = new EmberPagingSceneManagerFactory();

	//// Register our factory
	//mRoot->addSceneManagerFactory(mSceneManagerFactory);

	return mRoot;
}
void NativeEnginePrivate::initOgre()
{
#if !defined(NDEBUG)
    Ogre::String pluginsCfg = "plugins_d.cfg";
#else
    Ogre::String pluginsCfg = "plugins.cfg";
#endif

    Ogre::LogManager * lm = new Ogre::LogManager();
    Ogre::Log *log = lm->createLog("", true, false, false);
    log->addListener(this);

    /* Initialize Ogre */
    ogreRoot = new Ogre::Root(pluginsCfg);

    /* Set OpenGL render system on Ogre */
    Ogre::RenderSystem *renderSystem = ogreRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    if (!renderSystem)
        throw std::exception("Unable to find OpenGL Render System!");
    renderSystem->setConfigOption("Colour Depth", "32");
    renderSystem->setConfigOption("Fixed Pipeline Enabled", "Yes");
    renderSystem->setConfigOption("VSync", "No");
    ogreRoot->setRenderSystem(renderSystem);

    ogreRoot->initialise(false);

    /* Initialize the render window to use the GLWidget internally */
    Ogre::NameValuePairList params;
    params["externalGLControl"] = "true";
    params["externalGLContext"] = QString::number((uint)wglGetCurrentContext()).toStdString(); // TODO: Platform dependent
    params["externalWindowHandle"] = QString::number((uint)glWidget->winId()).toStdString();
    ogreWindow = ogreRoot->createRenderWindow("", glWidget->width(), glWidget->height(), false, &params);

    /* We don't use mip maps since our camera distance from all objects is fixed */
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);

    /* here we could load "builtin" resources, but all other resources should be controlled by c# */
    /*Ogre::ResourceGroupManager &resourceManager = Ogre::ResourceGroupManager::getSingleton();
    resourceManager.addResourceLocation("C:/Users/Sebastian/AppData/Local/EvilTemple/data.zip", "Zip", "General", true);
    resourceManager.initialiseAllResourceGroups();*/

    /* Create the actual scene manager */
    ogreRoot->addSceneManagerFactory(new SceneFactory);
    ogreRoot->addMovableObjectFactory(new GroundDiscFactory);
    sceneManager = static_cast<Scene*>(ogreRoot->createSceneManager("Scene"));
    sceneManager->resizeWindow(glWidget->width(), glWidget->height());

    /* Create and initialize the main camera */
    camera = sceneManager->getMainCamera();

    /* Create the viewport */
    viewport = ogreWindow->addViewport(camera);
    viewport->setBackgroundColour(Ogre::ColourValue(0.5, 0.5, 0.5));

    sceneManager->setAmbientLight(Ogre::ColourValue(0, 0, 0));

    /* TEST */
    /*Ogre::Entity* model = sceneManager->createEntity("meshes/pcs/pc_human_male/pc_human_male.mesh");

    Ogre::SceneNode* headNode = sceneManager->getRootSceneNode()->createChildSceneNode();
    headNode->setPosition(0, 0, 0);
    headNode->attachObject(model);

    Ogre::AnimationState *animState = model->getAnimationState("unarmed_unarmed_idle");
    animState->setEnabled(true);
    animState->setLoop(true);
    animState->setWeight(1.0f);

    sceneManager->setAmbientLight(Ogre::ColourValue(0, 0, 0));

    // Create a light
    Ogre::Light* l = sceneManager->createLight("MainLight");
    l->setType(Ogre::Light::LT_DIRECTIONAL);
    l->setDirection(-0.6324093645670703858428703903848,
                    -0.77463436252716949786709498111783,
                    0);*/

    /* /TEST */
}