Index: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/Bvh.h
===================================================================
--- GTP/trunk/App/Demos/Vis/FriendlyCulling/src/Bvh.h	(revision 3053)
+++ GTP/trunk/App/Demos/Vis/FriendlyCulling/src/Bvh.h	(revision 3059)
@@ -155,5 +155,9 @@
 	*/
 	inline int CountPrimitives() const;
-
+	/** This is an imporantent function once you have one or more
+		view point changes within a frame (e.g., camera view and shadow view for
+		shadow mapping), because each camera needs its own state in
+		order to not break temporal coherency.
+	*/
 	static void SetCurrentState(int _state) { sCurrentState = _state; }
 
@@ -170,20 +174,21 @@
 
 	//////////////
-	//-- members that define the current state
+	//-- members that define the current state. There is one state for each camera
+
+	/// the currently used state
+	static int sCurrentState;
 
 	/// stores the visibility related info 
 	VisibilityInfo mVisibility[NUM_STATES];
 	
-	/// used for view frustum culling
+	// members used to speed up view frustum culling
+	/// masks out planes of the frustum that do not have to be tested against
 	int mPlaneMask[NUM_STATES];
+	/// the plane that is usually responsible for culling this node. 
+	/** if our educated guess was right, we save up to 5 comparisons.
+	*/
 	int mPreferredPlane[NUM_STATES];
-
 	/// when the node was last rendered
 	int mLastRenderedFrame[NUM_STATES];
-
-
-	// the current state
-	static int sCurrentState;
-
 
 	////////////////////
Index: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/chcdemo.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/FriendlyCulling/src/chcdemo.cpp	(revision 3057)
+++ GTP/trunk/App/Demos/Vis/FriendlyCulling/src/chcdemo.cpp	(revision 3059)
@@ -75,5 +75,5 @@
 Bvh *bvh = NULL;
 /// handles scene loading
-ResourceManager *loader = NULL;
+ResourceManager *resourceManager = NULL;
 /// handles scene loading
 ShaderManager *shaderManager = NULL;
@@ -121,4 +121,7 @@
 int renderMethod = RENDER_FORWARD;
 
+static int winWidth = 1024;
+static int winHeight = 768;
+static float winAspectRatio = 1.0f;
 
 /// these values get scaled with the frame rate
@@ -127,17 +130,12 @@
 
 /// elapsed time in milliseconds
-double elapsedTime = 1000.0f;
-double algTime = 1000.0f;
-
-static int winWidth = 1024;
-static int winHeight = 768;
+double elapsedTime = 1000.0;
+double algTime = 1000.0;
+double accumulatedTime = 1000.0;
+float fps = 1e3f;
 
 int shadowSize = 2048;
 
-static float winAspectRatio = 1.0f;
-
-double accumulatedTime = 1000;
-float fps = 1e3f;
-
+/// the hud font
 glfont::GLFont myfont;
 
@@ -157,5 +155,4 @@
 int numBatches = 0;
 
-
 // mouse navigation state
 int xEyeBegin = 0;
@@ -200,5 +197,5 @@
 
 PerfTimer frameTimer, algTimer;
-
+/// the performance window
 PerformanceGraph *perfGraph = NULL;
 
@@ -217,30 +214,34 @@
 DeferredRenderer *ssaoShader = NULL;
 
-SceneEntity *cube = NULL;
-SceneEntity *aeroplane = NULL;
+//SceneEntity *cube = NULL;
+SceneEntity *buddha = NULL;
 SceneEntity *skyDome = NULL;
 
 
-
-// function forward declarations
+////////////////////
+//--- function forward declarations
+
 void InitExtensions();
+void InitGLstate();
+
 void DisplayVisualization();
-void InitGLstate();
-void InitRenderTexture();
+/// destroys all allocated resources
 void CleanUp();
 void SetupEyeView();
-void UpdateEyeMtx();
 void SetupLighting();
 void DisplayStats();
-void Output(int x, int y, const char *string);
+/// draw the help screen
 void DrawHelpMessage();
