Пример #1
0
void ModelMountTestCase::testModelMountScaling()
{
	Ogre::Root root;
	Ogre::SceneManager* sceneManager = root.createSceneManager(Ogre::ST_GENERIC);

	TestModel model(*sceneManager);

	//First test with a straight forward case.
	Ogre::SceneNode* node = sceneManager->getRootSceneNode()->createChildSceneNode();
	//We get an error when it's destroyed. So we don't destroy it.
	SceneNodeProvider* nodeProvider = new SceneNodeProvider(node, nullptr);
	Model::ModelMount mount(model, nodeProvider);
	scaleAndTestMount(model, mount, nodeProvider->getNode());

	//Test with the parent node being scaled
	node->setScale(Ogre::Vector3(3.0f, 0.2f, 200.0f));
	Ogre::SceneNode* subNode = node->createChildSceneNode();
	nodeProvider = new SceneNodeProvider(subNode, nullptr);
	Model::ModelMount mount2(model, nodeProvider);
	scaleAndTestMount(model, mount2, nodeProvider->getNode());

	//Test with the parent node being scaled and rotated
	node->setScale(Ogre::Vector3(3.0f, 0.2f, 200.0f));
	node->yaw(Ogre::Degree(42));
	node->pitch(Ogre::Degree(76));
	node->roll(Ogre::Degree(98));
	subNode = node->createChildSceneNode();
	nodeProvider = new SceneNodeProvider(subNode, nullptr);
	Model::ModelMount mount3(model, nodeProvider);
	scaleAndTestMount(model, mount3, nodeProvider->getNode());
}
Пример #2
0
void
TestScene5::runOgre()
{
	// initialize framework & open window
	Ogre::Root* root = new Ogre::Root();
	root->restoreConfig();
	root->initialise(false);
	auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false);
	auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
	// adjust camera
	auto cam1 = sceneMgr->createCamera("cam1");
	auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
	cam1->setNearClipDistance(5);
	camNode1->attachObject(cam1);
	camNode1->setPosition(100, 100, 100);
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	window->addViewport(cam1);
	// load & integrate model
	root->addResourceLocation("./resources/Ogre", "FileSystem");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	auto model = sceneMgr->createEntity("model", "alexandria.mesh");
	auto modelNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
	modelNode->attachObject(model);
	// position model
	modelNode->setPosition(-100, -100, -100);
	// loop
	runOgreLoop(root);
}
	 int startup(){
		 _root = new Ogre::Root("plugins_d.cfg");
		 if(!_root->showConfigDialog()){
			 return -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(500,100,500));
		 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;
	 }
Пример #4
0
int main(int argc, char* argv[]){
    cout << "Test Ogre Program blaha" << endl;

    //Relative to where its executed from, not binary location
    Ogre::Root *mRoot = new Ogre::Root("configs/plugins.cfg","configs/config.cfg","logs/main.log");
    if(!(mRoot->restoreConfig() || mRoot->showConfigDialog())){
        delete mRoot;
        return -1;
    }

    // setup resources
    // Only add the minimally required resource locations to load up the Ogre head mesh
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/Users/jgrey/OgreSDK/Media/materials/programs", "FileSystem", "General");
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/Users/jgrey/OgreSDK/Media/materials/programs/GLSL", "FileSystem", "General");
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/Users/jgrey/OgreSDK/Media/materials/scripts", "FileSystem", "General");
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/Users/jgrey/OgreSDK/Media/materials/textures", "FileSystem", "General");
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/Users/jgrey/OgreSDK/Media/models", "FileSystem", "General");

    
    //Create the window
    Ogre::RenderWindow *mWindow = mRoot->initialise(true, "initial Render Window");
    Ogre::SceneManager *sceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC);

    Ogre::Camera *camera = sceneManager->createCamera("PlayerCam");

    camera->setPosition(Ogre::Vector3(0,0,80));
    camera->lookAt(Ogre::Vector3(0,0,-300));
    camera->setNearClipDistance(5);
    
    Ogre::Viewport* vp = mWindow->addViewport(camera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0,0));
    camera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));

    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    
    Ogre::Entity* ogreHead = sceneManager->createEntity("Head","ogreHead.mesh");
    Ogre::SceneNode* headNode = sceneManager->getRootSceneNode()->createChildSceneNode();
    headNode->attachObject(ogreHead);

    sceneManager->setAmbientLight(Ogre::ColourValue(0.5,0.5,0.5));
    
    
    
    
    //Run the system
    bool continueRunning = true;
    while(continueRunning){
        mRoot->renderOneFrame();
        headNode->rotate(Ogre::Vector3(0,1,0),Ogre::Radian(0.005));
        if(mWindow->isClosed()){
            continueRunning = false;
        }

    }
    
    
    delete mRoot;
}
Пример #5
0
		int startup(){
			_root = new Ogre::Root("plugins_d.cfg");

			if(!_root->showConfigDialog()){
				return -1;
			}

			_window = _root->initialise(true,"Collision Object Exporter");
			_sceneManager = _root->createSceneManager(Ogre::ST_GENERIC);
	
			loadResources();
			createScene();
			_root->startRendering();
			return 0;
		}
Пример #6
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;

				
			}
Пример #7
0
void
TestScene12::runOgre()
{
	// initialize framework & open window
	Ogre::Root* root = new Ogre::Root();
	root->restoreConfig();
	root->initialise(false);
	auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false);
	auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
	// adjust camera
	auto cam1 = sceneMgr->createCamera("cam1");
	auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
	cam1->setNearClipDistance(5);
	camNode1->attachObject(cam1);
	camNode1->setPosition(Ogre::Vector3(100, 100, 100));
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	window->addViewport(cam1);
	// load & integrate model
	root->addResourceLocation("./resources/Ogre", "FileSystem");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	Mesh_Cube M(1);
	M.createMesh("cube");
	Ogre::SceneNode* groups[ROWS];
	std::list<Ogre::SceneNode*> nodes;
	for (int i = 0; i < ROWS; i++)
	{
		groups[i] = sceneMgr->getRootSceneNode()->createChildSceneNode();
		nodes.push_back(groups[i]);
	}
	for (int i = 0; i < ROWS * COLS; i++)
	{
		auto node = groups[i % ROWS]->createChildSceneNode();
		node->attachObject(sceneMgr->createEntity(std::string("model") + boost::lexical_cast<std::string>(i), "cube"));
		node->setPosition(
			camNode1->getOrientation() * -Ogre::Vector3::UNIT_X * LEFT(i)
			+ camNode1->getOrientation() * Ogre::Vector3::UNIT_Y * UP(i)
		);
	}
	root->addFrameListener(new MoveObjectTask_Ogre12(nodes));
	// loop
	runOgreLoop(root);
}
Пример #8
0
void
TestScene3::runOgre()
{
	// initialize framework & open window
	Ogre::Root* root = new Ogre::Root();
	root->restoreConfig();
	root->initialise(false);
	auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false);
	auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
	// adjust camera
	auto cam1 = sceneMgr->createCamera("cam1");
	auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
	cam1->setNearClipDistance(5);
	camNode1->attachObject(cam1);
	camNode1->setPosition(100, 100, 100);
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	window->addViewport(cam1);
	// loop
	runOgreLoop(root);
}
Пример #9
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;
	 }
Пример #10
0
    /**
     * This is the most basic "triangle" example, done as a Scene in Ogre.
     */
    Ogre::SceneManager* createTriangleScene() {
        Ogre::SceneManager* scene = mRoot->createSceneManager(Ogre::ST_GENERIC);

        // Configure camera (~ view & projection transforms, i.e. gluLookAt + glOrtho)
        Ogre::Camera* camera = scene->createCamera("MainCamera"); // We can use an arbitrary name here
        camera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
        camera->setOrthoWindow(2, 2);              // ~ glOrtho(-1, 1, -1, 1)
        camera->setAspectRatio((float) mWindow->getWidth() / mWindow->getHeight());
        camera->setNearClipDistance(0.5);
        camera->setPosition(Ogre::Vector3(0,0,1)); // Move camera away from (0, 0, 0), otherwise the triangle at z=0 will be clipped

        // Now add some geometry to the scene
        Ogre::ManualObject* triangle = scene->createManualObject("Triangle");

        // ~ glBegin, glVertex, glEnd
        // "BaseWhiteNoLighting" is a built-in name for a basic non-lit material
        triangle->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);
        triangle->position(0, 0.5, 0);            // ~ glVertex.
                                                  // Contrary to OpenGL we *first* must create the vertex
        triangle->colour(Ogre::ColourValue::Red); // .. and then provide its attributes such as color (~ glColor)
        triangle->position(-0.5, -0.5, 0);
        triangle->colour(Ogre::ColourValue::Green);
        triangle->position(0.5, -0.5, 0);
        triangle->colour(Ogre::ColourValue::Blue);
        triangle->end();

        // Add the created triangle object to the scene graph
        // For this we create a SceneNode object, which will combine information about
        // the object's geometry with its modeling transform
        // (see frameRenderingQueued to understand how to rotate the triangle by changing this transform)
        scene->getRootSceneNode()->createChildSceneNode("Triangle")->attachObject(triangle);

        // Exercise 1: Create new object, add vertices, attach the object to a new SceneNode
        // ...

        return scene;
    }
