Example #1
0
void Application::go()
{
	Ogre::Timer loopTimer;

	bool continueRunning = true;
	while ( continueRunning )
	{
		Ogre::WindowEventUtilities::messagePump();
		
		SimpleInputManager::capture();

		// Update logic stuff

		// Update graphics stuff
		
		bool windowClosed = m_window->isClosed();
		continueRunning &= ! windowClosed;

		loopTimer.reset();
		bool renderFrameSuccess = m_root->renderOneFrame();
		continueRunning &= renderFrameSuccess;

		continueRunning &= ! m_exitRequested;		
	}
}
Example #2
0
void Application::update()
{
	Ogre::Timer loopTimer;

	bool continueRunning = true;
	
	while (continueRunning)
	{
		Ogre::WindowEventUtilities::messagePump();

		SimpleInputManager::capture();
		
		float elapsedSeconds = loopTimer.getMicroseconds() * 1.0 / 1000000;

		m_NXOgreTimeController->advance(elapsedSeconds);
	
		loopTimer.reset();

		updateOverlayInfo();

		bool renderFrameSuccess = m_root->renderOneFrame();
		
		if (!renderFrameSuccess || m_exitRequested)
		{
			continueRunning = false;
		}
	}
}
Example #3
0
	/**
	 * Releases the object's resources
	 */
	void MediaPlayerOCV::end()
	{
		// Check if already released
		if ( !isValid() )
			return;
		
        // Release thread
        if ( m_multithreaded && m_captureThread )
        {
            // Signal the thread and wait for it to be done
            m_captureThread->signal();
            Ogre::Timer timerLimit;
            timerLimit.reset();
            while( (m_captureThread->get_finished() == false) && (timerLimit.getMilliseconds() < 250) )
                ;
			if ( m_captureThread->get_finished() )
            {
                delete m_captureThread;
            }
            else
                LOG_CRITICAL( "MediaPlayerOCV: capture thread timer expired, and the thread did not finish. Something is wrong, there will be a memory leak" );
            m_captureThread = NULL;
        }
        
		// Clear resources
		m_capture.release();
        
        m_frameImg.end();
        
		// Clear flags
		m_bIsValid			= false;
		m_newBufferReady	= false;
		m_loopPending		= false;
	}
Example #4
0
void App::UpdThr()
{
	Ogre::Timer gtim;
	//#ifdef _WIN32
	//DWORD af = 2;
	//gtim.setOption("QueryAffinityMask", &af);
	//#endif
	gtim.reset();

	while (!mShutDown)
	{
		///  step Game  **

		double dt = double(gtim.getMicroseconds()) * 0.000001;
		gtim.reset();
		
		if (pSet->multi_thr == 1 && !bLoading)
		{
			bSimulating = true;
			bool ret = pGame->OneLoop(dt);
			if (!ret)
				mShutDown = true;

			DoNetworking();
			bSimulating = false;
		}
		boost::this_thread::sleep(boost::posix_time::milliseconds(pSet->thread_sleep));
	}
}
Example #5
0
void Application::go()
{
	Ogre::Timer loopTimer;

	bool continueRunning = true;
	while ( continueRunning )
	{
		Ogre::WindowEventUtilities::messagePump();
		
		SimpleInputManager::capture();

		// Update logic stuff
		float elapsedSeconds = loopTimer.getMicroseconds() * 1.0 / 1000000;
		updateLogic( elapsedSeconds );

		// Update graphics stuff
		updateAnimations( elapsedSeconds );
		
		bool windowClosed = m_window->isClosed();
		continueRunning &= ! windowClosed;

		updateStats();

		loopTimer.reset();
		bool renderFrameSuccess = m_root->renderOneFrame();
		continueRunning &= renderFrameSuccess;

		continueRunning &= ! m_exitRequested;		
	}
}
//  Run
//-------------------------------------------------------------------------------------
void BaseApp::Run( bool showDialog )
{
	mShowDialog = showDialog;
	if (!setup())
		return;

	if (!pSet->limit_fps)
		mRoot->startRendering();  // default
	else
	{	Ogre::Timer tim;
		while (1)
		{
			Ogre::WindowEventUtilities::messagePump();
			if (tim.getMicroseconds() > 1000000.0 / pSet->limit_fps_val)
			{
				tim.reset();
				if (!mRoot->renderOneFrame())
					break;
			}else
			if (pSet->limit_sleep >= 0)
				boost::this_thread::sleep(boost::posix_time::milliseconds(pSet->limit_sleep));
	}	}

	destroyScene();
}
Example #7
0
//Run the app
void Application::go()
{
	Ogre::Timer loopTimer;	
	long lastTick,currentTick;
	lastTick=loopTimer.getMillisecondsCPU();
	float fpsStep = 1.0f/(float)FPS;
	float frameDelta;
	bool continueRunning=true;
	while(continueRunning)
	{
		Ogre::WindowEventUtilities::messagePump();
		capture();

		currentTick=loopTimer.getMillisecondsCPU();
		frameDelta = (currentTick-lastTick)*0.001;
		static float logicUpdateCounter=0;
		logicUpdateCounter+=frameDelta;
		while (logicUpdateCounter>fpsStep)
		{
			logicUpdateCounter-=fpsStep;
			updateLogic(fpsStep);
			updateGraphics(fpsStep);
		}
		bool windowClosed = m_window->isClosed();
		continueRunning &= ! windowClosed;
		bool renderFrameSuccess = m_root->renderOneFrame();

		continueRunning &= renderFrameSuccess;
		continueRunning &= ! m_exitRequested;
		lastTick=currentTick;
	}
}
Example #8
0
void Application::initializeCEGUI()
{
    Ogre::Timer timer;
    timer.reset();

    CEGUI::OgreRenderer::bootstrapSystem(*mOgreWindow);

    mUIRoot = static_cast<CEGUI::GUISheet*>(CEGUI::WindowManager::getSingleton().createWindow("DefaultWindow", "Root"));
    mUIRoot->setPosition(CEGUI::UVector2(CEGUI::UDim(0, 0), CEGUI::UDim(0, 0)));
    mUIRoot->setSize(CEGUI::UVector2(CEGUI::UDim(1, 0), CEGUI::UDim(1, 0)));
    mUIRoot->setVisible(true);

    CEGUI::System::getSingleton().setGUISheet(mUIRoot);

    CEGUI::SchemeManager::getSingleton().create("OISBDemo.scheme");
	CEGUI::System::getSingleton().setDefaultMouseCursor("OgreTrayImages", "MouseArrow");
    CEGUI::MouseCursor::getSingleton().hide();

    //mUIRoot->addChildWindow(CEGUI::WindowManager::getSingleton().loadWindowLayout("Introduction.layout"));
    mUIRoot->addChildWindow(CEGUI::WindowManager::getSingleton().loadWindowLayout("HUD.layout"));
    mUIHUDThrottle = static_cast<CEGUI::ProgressBar*>(CEGUI::WindowManager::getSingleton().getWindow("HUD/Throttle"));
    mUIHUDVelocity = CEGUI::WindowManager::getSingleton().getWindow("HUD/Velocity");
    mUIHUDAltitude = CEGUI::WindowManager::getSingleton().getWindow("HUD/Altitude");

    std::stringstream sstr;
    sstr << timer.getMicroseconds();

    CEGUI::Logger::getSingleton().logEvent("Time to start CEGUI: " + sstr.str());
}
Example #9
0
//---------------------------------------------------------------------------
void HeatVisionListener::notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat)
{
    if(pass_id == 0xDEADBABE)
    {
        // "random_fractions" parameter
        fpParams->setNamedConstant("random_fractions", Ogre::Vector4(Ogre::Math::RangeRandom(0.0, 1.0), Ogre::Math::RangeRandom(0, 1.0), 0, 0));

        // "depth_modulator" parameter
        float inc = ((float)timer->getMilliseconds())/1000.0f;
        if ( (fabs(curr-end) <= 0.001) )
        {
            // take a new value to reach
            end = Ogre::Math::RangeRandom(0.95, 1.0);
            start = curr;
        }
        else
        {
            if (curr > end) curr -= inc;
            else curr += inc;
        }
        timer->reset();

        fpParams->setNamedConstant("depth_modulator", Ogre::Vector4(curr, 0, 0, 0));
    }
}
//-------------------------------------------------------------------------------------
void App::go(void)
{
#ifdef _DEBUG
    mResourcesCfg = "resources_d.cfg";
    mPluginsCfg = "plugins_d.cfg";
#else
    mResourcesCfg = "resources.cfg";
    mPluginsCfg = "plugins.cfg";
#endif

    if (!setup())
        return;
	
	Ogre::Timer timer;
	//mRoot->startRendering();
	float lastTime = timer.getMicroseconds()/1000000.0f;
	float curTime = timer.getMicroseconds()/1000000.0f;
	while(update(curTime - lastTime))
	{
		lastTime = curTime;
		curTime = timer.getMicroseconds()/1000000.0f;
		//timer.reset();
	}

    // clean up
    destroyScene();
}
Example #11
0
void OMW::Engine::go()
{
    assert (!mContentFiles.empty());
    assert (!mOgre);

    Settings::Manager settings;
    std::string settingspath;

    settingspath = loadSettings (settings);

    // Create encoder
    ToUTF8::Utf8Encoder encoder (mEncoding);
    mEncoder = &encoder;

    prepareEngine (settings);

    // Play some good 'ol tunes
    MWBase::Environment::get().getSoundManager()->playPlaylist(std::string("Explore"));

    if (!mSaveGameFile.empty())
    {
        MWBase::Environment::get().getStateManager()->loadGame(mSaveGameFile);
    }
    else if (!mSkipMenu)
    {
        // start in main menu
        MWBase::Environment::get().getWindowManager()->pushGuiMode (MWGui::GM_MainMenu);
        try
        {
            // Is there an ini setting for this filename or something?
            MWBase::Environment::get().getSoundManager()->streamMusic("Special/morrowind title.mp3");

            std::string logo = mFallbackMap["Movies_Morrowind_Logo"];
            if (!logo.empty())
                MWBase::Environment::get().getWindowManager()->playVideo(logo, true);
        }
        catch (...) {}
    }
    else
    {
        MWBase::Environment::get().getStateManager()->newGame (!mNewGame);
    }

    // Start the main rendering loop
    Ogre::Timer timer;
    while (!MWBase::Environment::get().getStateManager()->hasQuitRequest())
    {
        float dt = timer.getMilliseconds()/1000.f;
        dt = std::min(dt, 0.2f);

        timer.reset();
        Ogre::Root::getSingleton().renderOneFrame(dt);
    }
    // Save user settings
    settings.saveUser(settingspath);

    std::cout << "Quitting peacefully." << std::endl;
}
Example #12
0
	::FreeConsole();
}