+/// render the sky dome
 void RenderSky();
+/// render the objects found visible in the depth pass
 void RenderVisibleObjects();
 
 void Begin2D();
 void End2D();
+/// the main loop
+void MainLoop();
+
 void KeyBoard(unsigned char c, int x, int y);
-void DrawStatistics();
-void Display();
 void Special(int c, int x, int y);
 void KeyUp(unsigned char c, int x, int y);
@@ -251,23 +252,28 @@
 void RightMotion(int x, int y);
 void MiddleMotion(int x, int y);
-void CalcDecimalPoint(string &str, int d);
-
-RenderTraverser *CreateTraverser(Camera *cam);
-
 void KeyHorizontalMotion(float shift);
 void KeyVerticalMotion(float shift);
-
+/// returns the string representation of a number with the decimal points
+void CalcDecimalPoint(string &str, int d);
+/// Creates the traversal method (vfc, stopandwait, chc, chc++)
+RenderTraverser *CreateTraverser(Camera *cam);
+
+/// place the viewer on the floor plane
 void PlaceViewer(const Vector3 &oldPos);
+// initialise the frame buffer objects
+void InitFBO();
+/// changes the sunlight direction
+void RightMotionLight(int x, int y);
+/// render the shader map
+void RenderShadowMap(float newfar);
+/// function that touches each material once in order to accelarate render queue
+void PrepareRenderQueue();
+/// loads the specified model
+void LoadModel(const string &model);
 
 inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
 inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
-// initialise the frame buffer objects
-void InitFBO();
-
-void RightMotionLight(int x, int y);
-
-void RenderShadowMap(float newfar);
-
-
+
+// the new and the old viewProjection matrix of the current camera
 static Matrix4x4 viewProjMat = IdentityMatrix();
 static Matrix4x4 oldViewProjMat = IdentityMatrix();
@@ -291,5 +297,4 @@
 {
 #ifdef _CRT_SET
-
 	//Now just call this function at the start of your program and if you're
 	//compiling in debug mode (F5), any leaks will be displayed in the Output
@@ -399,10 +404,10 @@
 	}
 
-	glutDisplayFunc(Display);
+	glutDisplayFunc(MainLoop);
 	glutKeyboardFunc(KeyBoard);
 	glutSpecialFunc(Special);
 	glutReshapeFunc(Reshape);
 	glutMouseFunc(Mouse);
-	glutIdleFunc(Display);
+	glutIdleFunc(MainLoop);
 	glutKeyboardUpFunc(KeyUp);
 	glutSpecialUpFunc(SpecialKeyUp);
@@ -421,18 +426,15 @@
 	perfGraph = new PerformanceGraph(1000);
 
-	loader = ResourceManager::GetSingleton();
+	resourceManager = ResourceManager::GetSingleton();
 	shaderManager = ShaderManager::GetSingleton();
 
-	const string filename = string(model_path + "city.dem");
-	
-	if (loader->Load(filename, sceneEntities))
-		cout << "model " << filename << " loaded" << endl;
-	else
-	{
-		cerr << "loading model " << filename << " failed" << endl;
-		CleanUp();
-		exit(0);
-	}
-	
+	///////////
+	//-- load the static scene geometry
+
+	LoadModel("city.dem");
+
+
+	///////////
+	//-- load the associated static bvh
 
 	const string bvh_filename = string(model_path + "city.bvh");
@@ -447,60 +449,53 @@
 	}
 
+	/// set the depth of the bvh depending on the triangles per leaf node
+	bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
+
 	// set far plane based on scene extent
 	farDist = 10.0f * Magnitude(bvh->GetBox().Diagonal());