Пример #11
0
void CSceneEditorView::EngineSetup(void)
{
	Ogre::Root *Root = ((CSceneEditorApp*)AfxGetApp())->m_Engine->GetRoot();
	m_SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "SceneEditor");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("SceneEditor");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("SceneEditor", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
	m_Camera = m_SceneManager->createCamera("Camera");
	m_Camera->setPosition(Ogre::Vector3(1683, 50, 2116));
    m_Camera->lookAt(Ogre::Vector3(0, 0, 0));
    m_Camera->setNearClipDistance(0.1);
    m_Camera->setFarClipDistance(50000);
 
    if (m_Root->getRenderSystem()->getCapabilities()->hasCapability(Ogre::RSC_INFINITE_FAR_PLANE))
    {
        m_Camera->setFarClipDistance(0);   // enable infinite far clip distance if we can
    }

	m_Camera->setAutoTracking(false);
	m_Camera->setFixedYawAxis(true);
	m_Camera->yaw(Ogre::Radian(0));
	m_Camera->pitch(Ogre::Radian(0));

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = m_SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");
 
	m_SceneManager->setAmbientLight(Ogre::ColourValue(0.2, 0.2, 0.2));

	//Create viewport
	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
	
	m_SceneManager->setSkyDome(true, "Examples/CloudySky", 5, 8);
	Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_ANISOTROPIC);
    Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(7);
 
    Ogre::Vector3 lightdir(0.55, -0.3, 0.75);
    lightdir.normalise();
 
	Ogre::Light* light = m_SceneManager->createLight("tstLight");
    light->setType(Ogre::Light::LT_DIRECTIONAL);
    light->setDirection(lightdir);
    light->setDiffuseColour(Ogre::ColourValue::White);
    light->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));
 
	m_SceneManager->setAmbientLight(Ogre::ColourValue(0.2, 0.2, 0.2));
	
	mTerrainGlobals = OGRE_NEW Ogre::TerrainGlobalOptions();
	mTerrainGroup = OGRE_NEW Ogre::TerrainGroup(m_SceneManager, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f);
    mTerrainGroup->setFilenameConvention(Ogre::String("Terrain"), Ogre::String("dat"));
    mTerrainGroup->setOrigin(Ogre::Vector3::ZERO);
 
    configureTerrainDefaults(light);
 
    for (long x = 0; x <= 0; ++x)
        for (long y = 0; y <= 0; ++y)
            defineTerrain(x, y);
 
    // sync load since we want everything in place when we start
    mTerrainGroup->loadAllTerrains(true);
 
    if (mTerrainsImported)
    {
        Ogre::TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator();
        while(ti.hasMoreElements())
        {
            Ogre::Terrain* t = ti.getNext()->instance;
            initBlendMaps(t);
        }
    }
 
    mTerrainGroup->freeTemporaryResources();
}
void application::choose_scene_mgr()
{
    scene_mgr = root->createSceneManager(Ogre::ST_GENERIC);
    overlay = new Ogre::OverlaySystem();
    scene_mgr->addRenderQueueListener(overlay);
}
void CManualObjectView::EngineSetup(void)
{
	Ogre::Root *Root = ((CManualObjectApp*)AfxGetApp())->m_Engine->GetRoot();
	m_SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "m_ManualObject");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("m_ManualObject");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("m_ManualObject", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = m_SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(200.0, 50.0, 100.0));
	m_Camera->lookAt(0.0, 0.0, 0.0);

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = m_SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(1.0f, 1.0f, 1.0f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	CreateManualObject();
	Ogre::AxisAlignedBox Box = m_ManualObject->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();
	m_Camera->lookAt(Center);
	m_Camera->setPosition(300, 100, 200);

//	m_Camera->setPolygonMode(Ogre::PM_WIREFRAME);
	Root->renderOneFrame();
}
Пример #14
0
bool
COgreWindowContext::Initialize( const GUI::CString& title                ,
                                const GUI::CVideoSettings& videoSettings ,
                                const GUI::CString& ogreRenderSystem     )
{GUCEF_TRACE;

    // Do not initialize twice
    Shutdown();

    // First create a regular O/S window
    if ( m_osWindow->WindowCreate( title                                       ,
                                   0                                           ,
                                   0                                           ,
                                   videoSettings.GetResolutionWidthInPixels()  ,
                                   videoSettings.GetResolutionHeightInPixels() ) )
    {
        // Display the new window
        m_osWindow->Show();
        m_osWindow->SendToForegound();
        m_osWindow->GrabFocus();

	    // Now proceed with setting up the Ogre specifics
        
        // We grab the O/S window identifier 'the handle' 
        // This is passed to Ogre to tie things together
        CORE::Int64 windowRef = 0; 
        CORE::CString windowIntStr = m_osWindow->GetProperty( "WINDOWINT" );
        if ( !windowIntStr.IsNULLOrEmpty() )
        {
            windowRef = CORE::StringToInt64( windowIntStr );
        }
        Ogre::NameValuePairList options;         
        options[ "externalWindowHandle" ] = Ogre::StringConverter::toString( (size_t) windowRef ); 

        Ogre::Root* ogreRoot = Ogre::Root::getSingletonPtr();
        if ( ogreRoot == nullptr )
        {            
            ogreRoot = OGRE_NEW Ogre::Root( "", "", "" ); 
        }

        if ( !ogreRoot->isInitialised() )
        {
            // Load any Ogre plugins not loaded yet from the bootstrap group
            CORE::CCoreGlobal::Instance()->GetPluginControl().LoadPluginGroup( "Ogre" );
            
            const Ogre::RenderSystemList& rsList = ogreRoot->getAvailableRenderers();
            if ( rsList.size() == 0 )
            {
                GUCEF_ERROR_LOG( CORE::LOGLEVEL_IMPORTANT, "OgreWindowContext: No Ogre render systems are available, cannot initialize" );
                return false;
            }

            Ogre::RenderSystem* renderSystem = nullptr;
            Ogre::RenderSystemList::const_iterator i = rsList.begin();
            while ( i != rsList.end() )
            {
                GUCEF_SYSTEM_LOG( CORE::LOGLEVEL_NORMAL, "OgreWindowContext: Available Ogre render system: " + (*i)->getFriendlyName() );
                if ( ogreRenderSystem == (*i)->getName() )
                {
                    GUCEF_SYSTEM_LOG( CORE::LOGLEVEL_NORMAL, "OgreWindowContext: Found desired/preferred Ogre render system: " + (*i)->getFriendlyName() );
                    renderSystem = (*i); 
                }
                ++i;
            }
            if ( renderSystem == nullptr )
            {
                GUCEF_WARNING_LOG( CORE::LOGLEVEL_IMPORTANT, "OgreWindowContext: Preferred Ogre render systems not available, using first available alternative: " + (*rsList.begin())->getFriendlyName() );
                renderSystem = *rsList.begin();
            }

            ogreRoot->setRenderSystem( renderSystem );
            m_sceneManager = ogreRoot->createSceneManager( Ogre::ST_GENERIC );

            m_renderWindow = ogreRoot->initialise( false, title );
        }

        m_renderWindow = ogreRoot->createRenderWindow( title, 
                                                       videoSettings.GetResolutionWidthInPixels(), 
                                                       videoSettings.GetResolutionHeightInPixels(), 
                                                       videoSettings.GetFullscreenState(),
                                                       &options ); 

        // Grab the main app pulse generator and set the update interval for the context to the desired refresh rate
        CORE::CPulseGenerator& pulseGenerator = CORE::CCoreGlobal::Instance()->GetPulseGenerator(); 
        pulseGenerator.RequestPeriodicPulses( this, 1000 / videoSettings.GetFrequency() );
        SubscribeTo( &pulseGenerator );

        GUCEF_SYSTEM_LOG( CORE::LOGLEVEL_NORMAL, "OgreWindowContext: Succesfully created Ogre rendering context" );
        m_initialized = true;
        return true;
    }
    return false;
}
Пример #15
0
void test()
{
	Ogre::Root* pOgre = new Ogre::Root("", "");

    pOgre->loadPlugin(RENDER_SYSTEM);
	pOgre->setRenderSystem(pOgre->getAvailableRenderers().front());

	pOgre->initialise(false);
	
	Ogre::NameValuePairList lArgs;
	//lArgs["externalWindowHandle"] = bk::format("%d", (bk::uint)l_window.get_handle()).astr;
	Ogre::RenderWindow* pWindow = pOgre->createRenderWindow("Heart|Dockyard", 1024, 768, false, &lArgs);

	Ogre::SceneManager* pSceneManager = pOgre->createSceneManager(Ogre::ST_GENERIC,"SceneManager");
	pSceneManager->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
	pSceneManager->setShadowCameraSetup(Ogre::ShadowCameraSetupPtr(new Ogre::FocusedShadowCameraSetup()));
	pSceneManager->setAmbientLight(Ogre::ColourValue(0.1f, 0.1f, 0.1f));

	Ogre::Camera* pCamera = pSceneManager->createCamera("Camera");
	pCamera->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z);
	pCamera->setPosition(Ogre::Vector3(0.0f, 50.0f, 20.0f));
	pCamera->lookAt(Ogre::Vector3(0.0f, 0.0f, 0.0f)); 
	pCamera->setNearClipDistance(0.1f);
	pCamera->setFarClipDistance(100.0f);
	Ogre::Viewport* pViewport = pWindow->addViewport(pCamera);
	pViewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
	pCamera->setAspectRatio(Ogre::Real(pViewport->getActualWidth()) / Ogre::Real(pViewport->getActualHeight()));

	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../data/dockyard.zip", "Zip", "Dockyard", true);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	Ogre::MeshManager::getSingleton().createPlane("GroundPlane", "Dockyard", Ogre::Plane(0.0f, 0.0f, 1.0f, 0.0f), 100.0f, 100.0f, 100, 100, true, 1, 3.0f, 3.0f);
	Ogre::Entity* pGroundEntity = pSceneManager->createEntity("GroundPlane");
	pGroundEntity->setMaterialName("Examples/Rockwall");
	pGroundEntity->setCastShadows(false);
	pGroundEntity->getSubEntity(0)->getMaterial()->setShadingMode(Ogre::SO_PHONG);
	Ogre::SceneNode* pGroundNode = pSceneManager->getRootSceneNode()->createChildSceneNode();
	pGroundNode->attachObject(pGroundEntity);

	Ogre::Entity* pCubeEntity = pSceneManager->createEntity("Cube", Ogre::SceneManager::PT_CUBE);
	pCubeEntity->setMaterialName("Examples/10PointBlock");
	pCubeEntity->setCastShadows(true);
	Ogre::SceneNode* pCubeNode = pSceneManager->getRootSceneNode()->createChildSceneNode();
	pCubeNode->attachObject(pCubeEntity);
	pCubeNode->setPosition(0.0f, 0.0f, 5.f);
	pCubeNode->setScale(0.1f, 0.1f, 0.1f);

	Ogre::ColourValue lColour1(1.0f, 1.0f, 1.0f);
	Ogre::ColourValue lColour2(1.0f, 1.0f, 1.0f);
	Ogre::ColourValue lColour3(1.0f, 1.0f, 1.0f);
	Ogre::Light* pLight1 = pSceneManager->createLight();
	pLight1->setType(Ogre::Light::LT_SPOTLIGHT);
	pLight1->setPosition(30.0f, 30.0f, 30.0f);
	pLight1->setDirection(-1.0f, -1.0f, -1.0f);
	pLight1->setSpotlightRange(Ogre::Degree(30), Ogre::Degree(50));
	pLight1->setDiffuseColour(lColour1 * 0.5f);
	Ogre::Light* pLight2 = pSceneManager->createLight();
	pLight2->setType(Ogre::Light::LT_SPOTLIGHT);
	pLight2->setPosition(-30.0f, 30.0f, 30.0f);
	pLight2->setDirection(1.0f, -1.0f, -1.0f);
	pLight2->setSpotlightRange(Ogre::Degree(30), Ogre::Degree(50));
	pLight2->setDiffuseColour(lColour2 * 0.5f);
	Ogre::Light* pLight3 = pSceneManager->createLight();
	pLight3->setType(Ogre::Light::LT_SPOTLIGHT);
	pLight3->setPosition(30.0f, -30.0f, 30.0f);
	pLight3->setDirection(-1.0f, 1.0f, -1.0f);
	pLight3->setSpotlightRange(Ogre::Degree(30), Ogre::Degree(50));
	pLight3->setDiffuseColour(lColour3 * 0.5f);

	Ogre::Overlay* pMenuOverlay = Ogre::OverlayManager::getSingleton().create("Menu");
	Ogre::OverlayElement* pMenu = Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "Menu");
    pMenu->setMetricsMode(Ogre::GMM_PIXELS);
    pMenu->setWidth(200);
    pMenu->setHeight(200);
    pMenu->setTop(30);
    pMenu->setLeft(30);
    pMenu->setMaterialName("Examples/BumpyMetal");
	if (pMenu->isContainer()) pMenuOverlay->add2D(static_cast<Ogre::OverlayContainer*>(pMenu));
	pMenuOverlay->show();

	pOgre->startRendering();
}
Пример #16
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 CSceletalAnimationView::EngineSetup(void)
{
	Ogre::Root *Root = ((CSceletalAnimationApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Animation");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Mouse Input");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Mouse Input", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(5.0, 5.0, 10.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
	m_Camera->lookAt(Ogre::Vector3(0.5, 0.5, 0.5));
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);

	Ogre::ManualObject* ManualObject = NULL;
	ManualObject = SceneManager->createManualObject("Animation");
	ManualObject->setDynamic(false);
    ManualObject->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);
	//face 1
	ManualObject->position(0, 0, 0);//0
	ManualObject->position(1, 0, 0);//1
	ManualObject->position(1, 1, 0);//2
	ManualObject->triangle(0, 1, 2);//3
	
	ManualObject->position(0, 0, 0);//4
	ManualObject->position(1, 1, 0);//5
	ManualObject->position(0, 1, 0);//6
	ManualObject->triangle(3, 4, 5);//7
	//face 2
	ManualObject->position(0, 0, 1);//8
	ManualObject->position(1, 0, 1);//9
	ManualObject->position(1, 1, 1);//10
	ManualObject->triangle(6, 7, 8);//11

	ManualObject->position(0, 0, 1);//12
	ManualObject->position(1, 1, 1);//13
	ManualObject->position(0, 1, 1);//14
	ManualObject->triangle(9, 10, 11);//15
	//face 3
	ManualObject->position(0, 0, 0);//16
	ManualObject->position(1, 0, 0);//17
	ManualObject->position(1, 0, 1);//18
	ManualObject->triangle(12, 13, 14);//19

	ManualObject->position(0, 0, 0);
	ManualObject->position(1, 0, 1);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(15, 16, 17);
	//face 4
	ManualObject->position(1, 0, 0);
	ManualObject->position(1, 1, 0);
	ManualObject->position(1, 1, 1);
	ManualObject->triangle(18, 19, 20);

	ManualObject->position(1, 0, 0);
	ManualObject->position(1, 1, 1);
	ManualObject->position(1, 0, 1);
	ManualObject->triangle(21, 22, 23);
	//face 5
	ManualObject->position(0, 1, 0);
	ManualObject->position(1, 1, 0);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(24, 25, 26);

	ManualObject->position(1, 1, 0);
	ManualObject->position(1, 1, 1);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(27, 28, 29);
	
	//face 6
	ManualObject->position(0, 0, 0);
	ManualObject->position(0, 1, 1);
	ManualObject->position(0, 0, 1);
	ManualObject->triangle(30, 31, 32);

	ManualObject->position(0, 0, 0);
	ManualObject->position(0, 1, 0);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(33, 34, 35);

	ManualObject->end();
	Ogre::MeshPtr MeshPtr = ManualObject->convertToMesh("Animation");
	Ogre::SubMesh* sub = MeshPtr->getSubMesh(0);
	
	Ogre::SkeletonPtr Skeleton = Ogre::SkeletonManager::getSingleton().create("Skeleton", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	MeshPtr.getPointer()->_notifySkeleton(Skeleton);
	Ogre::Bone *Root1 = NULL;
	Ogre::Bone *Child1 = NULL;
	Ogre::Bone *Child2 = NULL;

	Root1 = Skeleton.getPointer()->createBone("Root");
	Root1->setPosition(Ogre::Vector3(0.0, 0.0, 0.0));
	Root1->setOrientation(Ogre::Quaternion::IDENTITY);
	
	Child1 = Root1->createChild(1);
	Child1->setPosition(Ogre::Vector3(4.0, 0.0, 0.0));
	Child1->setOrientation(Ogre::Quaternion::IDENTITY);
	Child2 = Root1->createChild(2);
	Child2->setPosition(Ogre::Vector3(5.0, 0.0, 0.0));
	Child2->setOrientation(Ogre::Quaternion::IDENTITY);

	Ogre::VertexBoneAssignment Assignment;

	Assignment.boneIndex = 0;
	Assignment.vertexIndex = 0;
	Assignment.weight = 1.0;
	Skeleton->setBindingPose();

	sub->addBoneAssignment(Assignment);

	Assignment.vertexIndex = 1;
	sub->addBoneAssignment(Assignment);

	Assignment.vertexIndex = 2;
	sub->addBoneAssignment(Assignment);

	Ogre::Animation *Animation = MeshPtr->createAnimation("HandAnimation", 100.0);
	Ogre::NodeAnimationTrack *Track = Animation->createNodeTrack(0, Root1);
	Ogre::TransformKeyFrame *KeyFrame = NULL;

	for (float FrameTime = 0.0; FrameTime < 100.0; FrameTime += 0.1)
	{
		KeyFrame = Track->createNodeKeyFrame(FrameTime);
		KeyFrame->setTranslate(Ogre::Vector3(10.0, 0.0, 0.0));
	}

	Root1->setManuallyControlled(true);
	Child1->setManuallyControlled(true);
	Child2->setManuallyControlled(true);
	MeshPtr->load();

	MeshPtr.getPointer()->_notifySkeleton(Skeleton);
		
//	Ogre::SkeletonSerializer skeletonSerializer;
//	skeletonSerializer.exportSkeleton(Skeleton.get(), "C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\models\\testskeleton.skeleton");
//	Ogre::MeshSerializer ser;
//    ser.exportMesh(MeshPtr.get(), "C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\models\\testskeleton.mesh");

	Ogre::Entity *Entity = SceneManager->createEntity("Animation", "Animation"/*"testskeleton.mesh"*/);
	Ogre::SceneNode *SceneNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	SceneNode->attachObject(Entity);
	Entity->setDisplaySkeleton(true);

	m_AnimationState = Entity->getAnimationState("HandAnimation");
	m_AnimationState->setEnabled(true);
	m_AnimationState->setLoop(true);
	
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);
	 
	Root->renderOneFrame();
}
void CTerrainWalkingView::EngineSetup(void)
{
	Ogre::Root *Root = ((CTerrainWalkingApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Walking");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Walking", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(10);
	m_Camera->setFarClipDistance(10000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *TopographyNode = SceneManager->getRootSceneNode()->createChildSceneNode("Topography");
	Ogre::Entity *TopographyEntity = SceneManager->createEntity("Topography", "Topography.mesh");
	TopographyNode->attachObject(TopographyEntity);
	
	Ogre::AxisAlignedBox TopographyBox = TopographyEntity->getBoundingBox();
	
	Ogre::Vector3 Minimum = TopographyBox.getMinimum();
	Ogre::Vector3 Center = TopographyBox.getCenter();

	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode("Robot");
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	RobotNode->attachObject(RobotEntity);
	RobotEntity->getParentNode()->scale(10,10,10);
	Ogre::AxisAlignedBox RobotBox = RobotEntity->getBoundingBox();

	RobotNode->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + RobotBox.getSize()[1], Minimum[2]));

	m_Camera->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + 5000, Minimum[2]));
	m_Camera->lookAt(Center);
	
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);

	m_Animation = RobotEntity->getAnimationState("Walk");
	m_Animation->setEnabled(true);
	
	m_CollisionTools = new MOC::CollisionTools(SceneManager);

	Root->renderOneFrame();
}
void CSaveSceneView::EngineSetup(void)
{
	Ogre::Root *Root = ((CSaveSceneApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "SaveScene");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("SaveScene");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("SaveScene", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(200.0, 50.0, 100.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");
	CameraNode->attachObject(m_Camera);

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	RobotNode->attachObject(RobotEntity);


	Ogre::AxisAlignedBox Box = RobotEntity->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();
	m_Camera->lookAt(Center);

	int rc;

    xmlDocPtr doc;
   // Create a new Xmlm_XmlWriter for DOM, with no compression.
    m_XmlWriter = xmlNewTextWriterDoc(&doc, 0);
   // Start the document with the xml default for the version,
   // encoding ISO 8859-1 and the default for the standalone
   // declaration.
    xmlTextWriterStartDocument(m_XmlWriter, NULL, MY_ENCODING, NULL);
	
	SceneExplore(SceneManager);
   
	xmlTextWriterEndDocument(m_XmlWriter);
	xmlFreeTextWriter(m_XmlWriter);
    xmlSaveFileEnc("1.scene", doc, MY_ENCODING);
    xmlFreeDoc(doc);
}
Пример #20
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;
}
void CLinkedAnimationView::EngineSetup(void)
{
	Ogre::Root *Root = ((CLinkedAnimationApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Mouse Input");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Mouse Input", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(/*20*/0.0, /*5*/0.0, 100.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *RobotNode1 = SceneManager->getRootSceneNode()->createChildSceneNode("Robot1", Ogre::Vector3(-50,0,0));
	Ogre::Entity *RobotEntity1 = SceneManager->createEntity("Robot1", "robot.mesh");
	RobotNode1->attachObject(RobotEntity1);
	Ogre::Skeleton *Skeleton1 = RobotEntity1->getSkeleton();
	RobotEntity1->setDisplaySkeleton(true);

	Ogre::SceneNode *RobotNode2 = SceneManager->getRootSceneNode()->createChildSceneNode("Robot2", Ogre::Vector3(50,0,0));
	Ogre::Entity *RobotEntity2 = SceneManager->createEntity("Robot2", "robot.mesh");
	RobotNode2->attachObject(RobotEntity2);
	Ogre::Skeleton *Skeleton2 = RobotEntity2->getSkeleton(); 
	RobotEntity2->setDisplaySkeleton(true);

	Skeleton1->addLinkedSkeletonAnimationSource(Skeleton2->getName(), 2.0);

//	RobotEntity1->_initialise(true);
//	RobotEntity2->_initialise(true);

//	RobotEntity1->refreshAvailableAnimationState();
	m_Camera->lookAt(Ogre::Vector3(0.0, 0.0, 0.0));
	
	m_AnimationState1 = RobotEntity1->getAnimationState("Walk");
	m_AnimationState1->setEnabled(true);

	m_AnimationState2 = RobotEntity2->getAnimationState("Slump");
	m_AnimationState2->setEnabled(true);

	Root->renderOneFrame();
}
Пример #22
0
    bool initialise()
    {
		mRoot = new Ogre::Root(PLUGINS_CFG, OGRE_CFG, OGRE_LOG);

		if (!mRoot->restoreConfig())
			if (!mRoot->showConfigDialog())
				return false;

		initResources();

        mWindow = mRoot->initialise(true, "CS Clone Editor v0.0");
        Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

		mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
		mSceneMgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7));
		mCamera = mSceneMgr->createCamera("camera");
        mWindow->addViewport(mCamera);
        mCamera->setAutoAspectRatio(true);
        mCamera->setNearClipDistance(0.1);
        mCamera->setFarClipDistance(10000);
        mCamera->setPosition(10, 10, 10);
//        mCamera->lookAt(0, 0, 0);

        mRoot->addFrameListener(this);

		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
//Initializing OIS
		Ogre::LogManager::getSingletonPtr()->logMessage("*-*-* OIS Initialising");

		OIS::ParamList pl;
		size_t windowHnd = 0;
		mWindow->getCustomAttribute("WINDOW", &windowHnd);
		pl.insert(std::make_pair(std::string("WINDOW"), Ogre::StringConverter::toString(windowHnd)));

#if OGRE_DEBUG_MODE == 1
	#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
		#define NO_EXCLUSIVE_INPUT
	#endif
#endif

#ifdef NO_EXCLUSIVE_INPUT
	#if defined OIS_WIN32_PLATFORM
		pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND" )));
		pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
		pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND")));
		pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE")));
	#elif defined OIS_LINUX_PLATFORM
		pl.insert(std::make_pair(std::string("x11_mouse_grab"), std::string("false")));
		pl.insert(std::make_pair(std::string("x11_mouse_hide"), std::string("false")));
		pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false")));
		pl.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
	#endif
#endif
		mInputManager = OIS::InputManager::createInputSystem(pl);

		mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
		mKeyboard->setEventCallback(this);
		mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));
		mMouse->setEventCallback(this);

		windowResized(mWindow);
//Initialising GUI
		Ogre::LogManager::getSingletonPtr()->logMessage("*-*-* MyGUI Initialising");
		mGUI = new MyGUI::Gui;
		mGUI->initialise(mWindow);
		mGUI->load("editor.layout");

		mMenuBar = mGUI->createWidget<MyGUI::MenuBar>("MenuBar",
			MyGUI::IntCoord(0, 0, mGUI->getViewWidth(), 28),
			MyGUI::ALIGN_TOP | MyGUI::ALIGN_HSTRETCH, "Overlapped");

		mMenuBar->addItem("File");
		mPopupMenuFile = mMenuBar->getItemMenu(0);
		mPopupMenuFile->addItem("New");
		mPopupMenuFile->addItem("Open ...");
		mPopupMenuFile->addItem("Save");
		mPopupMenuFile->addItem("Save as ...", false, true);
		mPopupMenuFile->addItem("Settings", false, true);
		mPopupMenuFile->addItem("Quit");

		mMenuBar->addItem("Help");
		mPopupMenuHelp = mMenuBar->getItemMenu(1);
		mPopupMenuHelp->addItem("Help");
		mPopupMenuHelp->addItem("About ...");

		return (true);
    }
void CUsingControllersView::EngineSetup(void)
{
	Ogre::Root *Root = ((CUsingControllersApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Mouse Input");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Mouse Input", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(0.0, 0.0, 1000.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *SphereNode = SceneManager->getRootSceneNode()->createChildSceneNode("Sphere", Ogre::Vector3(0,0,0));
	Ogre::Entity *SphereEntity = SceneManager->createEntity("Sphere", "sphere.mesh");
	SphereEntity->setMaterialName("Wall/Screen");
	SphereNode->attachObject(SphereEntity);
	SphereEntity->getParentNode()->scale(0.2,0.2,0.2);

	m_Camera->lookAt(Ogre::Vector3(0.0, 0.0, 0.0));

#undef new

	Ogre::ControllerFunctionRealPtr func(OGRE_NEW Ogre::WaveformControllerFunction(Ogre::WFT_SINE, 0.0, 1.0));
	Ogre::ControllerValueRealPtr dest(OGRE_NEW SphereScale(SphereNode, 1.0));

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

	Ogre::ControllerManager& ControllerManager = Ogre::ControllerManager::getSingleton();
	m_SphereController = ControllerManager.createController(ControllerManager.getFrameTimeSource(), dest, func);

	Root->renderOneFrame();
}
Пример #24
0
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
#else
int main (int argc, char *argv[]) {
#endif

	#define OGRE_STATIC_ParticleFX 1

	Ogre::Root *ogre;
	Ogre::RenderWindow *window;
	Ogre::SceneManager *sceneMgr;
	Ogre::Camera *camera;

	// fire up an Ogre rendering window. Clearing the first two (of three) params will let us 
	// specify plugins and resources in code instead of via text file
	ogre = new Ogre::Root("", "");


	// This is a VERY minimal rendersystem loading example; we are hardcoding the OpenGL 
	// renderer, instead of loading GL and D3D9. We will add renderer selection support in a 
	// future article.

	// I separate the debug and release versions of my plugins using the same "_d" suffix that
	// the Ogre main libraries use; you may need to remove the "_d" in your code, depending on the
	// naming convention you use 
	ogre->loadPlugin("RenderSystem_GL_d");
	ogre->loadPlugin("Plugin_ParticleFX_d");
	const Ogre::RenderSystemList &renderSystems = ogre->getAvailableRenderers();
	Ogre::RenderSystemList::const_iterator r_it;

	// we do this step just to get an iterator that we can use with setRenderSystem. In a future article
	// we actually will iterate the list to display which renderers are available. 
	// renderSystems = ogre->getAvailableRenderers();
	r_it = renderSystems.begin();
	ogre->setRenderSystem(*r_it);
	ogre->initialise(false);

	// load common plugins
	ogre->loadPlugin("Plugin_CgProgramManager_d");		
	ogre->loadPlugin("Plugin_OctreeSceneManager_d");

	// setup main window; hardcode some defaults for the sake of presentation
	Ogre::NameValuePairList opts;
	opts["resolution"] = "1024x768";
	opts["fullscreen"] = "false";
	opts["vsync"] = "true";

	// create a rendering window with the title "CDK"
	window = ogre->createRenderWindow("CDK", 1024, 768, false, &opts);

		// load the basic resource location(s)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
		"resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
		"resource/gui.zip", "Zip", "GUI");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
		"resource/textures", "FileSystem", "Textures");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
		"resource/particles", "FileSystem", "Particles");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
		"resource/materials", "FileSystem", "Materials");
#if defined(WIN32)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
		"c:\\windows\\fonts", "FileSystem", "GUI"); 