void Game::Run()
{
	InitializeGame();
	ConnectToPVD();
	InitializeKinect();

	kinectController = BodyController();

	InputManager* inputManager = InputManager::GetInstance();

	inputManager->RegisterSensorListener(&kinectController);

	inputManager->BeginAllCapture();

	sceneManager = new SceneManager();
	sceneManager->Initialize(mWindow, mRoot);

	AllocConsole();
	freopen("conin$","r",stdin);
	freopen("conout$","w",stdout);
	freopen("conout$","w",stderr);
	printf("Debugging Window:\n");

	/*std::shared_ptr<GameScene> gameScene(new GameScene(sceneManager, mRoot, "Probending Arena", contestantData));
	sceneManager->FlagSceneSwitch(gameScene, true);
	gameScene.reset();*/

	std::shared_ptr<MenusScene> menuScene = std::make_shared<MenusScene>(sceneManager, mRoot, MenusScene::Screens::MainMenu);
	sceneManager->FlagSceneSwitch(menuScene, true);
	menuScene.reset();

	bool rendering = true;

	Ogre::Timer gameTimer = Ogre::Timer();
	float currentTime = 0;
	float previousTime = 0;

	while (rendering)
	{
		gameTimer.reset();
		
		if(!Update(currentTime / 1000.0f))
			rendering = false;

		//Ogre::WindowEventUtilities::messagePump();
#if(!MEMORY_LEAK_DETECT)
		mRoot->renderOneFrame();
#endif
		currentTime = (float)gameTimer.getMilliseconds();
		
//---------------------------------------------------------------------
unsigned long renderThreadApp(Ogre::ThreadHandle* threadHandle) {
	LeDernierMorkid::LeDernierMorkidThreadData* threadData     = reinterpret_cast<LeDernierMorkid::LeDernierMorkidThreadData*>(threadHandle->getUserParam());
	GraphicsSystem*                             graphicsSystem = threadData->graphicsSystem;
	Ogre::Barrier*                              barrier        = threadData->barrier;

	graphicsSystem->initialize("Le Dernier Morkid");
	graphicsSystem->getInputHandler()->setGrabMousePointer(true);
	graphicsSystem->getInputHandler()->setMouseVisible(false);
	barrier->sync();

	if (graphicsSystem->getQuit()) {
		graphicsSystem->deinitialize();
		return 0; // User cancelled config
	}

	graphicsSystem->createScene();
	barrier->sync();

	Ogre::RenderWindow* renderWindow = graphicsSystem->getRenderWindow();

	Ogre::Timer   timer;
	unsigned long startTime     = timer.getMicroseconds();
	double        timeSinceLast = 1.0 / 60.0;

	while (!graphicsSystem->getQuit()) {
		graphicsSystem->beginFrameParallel();
		graphicsSystem->update(timeSinceLast);
		graphicsSystem->finishFrameParallel();

		if (!renderWindow->isVisible()) {
			// Don't burn CPU cycles unnecessary when we're minimized.
			Ogre::Threads::Sleep(500);
		}

		unsigned long endTime = timer.getMicroseconds();
		timeSinceLast         = (endTime - startTime) / 1000000.0;
		timeSinceLast         = std::min(1.0, timeSinceLast); // Prevent from going haywire.
		startTime             = endTime;
	}

	barrier->sync();

	graphicsSystem->destroyScene();
	barrier->sync();

	graphicsSystem->deinitialize();
	barrier->sync();

	return 0;
}
Example #14
0
        unsigned long yield( double frameTime, unsigned long startTime )
        {
            unsigned long endTime = mExternalTimer->getMicroseconds();

            while( frameTime * 1000000.0 > (endTime - startTime) )
            {
                endTime = mExternalTimer->getMicroseconds();

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
                SwitchToThread();
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
                sched_yield();
#endif
            }

            return endTime;
        }
Example #15
0
//---------------------------------------------------------------------------
void HeatVisionListener::notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat)
{
    if(pass_id == 0xDEADBABE)
    {
        timer->reset();
        fpParams =
            mat->getTechnique(0)->getPass(0)->getFragmentProgramParameters();
    }
}
Example #16
0
void Application::run()
{
    initialize();
    setupScene();

    Ogre::Timer timer;
    timer.reset();

    mRunning = true;
    while (mRunning)
    {
        const Ogre::Real delta=
            timer.getMicroseconds() * static_cast<Ogre::Real>(0.000001f);
        timer.reset();

        runOneFrame(delta);
    }

    finalize();
}
Example #17
0
///  _Tool_	Warnings  ......................................................
///  check all tracks for warnings
///  Warning: takes about 16 sec
void CGui::ToolTracksWarnings()
{
	Ogre::Timer ti;
	LogO("ALL tracks warnings ---------\n");
	logWarn = true;

	for (int i=0; i < data->tracks->trks.size(); ++i)
	{	//  foreach track
		string trk = data->tracks->trks[i].name, path = gcom->pathTrk[0] +"/"+ trk +"/";
		/**/if (!(trk[0] >= 'A' && trk[0] <= 'Z'))  continue;
		/**/if (StringUtil::startsWith(trk,"test"))  continue;

		Scene sc;  sc.LoadXml(path +"scene.xml");
		SplineRoad rd(app);  rd.LoadFile(path +"road.xml");
		
		LogO("Track: "+trk);
		WarningsCheck(&sc,&rd);
	}
	LogO(String("::: Time ALL tracks: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");
	LogO("ALL tracks warnings ---------");
}
Example #18
0
    // FrameListener callback (~ idleFunc). Perform animation here
    bool frameRenderingQueued(const Ogre::FrameEvent& evt) {
        float t = mTimer.getMilliseconds()*0.001;

        // Do some simple animations by changing scene node transform parameters
        Ogre::SceneNode* triangle = mScene->getSceneNode("Triangle");
        triangle->resetToInitialState();
        triangle->rotate(Ogre::Vector3(0, 0, 1), Ogre::Radian(t));

        // Exercise 1: Use SceneNode to manipulate the object and create animation
        // ...

        return true; // Return false to quit
    }
Example #19
0
bool initOgreRoot(){
	try{
		// Create logs that funnel to android logs
		Ogre::LogManager *lm = OGRE_NEW Ogre::LogManager();
		Ogre::Log *l = lm->createLog("AndroidLog", true, true, true);
		g_ll = OGRE_NEW AndroidLogListener();
		l->addListener(g_ll);
		
		// Create a root object
		g_root = OGRE_NEW Ogre::Root("", "", "");
		
		// Register the ES2 plugin
		g_gles2Plugin = OGRE_NEW Ogre::GLES2Plugin();
		Ogre::Root::getSingleton().installPlugin(g_gles2Plugin);
		
		// Register particle plugin
		g_pfxPlugin = OGRE_NEW Ogre::ParticleFXPlugin();
		Ogre::Root::getSingleton().installPlugin(g_pfxPlugin);
		
		// Grab the available render systems
		const Ogre::RenderSystemList &renderSystemList = g_root->getAvailableRenderers();
		if(renderSystemList.empty())
		{
			return false;
		}
		
		// Set the render system and init
		Ogre::RenderSystem *system = renderSystemList.front();
		g_root->setRenderSystem(system);
		g_root->initialise(false);
		
		g_lastTime = g_timer.getMilliseconds();
		
		return true;
	}catch(Ogre::Exception &e){
	}
	return false;
}
Example #20
0
///--------------------------------------------------------------------------------------------------------------
//  Create Terrain
///--------------------------------------------------------------------------------------------------------------
void CScene::CreateTerrain(bool bNewHmap, bool bTer, bool terLoad)
{
	Ogre::Timer tm;
	terrain = 0;

	
	///  sky
	Vector3 scl = app->pSet->view_distance*Vector3::UNIT_SCALE;
	CreateSkyDome(sc->skyMtr, scl, sc->skyYaw);
	UpdFog();

	//  light
	app->mSceneMgr->destroyAllLights();
	sun = app->mSceneMgr->createLight("Sun");
	sun->setType(Light::LT_DIRECTIONAL);  UpdSun();


if (bTer)
{
	///.
	UpdShaderParams();
	UpdLayerPars();
	

	///  --------  fill HeightField data --------
	//Ogre::Timer ti;
	if (terLoad || bNewHmap)
	{
		int wx = sc->td.iVertsX, wy = sc->td.iVertsY, wxy = wx * wy;  //wy=wx
		delete[] sc->td.hfHeight;  sc->td.hfHeight = new float[wxy];
		const int size = wxy * sizeof(float);

		String name = app->gcom->TrkDir() + (bNewHmap ? "heightmap-new.f32" : "heightmap.f32");

		//  load from f32 HMap +
		{
			std::ifstream fi;
			fi.open(name.c_str(), std::ios_base::binary);
			fi.read((char*)&sc->td.hfHeight[0], size);
			fi.close();
		}
	}

	CreateBlendTex();  //+

	//LogO(String("::: Time Hmap: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");  ti.reset();  // 4MB ~13ms


	///.
	UpdBlendmap();
	

	//  Terrain
	{
		if (!mTerrainGlobals)
			mTerrainGlobals = OGRE_NEW TerrainGlobalOptions();
		OGRE_DELETE mTerrainGroup;

		mTerrainGroup = OGRE_NEW TerrainGroup(app->mSceneMgr, Terrain::ALIGN_X_Z,
			sc->td.iTerSize, sc->td.fTerWorldSize);
		mTerrainGroup->setOrigin(Vector3::ZERO);

		SetupTerrain();

		if (sc->td.hfHeight)
			mTerrainGroup->defineTerrain(0,0, sc->td.hfHeight);
		else
			mTerrainGroup->defineTerrain(0,0, 0.f);

		//  sync load since we want everything in place when we start
		mTerrainGroup->loadAllTerrains(true);

		TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator();
		while (ti.hasMoreElements())
		{
			Terrain* t = ti.getNext()->instance;
			terrain = t;  //<set
			terrain->setVisibilityFlags(RV_Terrain);
		}
		mTerrainGroup->freeTemporaryResources();
	}

	//  Horizon  ----------
	if (app->pSet->horizon)
	{
		if (!mHorizonGlobals)
			mHorizonGlobals = OGRE_NEW TerrainGlobalOptions();
		OGRE_DELETE mHorizonGroup;

		mHorizonGroup = OGRE_NEW TerrainGroup(app->mSceneMgr, Terrain::ALIGN_X_Z,
			sc->td.iTerSize, sc->td.fTerWorldSize * 16.f);
		mHorizonGroup->setOrigin(Vector3::ZERO);

		SetupHorizon();

		//if (sc->td.hfHeight)
		//	mHorizonGroup->defineTerrain(0,0, sc->td.hfHeight);
		//else
			mHorizonGroup->defineTerrain(0,0, 0.f);

		mHorizonGroup->loadAllTerrains(true);

		TerrainGroup::TerrainIterator ti = mHorizonGroup->getTerrainIterator();
		while (ti.hasMoreElements())
		{
			Terrain* t = ti.getNext()->instance;
			//initBlendMaps(t);
			horizon = t;  //<set
			horizon->setVisibilityFlags(RV_Terrain);
		}
		mHorizonGroup->freeTemporaryResources();
	}
}//bTer

	
	///.
	changeShadows();

	//UpdBlendmap();  //-

	LogO(String("::: Time Terrain: ") + fToStr(tm.getMilliseconds(),0,3) + " ms");
}
Example #21
0
void Client::Play() {
    OgreEasy::SimpleOgreInit lOgreInit;
    if(!lOgreInit.initOgre()) {
        std::cout<<"Could not init ogre"<<std::endl;
        return;
    }
    Ogre::Root* lRoot = lOgreInit.mRoot.get();
    Ogre::RenderWindow* lWindow = lOgreInit.mWindow;
    World* w = new World();
    w->SetDebugMode(false);
    GameObject camObject = w->AddObject("camera");
    camObject.AddCameraComponent("camera");
    camObject.SetPosition(Ogre::Vector3(0,0,0));
    camObject.LookAt(Ogre::Vector3(0,0,0));

    GameObject& light2 = w->AddObject("point_light");
    light2.AddLightComponent(Ogre::Light::LT_DIRECTIONAL);
    light2.SetPosition(Ogre::Vector3(0,0,40));
    light2.LookAt(Ogre::Vector3(0,100,0));

    GameObject& c = w->AddPhysicsObject("esine", "cube/Cube.mesh");
    c.SetPosition(Ogre::Vector3(0,0,0));
    c.AddBoxCollider(1,1,1);
    PhysicsComponent phys = c.GetPhysicsComponent();
    phys.SetMass(1.0);
    c.SetMaterial("tex");

    GameObject& c2 = w->AddPhysicsObject("esine2", "cube/Cube.mesh");
    c2.SetPosition(Ogre::Vector3(1,2,1));
    c2.AddBoxCollider(1,1,1);
    PhysicsComponent phys2 = c2.GetPhysicsComponent();
    phys2.SetMass(1.0);
    c2.SetMaterial("tex");

    GameObject& taso = w->AddPhysicsObject("taso", "cube/other/Cube.mesh");
    taso.SetPosition(Ogre::Vector3(0, -10, 0));
    taso.AddBoxCollider(10,0.1,10);
    taso.SetMaterial("plane");
    PhysicsComponent phys3 = taso.GetPhysicsComponent();
    phys3.SetMass(0.0);

    GameObject& anim = w->AddObject("anim"  , "second_anim/Cube.mesh");
    anim.SetPosition(Ogre::Vector3(0, -5, 0));
    anim.SetMaterial("tex");

    lRoot->clearEventTimes();
    float f=0.0;
    unsigned long t=0;
    double d;
    Ogre::Timer* a = new Ogre::Timer();
    while(!lWindow->isClosed()) {
        t=a->getMicroseconds();

        camObject.SetPosition(Ogre::Vector3(cos(f)*15.0, -5, sin(f)*15.0));
        camObject.LookAt(Ogre::Vector3(-0,-10,-0), Ogre::Vector3::UNIT_Y);
        w->Update(d);

        f+=d*.5;
        d = (double)(a->getMicroseconds()-t)/1000000;
    }
    delete w;
}
void App::LoadTrackEv()
{
	Ogre::Timer ti;
	NewCommon(false);  // full destroy
	iObjCur = -1;

	scn->DestroyRoad();
	scn->DestroyPace();
	

	// load scene
	scn->sc->LoadXml(gcom->TrkDir()+"scene.xml");
	scn->sc->vdr = IsVdrTrack();
	if (scn->sc->vdr)  scn->sc->ter = false;
	
	//  water RTT recreate
	scn->UpdateWaterRTT(mCamera);
	
	BltWorldInit();

	UpdWndTitle();

	scn->CreateFluids();

	scn->CreateWeather();


	//  set sky tex name for water
	sh::MaterialInstance* m = mFactory->getMaterialInstance(scn->sc->skyMtr);
	std::string skyTex = sh::retrieveValue<sh::StringValue>(m->getProperty("texture"), 0).get();
	sh::Factory::getInstance().setTextureAlias("SkyReflection", skyTex);
	sh::Factory::getInstance().setTextureAlias("CubeReflection", "ReflectionCube");


	bNewHmap = false;/**/
	scn->CreateTerrain(bNewHmap, scn->sc->ter);

	if (track)
	if (scn->sc->vdr)  // vdrift track
	{
		if (!LoadTrackVdr(pSet->gui.track))
			LogO("Error during track loading: " + pSet->gui.track);
		
		CreateVdrTrack(pSet->gui.track, track);
		CreateVdrTrackBlt();
	}


	//  road ~
	scn->road = new SplineRoad(this);
	scn->road->Setup("sphere.mesh", pSet->road_sphr, scn->terrain, mSceneMgr, mCamera);
	scn->road->LoadFile(gcom->TrkDir()+"road.xml");
	scn->UpdPSSMMaterials();
	
	//  pace ~ ~
	scn->pace = new PaceNotes(pSet);
	scn->pace->Setup(mSceneMgr, mCamera, scn->terrain, gui->mGui, mWindow);
	
	
	/// HW_Inst Test  * * *
	//inst = new Instanced();
	//inst->Create(mSceneMgr,"sphere_inst.mesh");
	
	
	CreateObjects();

	if (pSet->bTrees && scn->sc->ter)
		scn->CreateTrees();  // trees after objects so they aren't inside them


	//  updates after load
	//--------------------------
	gcom->ReadTrkStats();
	gui->SetGuiFromXmls();  ///
	
	Rnd2TexSetup();
	//UpdVisGui();
	//UpdStartPos();
	UpdEditWnds();  //

	try {
	TexturePtr tex = TextureManager::getSingleton().getByName("waterDepth.png");
	if (!tex.isNull())
		tex->reload();
	} catch(...) {  }

	gui->Status("#{Loaded}", 0.5,0.7,1.0);
	
	if (pSet->check_load)
		gui->WarningsCheck(scn->sc, scn->road);

	LogO(String("::: Time Load Track: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");
}
//  Create Scene
//-------------------------------------------------------------------------------------
void App::createScene()  // once, init
{
	//  prv tex
	int k=1024;
	prvView.Create(k,k,"PrvView");
	prvRoad.Create(k,k,"PrvRoad");
	 prvTer.Create(k,k,"PrvTer");

	scn->roadDens.Create(k+1,k+1,"RoadDens");
	
	///  ter lay tex
	for (int i=0; i < 6; ++i)
	{	String si = toStr(i);
		scn->texLayD[i].SetName("layD"+si);
		scn->texLayN[i].SetName("layN"+si);
	}


	//  camera
	asp = float(mWindow->getWidth())/float(mWindow->getHeight());
	mCamera->setFarClipDistance(pSet->view_distance*1.1f);
	mCamera->setNearClipDistance(0.1f);

	//  cam pos from last set
	mCamera->setPosition(Vector3(pSet->cam_x,pSet->cam_y,pSet->cam_z));
	mCamera->setDirection(Vector3(pSet->cam_dx,pSet->cam_dy,pSet->cam_dz).normalisedCopy());
	mViewport->setVisibilityMask(RV_MaskAll);  // hide prv cam rect

	//  tex fil
	MaterialManager::getSingleton().setDefaultTextureFiltering(TFO_ANISOTROPIC);
	MaterialManager::getSingleton().setDefaultAnisotropy(pSet->anisotropy);

	Ogre::Timer ti;


	//  data load xml
	scn->data->Load();
	scn->sc->pFluidsXml = scn->data->fluids;
	scn->sc->pReverbsXml = scn->data->reverbs;
	
	//  surfaces.cfg
	LoadAllSurfaces();
	
	LogO(String("::: Time load xmls: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");


	postInit();  // material factory

	//  gui  * * *
	if (pSet->startInMain)
		pSet->isMain = true;
		
	bGuiFocus = false/*true*/;  bMoveCam = true;  //*--

	gui->InitGui();
	

	///__  All  #if 0  in Release !!!

	///  _Tool_ scene  ...................
	#if 0
	gui->ToolSceneXml();
	exit(0);
	#endif
	
	///  _Tool_	warnings  ................
	///  takes some time
	#if 0
	gui->ToolTracksWarnings();
	exit(0);
	#endif
	

	TerCircleInit();
	createBrushPrv();
	
	///  _Tool_ brushes prv  .............
	#if 0
	gui->ToolBrushesPrv();
	#endif
		

	//  load
	if (pSet->autostart)
		LoadTrack();

	if (!pSet->autostart)
	{	bGuiFocus = true;  UpdVisGui();	}

	iObjTNew = 0;
	//SetObjNewType(0);  //?white


	gui->chkInputBar(0);  // upd vis
	gui->chkCamPos(0);
	gui->chkFps(0);
}
//  Setup
//-------------------------------------------------------------------------------------
bool BaseApp::setup()
{
	Ogre::Timer ti;
	LogO("*** start setup ***");

	if (pSet->rendersystem == "Default")
	{
		#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		pSet->rendersystem = "Direct3D9 Rendering Subsystem";
		#else
		pSet->rendersystem = "OpenGL Rendering Subsystem";
		#endif
	}
	//LogManager::getSingleton().setLogDetail(LL_BOREME);  //-

	#ifdef _DEBUG
	#define D_SUFFIX "_d"
	#else
	#define D_SUFFIX ""
	#endif

	//  when show ogre dialog is on, load both rendersystems so user can select
	if (pSet->ogre_dialog)
	{
		mRoot->loadPlugin(PATHMANAGER::OgrePluginDir() + "/RenderSystem_GL" + D_SUFFIX);
		#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		mRoot->loadPlugin(PATHMANAGER::OgrePluginDir() + "/RenderSystem_Direct3D9" + D_SUFFIX);
		#endif
	}else{
		if (pSet->rendersystem == "OpenGL Rendering Subsystem")
			mRoot->loadPlugin(PATHMANAGER::OgrePluginDir() + "/RenderSystem_GL" + D_SUFFIX);
		else if (pSet->rendersystem == "Direct3D9 Rendering Subsystem")
			mRoot->loadPlugin(PATHMANAGER::OgrePluginDir() + "/RenderSystem_Direct3D9" + D_SUFFIX);
	}

	mRoot->loadPlugin(PATHMANAGER::OgrePluginDir() + "/Plugin_ParticleFX" + D_SUFFIX);

	setupResources();

	if (!configure())
		return false;

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

	#if OGRE_VERSION >= MYGUI_DEFINE_VERSION(1, 9, 0) 
	Ogre::OverlaySystem* pOverlaySystem = new Ogre::OverlaySystem();
	mSceneMgr->addRenderQueueListener(pOverlaySystem);
	#endif

	createCamera();

	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	mSceneMgr->setFog(Ogre::FOG_NONE);

	loadResources();

	baseInitGui();

	createFrameListener();

	LogO(Ogre::String("::: Time Ogre Start: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");

	createScene();

	return true;
}
Example #25
0
MainMachineEvent SponsorsState::update(MainMachineInfo &info)
{
	Ogre::Timer timer;
	float timeStamp = 0;
	MainMachineEvent result = MME_DONE;
	Ogre::Real frameTime = 0;
	float press = false;

	// check we have loaded both overlays
	ASSERT(mFader);
	ASSERT(mOverlay);

	// here is the main loop
	bool running = true;
	mAccumTime = mFaderTime;
	mFader->show();
	mOverlay->show();
	while(running) {
		timeStamp = timer.getMilliseconds();

		GLOBAL_KEYBOARD->capture();
		if(GLOBAL_KEYBOARD->isKeyDown(OIS::KC_ESCAPE)){
			break;
		}

		// depending on the state we call the function
		switch(mState){
		case STATE_FADE_IN:
			if(enterFade(frameTime)){
				mState = STATE_SPONSORS;
				mAccumTime = 0;
				mFader->hide();
			}
			break;
		case STATE_SPONSORS:
			if(showSponsors(frameTime)){
				mState = STATE_FADE_OUT;
				mAccumTime = 0;
				mFader->show();
			}
			break;
		case STATE_FADE_OUT:
			if(exitFade(frameTime)){
				mState = STATE_END;
			}
			break;
		case STATE_END:
			running = false;
			break;
		default:
			ASSERT(false);
		}

		// render the frame
		if(!GLOBAL_ROOT->renderOneFrame()){
			result = MME_DONE; //TODO: poner un erro real aca
			break;
		}

		// This must be called when we use the renderOneFrame approach
		Ogre::WindowEventUtilities::messagePump();

		frameTime = (timer.getMilliseconds() - timeStamp) * 0.001;
	}

	return result;
}
Example #26
0
 bool mouseReleased(const OIS::MouseEvent& evt, OIS::MouseButtonID id)
 {
  if (evt.state.buttonDown(OIS::MB_Left) == false)
   SdkSample::mouseReleased(evt, id);
  
  Ogre::Ray ray = mTrayMgr->getCursorRay(mCamera);

  beastie::ray_query result;
  
  Ogre::Timer timer;
  unsigned long rayTime = 0;
  
  timer.reset();
  bool ret = mTree->intersect(ray, 10000, result);
  rayTime = timer.getMicroseconds();
  
  mResultObject->beginUpdate(0);
  
  if (ret)
  {
   // Hit something.

   mResultObject->position(result.hitTriangle.a + (result.hitTriangle.n * 3.f));
   mResultObject->position(result.hitTriangle.b + (result.hitTriangle.n * 3.f));
   mResultObject->position(result.hitTriangle.c + (result.hitTriangle.n * 3.f));
   
   mHitPosLabelX->setCaption(Ogre::StringConverter::toString(result.globalPosition.x));
   mHitPosLabelY->setCaption(Ogre::StringConverter::toString(result.globalPosition.y));
   mHitPosLabelZ->setCaption(Ogre::StringConverter::toString(result.globalPosition.z));

  }
  else
  {
   // Didn't hit anything.
   
   // Try raycasting the ground plane.
   Ogre::Vector3 globalPosition;
  
   if (beastie::intersections::line( beastie::line(ray, 100000) , mPlane, globalPosition ))
   {
    mHitPosLabelX->setCaption(Ogre::StringConverter::toString(globalPosition.x));
    mHitPosLabelY->setCaption(Ogre::StringConverter::toString(globalPosition.y));
    mHitPosLabelZ->setCaption(Ogre::StringConverter::toString(globalPosition.z));

    float const radius = 50;
 
    // accuracy is the count of points (and lines).
    // Higher values make the circle smoother, but may slowdown the performance.
    // The performance also is related to the count of circles.
    float const accuracy = 15;
 
    for(float theta = 0; theta <= 2 * Math::PI; theta += Ogre::Math::PI / accuracy) {
      mResultObject->position(globalPosition.x + (radius * cos(theta)), 0, globalPosition.z + (radius * sin(theta)));
      mResultObject->position(globalPosition);
    }


   }
   else
   {
    
    // Really didn't click on anything at all.
    
    mHitPosLabelX->setCaption("-");
    mHitPosLabelY->setCaption("-");
    mHitPosLabelZ->setCaption("-");
    mResultObject->position(0,0,0);
    mResultObject->position(0,0,0);
    mResultObject->position(0,0,0);
    
   }
   
   
  }
  
  mResultObject->end();

  return true;
 }
Example #27
0
//--------------------------------------------------------------------------------------------------
bool DiscoApplication::frameStarted( const Ogre::FrameEvent& evt )
{
	static Ogre::Timer a;

	static uint32_t lastTimeMS;
	static uint32_t curTimeMS;

	curTimeMS = a.getMilliseconds();
	uint32_t timeDiffMS = curTimeMS - lastTimeMS;

	if ( timeDiffMS > 0 )
	{
		//printf( "FPS = %f\n", 1000.0/(float)timeDiffMS );//1.0/((float)timeDiffMS/1000.0) );
	}
	lastTimeMS = curTimeMS;

	const int32_t MAX_DEPTH_MM = 10000;
	const float FOCAL_LENGTH = 0.525f;	// Focal length in metres
	const float FADE_START_XZ_DISTANCE = 0.5f;
	const float FADE_MAX_XZ_DISTANCE = 6.0f;

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;

	mpKinectController->getContext().WaitAndUpdateAll();
	mpKinectController->getDepthGenerator().GetMetaData( depthMD );
	mpKinectController->getUserGenerator().GetUserPixels( 0, sceneMD );

	XnUserID userIdx[15];
	XnUInt16 numUsers = 15;
	mpKinectController->getUserGenerator().GetUsers( userIdx, numUsers );

	if ( 0 == numUsers )
	{
		// Restart the time if there are no users to record
		mRecordingGapTimer.reset();
	}
	else
	{
		for ( uint32_t i = 0; i < numUsers; i++ )
		{
			if ( tryToAttachParticleToUser( userIdx[ i ] ) )
			{
				break;
			}
		}
	}

	// Start recording if we see a person
	if ( numUsers > 0 && !mbRecording
		&& mRecordingGapTimer.getMilliseconds() > TIME_BETWEEN_RECORDINGS_MS )
	{
		mbRecording = true;
		memset( mpImageData, 0, RECORDED_DATA_SIZE );
		mRecordingFrameIdx = 0;
	}


	// Build an accumulative histogram to work out the colour for each point
	uint32_t depthHist[ MAX_DEPTH_MM ];
	memset( depthHist, 0, sizeof( depthHist ) );

	uint32_t numPoints = 0;

	const XnDepthPixel* pDepth = depthMD.Data();

	int32_t recordingPixelStepX = depthMD.XRes() / SMALL_FRAME_WIDTH;
	int32_t recordingPixelStepY = depthMD.YRes() / SMALL_FRAME_HEIGHT;
	if ( recordingPixelStepX <= 0 ) recordingPixelStepX = 1;
	if ( recordingPixelStepY <= 0 ) recordingPixelStepY = 1;

	for ( uint32_t y = 0; y < depthMD.YRes(); y++ )
	{
		for ( uint32_t x = 0; x < depthMD.XRes(); x++ )
		{
			XnUInt16 value = *pDepth;

			if ( 0 != value )
			{
				depthHist[ value ]++;
				numPoints++;
			}

			pDepth++;
		}
	}

	for ( uint32_t i = 1; i < MAX_DEPTH_MM; i++ )
	{
		depthHist[ i ] += depthHist[ i - 1 ];
	}

	if ( numPoints > 0 )
	{
		for ( uint32_t i = 1; i < MAX_DEPTH_MM; i++ )
		{
			depthHist[ i ] = (unsigned int)(256 * (1.0f - ((float)depthHist[ i ] / numPoints)));
		}
	}

	// Update the point cloud to reflect the depth data
	const float COLOURS[][3] =
	{
		{0,1,1},
		{0,0,1},
		{0,1,0},
		{1,1,0},
		{1,0,0},
		{1,.5,0},
		{.5,1,0},
		{0,.5,1},
		{.5,0,1},
		{1,1,.5},
		{1,1,1}
	};
	const uint32_t NUM_COLOURS = 10;

	pDepth = depthMD.Data();
	const XnLabel* pLabels = sceneMD.Data();


	mpRosPointCloud->clear();

	ogre_tools::PointCloud::Point* pPoints = new ogre_tools::PointCloud::Point[ numPoints ];
	int32_t pointIdx = 0;

	int32_t width = depthMD.XRes();
	int32_t height = depthMD.YRes();
	int32_t halfWidth = width / 2;
	int32_t halfHeight = height / 2;

	for ( int32_t y = 0; y < height; y++ )
	{
		for ( int32_t x = 0; x < width; x++ )
		{
			XnUInt16 value = *pDepth;
			XnLabel label = *pLabels;
			XnUInt32 colorId = label % NUM_COLOURS;

			float fade = 1.0;

			if (label == 0)
			{
				// Ignore background
				colorId = NUM_COLOURS;
			}


			{

				float worldZ = (float)(*pDepth)/1000.0;		// Convert from mm to m
				float worldX = (((float)(x-halfWidth)/1000.0)*worldZ) / FOCAL_LENGTH;

				float distanceXZ = sqrtf( worldX*worldX + worldZ*worldZ );
				if ( distanceXZ > FADE_MAX_XZ_DISTANCE )
				{
					fade = 0.0f;
				}
				else if ( distanceXZ > FADE_START_XZ_DISTANCE )
				{
					fade = 1.0 - (distanceXZ - FADE_START_XZ_DISTANCE)/(FADE_MAX_XZ_DISTANCE - FADE_START_XZ_DISTANCE);
				}
			}

			if ( //mbRecording
				0 != value && fade > 0.0
				&& ( SHOW_BACKGROUND || label != 0 ) )
			{
				float worldZ = (float)(*pDepth)/1000.0;		// Convert from mm to m
				float worldX = (((float)(x-halfWidth)/1000.0)*worldZ) / FOCAL_LENGTH;
				float worldY = (((float)(y-halfHeight)/1000.0)*worldZ) / FOCAL_LENGTH;
				//float worldY = (((float)(((height-1)-y)-halfHeight)/1000.0)*worldZ) / FOCAL_LENGTH;

				float histValue = (float)depthHist[ value ]/255.0;

				pPoints[ pointIdx ].setColor(
					fade * histValue * COLOURS[ colorId ][ 0 ],
					fade * histValue * COLOURS[ colorId ][ 1 ],
					fade * histValue * COLOURS[ colorId ][ 2 ] );

				pPoints[ pointIdx ].x = worldX;
				pPoints[ pointIdx ].y = worldY;
				pPoints[ pointIdx ].z = worldZ;

				pointIdx++;

				if ( mbRecording && label != 0
					&& x%recordingPixelStepX == 0 && y%recordingPixelStepY == 0 )
				{
					int32_t smallFrameX = x / recordingPixelStepX;
					int32_t smallFrameY = y / recordingPixelStepY;

					int32_t smallPixelIdx = mRecordingFrameIdx*SMALL_FRAME_WIDTH*SMALL_FRAME_HEIGHT
						+ smallFrameY*SMALL_FRAME_WIDTH + smallFrameX;

					//((uint16_t*)mpImageData)[ smallPixelIdx ] = 0xFFFF;
					//((uint32_t*)mpImageData)[ smallPixelIdx ] = 0xFFFFFFFF;

					mpImageData[ smallPixelIdx ] = 0xFF; // 255; //(uint8_t)(fade * histValue * 255.0);
					//printf( "recorded %i to pixel %i\n", mpImageData[ smallPixelIdx ], smallPixelIdx );
				}
			}

			pDepth++;
			pLabels++;
		}
	}

	mpRosPointCloud->addPoints( pPoints, pointIdx );
	//printf( "Added %i points\n", pointIdx );

	delete [] pPoints;

	// Draw the crowd
	uint32_t numCrowdMembers = mCrowdMembers.size();
	mpCrowdObject->clear();
	mpCrowdObject->estimateVertexCount( numCrowdMembers*4 );
	mpCrowdObject->estimateIndexCount( numCrowdMembers*12 );

	for ( uint32_t personIdx = 0; personIdx < numCrowdMembers; personIdx++ )
	{
		CrowdMember& crowdMember = mCrowdMembers[ personIdx ];

		float startV = (float)crowdMember.mFrameIdx/(float)NUM_FRAMES_TO_RECORD;
		float endV = (float)(crowdMember.mFrameIdx+1)/(float)NUM_FRAMES_TO_RECORD;

		mpCrowdObject->begin( crowdMember.mMaterialName, Ogre::RenderOperation::OT_TRIANGLE_LIST );

		//float startV = 0.0; //(float)crowdMember.mFrameIdx/(float)NUM_FRAMES_TO_RECORD;
		//float endV = 1.0;// (float)(crowdMember.mFrameIdx+1)/(float)NUM_FRAMES_TO_RECORD;

		//mpCrowdObject->begin( "Template/CutOut", Ogre::RenderOperation::OT_TRIANGLE_LIST );


		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( -0.5f, -0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 0.0, startV );
		mpCrowdObject->colour( COLOURS[ crowdMember.mColourIdx ][ 0 ],
			COLOURS[ crowdMember.mColourIdx ][ 1 ], COLOURS[ crowdMember.mColourIdx ][ 2 ], 1.0 );

		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( 0.5f, -0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 1.0, startV );

		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( 0.5f, 0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 1.0, endV );

		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( -0.5f, 0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 0.0, endV );

		//mpCrowdObject->quad( 0, 1, 2, 3 );
		mpCrowdObject->quad( 3, 2, 1, 0 );

		mpCrowdObject->end();

		// Move to the next frame
		if ( crowdMember.mbReversing )
		{
			crowdMember.mFrameIdx--;
			if ( crowdMember.mFrameIdx < 0 )
			{
				crowdMember.mFrameIdx = 1;
				crowdMember.mbReversing = false;
			}
		}
		else
		{
			crowdMember.mFrameIdx++;
			if ( crowdMember.mFrameIdx >= NUM_FRAMES_TO_RECORD )
			{
				crowdMember.mFrameIdx = NUM_FRAMES_TO_RECORD-1;
				crowdMember.mbReversing = true;
			}
		}
	}


	// Check to see if we can stop recording
	if ( mbRecording )
	{
		mRecordingFrameIdx++;
		if ( mRecordingFrameIdx >= NUM_FRAMES_TO_RECORD )
		{
			// Create a new crowd member
			Ogre::Image image;
			image.loadDynamicImage(
				mpImageData, SMALL_FRAME_WIDTH, NUM_FRAMES_TO_RECORD*SMALL_FRAME_HEIGHT, 1, Ogre::PF_A4L4 );

			std::stringstream ss;
			ss << "RecordedSequenceTex_" << numCrowdMembers;
			Ogre::String texName = ss.str();

			Ogre::TextureManager* pTextureMgr = Ogre::TextureManager::getSingletonPtr();
			Ogre::TexturePtr pTexture = pTextureMgr->loadImage( texName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, image );

			ss.clear();
			ss << "RecordedSequenceMat_" << numCrowdMembers;
			Ogre::String matName = ss.str();

			Ogre::MaterialManager* pMatMgr = Ogre::MaterialManager::getSingletonPtr();
			Ogre::MaterialPtr pSrcMat = (Ogre::MaterialPtr)pMatMgr->getByName( "Template/CutOut", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
			Ogre::MaterialPtr pMat = pSrcMat->clone( matName ); //  (Ogre::MaterialPtr)pMatMgr->create( matName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );

			pMat->getTechnique( 0 )->getPass( 0 )->removeAllTextureUnitStates();
			Ogre::TextureUnitState* pTex = pMat->getTechnique( 0 )->getPass( 0 )->createTextureUnitState( texName, 0 );
			pMat->getTechnique( 0 )->getPass( 0 )->addTextureUnitState( pTex );

			/*Ogre::Technique* pTech = pMat->getTechnique( 0 );
			pTech->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );

			Ogre::Pass *pPass = pTech->createPass();

			pPass->setLightingEnabled( false );

			pPass->setAmbient( 1.0, 1.0, 1.0 );
			pPass->setDiffuse( 1.0, 1.0, 1.0, 1.0 );
			pPass->setSpecular( 0.0, 0.0, 0.0, 0.0 );

			Ogre::ColourValue val(0.0f, 0.0f, 0.0f, 1.0f);
			pPass->setSelfIllumination(val);

			//pPass->setE ( 0.0, 0.0, 0.0, 0.0 );

			pPass->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );
			pPass->setDepthWriteEnabled( false );

			Ogre::TextureUnitState* pTex = pPass->createTextureUnitState( texName, 0 );
			pPass->addTextureUnitState( pTex );


			pTex->setColourOperation( Ogre::LBO_MODULATE );*/

			pMat->setCullingMode( Ogre::CULL_NONE );
			pMat->compile();

			CrowdMember crowdMember;
			crowdMember.mMaterialName = matName;
			crowdMember.mFrameIdx = 0;
			crowdMember.mColourIdx = rand()%NUM_COLOURS;
			crowdMember.mbReversing = false;

			int32_t rowIdx = rand()%NUM_ROWS;
			float angle = MIN_CROWD_ANGLE + ((float)rand()/(float)RAND_MAX)*(MAX_CROWD_ANGLE-MIN_CROWD_ANGLE);
			float x = ROW_DEPTHS[ rowIdx ]*sin( angle );
			float z = ROW_DEPTHS[ rowIdx ]*cos( angle );
			crowdMember.mPos = Ogre::Vector3( x, ROW_HEIGHTS[ rowIdx ], z );
			mCrowdMembers.push_back( crowdMember );

			mbRecording = false;
			mRecordingGapTimer.reset();		// Reset time so that there's a gap between recording
			printf( "Got frame\n" );
		}
	}

	return true;
}
Example #28
0
/*!
 * Starts the main event loop. This function does not return, unless the
 * application is supposed to quit - either by closing the rendering window or
 * by telling the \ref InputHandler to quit (see \ref InputHandler::queueQuit).
 */
void TestApp::startEventLoop()
{
//    try {
        Ogre::Timer timer;
        unsigned long lastFrameStarted = timer.getMilliseconds();

        mFrameCount = 0;

    #ifdef USE_CALLGRIND
        CALLGRIND_START_INSTRUMENTATION;
        CALLGRIND_TOGGLE_COLLECT; // switch collect off
    #endif
        while (!mInputHandler->getWantQuit() && (!mRenderWindow->isClosed() || !mUseGUI))
		{
            mFrameHistory->startFrame();

            // emulate Ogre's timeSinceLastFrame feature
            unsigned long now = timer.getMilliseconds();
            float timeSinceLastFrame = ((float)(now - lastFrameStarted)) / 1000.0f;
            lastFrameStarted = now;

            mInputHandler->captureInput(timeSinceLastFrame);
            Ogre::WindowEventUtilities::messagePump();

            // AB: note: a "scene frame" is not necessarily a "graphic frame".
            // -> the collision detection library may be called more often or less
            //    often than ogre.
            //    usually we should NOT couple the scene speed to the rendering
            //    speed, otherwise the scene will be VERY fast with a newer graphic
            //    card
            //
            //    we do this here atm for the sake of simplicity only. we really
            //    should use a timer instead.
            if (!mInputHandler->getPause() )
			{
                
                if (!mInputHandler->isChecked("PauseMovements"))
				{
                    mSceneUpdateHistory->startFrame();
                    mScene->beginNextSceneFrame();
                }

                    mSceneUpdateHistory->stopFrame();
            }

            if (mUseGUI)
			{
                if (!mGui->updateGui(mInputHandler->getPause()))
				{
                    mInputHandler->queueQuit();
                }

                mGraphicFrameHistory->startFrame();
                mOgreRoot->renderOneFrame();
                mGraphicFrameHistory->stopFrame();
            }

            mFrameHistory->stopFrame();

            mFrameCount++;
            if (mMaxFrameCount > 0 && mFrameCount >= mMaxFrameCount)
			{
                mInputHandler->queueQuit();
            }
        }
    //} catch (Exception e) {
    //    std::cerr   << "Unhandled exception reached main-program: \n"
    //            << e.getErrorMessage() <<std::endl;
    //    e.printBacktrace();
    //    exit(1);
    //}
}
void World::processInput()
{
	using namespace OIS;
	static Ogre::Timer timer;
	static unsigned long lastTime = 0;
	unsigned long currentTime = timer.getMilliseconds();

	//Calculate the amount of time passed since the last frame
	Real timeScale = (currentTime - lastTime) * 0.001f;
	if (timeScale < 0.001f)
		timeScale = 0.001f;
	lastTime = currentTime;

	//Get the current state of the keyboard and mouse
	keyboard->capture();
	mouse->capture();

	//Always exit if ESC is pressed
	if (keyboard->isKeyDown(OIS::KC_ESCAPE))
		running = false;

	//Reload the scene if R is pressed
	static bool reloadedLast = false;
	if (keyboard->isKeyDown(OIS::KC_R) && !reloadedLast){
		unload();
		load();
		reloadedLast = true;
	}
	else {
		reloadedLast = false;
	}

	//Get mouse movement
	const OIS::MouseState &ms = mouse->getMouseState();

	//Update camera rotation based on the mouse
	camYaw += Radian(-ms.X.rel / 200.0f);
	camPitch += Radian(-ms.Y.rel / 200.0f);
	camera->setOrientation(Quaternion::IDENTITY);
	camera->pitch(camPitch);
	camera->yaw(camYaw);

	//Allow the camera to move around with the arrow/WASD keys
	Ogre::Vector3 trans(0, 0, 0);
	if (keyboard->isKeyDown(KC_UP) || keyboard->isKeyDown(KC_W))
		trans.z = -1;
	if (keyboard->isKeyDown(KC_DOWN) || keyboard->isKeyDown(KC_S))
		trans.z = 1;
	if (keyboard->isKeyDown(KC_RIGHT) || keyboard->isKeyDown(KC_D))
		trans.x = 1;
	if (keyboard->isKeyDown(KC_LEFT) || keyboard->isKeyDown(KC_A))
		trans.x = -1;
	if (keyboard->isKeyDown(KC_PGUP) || keyboard->isKeyDown(KC_E))
		trans.y = 1;
	if (keyboard->isKeyDown(KC_PGDOWN) || keyboard->isKeyDown(KC_Q))
		trans.y = -1;

	//Shift = speed boost
	if (keyboard->isKeyDown(KC_LSHIFT) || keyboard->isKeyDown(KC_RSHIFT))
		trans *= 4;
	else
		trans *= 0.5f;

	trans *= 30;
	camera->moveRelative(trans * timeScale);

	//Make sure the camera doesn't go under the terrain
	Ogre::Vector3 camPos = camera->getPosition();
	float terrY = HeightFunction::getTerrainHeight(camPos.x, camPos.z);
	if (camPos.y < terrY + 1.5 || !keyboard->isKeyDown(KC_SPACE)){		//Space = walk
		camPos.y = terrY + 1.5;
		camera->setPosition(camPos);
	}
}
//----------------------------------------------------------------------------------------------------------------------------------
///  Load  (.car file)
//----------------------------------------------------------------------------------------------------------------------------------
bool CARDYNAMICS::Load(GAME* game, CONFIGFILE & c, ostream & error_output)
{
	pGame = game;
	Ogre::Timer ti;

	//bTerrain = false;
	string drive = "RWD";
	int version(1);
	c.GetParam("version", version);
	if (version > 2)
	{
		error_output << "Unsupported car version: " << version << endl;
		return false;
	}
	float temp_vec3[3];

	//load the engine
	{
		float mass, rpm_limit, inertia, friction,
			start_rpm, stall_rpm, fuel_consumption;
		MATHVECTOR<double,3> position;

		if (!c.GetParam("engine.rpm-limit", rpm_limit, error_output))  return false;
		engine.SetRpmMax(rpm_limit);

		if (!c.GetParam("engine.inertia", inertia, error_output))  return false;
		engine.SetInertia(inertia);

		if (!c.GetParam("engine.friction", friction, error_output))  return false;
		engine.SetFrictionB(friction);

		if (!c.GetParam("engine.start-rpm", start_rpm, error_output))  return false;
		engine.SetStartRPM(start_rpm);

		if (!c.GetParam("engine.stall-rpm", stall_rpm, error_output))  return false;
		engine.SetStallRPM(stall_rpm);

		if (!c.GetParam("engine.fuel-consumption", fuel_consumption, error_output))  return false;
		engine.SetFuelConsumption(fuel_consumption);

		if (!c.GetParam("engine.mass", mass, error_output))  return false;
		if (!c.GetParam("engine.position", temp_vec3, error_output))  return false;
		if (version == 2)  ConvertV2to1(temp_vec3[0],temp_vec3[1],temp_vec3[2]);
		position.Set(temp_vec3[0],temp_vec3[1],temp_vec3[2]);
		engine.SetMass(mass);
		engine.SetPosition(position);
		AddMassParticle(mass, position);

		float mul = 1.f, max_torque = 0;
		c.GetParam("engine.torque-val-mul", mul);

		float torque_point[3];
		string torque_str("engine.torque-curve-00");
		vector <pair <double, double> > torques;
		int curve_num = 0;
		while (c.GetParam(torque_str, torque_point))
		{
			max_torque = max(max_torque, torque_point[1] * mul);
			torques.push_back(pair <float, float> (torque_point[0], torque_point[1] * mul));

			curve_num++;
			stringstream str;
			str << "engine.torque-curve-";  str.width(2);  str.fill('0');
			str << curve_num;
			torque_str = str.str();
		}
		if (torques.size() <= 1)
		{
			error_output << "You must define at least 2 torque curve points." << endl;
			return false;
		}
		engine.SetTorqueCurve(rpm_limit, torques);

		//load the clutch
		{
			float mul;  //max_torque = sliding * radius * area * max_pressure;
			//if (!c.GetParam("clutch.max-torque", max_torque, error_output))  return false;
			if (!c.GetParam("clutch.max-torque-mul", mul, error_output))  return false;
			clutch.SetMaxTorque(max_torque * mul);
		}

		//  factor for stats  -
		mul = 1.f;
		if (c.GetParam("engine.real-pow-tq-mul", mul))
			engine.real_pow_tq_mul = mul;
		
		mul = 1.f;
		if (c.GetParam("engine.sound-vol-mul", mul))
			engine_vol_mul = mul;
	}

	//load the transmission
	{
		float time = 0;
		float ratio;
		int gears;

		c.GetParam("transmission.shift-delay", time);
		shift_time = time;

		if (!c.GetParam("transmission.gear-ratio-r", ratio, error_output))  return false;
		transmission.SetGearRatio(-1, ratio);

		if (!c.GetParam("transmission.gears", gears, error_output))  return false;

		for (int i = 0; i < gears; i++)
		{
			stringstream s;
			s << "transmission.gear-ratio-" << i+1;
			if (!c.GetParam(s.str(), ratio, error_output))  return false;
			transmission.SetGearRatio(i+1, ratio);
		}
	}

	//load the differential(s)
	string drivetype;
	if (!c.GetParam("drive", drivetype, error_output))  return false;

	if (drivetype == "hover")  //>
	{	hover = true;  drivetype = "AWD";  }
	else if (drivetype == "sphere")
	{	sphere = true;  drivetype = "AWD";  }
	//if (!hover)
		SetDrive(drivetype);

	float final_drive, a, a_tq(0), a_tq_dec(0);
	///  new 3 sets
	if (drivetype == "AWD" &&
		c.GetParam("diff-center.final-drive", a))
	{
		c.GetParam("diff-rear.anti-slip", a, error_output);
		c.GetParam("diff-rear.torque", a_tq);
		c.GetParam("diff-rear.torque-dec", a_tq_dec);
		diff_rear.SetFinalDrive(1.0);
		diff_rear.SetAntiSlip(a, a_tq, a_tq_dec);

		c.GetParam("diff-front.anti-slip", a, error_output);
		c.GetParam("diff-front.torque", a_tq);
		c.GetParam("diff-front.torque-dec", a_tq_dec);
		diff_front.SetFinalDrive(1.0);
		diff_front.SetAntiSlip(a, a_tq, a_tq_dec);

		c.GetParam("diff-center.final-drive", final_drive, error_output);
		c.GetParam("diff-center.anti-slip", a, error_output);
		c.GetParam("diff-center.torque", a_tq);
		c.GetParam("diff-center.torque-dec", a_tq_dec);
		diff_center.SetFinalDrive(final_drive);
		diff_center.SetAntiSlip(a, a_tq, a_tq_dec);
	}
	else  // old 1 for all
	{
		if (!c.GetParam("differential.final-drive", final_drive, error_output))  return false;
		if (!c.GetParam("differential.anti-slip", a, error_output))  return false;
		c.GetParam("differential.torque", a_tq);
		c.GetParam("differential.torque-dec", a_tq_dec);

		if (drivetype == "RWD")
		{
			diff_rear.SetFinalDrive(final_drive);
			diff_rear.SetAntiSlip(a, a_tq, a_tq_dec);
		}
		else if (drivetype == "FWD")
		{
			diff_front.SetFinalDrive(final_drive);
			diff_front.SetAntiSlip(a, a_tq, a_tq_dec);
		}
		else if (drivetype == "AWD")
		{
			diff_rear.SetFinalDrive(1.0);
			diff_rear.SetAntiSlip(a, a_tq, a_tq_dec);

			diff_front.SetFinalDrive(1.0);
			diff_front.SetAntiSlip(a, a_tq, a_tq_dec);

			diff_center.SetFinalDrive(final_drive);
			diff_center.SetAntiSlip(a, a_tq, a_tq_dec);
		}else
		{	error_output << "Unknown drive type: " << drive << endl;
			return false;
		}
	}

	//load the brake
	{
		for (int i = 0; i < 2; i++)
		{
			string pos = "front";
			WHEEL_POSITION left = FRONT_LEFT;
			WHEEL_POSITION right = FRONT_RIGHT;
			if (i == 1)
			{
				left = REAR_LEFT;
				right = REAR_RIGHT;
				pos = "rear";
			}

			float friction, max_pressure, area, bias, radius, handbrake(0);

			if (!c.GetParam("brakes-"+pos+".friction", friction, error_output))  return false;
			brake[left].SetFriction(friction);
			brake[right].SetFriction(friction);

			if (!c.GetParam("brakes-"+pos+".area", area, error_output))  return false;
			brake[left].SetArea(area);
			brake[right].SetArea(area);

			if (!c.GetParam("brakes-"+pos+".radius", radius, error_output))  return false;
			brake[left].SetRadius(radius);
			brake[right].SetRadius(radius);

			c.GetParam("brakes-"+pos+".handbrake", handbrake);
			brake[left].SetHandbrake(handbrake);
			brake[right].SetHandbrake(handbrake);

			if (!c.GetParam("brakes-"+pos+".bias", bias, error_output))  return false;
			brake[left].SetBias(bias);
			brake[right].SetBias(bias);

			if (!c.GetParam("brakes-"+pos+".max-pressure", max_pressure, error_output))  return false;
			brake[left].SetMaxPressure(max_pressure*bias);
			brake[right].SetMaxPressure(max_pressure*bias);
		}
	}

	//load the fuel tank
	{
		float pos[3];
		MATHVECTOR<double,3> position;
		float capacity, volume, fuel_density;

		if (!c.GetParam("fuel-tank.capacity", capacity, error_output))  return false;
		fuel_tank.SetCapacity(capacity);

		if (!c.GetParam("fuel-tank.volume", volume, error_output))  return false;
		fuel_tank.SetVolume(volume);

		if (!c.GetParam("fuel-tank.fuel-density", fuel_density, error_output))  return false;
		fuel_tank.SetDensity(fuel_density);

		if (!c.GetParam("fuel-tank.position", pos, error_output))  return false;
		if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
		position.Set(pos[0],pos[1],pos[2]);
		fuel_tank.SetPosition(position);
		//AddMassParticle(fuel_density*volume, position);
	}

	//load the suspension
	{
		for (int i = 0; i < 2; i++)
		{
			string posstr = "front";
			string posshortstr = "F";
			WHEEL_POSITION posl = FRONT_LEFT;
			WHEEL_POSITION posr = FRONT_RIGHT;
			if (i == 1)
			{
				posstr = "rear";
				posshortstr = "R";
				posl = REAR_LEFT;
				posr = REAR_RIGHT;
			}

			float spring_constant, bounce, rebound, travel, camber, caster, toe, anti_roll;//, maxcompvel;
			float hinge[3];
			MATHVECTOR<double,3> tempvec;

			if (!c.GetParam("suspension-"+posstr+".spring-constant", spring_constant, error_output))  return false;
			suspension[posl].SetSpringConstant(spring_constant);
			suspension[posr].SetSpringConstant(spring_constant);

			if (!c.GetParam("suspension-"+posstr+".bounce", bounce, error_output))  return false;
			suspension[posl].SetBounce(bounce);
			suspension[posr].SetBounce(bounce);

			if (!c.GetParam("suspension-"+posstr+".rebound", rebound, error_output))  return false;
			suspension[posl].SetRebound(rebound);
			suspension[posr].SetRebound(rebound);

			string file;
			if (c.GetParam("suspension-"+posstr+".factors-file", file))
			{
				int id = game->suspS_map[file]-1;
				if (id == -1)  {  id = 0;
					error_output << "Can't find suspension spring factors file: " << file << endl;  }

				suspension[posl].SetSpringFactorPoints(game->suspS[id]);
				suspension[posr].SetSpringFactorPoints(game->suspS[id]);

				id = game->suspD_map[file]-1;
				if (id == -1)  {  id = 0;
					error_output << "Can't find suspension damper factors file: " << file << endl;  }
				
				suspension[posl].SetDamperFactorPoints(game->suspD[id]);
				suspension[posr].SetDamperFactorPoints(game->suspD[id]);
			}else
			{	//  factor points
				vector <pair <double, double> > damper, spring;
				c.GetPoints("suspension-"+posstr, "damper-factor", damper);
				suspension[posl].SetDamperFactorPoints(damper);
				suspension[posr].SetDamperFactorPoints(damper);

				c.GetPoints("suspension-"+posstr, "spring-factor", spring);
				suspension[posl].SetSpringFactorPoints(spring);
				suspension[posr].SetSpringFactorPoints(spring);
			}

			if (!c.GetParam("suspension-"+posstr+".travel", travel, error_output))  return false;
			suspension[posl].SetTravel(travel);
			suspension[posr].SetTravel(travel);

			if (!c.GetParam("suspension-"+posstr+".camber", camber, error_output))  return false;
			suspension[posl].SetCamber(camber);
			suspension[posr].SetCamber(camber);

			if (!c.GetParam("suspension-"+posstr+".caster", caster, error_output))  return false;
			suspension[posl].SetCaster(caster);
			suspension[posr].SetCaster(caster);

			if (!c.GetParam("suspension-"+posstr+".toe", toe, error_output))  return false;
			suspension[posl].SetToe(toe);
			suspension[posr].SetToe(toe);

			if (!c.GetParam("suspension-"+posstr+".anti-roll", anti_roll, error_output))  return false;
			suspension[posl].SetAntiRollK(anti_roll);
			suspension[posr].SetAntiRollK(anti_roll);

			if (!c.GetParam("suspension-"+posshortstr+"L.hinge", hinge, error_output))  return false;
			//cap hinge to reasonable values
			for (int i = 0; i < 3; i++)
			{
				if (hinge[i] < -100)	hinge[i] = -100;
				if (hinge[i] > 100)		hinge[i] = 100;
			}
			if (version == 2)  ConvertV2to1(hinge[0],hinge[1],hinge[2]);
			tempvec.Set(hinge[0],hinge[1], hinge[2]);
			suspension[posl].SetHinge(tempvec);

			if (!c.GetParam("suspension-"+posshortstr+"R.hinge", hinge, error_output))  return false;
			for (int i = 0; i < 3; i++)
			{
				if (hinge[i] < -100)	hinge[i] = -100;
				if (hinge[i] > 100)		hinge[i] = 100;
			}
			if (version == 2)  ConvertV2to1(hinge[0],hinge[1],hinge[2]);
			tempvec.Set(hinge[0],hinge[1], hinge[2]);
			suspension[posr].SetHinge(tempvec);
		}
	}

	//load the wheels
	{
		for (int i = 0; i < 4; i++)
		{
			string sPos;
			WHEEL_POSITION wp;
			if (i == 0)		{	sPos = "FL";	wp = FRONT_LEFT;	}
			else if (i == 1){	sPos = "FR";	wp = FRONT_RIGHT;	}
			else if (i == 2){	sPos = "RL";	wp = REAR_LEFT;	}
			else			{	sPos = "RR";	wp = REAR_RIGHT;	}

			float roll_h, mass;
			float pos[3];
			MATHVECTOR<double,3> vec;

			if (!c.GetParam("wheel-"+sPos+".mass", mass, error_output))  return false;
			wheel[wp].SetMass(mass);

			if (!c.GetParam("wheel-"+sPos+".roll-height", roll_h, error_output))  return false;
			wheel[wp].SetRollHeight(roll_h);

			if (!c.GetParam("wheel-"+sPos+".position", pos, error_output))  return false;
			if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
			vec.Set(pos[0],pos[1], pos[2]);
			wheel[wp].SetExtendedPosition(vec);

			AddMassParticle(mass, vec);
		}

		//load the rotational inertia parameter from the tire section
		float front_inertia;
		float rear_inertia;
		if (c.GetParam("tire-both.rotational-inertia", front_inertia, error_output))
			rear_inertia = front_inertia;
		else
		{	if (!c.GetParam("tire-front.rotational-inertia", front_inertia, error_output))  return false;
			if (!c.GetParam("tire-rear.rotational-inertia", rear_inertia, error_output))  return false;
		}
		wheel[FRONT_LEFT].SetInertia(front_inertia);
		wheel[FRONT_RIGHT].SetInertia(front_inertia);

		wheel[REAR_LEFT].SetInertia(rear_inertia);
		wheel[REAR_RIGHT].SetInertia(rear_inertia);
	}

	//load the tire parameters
	{
		WHEEL_POSITION leftside = FRONT_LEFT;
		WHEEL_POSITION rightside = FRONT_RIGHT;
		float value;
		bool both = c.GetParam("tire-both.radius", value);
		string posstr = both ? "both" : "front";

		for (int p = 0; p < 2; ++p)
		{
			if (p == 1)
			{
				leftside = REAR_LEFT;
				rightside = REAR_RIGHT;
				if (!both)  posstr = "rear";
			}

			float rolling_resistance[3];
			if (!c.GetParam("tire-"+posstr+".rolling-resistance", rolling_resistance, error_output))  return false;
			wheel[leftside].SetRollingResistance(rolling_resistance[0], rolling_resistance[1]);
			wheel[rightside].SetRollingResistance(rolling_resistance[0], rolling_resistance[1]);

			float radius;
			if (!c.GetParam("tire-"+posstr+".radius", radius, error_output))  return false;
			wheel[leftside].SetRadius(radius);
			wheel[rightside].SetRadius(radius);
		}
	}

	//load the mass-only particles
	{
		MATHVECTOR<double,3> position;
		float pos[3], mass;

		if (c.GetParam("contact-points.mass", mass))
		{
			int paramnum(0);
			string paramname("contact-points.position-00");
			stringstream output_supression;
			while (c.GetParam(paramname, pos))
			{
				if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
				position.Set(pos[0],pos[1],pos[2]);
				AddMassParticle(mass, position);
				paramnum++;
				stringstream str;
				str << "contact-points.position-";  str.width(2);  str.fill('0');
				str << paramnum;
				paramname = str.str();
			}
		}

		string paramname = "particle-00";
		int paramnum = 0;
		while (c.GetParam(paramname+".mass", mass))
		{
			if (!c.GetParam(paramname+".position", pos, error_output))  return false;
			if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
			position.Set(pos[0],pos[1],pos[2]);
			AddMassParticle(mass, position);
			paramnum++;
			stringstream str;
			str << "particle-";  str.width(2);  str.fill('0');
			str << paramnum;
			paramname = str.str();
		}
	}

	//load the max steering angle
	{
		float maxangle = 26.f;
		if (!c.GetParam("steering.max-angle", maxangle, error_output))  return false;
		SetMaxSteeringAngle( maxangle );

		float a = 1.f;
		c.GetParam("steering.flip-pow-mul", a);	 flip_mul = a;
	}
	///car angular damping -new
	{
		float a = 0.4f;
		c.GetParam("steering.angular-damping", a, error_output);
		SetAngDamp(a);

		a=0.f;  c.GetParam("rot_drag.roll", a);  rot_coef[0] = a;
		a=0.f;  c.GetParam("rot_drag.pitch", a); rot_coef[1] = a;
		a=0.f;  c.GetParam("rot_drag.yaw", a);	 rot_coef[2] = a;
		a=0.f;  c.GetParam("rot_drag.yaw2", a);	 rot_coef[3] = a;
	}

	//load the driver
	{
		float mass;
		float pos[3];
		MATHVECTOR<double,3> position;

		if (!c.GetParam("driver.mass", mass, error_output))  return false;
		if (!c.GetParam("driver.position", pos, error_output))  return false;
		if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
		position.Set(pos[0], pos[1], pos[2]);
		AddMassParticle(mass, position);
	}

	//load the aerodynamics
	{
		float drag_area, drag_c, lift_area, lift_c, lift_eff;
		float pos[3];
		MATHVECTOR<double,3> position;

		if (!c.GetParam("drag.frontal-area", drag_area, error_output))  return false;
		if (!c.GetParam("drag.drag-coefficient", drag_c, error_output))  return false;
		if (!c.GetParam("drag.position", pos, error_output))  return false;
		if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
		position.Set(pos[0], pos[1], pos[2]);
		AddAerodynamicDevice(position, drag_area, drag_c, 0,0,0);

		for (int i = 0; i < 2; i++)
		{
			string wingpos = "front";
			if (i == 1)
				wingpos = "rear";
			if (!c.GetParam("wing-"+wingpos+".frontal-area", drag_area, error_output))  return false;
			if (!c.GetParam("wing-"+wingpos+".drag-coefficient", drag_c, error_output))  return false;
			if (!c.GetParam("wing-"+wingpos+".surface-area", lift_area, error_output))  return false;
			if (!c.GetParam("wing-"+wingpos+".lift-coefficient", lift_c, error_output))  return false;
			if (!c.GetParam("wing-"+wingpos+".efficiency", lift_eff, error_output))  return false;
			if (!c.GetParam("wing-"+wingpos+".position", pos, error_output))  return false;
			if (version == 2)  ConvertV2to1(pos[0],pos[1],pos[2]);
			position.Set(pos[0], pos[1], pos[2]);
			AddAerodynamicDevice(position, drag_area, drag_c, lift_area, lift_c, lift_eff);
		}
	}

	//  hover params
	if (hover || sphere)
	{
		c.GetParam("hover.hAbove",		 hov.hAbove);		c.GetParam("hover.hRayLen",		 hov.hRayLen);
										 
		c.GetParam("hover.steerForce",	 hov.steerForce);
		c.GetParam("hover.steerDamp",	 hov.steerDamp);	c.GetParam("hover.steerDampP",	 hov.steerDampP);
										 
		c.GetParam("hover.engineForce",	 hov.engineForce);	c.GetParam("hover.engineVelDec", hov.engineVelDec);
		c.GetParam("hover.brakeForce",	 hov.brakeForce);
										 
		c.GetParam("hover.dampAirRes",	 hov.dampAirRes);	c.GetParam("hover.dampSide",	 hov.dampSide);
		c.GetParam("hover.dampUp",		 hov.dampUp);		c.GetParam("hover.dampDn",		 hov.dampDn);
		c.GetParam("hover.dampPmul",	 hov.dampPmul);

		float al[3];
		c.GetParam("hover.alignTqP", al);  hov.alp.Set(al[0],al[1],al[2]);
		c.GetParam("hover.alignTq",  al);  hov.alt.Set(al[0],al[1],al[2]);
		c.GetParam("hover.pitchTq",  hov.pitchTq);
		c.GetParam("hover.rollTq",   hov.rollTq);		c.GetParam("hover.roll",     hov.roll);

		c.GetParam("hover_h.hov_vz",   hov.hov_vz);		c.GetParam("hover_h.hov_vsat", hov.hov_vsat);
		c.GetParam("hover_h.hov_dsat", hov.hov_dsat);
		c.GetParam("hover_h.hov_dampP",hov.hov_dampP);	c.GetParam("hover_h.hov_damp", hov.hov_damp);
		c.GetParam("hover_h.hov_fall", hov.hov_fall);
		c.GetParam("hover_h.hov_riseP",hov.hov_riseP);	c.GetParam("hover_h.hov_rise", hov.hov_rise);
	}

	UpdateMass();

	LogO(Ogre::String(":::: Time car dynamics load: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");
	return true;
}