Index: trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp	(revision 187)
+++ trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp	(revision 254)
@@ -70,5 +70,6 @@
 // output file for object positions / orientations
 const char* objects_out_filename = "objects.out";
-
+	
+std::ofstream video_out("video.lst");
 
 //-----------------------------------------------------------------------
@@ -117,5 +118,5 @@
 mShowVisualization(false),
 mCullCamera(false),
-mRecord(false),
+mRecordFrames(false),
 mShowShadows(false),
 mShowHelp(false),
@@ -134,5 +135,10 @@
 mDeleteObjects(false),
 mUseItemBuffer(false),
-mItemBufferMode(GtpVisibility::QueryManager::PATCH_VISIBILITY)
+mItemBufferMode(GtpVisibility::QueryManager::PATCH_VISIBILITY),
+mRecordVideo(false),
+mPureRenderTimeFps(0.0),
+mNumVideoFrames(0),
+mDemoFps(0),
+mUseDemoFps(false)
 {
 	//mInputDevice = PlatformManager::getSingleton().createInputReader();
@@ -159,6 +165,6 @@
 
 	initVisStatsOverlay(); // visibility stats overlay
-	initHelpOverlay(); // help overlay
-	initQueryOverlay(); // visibility query stats overlay
+	initHelpOverlay();     // help overlay
+	initQueryOverlay();    // visibility query stats overlay
 
 	// show stats overlays
@@ -179,4 +185,8 @@
 	setObjectType(mCurrentObjectType);
 
+	// initialise timer
+	mTimer = Root::getSingleton().getTimer();
+	mTimeFrameEnded = mTimeFrameStarted = mTimer->getMilliseconds();
+	
 	// reset statistics
 	resetStats();
@@ -356,5 +366,5 @@
 	{	return false;	}*/
 
-	// --- set parameters for visualization
+	//-- set parameters for visualization
 	if (mShowVisualization)
 	{
@@ -362,5 +372,5 @@
 		mSceneMgr->setOption("ShowOctree", &mShowVisualization);
 		
-		// ---- setup visualization camera
+		//-- setup visualization camera
 
 		mVizCamera->setPosition(0, 0, 0);
@@ -380,4 +390,10 @@
 		mVizCamera->moveRelative(Vector3(0, 800, 0));
 	}
+	else
+	{
+		// frame start time
+		mTimeFrameStarted = mTimer->getMilliseconds();
+		//Ogre::LogManager::getSingleton().logMessage("Frame started");
+	}
 
 	//-- set application state
@@ -385,11 +401,14 @@
 	{
 	case REPLAY:
+		/// set the current camera data to loaded frame information 
 		setCurrentFrameInfo(evt.timeSinceLastFrame);
+		// HACK to produce demo
+		addFrameInfo(mSavedFrameInfo, mCamNode, evt.timeSinceLastFrame);
 		break;
 	case WALKTHROUGH:
-		//-- if we are recording camera status per frame
-		if (mRecord)
+		//-- recording the camera settings per frame
+		if (mRecordFrames)
 		{
-			addFrameInfo(mCamNode, evt.timeSinceLastFrame);
+			addFrameInfo(mFrameInfo, mCamNode, evt.timeSinceLastFrame);
 			// print recording message
 			mWindow->setDebugText("Recording frame " + 
@@ -573,10 +592,23 @@
 		return false;
 
+	// timer end time
+	if (!mShowVisualization)
+	{
+		mTimeFrameEnded = mTimer->getMilliseconds();
+		//Ogre::LogManager::getSingleton().logMessage("Frame ended");
+	}
+
     updateStats();
 
+	if (mRecordVideo) // record current frame
+	{
+		//Ogre::LogManager::getSingleton().logMessage("taking video frame");
+		takeVideoFrame(video_out);
+		//Ogre::LogManager::getSingleton().logMessage("finished");
+	}
 	//-- IMPORTANT: must be set, otherwise terrain is not rendered correctly
 	mSceneMgr->endFrame();
 
-	if (mTimeDelay <= 0) // approx. one second
+	if (mTimeDelay <= 0) // simulates approx. one second
 		mTimeDelay = 1.0;
 
@@ -603,5 +635,23 @@
 		ofstr << StringConverter::toString((*it).position) << " " 
 			  << StringConverter::toString((*it).orientation) << " "
-			  << StringConverter::toString((*it).timeElapsed) << "\n";
+			  << StringConverter::toString((*it).timeElapsed) << " "
+			  << StringConverter::toString((*it).fps) << "\n";
+	}
+	ofstr.close();
+}
+// quick hack
+void TerrainFrameListener::writeNewFrameInfo()
+{
+	std::ofstream ofstr("newframe.out");
+	
+	std::vector<frame_info>::const_iterator it, it_end;
+
+	it_end = mSavedFrameInfo.end();
+	for (it = mSavedFrameInfo.begin(); it < it_end; ++it)
+	{
+		ofstr << StringConverter::toString((*it).position) << " " 
+			  << StringConverter::toString((*it).orientation) << " "
+			  << StringConverter::toString((*it).timeElapsed) << " "
+			  << StringConverter::toString((*it).fps) << "\n";
 	}
 	ofstr.close();
@@ -621,7 +671,7 @@
 	{
 		ifstr.getline(line, 256);
-		sscanf(line, "%f %f %f %f %f %f %f %f", &info.position.x, &info.position.y, &info.position.z,
+		sscanf(line, "%f %f %f %f %f %f %f %f %f", &info.position.x, &info.position.y, &info.position.z,
 			   &info.orientation.w, &info.orientation.x, &info.orientation.y, &info.orientation.z,
-			   &info.timeElapsed);
+			   &info.timeElapsed, &info.fps);
 		
 		mFrameInfo.push_back(info);
@@ -636,12 +686,19 @@
 {
 	mCurrentFrame = 0;
+	int lastState = mAppState;
+
+	// transition to the next state
+	mAppState = (mAppState + 1) % STATE_NUM;
 
 	// if last state was replay state
-	if (mAppState == REPLAY)
-	{
-		// reset debug text and write frame info to file
+	if (lastState == REPLAY)
+	{
+        // reset debug text
 		mWindow->setDebugText("");
-		writeFrames();
-		
+				
+		// hack for producing demo
+		writeNewFrameInfo();
+		mSavedFrameInfo.clear();
+
 		float avgFps = (float)mAvgFps / (float)mFrameCount;
 
@@ -659,19 +716,16 @@
 	}
 	
-	//-- set the next státe
-	mAppState = (mAppState + 1) % STATE_NUM;
-
 	// replay recorded walkthrough
 	if (mAppState == REPLAY)
 	{
 		// no recording during replay
-		mRecord = false;
-
-		// load recorded walkthrough
+		mRecordFrames = false; mWindow->setDebugText("");
+
+		// load recorded walkthrough from disk
 		if (mFrameInfo.size() == 0)
 		{
 			loadFrames();
 		}
-
+		
 		// if there are no recorded frames => set next state
 		if (mFrameInfo.size() == 0) 
@@ -679,5 +733,5 @@
 			nextAppState();
 		}
-		else
+		else // replay
 		{
 			mWindow->setDebugText("Replay");
@@ -699,11 +753,16 @@
 void TerrainFrameListener::toggleRecord()
 {
-	mRecord = !mRecord;
-
-	// clear previous camera path
-	if (mRecord)
+	mRecordFrames = !mRecordFrames;
+
+	if (mRecordFrames) 
+	{
+		// starting new recording => clear old frame info
 		mFrameInfo.clear();
+	}
 	else
+	{
+		writeFrames(); // write frame info to file
 		mWindow->setDebugText("");
+	}
 }
 //-----------------------------------------------------------------------
@@ -711,6 +770,10 @@
 {
 	mVisibilityThreshold += incr; 
-	if(mVisibilityThreshold < 0) mVisibilityThreshold = 0;
-	
+
+	if (mVisibilityThreshold < 0)
+	{
+		mVisibilityThreshold = 0;
+	}
+
 	char str[100]; sprintf(str,": %d", mVisibilityThreshold);
 
@@ -722,6 +785,10 @@
 {
 	mAssumedVisibility += incr; 
-	if(mAssumedVisibility < 0) mAssumedVisibility = 0;
-	
+
+	if (mAssumedVisibility < 0) 
+	{	
+		mAssumedVisibility = 0;
+	}
+
 	char str[100]; sprintf(str,": %d", mAssumedVisibility);
 
@@ -739,5 +806,5 @@
 {
 	mCurrentAlgorithm = (mCurrentAlgorithm + 1) % 
-		(GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS - 1);
+		GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS;
 	setAlgorithm(mCurrentAlgorithm);
 }
@@ -745,5 +812,5 @@
 void TerrainFrameListener::setObjectType(int objectType)
 {
-	if (mCurrentObjectType >= 3)
+	if (mCurrentObjectType >= 3) // TODO: define a constant
 		mCurrentObjectType = 0;
 
@@ -779,11 +846,26 @@
 	static String trisString = "Triangle Count: ";
 
+	int currentFps = mWindow->getStatistics().lastFPS;
+	
+	if (mUseDemoFps)
+		currentFps = mDemoFps;
+#if 0
+	// HACK: take pure rendering time, only measures the render call
+	long pureRenderTime = mTimeFrameEnded - mTimeFrameStarted;
+
+	if (pureRenderTime)
+	{
+		mPureRenderTimeFps = 1000.0 / (float) pureRenderTime;
+	}
+	currentFps = mPureRenderRenderTimeFps;
+	//std::stringstream d; d << "Pure render time fps: " << mPureRenderTimeFps << "\n";
+	//Ogre::LogManager::getSingleton().logMessage(d.str());
+#endif
+	
 	// HACK: compute average fps ourselfs, because ogre avg. fps is wrong
 	// TODO: update only once per second
-	mAvgFps += mWindow->getStatistics().lastFPS;
-	++ mFrameCount;
-	
-	float avgFps = (float)mAvgFps / (float)mFrameCount;
-    
+	mAvgFps += currentFps;
+	float avgFps = (float)mAvgFps / (float)(mFrameCount++);
+   
 	// update stats when necessary
     try 
@@ -796,11 +878,14 @@
 		const RenderTarget::FrameStats& stats = mWindow->getStatistics();
 
-		//guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
-		if (mTimeDelay < 0) // only update once per second
+		// HACK: take newly computed avg. fps instead of Ogre avg fps and update only once per second
+		if (mTimeDelay < 0) 
 		{		
 			guiAvg->setCaption(avgFpsString + StringConverter::toString(avgFps) + " ms");
+			//guiCurr->setCaption(currFpsString + StringConverter::toString(currentFps));
 		}
-
-		guiCurr->setCaption(currFpsString + StringConverter::toString(stats.lastFPS));
+		//guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
+		guiCurr->setCaption(currFpsString + StringConverter::toString(currentFps));
+		
+
 		guiBest->setCaption(bestFpsString + StringConverter::toString(stats.bestFPS)
 			+" "+StringConverter::toString(stats.bestFrameTime) + " ms");
@@ -1039,5 +1124,6 @@
 		break;
 	case KC_F2:
-		toggleShowStats();
+		mStatsOn = !mStatsOn;
+		showStats(mStatsOn);
 		break;
 	case KC_F3:
@@ -1063,4 +1149,8 @@
 		mUseAnimation = !mUseAnimation;
 		break;
+
+	case KC_F10:
+		mRecordVideo = !mRecordVideo;
+			
 	case KC_F11:
 		takeScreenshot();
@@ -1081,4 +1171,7 @@
 	case KC_DELETE:
 		mDeleteObjects = true;
+		break;
+	case KC_M: // hack
+		mUseDemoFps = !mUseDemoFps;
 		break;
 	//KEY_PRESSED(KC_F3, 0.3, writeFrames());
@@ -1110,12 +1203,14 @@
 }
 //-----------------------------------------------------------------------
-void TerrainFrameListener::addFrameInfo(SceneNode *camNode, Real timeElapsed)
+void TerrainFrameListener::addFrameInfo(FrameInfoContainer &frameInfos, SceneNode *camNode, Real timeElapsed)
 {
 	frame_info info;
+
 	info.orientation = mCamNode->getOrientation();
 	info.position = mCamNode->getPosition();
 	info.timeElapsed = timeElapsed;
-
-	mFrameInfo.push_back(info);
+	info.fps = mWindow->getStatistics().lastFPS;
+
+	frameInfos.push_back(info);
 }
 //-----------------------------------------------------------------------
@@ -1124,5 +1219,5 @@
 	//-- find current frame relative to elapsed frame time		
 	mReplayTimeElapsed -= timeElapsed;
-
+	
 	while ((mReplayTimeElapsed <= 0) && (mCurrentFrame < (int)mFrameInfo.size() - 1))
 	{
@@ -1130,5 +1225,7 @@
 	}
 
-	frame_info new_frame = mFrameInfo[mCurrentFrame];
+
+	// TODO: crashes here if recording / replaying on the same time!!
+	frame_info new_frame = mFrameInfo[mCurrentFrame]; 
 	frame_info old_frame = mFrameInfo[mCurrentFrame - 1];
 		
@@ -1143,11 +1240,16 @@
 	Vector3 camPos = old_frame.position + factor 
 		* (new_frame.position - old_frame.position);
+
+	// interpolate the orientation
 	Quaternion camOrienation = Quaternion::Slerp(factor, old_frame.orientation, 
 		new_frame.orientation, true);
 
+	// HACK: interpolate fps
+	mDemoFps = old_frame.fps + factor * (new_frame.fps -old_frame.fps);
+
 	mCamNode->setPosition(camPos);
 	mCamNode->setOrientation(camOrienation);
 	
-	// stop replay after a full walkthrough
+	// stop replaying after one full walkthrough
 	if (mCurrentFrame == (int)mFrameInfo.size() - 1)
 	{
@@ -1249,10 +1351,22 @@
 }
 //-----------------------------------------------------------------------
+void TerrainFrameListener::takeVideoFrame(std::ofstream &ofstr)
+{
+	char name[50];
+
+	sprintf(name, "frame_%05d.tga", ++mNumVideoFrames);
+    mWindow->writeContentsToFile(name);
+    //mWindow->setDebugText(String("Wrote ") + name);
+
+	ofstr << name << "\n";
+}
+//-----------------------------------------------------------------------
 void TerrainFrameListener::takeScreenshot()
 {
-	char tmp[20];
-	sprintf(tmp, "screenshot_%d.png", ++mNumScreenShots);
-    mWindow->writeContentsToFile(tmp);
-    mWindow->setDebugText(String("Wrote ") + tmp);
+	char name[50];
+
+	sprintf(name, "screenshot_%05d.png", ++mNumScreenShots);
+    mWindow->writeContentsToFile(name);
+    //mWindow->setDebugText(String("Wrote ") + name);
 }
 //-----------------------------------------------------------------------
@@ -1283,11 +1397,5 @@
 	}
 }
-//-----------------------------------------------------------------------
-void TerrainFrameListener::toggleShowStats()
-{
-	mStatsOn = !mStatsOn;
-
-	showStats(mStatsOn);
-}
+
 //-----------------------------------------------------------------------
 void TerrainFrameListener::toggleShowHelp()
@@ -1336,6 +1444,8 @@
 	initHelpOverlayElement("Recorded", top); top += vert_space;
 	initHelpOverlayElement("Animation", top); top += vert_space;
+	initHelpOverlayElement("Video", top); top += vert_space;
 	initHelpOverlayElement("Screenshots", top); top += vert_space;
 	initHelpOverlayElement("WriteOut", top); top += vert_space;
+
 
 	top +=vert_space;
