Exemple #1
0
Ogre::Root* OgreEngine::startEngine()
{
    m_resources_cfg = "resources.cfg";

    activateOgreContext();

    Ogre::Root *ogreRoot = new Ogre::Root;
    Ogre::RenderSystem *renderSystem = ogreRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    ogreRoot->setRenderSystem(renderSystem);
    ogreRoot->initialise(false);

    Ogre::NameValuePairList params;

    params["externalGLControl"] = "true";
    params["currentGLContext"] = "true";

    //Finally create our window.
    m_ogreWindow = ogreRoot->createRenderWindow("OgreWindow", 1, 1, false, &params);
    m_ogreWindow->setVisible(false);
    m_ogreWindow->update(false);

    doneOgreContext();

    return ogreRoot;
}
Exemple #2
0
	void init_render_sys()
	{
		m_root = new Ogre::Root();
		m_root->setRenderSystem(m_root->getRenderSystemByName("OpenGL Rendering Subsystem"));
		m_root->initialise(false);
		m_frm = new wxFrame(0,-1,wxT(""));
		NameValuePairList a;
		a.insert(std::pair<String,String>("externalWindowHandle",StringConverter::toString( (size_t) m_frm->GetHandle() )));
		RenderSystem *sys = m_root->getRenderSystem();
		RenderWindow *m_ren = sys->_createRenderWindow(String("OgreRenderWindow_00"),1,1,false,&a);
		MaterialManager::getSingleton().initialise();
		m_frm->Show(false);
	}
Exemple #3
0
        void GraphicsManager::InitOgreRenderSystem()
        {
            if( !this->OgreBeenInitialized ) {
                Ogre::Root* OgreCore = Ogre::Root::getSingletonPtr();
                const Ogre::RenderSystemList& RSList = OgreCore->getAvailableRenderers();
                if( RSList.size() == 1 ) {
                    //Ogre::RenderSystem* temp = OgreCore->getRenderSystemByName( this->GetRenderSystemName( this->RenderSystemTypes[0] ) );
                    OgreCore->setRenderSystem( RSList[0] );
                }else{
                    //Ogre::RenderSystem* temp = OgreCore->getRenderSystemByName( this->GetRenderSystemName( this->CurrRenderSys ) );
                    OgreCore->setRenderSystem( OgreCore->getRenderSystemByName( this->GetRenderSystemName( this->CurrRenderSys ) ) );
                }

                OgreCore->initialise(false,"");
                this->OgreBeenInitialized = true;

                this->PrimaryGameWindow = new GameWindow("Primary",1,1,GameWindow::WF_Hidden);
            }
        }