#endif
	//Must initialize resource groups after window if using particle effects.
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("General");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("GUI");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Textures");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Materials");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Particles");

	// since this is basically a CEGUI app, we can use the ST_GENERIC scene manager for now; in a later article 
	// we'll see how to change this
	sceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);
	camera = sceneMgr->createCamera("camera");
	camera->setNearClipDistance(1);
    Ogre::Viewport* vp = window->addViewport(camera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

	// most examples get the viewport size to calculate this; for now, we'll just 
	// set it to 4:3 the easy way
	camera->setAspectRatio((Ogre::Real)1.333333);

// with a scene manager and window, we can create a the GUI renderer
	
	// new way to instantiate a CEGUIOgreRenderer (Ogre 1.7)
	Ogre::RenderTarget *mRenderTarget = window;
	CEGUI::OgreRenderer* pGUIRenderer = &CEGUI::OgreRenderer::bootstrapSystem(*mRenderTarget);
 
	// create the root CEGUI class
	CEGUI::System* pSystem = CEGUI::System::getSingletonPtr();
 
	// tell us a lot about what is going on (see CEGUI.log in the working directory)
	CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative);
 
	// use this CEGUI scheme definition (see CEGUI docs for more)
	CEGUI::SchemeManager::getSingleton().create((CEGUI::utf8*)"TaharezLookSkin.scheme", (CEGUI::utf8*)"GUI");
 
	// show the CEGUI mouse cursor (defined in the look-n-feel)
	pSystem->setDefaultMouseCursor((CEGUI::utf8*)"TaharezLook", (CEGUI::utf8*)"MouseArrow");
 
	// use this font for text in the UI
	CEGUI::FontManager::getSingleton().create("Tahoma-8.font", (CEGUI::utf8*)"GUI");
	pSystem->setDefaultFont((CEGUI::utf8*)"Tahoma-8");
 
	// load a layout from the XML layout file (you'll find this in resources/gui.zip), and 
	// put it in the GUI resource group
	CEGUI::Window* pLayout = CEGUI::WindowManager::getSingleton().loadWindowLayout("katana.layout", "", "GUI");
 
	// you need to tell CEGUI which layout to display. You can call this at any time to change the layout to
	// another loaded layout (i.e. moving from screen to screen or to load your HUD layout). Note that this takes
	// a CEGUI::Window instance -- you can use anything (any widget) that serves as a root window.
	pSystem->setGUISheet(pLayout);

	// this next bit is for the sake of the input handler
	unsigned long hWnd;
	// WINDOW is generic to all platforms now as of Eihort
	window->getCustomAttribute("WINDOW", &hWnd);

	// set up the input handlers
	Simulation *sim = new Simulation();

	// since the input handler deals with pushing input to CEGUI, we need to give it a pointer
	// to the CEGUI System instance to use
	InputHandler *handler = new InputHandler(pSystem, sim, hWnd);

	// put us into our "main menu" state
	sim->requestStateChange(GUI);

	// make an instance of our GUI sheet handler class
	MainMenuDlg* pDlg = new MainMenuDlg(pSystem, pLayout, sim);
	
	//testing shit
	Ogre::SceneNode *systemNode = sceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(0,0,0));
	

	
	SphereMesh *sphere = NULL;
	sphere->createSphere("sphereMesh", 80, 64, 64);


	/*
	// Now I can create several entities using that mesh
	Ogre::Entity *MoonEntity = sceneMgr->createEntity("Moon", planetMesh);
	// Now I attach it to a scenenode, so that it becomes present in the scene.
	Ogre::SceneNode *EarthOrbitNode = systemNode->createChildSceneNode("Earth Orbit", Ogre::Vector3(0,0,0));
	Ogre::SceneNode *EarthNode = EarthOrbitNode->createChildSceneNode("Earth", Ogre::Vector3(200,0,0));
	Ogre::SceneNode *MoonNode = EarthNode->createChildSceneNode("Moon", Ogre::Vector3(150,0,0));
	MoonNode->attachObject(MoonEntity);
	MoonEntity->getParentNode()->scale(0.5,0.5,0.5);
	*/
	//Material Tests
	Ogre::MaterialManager& lMaterialManager = Ogre::MaterialManager::getSingleton();
	Ogre::String lNameOfResourceGroup = "Mission 1 : Deliver Tom";
	
	Ogre::ResourceGroupManager& lRgMgr = Ogre::ResourceGroupManager::getSingleton();
	lRgMgr.createResourceGroup(lNameOfResourceGroup);

	{
			Ogre::MaterialPtr lMaterial = lMaterialManager.create("M_Lighting+OneTexture",lNameOfResourceGroup);
			Ogre::Technique* lFirstTechnique = lMaterial->getTechnique(0);
			Ogre::Pass* lFirstPass = lFirstTechnique->getPass(0);
 
			lFirstPass->setDiffuse(0.8f, 0.8f, 0.8f,1.0f);
			lFirstPass->setAmbient(0.3f, 0.3f, 0.3f);
			lFirstPass->setSpecular(1.0f, 1.0f, 1.0f, 1.0f);
			lFirstPass->setShininess(64.0f);
			lFirstPass->setSelfIllumination(0.1f, 0.1f, 0.1f);

			Ogre::TextureUnitState* lTextureUnit = lFirstPass->createTextureUnitState();
			lTextureUnit->setTextureName("SimpleTexture.bmp", Ogre::TEX_TYPE_2D);
			lTextureUnit->setTextureCoordSet(0);
	}
	
	
	// 3/ Lighting color.
	// To have the feeling of '3D', the lighting is good feeling.
		// It often requires the object to have correct normals (see my manual object construction), 
		// and some lights in the scene.
		
	{
			Ogre::MaterialPtr lMaterial = lMaterialManager.create("Sun",lNameOfResourceGroup);
			Ogre::Technique* lFirstTechnique = lMaterial->getTechnique(0);
			Ogre::Pass* lFirstPass = lFirstTechnique->getPass(0);
			
			// Lighting is allowed on this pass.
			lFirstPass->setLightingEnabled(true);

			// Emissive / self illumination is the color 'produced' by the object.
			// Color values vary between 0.0(minimum) to 1.0 (maximum).
			Ogre::ColourValue lSelfIllumnationColour(0.5f, 0.0f, 0.0f, 1.0f);
			lFirstPass->setSelfIllumination(lSelfIllumnationColour);

			// diffuse color is the traditionnal color of the lit object.
			Ogre::ColourValue lDiffuseColour(1.0f, 0.4f, 0.4f, 1.0f);
			lFirstPass->setDiffuse(lDiffuseColour);

			// ambient colour is linked to ambient lighting.
			// If there is no ambient lighting, then this has no influence.
			// It the ambient lighting is at 1, then this colour is fully added.
			// This is often use to change the general feeling of a whole scene.
			Ogre::ColourValue lAmbientColour(0.4f, 0.1f, 0.1f, 1.0f);
			lFirstPass->setAmbient(lAmbientColour);

			// specular colour, is the colour of the 'little light reflection'
			// that you can see on some object. For example, my bald head skin
			// reflect the sun. This make a 'round of specular lighting'.
			// Set this to black if you don't want to see it.
			Ogre::ColourValue lSpecularColour(1.0f, 1.0f, 1.0f, 1.0f);
			lFirstPass->setSpecular(lSpecularColour);

			// Shininess is the 'inverse of specular color splattering' coefficient.
			// If this is big (e.g : 64) you get a very tiny dot with a quite strong color (on round surface).
			// If this is 0, you get a simple color layer (the dot has become very wide).
			Ogre::Real lShininess = 64.0f;
			lFirstPass->setShininess(lShininess);
	}
		{
			Ogre::MaterialPtr lMaterial = lMaterialManager.create("mars",lNameOfResourceGroup);
			Ogre::Technique* lFirstTechnique = lMaterial->getTechnique(0);
			Ogre::Pass* lFirstPass = lFirstTechnique->getPass(0);
			
			// Lighting is allowed on this pass.
			lFirstPass->setLightingEnabled(true);

			// Emissive / self illumination is the color 'produced' by the object.
			// Color values vary between 0.0(minimum) to 1.0 (maximum).
			Ogre::ColourValue lSelfIllumnationColour(0.6f, 0.1f, 0.1f, 0.0f);
			lFirstPass->setSelfIllumination(lSelfIllumnationColour);

			// diffuse color is the traditionnal color of the lit object.
			Ogre::ColourValue lDiffuseColour(1.0f, 0.2f, 0.0f, 0.0f);
			lFirstPass->setDiffuse(lDiffuseColour);

			// ambient colour is linked to ambient lighting.
			// If there is no ambient lighting, then this has no influence.
			// It the ambient lighting is at 1, then this colour is fully added.
			// This is often use to change the general feeling of a whole scene.
			Ogre::ColourValue lAmbientColour(1.0f, 0.2f, 0.0f, 0.0f);
			lFirstPass->setAmbient(lAmbientColour);

			// specular colour, is the colour of the 'little light reflection'
			// that you can see on some object. For example, my bald head skin
			// reflect the sun. This make a 'round of specular lighting'.
			// Set this to black if you don't want to see it.
			Ogre::ColourValue lSpecularColour(1.0f, 0.3f, 0.3f, 0.3f);
			lFirstPass->setSpecular(lSpecularColour);

			// Shininess is the 'inverse of specular color splattering' coefficient.
			// If this is big (e.g : 64) you get a very tiny dot with a quite strong color (on round surface).
			// If this is 0, you get a simple color layer (the dot has become very wide).
			Ogre::Real lShininess = 34.0f;
			lFirstPass->setShininess(lShininess);
		}

	{
			Ogre::MaterialPtr lMaterial = lMaterialManager.create("gaia",lNameOfResourceGroup);
			Ogre::Technique* lFirstTechnique = lMaterial->getTechnique(0);
			Ogre::Pass* lFirstPass = lFirstTechnique->getPass(0);
			
			// Lighting is allowed on this pass.
			lFirstPass->setLightingEnabled(true);

			// Emissive / self illumination is the color 'produced' by the object.
			// Color values vary between 0.0(minimum) to 1.0 (maximum).
			Ogre::ColourValue lSelfIllumnationColour(0.0f, 0.0f, 0.1f, 0.3f);
			lFirstPass->setSelfIllumination(lSelfIllumnationColour);

			// diffuse color is the traditionnal color of the lit object.
			Ogre::ColourValue lDiffuseColour(0.1f, 0.2f, 0.8f, 1.0f);
			lFirstPass->setDiffuse(lDiffuseColour);

			// ambient colour is linked to ambient lighting.
			// If there is no ambient lighting, then this has no influence.
			// It the ambient lighting is at 1, then this colour is fully added.
			// This is often use to change the general feeling of a whole scene.
			Ogre::ColourValue lAmbientColour(0.0f, 0.1f, 0.4f, 1.0f);
			lFirstPass->setAmbient(lAmbientColour);

			// specular colour, is the colour of the 'little light reflection'
			// that you can see on some object. For example, my bald head skin
			// reflect the sun. This make a 'round of specular lighting'.
			// Set this to black if you don't want to see it.
			Ogre::ColourValue lSpecularColour(0.0f, 0.3f, 1.0f, 1.0f);
			lFirstPass->setSpecular(lSpecularColour);

			// Shininess is the 'inverse of specular color splattering' coefficient.
			// If this is big (e.g : 64) you get a very tiny dot with a quite strong color (on round surface).
			// If this is 0, you get a simple color layer (the dot has become very wide).
			Ogre::Real lShininess = 34.0f;
			lFirstPass->setShininess(lShininess);
		}
		{
			Ogre::MaterialPtr lMaterial = lMaterialManager.create("barren",lNameOfResourceGroup);
			Ogre::Technique* lFirstTechnique = lMaterial->getTechnique(0);
			Ogre::Pass* lFirstPass = lFirstTechnique->getPass(0);
			
			// Lighting is allowed on this pass.
			lFirstPass->setLightingEnabled(true);

			// Emissive / self illumination is the color 'produced' by the object.
			// Color values vary between 0.0(minimum) to 1.0 (maximum).
			Ogre::ColourValue lSelfIllumnationColour(0.1f, 0.1f, 0.1f, 0.1f);
			lFirstPass->setSelfIllumination(lSelfIllumnationColour);

			// diffuse color is the traditionnal color of the lit object.
			Ogre::ColourValue lDiffuseColour(0.3f, 0.3f, 0.3f, 0.3f);
			lFirstPass->setDiffuse(lDiffuseColour);

			// ambient colour is linked to ambient lighting.
			// If there is no ambient lighting, then this has no influence.
			// It the ambient lighting is at 1, then this colour is fully added.
			// This is often use to change the general feeling of a whole scene.
			Ogre::ColourValue lAmbientColour(0.3f, 0.3f, 0.3f, 0.3f);
			lFirstPass->setAmbient(lAmbientColour);

			// specular colour, is the colour of the 'little light reflection'
			// that you can see on some object. For example, my bald head skin
			// reflect the sun. This make a 'round of specular lighting'.
			// Set this to black if you don't want to see it.
			Ogre::ColourValue lSpecularColour(0.7f, 0.7f, 0.7f, 0.7f);
			lFirstPass->setSpecular(lSpecularColour);

			// Shininess is the 'inverse of specular color splattering' coefficient.
			// If this is big (e.g : 64) you get a very tiny dot with a quite strong color (on round surface).
			// If this is 0, you get a simple color layer (the dot has become very wide).
			Ogre::Real lShininess = 34.0f;
			lFirstPass->setShininess(lShininess);
		}
	{
			Ogre::MaterialPtr lMaterial = lMaterialManager.create("gasgiant",lNameOfResourceGroup);
			Ogre::Technique* lFirstTechnique = lMaterial->getTechnique(0);
			Ogre::Pass* lFirstPass = lFirstTechnique->getPass(0);
			
			// Lighting is allowed on this pass.
			lFirstPass->setLightingEnabled(true);

			// Emissive / self illumination is the color 'produced' by the object.
			// Color values vary between 0.0(minimum) to 1.0 (maximum).
			Ogre::ColourValue lSelfIllumnationColour(0.0f, 0.3f, 0.0f, 0.1f);
			lFirstPass->setSelfIllumination(lSelfIllumnationColour);

			// diffuse color is the traditionnal color of the lit object.
			Ogre::ColourValue lDiffuseColour(0.1f, 0.7f, 0.1f, 0.3f);
			lFirstPass->setDiffuse(lDiffuseColour);

			// ambient colour is linked to ambient lighting.
			// If there is no ambient lighting, then this has no influence.
			// It the ambient lighting is at 1, then this colour is fully added.
			// This is often use to change the general feeling of a whole scene.
			Ogre::ColourValue lAmbientColour(0.1f, 0.7f, 0.3f, 0.3f);
			lFirstPass->setAmbient(lAmbientColour);

			// specular colour, is the colour of the 'little light reflection'
			// that you can see on some object. For example, my bald head skin
			// reflect the sun. This make a 'round of specular lighting'.
			// Set this to black if you don't want to see it.
			Ogre::ColourValue lSpecularColour(0.2f, 1.0f, 0.6f, 0.6f);
			lFirstPass->setSpecular(lSpecularColour);

			// Shininess is the 'inverse of specular color splattering' coefficient.
			// If this is big (e.g : 64) you get a very tiny dot with a quite strong color (on round surface).
			// If this is 0, you get a simple color layer (the dot has become very wide).
			Ogre::Real lShininess = 34.0f;
			lFirstPass->setShininess(lShininess);
		}

	//end material tests

	//System Creator
	std::string systemDefinition[10] = {"15000,0,0,false,false,false,700000,0", "300,0,0,false,false,barren,2500,1",
		"300,x,y,false,co2,barren,6000,2", "300,x,y,h2o,n2/o2,gaia,6300,3", "300,x,y,false,co2,mars,3400,4",
		"300,x,y,false,h2/he,gasgiant,71000,5", "300,x,y,false,h2/he,gasgiant,60000,6", "300,x,y,false,h2/he,gasgiant,25001,7",
		"300,x,y,false,h2/he,gasgiant,25000,8", "300,x,y,false,n-ice,ice,1100,9"};

	StarSystem sol = StarSystem::StarSystem(sceneMgr, systemDefinition);

	//Star Creator
	/*
	{
	int x = 0;
	int y = 0;
	int kelvin = 15000;
	CelestialBody newstar = CelestialBody::CelestialBody(kelvin, 100, systemNode, sceneMgr, x, y);
	}

	// Spectrum testing and multi star generation.
	
	int time = 200;
	int x = -500;
	int y = 500;

	for ( int count = 1; count <= time; count++){
	
		int kelvin = count * (40000/time);
		Star newstar = Star::Star(kelvin, 100, systemNode, sceneMgr, x, y);
		x += 20;

		if (count % 10 == 0) {
			y -= 20;
			x = -500;
		}
	}
	*/

	// I move the SceneNode back 15 so that it is visible to the camera.
	float PositionOffset = 0.0;
	float distance = -2000.0;

	systemNode->translate(0, PositionOffset, distance);
	
	camera->lookAt(Ogre::Vector3(0,0,distance));

	while (sim->getCurrentState() != SHUTDOWN) {
		
		sol.rotateOrbits();
		
		handler->capture();

		ogre->renderOneFrame();

		// run the message pump (uncomment for Eihort)
		Ogre::WindowEventUtilities::messagePump();
	}

	{
		window->removeAllViewports();
	}
	{
		sceneMgr->destroyAllCameras();
		sceneMgr->destroyAllManualObjects();
		sceneMgr->destroyAllEntities();
		sceneMgr->destroyAllLights();
		systemNode->removeAndDestroyAllChildren();
	}

	{
		Ogre::ResourceGroupManager& lRgMgr = Ogre::ResourceGroupManager::getSingleton();
		lRgMgr.destroyResourceGroup(lNameOfResourceGroup);
	}

	// clean up after ourselves
	delete pDlg;
	delete handler;
	delete sim;
	delete ogre;

	return 0;
}
Пример #25
0
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;
}
Пример #26
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
#else
int main (int argc, char *argv[]) {
#endif

	Ogre::Root *ogre;
	Ogre::RenderWindow *window;
	Ogre::SceneManager *sceneMgr;
	Ogre::SceneManager *guiSceneMgr;
	Ogre::Camera *camera;
	Ogre::Camera *guiCamera;

	// fire up an Ogre rendering window. Clearing the first two (of three) params will let us 
	// specify plugins and resources in code instead of via text file
	ogre = new Ogre::Root("", "");

#if defined(_DEBUG)
	ogre->loadPlugin("RenderSystem_GL_d");
#else
	ogre->loadPlugin("RenderSystem_GL");
#endif

	Ogre::RenderSystemList *renderSystems = NULL;
	Ogre::RenderSystemList::iterator r_it;

	renderSystems = ogre->getAvailableRenderers();
	r_it = renderSystems->begin();
	ogre->setRenderSystem(*r_it);
	ogre->initialise(false);

	// load common plugins
#if defined(_DEBUG)
	//ogre->loadPlugin("Plugin_CgProgramManager_d");		
	ogre->loadPlugin("Plugin_OctreeSceneManager_d");
#else
	//ogre->loadPlugin("Plugin_CgProgramManager");		
	ogre->loadPlugin("Plugin_OctreeSceneManager");
#endif
	// load the basic resource location(s)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource/gui.zip", "Zip", "GUI");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("meshes", "FileSystem", "Meshes");
#if defined(WIN32)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("c:\\windows\\fonts", "FileSystem", "GUI");
#endif

	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("General");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("GUI");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Meshes");

	// setup main window; hardcode some defaults for the sake of presentation
	Ogre::NameValuePairList opts;
	opts["resolution"] = "1024x768";
	opts["fullscreen"] = "false";
	opts["vsync"] = "false";

	// create a rendering window with the title "CDK"
	window = ogre->createRenderWindow("Bouwgame Client v0.1", 1024, 768, false, &opts);

	// since this is basically a CEGUI app, we can use the ST_GENERIC scene manager for now; in a later article 
	// we'll see how to change this
	sceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);
	guiSceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);

	guiCamera = guiSceneMgr->createCamera("GUICamera");
	guiCamera->setNearClipDistance(5);
	camera = sceneMgr->createCamera("camera");
	camera->setNearClipDistance(5);
    Ogre::Viewport* vp = window->addViewport(guiCamera);
    vp->setBackgroundColour(Ogre::ColourValue(0.2f,0.2f,0.8f));

	/* ambient light */
	sceneMgr->setAmbientLight(Ogre::ColourValue(0.8, 0.8, 0.8));
	sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	/* meshes */
	Ogre::Entity* ent = sceneMgr->createEntity( "BouwPlaatsEntity", "world.mesh" );
	Ogre::SceneNode* node = sceneMgr->getRootSceneNode()->createChildSceneNode("BouwNode", Ogre::Vector3(0, 0, 0));
    node->attachObject(ent);
	//node->setScale(Ogre::Vector3(0.7,0.7,0.7));

	ent = sceneMgr->createEntity("plaats", "bouwplaats_step_00.mesh");
	Ogre::Vector3 size = ent->getBoundingBox().getSize();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats size: ") + Ogre::StringConverter::toString(size));
	size = ent->getBoundingBox().getMaximum();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats max: ") + Ogre::StringConverter::toString(size));
	size = ent->getBoundingBox().getMinimum();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats min: ") + Ogre::StringConverter::toString(size));

    Ogre::Entity* ent1 = sceneMgr->createEntity( "KeetEntity", "keet.mesh" );
	Ogre::SceneNode* scenenode = sceneMgr->getRootSceneNode()->createChildSceneNode("KeetNode", Ogre::Vector3(0, 0, 0));
    scenenode->attachObject(ent1);

	
	Ogre::Entity* ent2 = sceneMgr->createEntity( "HekjeEntity", "hekje.mesh" );
	Ogre::SceneNode* scenenode2 = sceneMgr->getRootSceneNode()->createChildSceneNode("HekjeNode", Ogre::Vector3(0, -100, 0));
    scenenode2->attachObject(ent2);
	scenenode2->setScale(Ogre::Vector3(400,0,100));

	// most examples get the viewport size to calculate this; for now, we'll just 
	// set it to 4:3 the easy way
	camera->setAspectRatio((Ogre::Real)1.333333);
	camera->setPosition(Ogre::Vector3(40,100,10));
	guiCamera->setPosition(0, 0, 300);
	guiCamera->lookAt(node->getPosition());

	// this next bit is for the sake of the input handler
	unsigned long hWnd;
	window->getCustomAttribute("WINDOW", &hWnd);

	
	// set up the input handlers
	Simulation *sim = new Simulation();
	InputHandler *handler = new InputHandler(sim, hWnd, camera);
	DataManager *dataManager = new DataManager();
	GameAI* gameAI = new GameAI(dataManager);

	//Create Network
	Network * net = new Network(dataManager);
	//net->start();

	sim->requestStateChange(GUI);
	gui = new GuiManager();

	// networkshit
	while(!net->isConnected())
	{
		Sleep(1000);
	}
	net->Send(GETGROUPS, "", "", NULL);
	net->Send(LOGIN, "gast", "gast", 1);

	gui->setSimulation(sim);
	gui->init("", ogre, guiSceneMgr, window);
	gui->activate("main");
	handler->setWindowExtents(1024,768);
	
	SimulationState cState;
	Ogre::WindowEventUtilities::addWindowEventListener(window, handler);

	DWORD tFrameStart = 0x0; //in miliseconds
	signed long tFrameX = 0x0;
	float tDelta2 = 0.0f; //in seconds
	float m_fps = 60.0f;
	tFrameStart = GetTickCount();

	float tDelta;

	//testAI->calculateNextPath(40,10);

	while ((cState = sim->getCurrentState()) != SHUTDOWN) {

		tFrameX = GetTickCount() - tFrameStart;
		tDelta2 = (float)tFrameX / 1000.0f;
		if (tDelta2 > 3600) // tDelta > 1 hour
			tDelta2 = 1.0f / m_fps; //< System tick count has highly likely overflowed, so get approximation
		tFrameStart = GetTickCount();
		m_fps = (int)(1.0f / tDelta2);

		tDelta = tDelta2;

		handler->capture();
		handler->update(tDelta);
		gui->update(tDelta);

		//if (sim->getCurrentState() == SIMULATION || sim->getCurrentState() == SIMULATION_MOUSELOOK)
//			testAI->update(tDelta);

		// run the message pump (Eihort)
		Ogre::WindowEventUtilities::messagePump();

		ogre->renderOneFrame();

		if (sim->getCurrentState() != cState) {
			handler->StateSwitched(cState, sim->getCurrentState());
			switch (sim->getCurrentState()) {
				case GUI:
					window->getViewport(0)->setCamera(guiCamera);
					break;
				case SIMULATION:
					window->getViewport(0)->setCamera(camera);
					break;
			}
		}

	}

	// clean up after ourselves
	//delete testAI;
	delete sim;
	delete ogre;
	delete handler;
	delete gameAI;
	delete dataManager;

	return 0;
}
void CTransparentMaterialView::EngineSetup(void)
{
	Ogre::Root *Root = ((CTransparentMaterialApp*)AfxGetApp())->m_Engine->GetRoot();

	Ogre::SceneManager *SceneManager = NULL;

	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "MFCOgre");

    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

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

	CRect   rect;
    GetClientRect(&rect);

	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Ogre in MFC");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Ogre in MFC", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(320.0, 240.0, 500.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 1.0f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::ManualObject *Screen = SceneManager->createManualObject("Screen");
	Screen->setDynamic(true);
	Screen->begin("window", Ogre::RenderOperation::OT_TRIANGLE_LIST);

	Screen->position(-100,-100,50);
	Screen->textureCoord(0,0);

	Screen->position(300,-100,50);
	Screen->textureCoord(1,0);

	Screen->position(300,300,50);
	Screen->textureCoord(1,1);

	Screen->triangle(0, 1, 2);
		
	Screen->position(-100,-100,50);
	Screen->textureCoord(0,0);

	Screen->position(300,300,50);
	Screen->textureCoord(1,1);

	Screen->position(-100,300,50);
	Screen->textureCoord(0,1);

	Screen->triangle(3, 4, 5);
	 
	Screen->end();
	
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	RobotNode->attachObject(RobotEntity);

	Ogre::SceneNode *WindowNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	WindowNode->attachObject(Screen);
}
Пример #28
0
int main() {
    Ogre::Root* root = new Ogre::Root();
    root->addResourceLocation("/home/soulmerge/projects/Diplomarbeit/Prototype/resources/Ogre/", "FileSystem");
    if (!root->restoreConfig() && !root->showConfigDialog()) {
        throw 1;
    }
    root->initialise(false);
    Ogre::SceneManager* sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
    sceneMgr->setAmbientLight(Ogre::ColourValue::White * 10);
    Ogre::RenderWindow* window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false, NULL);
    Ogre::Camera* cam1 = sceneMgr->createCamera("cam1");
    Ogre::Camera* cam2 = sceneMgr->createCamera("cam2");
    Ogre::Camera* cam3 = sceneMgr->createCamera("cam3");
    Ogre::Camera* cam4 = sceneMgr->createCamera("cam4");
	Ogre::Viewport* vp1 = window->addViewport(cam1, 1, 0  , 0  , 0.5, 0.5);
	Ogre::Viewport* vp2 = window->addViewport(cam2, 2, 0.5, 0  , 0.5, 0.5);
	Ogre::Viewport* vp3 = window->addViewport(cam3, 3, 0  , 0.5, 0.5, 0.5);
	Ogre::Viewport* vp4 = window->addViewport(cam4, 4, 0.5, 0.5, 0.5, 0.5);
    vp1->setBackgroundColour(Ogre::ColourValue(1, 1, 1));
    vp2->setBackgroundColour(Ogre::ColourValue(1, 1, 1) * 0.95);
    vp3->setBackgroundColour(Ogre::ColourValue(1, 1, 1) * 0.95);
    vp4->setBackgroundColour(Ogre::ColourValue(1, 1, 1));
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    Ogre::Entity* model = sceneMgr->createEntity("model", "alexandria.mesh");
    Ogre::SceneNode* modelNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("modelnode1");
    modelNode1->attachObject(model);
    cam1->setNearClipDistance(5);
    cam2->setNearClipDistance(5);
    cam3->setNearClipDistance(5);
    cam4->setNearClipDistance(5);
	/*
    cam1->setPolygonMode(Ogre::PM_WIREFRAME);
    cam2->setPolygonMode(Ogre::PM_WIREFRAME);
    cam3->setPolygonMode(Ogre::PM_WIREFRAME);
    cam4->setPolygonMode(Ogre::PM_WIREFRAME);
	*/
    Ogre::SceneNode* camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
    Ogre::SceneNode* camNode2 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode2");
    Ogre::SceneNode* camNode3 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode3");
    Ogre::SceneNode* camNode4 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode4");
    camNode1->attachObject(cam1);
    camNode2->attachObject(cam2);
    camNode3->attachObject(cam3);
    camNode4->attachObject(cam4);
	Ogre::Quaternion q;
	q.FromAngleAxis(Ogre::Degree(90), Ogre::Vector3::UNIT_Y);
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	camNode2->setOrientation(q * camNode1->getOrientation());
	camNode3->setOrientation(q * camNode2->getOrientation());
	camNode4->setOrientation(q * camNode3->getOrientation());
    camNode1->setPosition(100, 100, 100);
    camNode2->setPosition(100, 100, -100);
    camNode3->setPosition(-100, 100, -100);
    camNode4->setPosition(-100, 100, 100);
    while(true) {
        Ogre::WindowEventUtilities::messagePump();
        if (window->isClosed()) {
            return 0;
        }
        if (!root->renderOneFrame()) {
            return 0;
        }
    }
    return 0;
}
Пример #29
0
void GraphicsImpl::chooseSceneManager()
{
	sceneMgr = root->createSceneManager("TerrainSceneManager");
}
Пример #30
0
int
main( int argc, char *argv[] )
{
    Ogre::Root*         root;
    Ogre::RenderWindow* window;

    root = new Ogre::Root( "", "" );
#ifndef _DEBUG
    root->loadPlugin( "RenderSystem_GL.dll" );
#else
    root->loadPlugin( "RenderSystem_GL_d.dll" );
#endif
    root->setRenderSystem( root->getAvailableRenderers()[ 0 ] );
    root->initialise( false );
    Ogre::NameValuePairList misc;
    misc[ "title" ] = "Xenogears SoundDumper";
    window = root->createRenderWindow( "QGearsWindow", 800, 600, false, &misc );




    LOGGER = new Logger( "game.log" );

    state = GAME;



    DisplayFrameListener* frame_listener = new DisplayFrameListener( window );
    root->addFrameListener( frame_listener );

    Ogre::SceneManager* scene_manager = root->createSceneManager( Ogre::ST_GENERIC, "Scene" );
    scene_manager->setAmbientLight( Ogre::ColourValue( 1.0, 1.0, 1.0 ) );

    Ogre::Camera* camera = scene_manager->createCamera( "Camera" );
    camera->setNearClipDistance( 5 );

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



    SOUNDMAN = new SoundManager();
    SOUND_PARSER = new SoundParser();



    Ogre::Root::getSingleton().startRendering();



    delete SOUND_PARSER;
    delete SOUNDMAN;



    delete root;
    delete frame_listener;

    delete LOGGER;

    return 0;
}