-	bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
-
-	camera->SetFar(Magnitude(bvh->GetBox().Diagonal()));
-	
-	Vector3 cubeCenter(470.398f, 240.364f, 182.5f);
-	
-	Matrix4x4 transl = TranslationMatrix(cubeCenter);
-
-	string skyDomeStr(model_path + "sky.dem");
-
-	if (loader->Load(skyDomeStr, sceneEntities))
-	{
-		cout << "successfully loaded " << sceneEntities.size() << " scene entities" << endl;
-	}
-	else
-	{
-		cerr << "loading file " << skyDomeStr << " failed" << endl;
-		CleanUp();
-		exit(0);
-	}
-
+	camera->SetFar(farDist);
+
+
+	//////////////////
+	//-- setup the skydome model
+
+	LoadModel("sky.dem");
 	skyDome = sceneEntities.back();
 
+	/// the turbitity of the sky (from clear to hazy, use <3 for clear sky)
 	const float turbitiy = 5.0f;
 	preetham = new SkyPreetham(turbitiy, skyDome);
 
-	// initialize the render traverser
+
+	//////////
+	//-- initialize the traversal algorithm
+
 	traverser = CreateTraverser(camera);
-
+	
+	// the bird-eye visualization
 	visualization = new Visualization(bvh, camera, NULL, &state);
-	
-	for (int i = 0; i < 3; ++ i)
-	{
-		state.SetRenderTechnique((RenderState::RenderTechnique)i);
-
-		// fill all shapes into the render queue	once so we can establish the buckets
-		ShapeContainer::const_iterator sit, sit_end = (*loader->GetShapes()).end();
-
-		for (sit = (*loader->GetShapes()).begin(); sit != sit_end; ++ sit)
-		{
-			renderQueue->Enqueue(*sit);
-		}
-	
-		//renderQueue->Apply();
-		// just clear queue again
-		renderQueue->Clear();
-	}
-
+
+
+	LoadModel("hbuddha.dem");
+	buddha = sceneEntities.back();
+
+	Vector3 sceneCenter(470.398f, 240.364f, 182.5f);
+	Matrix4x4 transl = TranslationMatrix(sceneCenter);
+
+	buddha->GetTransform()->SetMatrix(transl);
+
+	// this function assign the render queue bucket ids of the materials in beforehand
+	// => probably a little less overhead for new parts of the scene that are not yet assigned
+	PrepareRenderQueue();
+	
+	/// forward rendering is the default
 	state.SetRenderTechnique(RenderState::FORWARD);
 
 	// frame time is restarted every frame
 	frameTimer.Start();
+
 	// the rendering loop
 	glutMainLoop();
+	
 	// clean up
 	CleanUp();
@@ -709,5 +704,6 @@
 }
 
-
+/** Setup sunlight
+*/
 void SetupLighting()
 {
@@ -773,7 +769,7 @@
 	// set up the camera view
 	camera->SetupCameraView();
-
 		
 	/////////////////
+	//-- compute view projection matrix and store for later use
 
 	Matrix4x4 matViewing, matProjection;
@@ -782,5 +778,4 @@
 	camera->GetProjectionMatrix(matProjection);
 
-	// store matrix for later use
 	viewProjMat = matViewing * matProjection;
 }