Exemple #4
0
			//Funcion que inicializa la aplicacion
			int startup(){
				_root = new Ogre::Root("plugins_d.cfg");
				
				//Muestra la ventana inicial...
				
				//if(!_root->showConfigDialog()){
				//	return -1;
				//}


				// Evitan cargar la ventana inicial...
				Ogre::RenderSystem* _rs = _root->getRenderSystemByName("Direct3D9 Rendering Subsystem");
				// or use "OpenGL Rendering Subsystem"
				_root->setRenderSystem(_rs);
				_rs->setConfigOption("Full Screen", "No");
				_rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
				_rs->setConfigOption("FSAA", "0");
				_rs->setConfigOption("Floating-point mode", "Fastest");
				_rs->setConfigOption("Use Multihead", "Auto");
				_rs->setConfigOption("VSync", "No");
				_rs->setConfigOption("VSync Interval", "1");


			
				Ogre::RenderWindow* window = _root->initialise(true,"Ventana de Ogre3D");
				_sceneManager = _root->createSceneManager(Ogre::ST_GENERIC);

				
				loadResources();
				createScene();
				createCamera(window);



				_listener = new AppFrameListener(window,camera,_sceneManager);
				_root->addFrameListener(_listener);				


				//_root->startRendering();
				return 0;

				
			}
	 int startup(){
		 _root = new Ogre::Root("plugins_d.cfg");
		 /*
		 if(!_root->showConfigDialog()){
			 return -1;
		 }
		 */

		 Ogre::RenderSystem* _rs = _root->getRenderSystemByName("Direct3D9 Rendering Subsystem");
		// or use "OpenGL Rendering Subsystem"
		_root->setRenderSystem(_rs);
		_rs->setConfigOption("Full Screen", "No");
		_rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
		_rs->setConfigOption("FSAA", "0");
		_rs->setConfigOption("Floating-point mode", "Fastest");
		_rs->setConfigOption("Use Multihead", "Auto");
		_rs->setConfigOption("VSync", "No");
		_rs->setConfigOption("VSync Interval", "1");

		 Ogre::RenderWindow* window = _root->initialise(true, "Ventana Ogre");

		 _sceneManager =  _root->createSceneManager(Ogre::ST_GENERIC);

		 Ogre::Camera* camera = _sceneManager->createCamera("Camera");
		 camera->setPosition(Ogre::Vector3(0.0f,300.0f,-1000.0f));
		 camera->lookAt(Ogre::Vector3(0,0,0));
		 camera->setNearClipDistance(5);

		 Ogre::Viewport* viewport = window->addViewport(camera);
		 viewport->setBackgroundColour(Ogre::ColourValue(0.0,0.0,0.0));
		 camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()/viewport->getActualHeight()));

		 _listener = new FrameListenerProyectos(window,camera);
		 _root->addFrameListener(_listener);

		 loadResources();
		 createScene();
		 _root->startRendering();

		 return 0;
	 }
Exemple #6
0
int mainSetupAndRunOgre()
{
    Ogre::LogManager*       log_manager = 0;
    Ogre::Root*             root = 0;
#ifdef FREEORION_MACOSX
    OISInput*               ois_input_plugin = 0;
#elif defined(OGRE_STATIC_LIB)
    OISInput*               ois_input_plugin = 0;
    Ogre::OctreePlugin*     octree_plugin = 0;
    Ogre::ParticleFXPlugin* particle_fx_plugin = 0;
    Ogre::GLPlugin*         gl_plugin = 0;
#endif

    try {
        using namespace Ogre;

        log_manager = new LogManager();
        log_manager->createLog((GetUserDir() / "ogre.log").string(), true, false);

        root = new Root((GetRootDataDir() / "ogre_plugins.cfg").string());

        // this line is needed on some Linux systems which otherwise will crash with
        // errors about GLX_icon.png being missing.
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation((ClientUI::ArtDir() / ".").string(),
                                                                       "FileSystem", "General");

#if defined(OGRE_STATIC_LIB)
        octree_plugin = new Ogre::OctreePlugin;
        particle_fx_plugin = new Ogre::ParticleFXPlugin;
        gl_plugin = new Ogre::GLPlugin;
        root->installPlugin(octree_plugin);
        root->installPlugin(particle_fx_plugin);
        root->installPlugin(gl_plugin);
#endif


        RenderSystem* selected_render_system = root->getRenderSystemByName("OpenGL Rendering Subsystem");
        if (selected_render_system == 0)
            throw std::runtime_error("Failed to find an Ogre GL render system.");

        root->setRenderSystem(selected_render_system);

        int colour_depth = GetOptionsDB().Get<int>("color-depth");
        bool fullscreen = GetOptionsDB().Get<bool>("fullscreen");
        std::pair<int, int> width_height = HumanClientApp::GetWindowWidthHeight(selected_render_system);
        int width(width_height.first), height(width_height.second);

        selected_render_system->setConfigOption("Full Screen", fullscreen ? "Yes" : "No");
        std::string video_mode_str =
            boost::io::str(boost::format("%1% x %2% @ %3%-bit colour") %
                           width %
                           height %
                           colour_depth);
        selected_render_system->setConfigOption("Video Mode", video_mode_str);

        RenderWindow* window = root->initialise(true, "FreeOrion " + FreeOrionVersionString());

#ifdef FREEORION_WIN32
#  ifdef IDI_ICON1
        // set window icon to embedded application icon
        HWND hwnd;
        window->getCustomAttribute("WINDOW", &hwnd);
        HINSTANCE hInst = (HINSTANCE)GetModuleHandle(NULL);
        SetClassLong (hwnd, GCL_HICON,
            (LONG)LoadIcon (hInst, MAKEINTRESOURCE (IDI_ICON1)));
#  endif
#endif

        SceneManager* scene_manager = root->createSceneManager("OctreeSceneManager", "SceneMgr");

        Camera* camera = scene_manager->createCamera("Camera");
        camera->setPosition(Vector3(0, 0, 500));    // Position it at 500 in Z direction
        camera->lookAt(Vector3(0, 0, -300));        // Look back along -Z
        camera->setNearClipDistance(5);

        Viewport* viewport = window->addViewport(camera);
        viewport->setBackgroundColour(ColourValue(0, 0, 0));

        //EntityRenderer entity_renderer(scene_manager);

        parse::init();

        HumanClientApp app(root, window, scene_manager, camera, viewport, (GetRootDataDir() / "OISInput.cfg").string());

#ifdef FREEORION_MACOSX
        ois_input_plugin = new OISInput;
        root->installPlugin(ois_input_plugin);
#elif defined(OGRE_STATIC_LIB)
        ois_input_plugin = new OISInput;
        root->installPlugin(ois_input_plugin);
#else
        root->loadPlugin(OGRE_INPUT_PLUGIN_NAME);
#endif

        if (GetOptionsDB().Get<bool>("quickstart")) {
            // immediately start the server, establish network connections, and
            // go into a single player game, using default universe options (a
            // standard quickstart, without requiring the user to click the
            // quickstart button).
            app.NewSinglePlayerGame(true);  // acceptable to call before app()
        }

        std::string load_filename = GetOptionsDB().Get<std::string>("load");
        if (load_filename != "") {
            // immediately start the server, establish network connections, and
            // go into a single player game, loading the indicated file
            // (without requiring the user to click the load button).
            app.LoadSinglePlayerGame(load_filename);  // acceptable to call before app()
        }

        // run rendering loop
        app();  // calls GUI::operator() which calls OgreGUI::Run() which starts rendering loop

    } catch (const HumanClientApp::CleanQuit&) {
        // do nothing
        std::cout << "mainSetupAndRunOgre caught CleanQuit" << std::endl;
    } catch (const std::invalid_argument& e) {
        Logger().errorStream() << "main() caught exception(std::invalid_argument): " << e.what();
        std::cerr << "main() caught exception(std::invalid_arg): " << e.what() << std::endl;
    } catch (const std::runtime_error& e) {
        Logger().errorStream() << "main() caught exception(std::runtime_error): " << e.what();
        std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl;
    } catch (const  boost::io::format_error& e) {
        Logger().errorStream() << "main() caught exception(boost::io::format_error): " << e.what();
        std::cerr << "main() caught exception(boost::io::format_error): " << e.what() << std::endl;
    } catch (const GG::ExceptionBase& e) {
        Logger().errorStream() << "main() caught exception(" << e.type() << "): " << e.what();
        std::cerr << "main() caught exception(" << e.type() << "): " << e.what() << std::endl;
    } catch (const std::exception& e) {
        Logger().errorStream() << "main() caught exception(std::exception): " << e.what();
        std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl;
    } catch (...) {
        Logger().errorStream() << "main() caught unknown exception.";
        std::cerr << "main() caught unknown exception." << std::endl;
    }

    if (root) {
#ifdef FREEORION_MACOSX
        root->uninstallPlugin(ois_input_plugin);
        delete ois_input_plugin;
#elif defined(OGRE_STATIC_LIB)
        root->uninstallPlugin(ois_input_plugin);
        root->uninstallPlugin(octree_plugin);
        root->uninstallPlugin(particle_fx_plugin);
        root->uninstallPlugin(gl_plugin);
        delete ois_input_plugin;
        delete octree_plugin;
        delete particle_fx_plugin;
        delete gl_plugin;
#else
        root->unloadPlugin(OGRE_INPUT_PLUGIN_NAME);
#endif
        delete root;
    }

    if (log_manager)
        delete log_manager;

    return 0;
}
// 初始化
VOID CEngineInterface::Initial(VOID* pParam)
{
#if (_MSC_VER >= 1400)
	setlocale( LC_CTYPE, "" );
#endif

	//---------------------------------------------------------
	//取得渲染窗口句柄
	KLAssert(pParam);
	HWND hMainWnd = *((HWND*)pParam);
	g_hMainWnd = hMainWnd;

	g_pVaribleSys = (tVariableSystem*)g_theKernel.GetNode("bin\\var");
	KLAssert(g_pVaribleSys);

	g_pEventSys = (tEventSystem*)g_theKernel.GetNode("bin\\event");
	KLAssert(g_pEventSys);

	//---------------------------------------------------------

	// 改变加载方式
	// 屏掉下边这句了by czg 200911-30
	// CFairyScriptResGet::EnableResDynamicLoad(false);
	// 影响场景效果Z
	Ogre::SystemSetting::forcePixelShader(false);

	// 初始化KylinSystem
	m_pFairySystem->init("Resources.cfg", "", "", "Engine.log");	// Resources

	//---------------------------------------------------------
	// 加载OGRE插件
	g_pDebuger = (tDebuger*)g_theKernel.GetNode("bin\\debuger");

	g_pSoundSystem = (tSoundSystem*)g_theKernel.GetNode("bin\\snd");
	KLAssert(g_pSoundSystem);

	g_pWorldSystem = (tWorldSystem*)g_theKernel.GetNode("bin\\worldman");
	KLAssert(g_pWorldSystem);

	g_pTimeSystem = (tTimeSystem*)g_theKernel.GetNode("bin\\time");
	KLAssert(g_pTimeSystem);

	g_pResourceProvider = (tResourceProvider*)g_theKernel.GetNode("bin\\resprovider");
	KLAssert(g_pResourceProvider);
	g_pDataBase = (tDataBaseSystem*)g_theKernel.GetNode("bin\\dbc");
	KLAssert(g_pDataBase);

	STRING str = g_pVaribleSys->GetAs_String("Gfx_API");
	Ogre::Root* pTheRoot = &(Ogre::Root::getSingleton());
	// 选择渲染系统
	if(str == "Direct3D")
	{
#ifdef  USEOGRELIB
		Ogre::InstallD3D9Plugin();
#else
		pTheRoot->loadPlugin("RenderSystem_Direct3D9.dll");
		pTheRoot->setRenderSystem(pTheRoot->getRenderSystemByName("Direct3D9 Rendering Subsystem"));
#endif
	
	}
	else if(str == "OpenGL")
	{
#ifdef  USEOGRELIB
	
#else
		pTheRoot->loadPlugin("RenderSystem_GL.dll");
		pTheRoot->setRenderSystem(pTheRoot->getRenderSystemByName("OpenGL Rendering Subsystem"));
#endif
	}
	else 
		KLThrow("UnKnown RenderSystem!");
	// 加载其他插件
#ifdef  USEOGRELIB
	Ogre::InstallParticleFXPlugin();
	Ogre::InstallParticleFX2Plugin();
	Ogre::InstallOctreeScenePlugin();
	Ogre::InstallCgProgramManagerPlugin();
#else
	pTheRoot->loadPlugin("Plugin_ParticleFX.dll");
	pTheRoot->loadPlugin("Plugin_ParticleFX2.dll");
	pTheRoot->loadPlugin("Plugin_OctreeSceneManager.dll");
	pTheRoot->loadPlugin("Plugin_CgProgramManager.dll");
#endif
	

	// 分析资源
	ScriptParsingListener listener;
	try 
	{
		// 传入渲染窗口句柄
		Ogre::NameValuePairList ViewSetting;
		INT nFSAA = g_pVaribleSys->GetAs_Int(szFSAAVar);
		INT nVsync = g_pVaribleSys->GetAs_Int(szvsyncVar);

		switch(nFSAA)
		{
		case 0:
			ViewSetting["FSAA"]  = Ogre::StringConverter::toString(0);
			break;
		case 1:
			ViewSetting["FSAA"]  = Ogre::StringConverter::toString(2);
			break;
		case 2:
			ViewSetting["FSAA"]  = Ogre::StringConverter::toString(4);
			break;
		default:
			ViewSetting["FSAA"]  = Ogre::StringConverter::toString(0);
			break;
		}

		if(nVsync == 1)
			ViewSetting["vsync"] = "true";
		else
			ViewSetting["vsync"] = "false";

		m_pFairySystem->setup((Fairy::ulong)(UINT_PTR)g_hMainWnd, &ViewSetting);

		// 关闭OGRE图标
		m_pFairySystem->getFrameStatsListener()->showLogoPanel(FALSE);
		
		// 状态板
		m_pFairySystem->getFrameStatsListener()->showStatPanel(FALSE);

		// 创建射线交集
		m_pRaySceneQuery = m_pFairySystem->getSceneManager()->createRayQuery(Ogre::Ray());
        m_pRaySceneQuery->setSortByDistance(TRUE);

		//---------------------------------------------------------
		// 设置DebugPanel
		m_pDebugPanel = new CDebugPanel(Ogre::OverlayManager::getSingleton().getByName("WXSJ/DebugOverlay"),		// CJSH
										Ogre::OverlayManager::getSingleton().getOverlayElement("WXSJ/StatPanel"), 
										Ogre::OverlayManager::getSingleton().getOverlayElement("WXSJ/HitObjPanel"), 
										Ogre::OverlayManager::getSingleton().getOverlayElement("WXSJ/HitObjText"), 
										m_pFairySystem->getRenderWindow());

		//---------------------------------------------------------
		// 创建摄像机
		{
			// 设置摄像机
			// 取得环境变量
		
			BOOL bHave;
			FLOAT fCamera_MinDistance = g_pVaribleSys->GetAs_Float("Camera_MinDistance", &bHave);
			if(bHave) 
				CCamera_Scene::MIN_DISTANCE = fCamera_MinDistance;

			FLOAT fCamera_MaxDistance = g_pVaribleSys->GetAs_Float("Camera_MaxDistance", &bHave);
			if(bHave)
				CCamera_Scene::MAX_DISTANCE = fCamera_MaxDistance;

			FLOAT fCamera_Pitch = g_pVaribleSys->GetAs_Float("Camera_Pitch", &bHave);
			if(bHave) 
				CCamera_Scene::STATIC_PITCH = -fCamera_Pitch * KLU_PI / 180.0f;

			FLOAT fCamera_PitchApproch = g_pVaribleSys->GetAs_Float("Camera_PitchApproch", &bHave);
			if(bHave) 
				CCamera_Scene::APPROCH_PITCH = -fCamera_PitchApproch * KLU_PI / 180.0f;

/*
			// 摄象机偏移量
			INT fCamera_Offset = g_pVaribleSys->GetAs_Float("Camera_Varible_Offset", &bHave);
			if( bHave )
//				Camera_SetOffset( 0.0f, m_fVerticalOffset );
				m_fVerticalOffset = fCamera_Offset;
*/

/*
			fCamera_Offset = g_pVaribleSys->GetAs_Float("Camera_Parallel_Offset", &bHave);
			if( bHave )
				m_fSaveParallelOffset = fCamera_Offset;
*/
		}

		m_pCamera_CharView = new CCamera_CharSel(m_pFairySystem->getCamera());
		m_pCamera_Scene = new CCamera_Scene(m_pFairySystem->getCamera());
		m_pCamera_Scene->SetDistance(CCamera_Scene::MAX_DISTANCE);

		m_pCamera_Current = m_pCamera_CharView;

		//--------------------------------------------
		// 初始化PostFilter系统
		m_pPostFilterManager = m_pFairySystem->getPostFilterManager();
		// 注册所有全局渲染器
		Fairy::registerAllPostFilterFactories(m_pPostFilterManager);
		m_pPostFilterManager->createPostFilter("Floodlighting", m_pFairySystem->getViewport());
		m_pPostFilterManager->createPostFilter("Bloom", m_pFairySystem->getViewport());
		m_pPostFilterManager->createPostFilter("HeatVision", m_pFairySystem->getViewport());
		m_pPostFilterManager->createPostFilter("Fade", m_pFairySystem->getViewport());
		m_pPostFilterManager->createPostFilter("MotionBlur", m_pFairySystem->getViewport());

		//--------------------------------------------
		// 设置特效系统的声音播放函数
		Fairy::LogicModel::SetPlaySoundFuncton((OnPlaySound)(g_pSoundSystem->GetPlaySoundFunc()));
		Fairy::LogicModel::SetStopSoundFunction((OnStopSound)(g_pSoundSystem->GetStopSoundFunc()));
		Fairy::BulletSystem::SetPlaySoundFuncton((OnPlaySound)(g_pSoundSystem->GetPlaySoundFunc()));
		Fairy::BulletSystem::SetStopSoundFunction((OnStopSound)(g_pSoundSystem->GetStopSoundFunc()));
		Fairy::LogicModel::SetGetHeightInWorldListener((GetHeightInWorld)(g_pWorldSystem->GetTerrainHeightFunc()));

		// 初始化 fake obeject manager
		m_pFakeObjectManager = new CFakeObjectEntityManager;
		m_pFakeObjectManager->Initial();

//		Fairy::Effect::setDefaultIterativeInterval(0.01f);
		Ogre::ParticleSystem::setDefaultIterationInterval(0.033f);

		// 系统设置接口挂接变量控制系统
		g_pEventSys->RegisterEventHandle("VARIABLE_CHANGED",_OnVariableChangedEvent);

		// 恢复上次颜色设置
		g_pEventSys->PushEvent(GE_VARIABLE_CHANGED, sz32BitTexturesVar, g_pVaribleSys->GetAs_String(sz32BitTexturesVar).c_str());


//		Ogre::TextureManager::getSingleton().setDefaultNumMipmaps( 1 );


		// 加载人物阴影配置
		BOOL bHave;
		INT nHumanLightmap = g_pVaribleSys->GetAs_Float(szShadowTechniqueVar, &bHave );
		if( bHave )
			Scene_SetShadowTechnique( (BOOL)nHumanLightmap );

		// 加载全局泛光配置
		INT nFullScreenLight = g_pVaribleSys->GetAs_Float( szPostFilterEnabledVar, &bHave );
		if( bHave )
			Scene_SetPostFilterEnabled( (BOOL)nFullScreenLight );

		//初始化小地图探灯功能
		m_pMapLight = new CUIMapLight;
		m_pMapLight->Initial();

	} 
	catch(const Ogre::Exception& e)
	{
        BOOL rethrow = TRUE;

        if (e.getNumber() == Ogre::Exception::ERR_DUPLICATE_ITEM)
        {
            if (e.getSource() == "ResourceManager::add")
            {
                if (Ogre::StringUtil::endsWith(listener._scriptName, ".material", TRUE))
                {
                    char materialName[256];
                    if (sscanf(e.getDescription().c_str(), "Resource with the name %255s already exists.", materialName) == 1)
                    {
                        Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(materialName);
                        if (!material.isNull())
                        {
                            char message[1024];

                            Ogre::StringVectorPtr currentNames = Fairy::findResourceFilenames(listener._groupName, listener._scriptName);
                            const Ogre::String& currentName = currentNames.isNull() || currentNames->empty() ? listener._scriptName : currentNames->front();
                            if (material->getOrigin().empty())
                            {
								_snprintf(message, 1024,
										("Predefined material \"%s\" duplicated in file \"%s\", the application will exit."),
                                        material->getName().c_str(), currentName.c_str());
                            }
                            else
                            {
                                Ogre::StringVectorPtr originNames = Fairy::findResourceFilenames(material->getGroup(), material->getOrigin());
                                const Ogre::String& originName = originNames.isNull() || originNames->empty() ? material->getOrigin() : originNames->front();
                                if (currentName == originName)
                                {
									_snprintf(message, 1024,
												("The material \"%s\" occuring in the file \"%s\" more than once, the application will exit."),
			                                    material->getName().c_str(), currentName.c_str());
                                }
                                else
                                {
									_snprintf(message, 1024,
											("Duplicate material \"%s\" in files \"%s\" and \"%s\", the application will exit."),
                                            material->getName().c_str(), currentName.c_str(), originName.c_str());
                                }
                            }

							KLThrow("Ogre::%s", message);
                        }
                    }
                }
            }
		}
		
		throw;
	}
}
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 #9
0
int mainSetupAndRunOgre() {
    Ogre::LogManager*       log_manager = 0;
    Ogre::Root*             root = 0;
    OISInput*               ois_input_plugin = 0;
#ifdef OGRE_STATIC_LIB
    Ogre::OctreePlugin*     octree_plugin = 0;
    Ogre::ParticleFXPlugin* particle_fx_plugin = 0;
    Ogre::GLPlugin*         gl_plugin = 0;
#endif

    try {
        using namespace Ogre;
        log_manager = new LogManager();

#ifndef FREEORION_WIN32
        log_manager->createLog((GetUserDir() / "ogre.log").string(), true, false);
        root = new Root((GetRootDataDir() / "ogre_plugins.cfg").string());
        // this line is needed on some Linux systems which otherwise will crash with
        // errors about GLX_icon.png being missing.
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation((ClientUI::ArtDir() / ".").string(),
                                                                       "FileSystem", "General");
#else
        boost::filesystem::path::string_type file_native = (GetUserDir() / "ogre.log").native();
        std::string ogre_log_file;
        utf8::utf16to8(file_native.begin(), file_native.end(), std::back_inserter(ogre_log_file));
        log_manager->createLog(ogre_log_file, true, false);

        // for some reason, for this file, the built-in path conversion seems to work properly
        std::string plugins_cfg_file = (GetRootDataDir() / "ogre_plugins.cfg").string();
        root = new Root(plugins_cfg_file);
#endif

#if defined(OGRE_STATIC_LIB)
        octree_plugin = new Ogre::OctreePlugin;
        particle_fx_plugin = new Ogre::ParticleFXPlugin;
        gl_plugin = new Ogre::GLPlugin;
        root->installPlugin(octree_plugin);
        root->installPlugin(particle_fx_plugin);
        root->installPlugin(gl_plugin);
#endif


        RenderSystem* selected_render_system = root->getRenderSystemByName("OpenGL Rendering Subsystem");
        if (!selected_render_system)
            throw std::runtime_error("Failed to find an Ogre GL render system.");

        root->setRenderSystem(selected_render_system);

        int colour_depth = GetOptionsDB().Get<int>("color-depth");
        bool fullscreen = GetOptionsDB().Get<bool>("fullscreen");
        std::pair<int, int> width_height = HumanClientApp::GetWindowWidthHeight(selected_render_system);
        int width(width_height.first), height(width_height.second);
        std::pair<int, int> left_top = HumanClientApp::GetWindowLeftTop();
        int left(left_top.first), top(left_top.second);

        root->initialise(false);

        Ogre::NameValuePairList misc_window_params;
        misc_window_params["title"] = "FreeOrion " + FreeOrionVersionString();
        misc_window_params["colourDepth"] = boost::lexical_cast<std::string>(colour_depth);
        misc_window_params["left"] = boost::lexical_cast<std::string>(left);
        misc_window_params["top"] = boost::lexical_cast<std::string>(top);
        misc_window_params["macAPI"] = "carbon";
        misc_window_params["border"] = "resize";
        if (fullscreen)
            misc_window_params["monitorIndex"] = boost::lexical_cast<std::string>(
                GetOptionsDB().Get<int>("fullscreen-monitor-id"));

        RenderWindow* window = root->createRenderWindow("FreeOrion " + FreeOrionVersionString(),
                                                        width, height, fullscreen, &misc_window_params);

#ifdef FREEORION_WIN32
#  ifdef IDI_ICON1
        // set window icon to embedded application icon
        HWND hwnd;
        window->getCustomAttribute("WINDOW", &hwnd);
        HINSTANCE hInst = (HINSTANCE)GetModuleHandle(NULL);
        SetClassLong (hwnd, GCL_HICON,
            (LONG)LoadIcon (hInst, MAKEINTRESOURCE (IDI_ICON1)));
#  endif
#endif

        SceneManager* scene_manager = root->createSceneManager("OctreeSceneManager", "SceneMgr");

        Camera* camera = scene_manager->createCamera("Camera");

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

        Viewport* viewport = window->addViewport(camera);
        viewport->setBackgroundColour(ColourValue(0, 0, 0));

        //EntityRenderer entity_renderer(scene_manager);

        parse::init();
        HumanClientApp app(root, window, scene_manager, camera, viewport, GetRootDataDir() / "OISInput.cfg");


        ois_input_plugin = new OISInput;
        ois_input_plugin->SetRenderWindow(window);
        root->installPlugin(ois_input_plugin);


        if (GetOptionsDB().Get<bool>("quickstart")) {
            // immediately start the server, establish network connections, and
            // go into a single player game, using default universe options (a
            // standard quickstart, without requiring the user to click the
            // quickstart button).
            app.NewSinglePlayerGame(true);  // acceptable to call before app()
        }

        std::string load_filename = GetOptionsDB().Get<std::string>("load");
        if (!load_filename.empty()) {
            // immediately start the server, establish network connections, and
            // go into a single player game, loading the indicated file
            // (without requiring the user to click the load button).
            app.LoadSinglePlayerGame(load_filename);  // acceptable to call before app()
        }

        // run rendering loop
        app();  // calls GUI::operator() which calls OgreGUI::Run() which starts rendering loop

    } catch (const HumanClientApp::CleanQuit&) {
        // do nothing
        std::cout << "mainSetupAndRunOgre caught CleanQuit" << std::endl;
    } catch (const std::invalid_argument& e) {
        Logger().errorStream() << "main() caught exception(std::invalid_argument): " << e.what();
        std::cerr << "main() caught exception(std::invalid_arg): " << e.what() << std::endl;
    } catch (const std::runtime_error& e) {
        Logger().errorStream() << "main() caught exception(std::runtime_error): " << e.what();
        std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl;
    } catch (const  boost::io::format_error& e) {
        Logger().errorStream() << "main() caught exception(boost::io::format_error): " << e.what();
        std::cerr << "main() caught exception(boost::io::format_error): " << e.what() << std::endl;
    } catch (const GG::ExceptionBase& e) {
        Logger().errorStream() << "main() caught exception(" << e.type() << "): " << e.what();
        std::cerr << "main() caught exception(" << e.type() << "): " << e.what() << std::endl;
    } catch (const std::exception& e) {
        Logger().errorStream() << "main() caught exception(std::exception): " << e.what();
        std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl;
    } catch (...) {
        Logger().errorStream() << "main() caught unknown exception.";
        std::cerr << "main() caught unknown exception." << std::endl;
    }

    if (root) {
        root->uninstallPlugin(ois_input_plugin);
        delete ois_input_plugin;

#ifdef OGRE_STATIC_LIB
        root->uninstallPlugin(octree_plugin);
        root->uninstallPlugin(particle_fx_plugin);
        root->uninstallPlugin(gl_plugin);
        delete octree_plugin;
        delete particle_fx_plugin;
        delete gl_plugin;
#endif

        delete root;
    }

    if (log_manager)
        delete log_manager;

    return 0;
}