@@ -810,17 +805,6 @@
 
 
-static void ComputeViewVectors(Vector3 &tl, Vector3 &tr, Vector3 &bl, Vector3 &br)
-{
-	Vector3 ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr;
-
-	camera->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
-
-	bl = Normalize(nbl - fbl);
-	br = Normalize(nbr - fbr);
-	tl = Normalize(ntl - ftl);
-	tr = Normalize(ntr - ftr);
-}
-
-
+/** Initialize the deferred rendering pass.
+*/
 void InitDeferredRendering()
 {
@@ -856,6 +840,7 @@
 
 
-// the main rendering loop
-void Display() 
+/** the main rendering loop
+*/
+void MainLoop() 
 {	
 	Vector3 oldPos = camera->GetPosition();
@@ -896,10 +881,8 @@
 	// bring eye modelview matrix up-to-date
 	SetupEyeView();
-
-	// set GPU related parameters
+	// set frame related parameters for GPU programs
 	GPUProgramParameters::InitFrame(camera, light);
 
-
-	// hack
+	// hack: store current rendering method and restore later
 	int oldRenderMethod = renderMethod;
 	// for rendering the light view, we use forward rendering
@@ -907,6 +890,6 @@
 		renderMethod = RenderState::FORWARD;
 
+	/// enable vbo vertex array
 	glEnableClientState(GL_VERTEX_ARRAY);
-
 
 	// render with the specified method (forward rendering, forward + depth, deferred)
@@ -980,13 +963,11 @@
 
 	glDepthFunc(GL_LESS);
-
 	glDisable(GL_TEXTURE_2D);
 	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 		
 
-	// reset lod levels for current frame
+	// set proper lod levels for current frame using current eye point
 	LODLevel::InitFrame(camera->GetPosition());
-
-	// set up lights
+	// set up sunlight
 	SetupLighting();
 
@@ -994,6 +975,7 @@
 	if (renderLightView)
 	{
-		// change CHC++ set of state variables (must be done for each change of camera because
-		// otherwise the temporal coherency is broken
+		// change CHC++ set of state variables: 
+		// must be done for each change of camera because otherwise 
+		// the temporal coherency is broken
 		BvhNode::SetCurrentState(LIGHT_PASS);
 		shadowMap->RenderShadowView(shadowTraverser, viewProjMat);
@@ -1661,5 +1643,5 @@
 	ShaderManager::DelSingleton();
 
-	loader = NULL;
+	resourceManager = NULL;
 	shaderManager = NULL;
 }
@@ -1822,5 +1804,5 @@
 			int len = 10;
 			CalcDecimalPoint(objStr, renderedObjects, len);
-			CalcDecimalPoint(totalObjStr, (int)loader->GetNumEntities(), len);
+			CalcDecimalPoint(totalObjStr, (int)resourceManager->GetNumEntities(), len);
 
 			CalcDecimalPoint(triStr, renderedTriangles, len);
@@ -1873,4 +1855,6 @@
 void RenderSky()
 {
+	buddha->Render(&state);
+
 	if ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
 		state.SetRenderTechnique(RenderState::DEFERRED);
@@ -1879,5 +1863,5 @@
 		((renderMethod == RENDER_DEPTH_PASS_DEFERRED) || 
 		 (renderMethod == RENDER_DEFERRED)) && useHDR;
-
+	
 	preetham->RenderSkyDome(-light->GetDirection(), camera, &state, !useToneMapping);
 	/// once again reset the state
@@ -1995,2 +1979,39 @@
 	BvhNode::SetCurrentState(CAMERA_PASS);
 }
+
+/** Toach each material once in order to preload the render queue 
+	bucket id of each material
+*/
+void PrepareRenderQueue()
+{
+	for (int i = 0; i < 3; ++ i)
+	{
+		state.SetRenderTechnique((RenderState::RenderTechnique)i);
+
+		// fill all shapes into the render queue	once so we can establish the buckets
+		ShapeContainer::const_iterator sit, sit_end = (*resourceManager->GetShapes()).end();
+
+		for (sit = (*resourceManager->GetShapes()).begin(); sit != sit_end; ++ sit)
+		{
+			renderQueue->Enqueue(*sit);
+		}
+	
+		// just clear queue again
+		renderQueue->Clear();
+	}
+}
+
+
+void LoadModel(const string &model)
+{
+	const string filename = string(model_path + model);
+
+	if (resourceManager->Load(filename, sceneEntities))
+		cout << "model " << filename << " loaded" << endl;
+	else
+	{
+		cerr << "loading model " << filename << " failed" << endl;
+		CleanUp();
+		exit(0);
+	}
+}
Index: GTP/trunk/App/Demos/Vis/FriendlyCulling/Converter/ObjConverter.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/FriendlyCulling/Converter/ObjConverter.cpp	(revision 3012)
+++ GTP/trunk/App/Demos/Vis/FriendlyCulling/Converter/ObjConverter.cpp	(revision 3059)
@@ -70,5 +70,5 @@
 		if (indices.size() > 2)
 		{
-#if 0
+#if 1
 			int idx1 = 0;
 			int idx2 = (int)indices.size() - 2;
