Index: trunk/VUT/work/TestCullingTerrain/TerrainMouseQueryListener.h
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TerrainMouseQueryListener.h	(revision 115)
+++ trunk/VUT/work/TestCullingTerrain/TerrainMouseQueryListener.h	(revision 115)
@@ -0,0 +1,192 @@
+#ifndef _TerrainMouseQueryListener_H__
+#define _TerrainMouseQueryListener_H__
+
+#include "CEGUIForwardRefs.h"
+#include <Ogre.h>
+#include <OgreKeyEvent.h>
+#include <OgreEventListeners.h>
+#include <OgreStringConverter.h>
+#include <OgreException.h>
+#include "VisibilityEnvironment.h"
+#include "OgreTerrainContentGenerator.h"
+
+using namespace Ogre;
+
+// z order index of visualizaion viewport
+#define VIZ_VIEWPORT_Z_ORDER 10
+
+
+/** Mouse query listener for terrain 
+*/
+class TerrainMouseQueryListener: public FrameListener, public MouseListener, public MouseMotionListener
+{
+public:
+	
+   TerrainMouseQueryListener(RenderWindow* win, Camera* cam, SceneManager *sceneManager, 
+		CEGUI::Renderer *renderer, TerrainContentGenerator *contentGenerator, Camera *vizCamera,
+		SceneNode *camNode);
+
+   ~TerrainMouseQueryListener();
+
+
+   bool frameStarted(const FrameEvent& evt);
+   bool frameEnded(const FrameEvent& evt);
+   //bool processUnbufferedKeyInput(const FrameEvent& evt);
+    
+
+   /* MouseListener callbacks. */
+   virtual void mouseClicked(MouseEvent* e) { }
+   virtual void mouseEntered(MouseEvent* e) { }
+   virtual void mouseExited(MouseEvent* e)  { }
+
+   // This is when the mouse button goes DOWN.
+   virtual void mousePressed(MouseEvent* e);
+
+   // This is when the mouse button is let UP.
+   virtual void mouseReleased(MouseEvent* e);
+
+   /* MouseMotionListener callbacks */
+   virtual void mouseMoved (MouseEvent *e);
+   
+   // This is when the mouse is clicked, held and dragged.
+   virtual void mouseDragged (MouseEvent *e);
+
+   void keyPressed(KeyEvent* e);
+
+   void keyReleased(KeyEvent* e);
+   void keyClicked(KeyEvent* e);
+  
+   /** The information about camera position and orienation per frame */
+   typedef struct
+   {
+	   Vector3 position;
+	   Quaternion orientation;
+	   Real timeElapsed;
+   } frame_info;
+
+   enum  {WALKTHROUGH, REPLAY, STATE_NUM};
+
+   // visualization modes for scene nodes
+   enum {NODEVIZ_NONE, NODEVIZ_RENDER_NODES, NODEVIZ_RENDER_NODES_AND_CONTENT, NODEVIZ_MODES_NUM};
+   //enum {NODEVIZ_NONE, NODEVIZ_RENDER_GEOMETRY, NODEVIZ_MODES_NUM};
+
+   void nextAlgorithm();
+   void changeThreshold(int incr);
+   void updateStats();
+
+   void toggleUseOptimization();
+   void toggleShowOctree();
+   void toggleUseDepthPass();
+   void toggleShowViz();
+   void nextNodeVizMode();
+   void toggleRecord();
+
+   void zoomVizCamera(int zoom);
+	
+   void addFrameInfo(SceneNode *camNode, Real timeElapsed);
+   void setCurrentFrameInfo(Real timeElapsed);
+
+   void setAppState(int state);
+   void nextAppState();
+
+   void setAlgorithm(int algorithm);
+
+   void moveCamera();
+
+   void writeFrames();
+   void loadFrames();
+
+   void toggleUseShadows();
+  
+
+    // Constructor takes a RenderWindow because it uses that to determine input context
+    //ExampleFrameListener(RenderWindow* win, Camera* cam, bool useBufferedInputKeys = false, bool useBufferedInputMouse = false)
+    
+    bool processUnbufferedKeyInput(const FrameEvent& evt);
+    bool processUnbufferedMouseInput(const FrameEvent& evt);
+
+    void showDebugOverlay(bool show);
+
+protected:
+
+	/** Clamp camera to terrain.
+	*/
+	void Clamp2Terrain();
+	
+    bool mLMouseDown, mRMouseDown;     // True if the mouse buttons are down
+    SceneManager *mSceneMgr;           // A pointer to the scene manager
+    
+	CEGUI::Renderer *mGUIRenderer;     // cegui renderer
+	
+	bool mShutdownRequested;
+	int mCurrentAlgorithm;
+	int mVisibilityThreshold;
+	
+	OverlayElement *mAlgorithmInfo;
+	OverlayElement *mThresholdInfo;
+	OverlayElement *mFrustumCulledNodesInfo;
+	OverlayElement *mQueryCulledNodesInfo;
+    OverlayElement *mTraversedNodesInfo;
+	OverlayElement *mHierarchyNodesInfo;
+	OverlayElement *mUseOptimizationInfo;
+	OverlayElement *mUseDepthPassInfo;
+	OverlayElement *mRenderedNodesInfo;
+	OverlayElement *mObjectsInfo;
+	OverlayElement *mQueriesIssuedInfo;
+
+	SceneNode *mCurrentObject;    // the newly created object
+	int mObjectCount;             // The number of objects on the screen
+
+	RayQueryExecutor *mRayQueryExecutor;
+	TerrainContentGenerator *mTerrainContentGenerator;
+
+	bool mUseOptimization;
+	bool mShowOctree;
+	bool mUseDepthPass;
+	bool mShowVisualization;
+	int mNodeVizMode;
+	bool mCullCamera;
+
+	Real mVizCameraHeight;
+
+	Camera *mVizCamera;
+	SceneNode *mCamNode;
+	
+	//std::deque<Vector3> mWalkList;   // The list of points we are walking to
+	std::vector<frame_info> mFrameInfo;
+		
+	int mCurrentFrame;
+	// the current application state
+	int mAppState;
+	bool mRecord;
+	Real mTimeElapsed;
+	bool mUseShadows;
+
+	bool mVisualizeCulledNodes;
+
+
+	//EventProcessor* mEventProcessor;
+    InputReader* mInputDevice;
+    Camera* mCamera;
+
+    Vector3 mTranslateVector;
+    RenderWindow* mWindow;
+    bool mStatsOn;
+    bool mUseBufferedInputKeys, mUseBufferedInputMouse, mInputTypeSwitchingOn;
+	unsigned int mNumScreenShots;
+    float mMoveScale;
+    Degree mRotScale;
+    // just to stop toggles flipping too fast
+    Real mTimeUntilNextToggle;
+    Radian mRotX, mRotY;
+    TextureFilterOptions mFiltering;
+    int mAniso;
+
+	int mSceneDetailIndex;
+    Real mMoveSpeed;
+    Degree mRotateSpeed;
+    Overlay* mDebugOverlay;
+};
+
+
+#endif //_TerrainMouseQueryListener_H__
Index: trunk/VUT/work/TestCullingTerrain/TestCullingTerrain.vcproj
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TestCullingTerrain.vcproj	(revision 107)
+++ trunk/VUT/work/TestCullingTerrain/TestCullingTerrain.vcproj	(revision 115)
@@ -34,8 +34,8 @@
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="Plugin_OctreeSceneManager.lib OGREMain_d.LIB CEGUIBase_d.lib OgreGUIRenderer_d.lib Plugin_DotSceneManager.lib"
+				AdditionalDependencies="Plugin_OctreeSceneManager.lib Plugin_VisibilitySceneManager.lib OGREMain_d.LIB CEGUIBase_d.lib OgreGUIRenderer_d.lib Plugin_DotSceneManager.lib"
 				OutputFile="$(OGRE_PATH)/Samples/Common/bin/Debug/TestCullingTerrain.exe"
 				LinkIncremental="2"
-				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\Dependencies\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\Dependencies\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(GAMETOOLS_PATH)\trunk\VUT\Ogre\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;"
 				GenerateDebugInformation="TRUE"
 				ProgramDatabaseFile="$(OutDir)/TestCullingTerrain.pdb"
@@ -122,4 +122,7 @@
 			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
 			<File
+				RelativePath=".\TerrainMouseQueryListener.cpp">
+			</File>
+			<File
 				RelativePath=".\TestCullingTerrainApplication.cpp">
 			</File>
@@ -130,4 +133,7 @@
 			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
 			<File
+				RelativePath=".\TerrainMouseQueryListener.h">
+			</File>
+			<File
 				RelativePath=".\TestCullingTerrainApplication.h">
 			</File>
Index: trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.cpp
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.cpp	(revision 114)
+++ trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.cpp	(revision 115)
@@ -1,9 +1,2 @@
-/**
-    \file 
-        TestCullingTerrainApplication.cpp
-    \brief
-        Tests the visibility culling algorithm
-*/
-
 #include <OgreNoMemoryMacros.h>
 #include <CEGUI/CEGUI.h>
@@ -14,15 +7,11 @@
 
 #include <Ogre.h>
-#include "OgreReferenceAppLayer.h"
+//#include "OgreReferenceAppLayer.h"
 //#include "OgreRefAppWorld.h"
 #include "TestCullingTerrainApplication.h"
 
+
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
-
-#define VIZ_VIEWPORT_Z_ORDER 10
-
-const char* frame_outfile = "frame.out";
-const char* objects_outfile = "objects.out";
 
 /*******************************************************/
@@ -201,8 +190,8 @@
 void TestCullingTerrainApplication::createFrameListener()
 {
-	mFrameListener= new MouseQueryListener(mWindow, mCamera, mSceneMgr, 
+	mTerrainFrameListener = new TerrainMouseQueryListener(mWindow, mCamera, mSceneMgr, 
 		mGUIRenderer, mTerrainContentGenerator, mVizCamera, mCamNode);
-	mFrameListener->showDebugOverlay(true);
-	mRoot->addFrameListener(mFrameListener);
+	mTerrainFrameListener->showDebugOverlay(true);
+	mRoot->addFrameListener(mTerrainFrameListener);
 }
 //-----------------------------------------------------------------------
@@ -211,628 +200,5 @@
 	mSceneMgr = mRoot->getSceneManager(ST_EXTERIOR_CLOSE);
 }
-/***********************************************/
-/*      MouseQueryListener implementation      */
-/***********************************************/
-//-----------------------------------------------------------------------
-MouseQueryListener::MouseQueryListener(RenderWindow* win, Camera* cam, 
-									   SceneManager *sceneManager, 
-									   CEGUI::Renderer *renderer,
-									   TerrainContentGenerator *sceneGenerator,
-									   Camera *vizCamera,
-									   SceneNode *camNode): 
-ExampleFrameListener(win, cam, false, true), 
-mGUIRenderer(renderer), 
-mShutdownRequested(false), 
-mLMouseDown(false),
-mRMouseDown(false),
-mSceneMgr(sceneManager),
-mCurrentObject(NULL),
-mTerrainContentGenerator(sceneGenerator),
-mVisibilityThreshold(0),
-mCurrentAlgorithm(GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING),
-mShowOctree(false),
-mUseVisibilityCulling(true),
-mUseOptimization(true),
-mVizCamera(vizCamera),
-mShowVisualization(false),
-mNodeVizMode(NODEVIZ_NONE),
-mVizCameraHeight(Real(2500.0)),
-mCamNode(camNode),
-mCullCamera(false),
-mAppState(WALKTHROUGH),
-mCurrentFrame(0),
-mRecord(false),
-mTimeElapsed(0),
-mUseShadows(false),
-mVisualizeCulledNodes(false)
-{
-	// Reduce move speed
-	mMoveSpeed = 50;
-	mRotateSpeed *= 2;
-    
-	// Register this so that we get mouse events.
-	mEventProcessor->addMouseListener(this);
-	mEventProcessor->addMouseMotionListener(this);
-	mEventProcessor->addKeyListener(this);
-
-	mRayQueryExecutor = new RayQueryExecutor(mSceneMgr);
-	
-	// show overlay
-	Overlay* pOver = OverlayManager::getSingleton().getByName("Example/VisibilityDemoOverlay"); 
-
-	mAlgorithmInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/AlgorithmInfo");
-	mThresholdInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/ThresholdInfo");
-	
-	mFrustumCulledNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/FrustumCulledNodesInfo");
-	mQueryCulledNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/QueryCulledNodesInfo");
-    mTraversedNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/TraversedNodesInfo");
-	mHierarchyNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/HierarchyNodesInfo");
-	mRenderedNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/RenderedNodesInfo");
-	mObjectsInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/ObjectsInfo");
-	mUseOptimizationInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/UseOptimizationInfo");
-	mQueriesIssuedInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/QueriesIssuedInfo");
-	
-	mAlgorithmInfo->setCaption(": " + mCurrentAlgorithmCaptions[mCurrentAlgorithm]);
-	mThresholdInfo->setCaption(": 0");
-	mFrustumCulledNodesInfo->setCaption(": 0");
-	mQueryCulledNodesInfo->setCaption(": 0");
-	mTraversedNodesInfo->setCaption(": 0");
-	mHierarchyNodesInfo->setCaption(": 0");
-	mRenderedNodesInfo->setCaption(": 0");
-	mObjectsInfo->setCaption(": 0");
-	mUseOptimizationInfo->setCaption(": true");
-	mQueriesIssuedInfo->setCaption(": 0");
-
-	setAlgorithm(mCurrentAlgorithm);
-
-	mSceneMgr->setOption("UseOptimization", &mUseOptimization);
-	mSceneMgr->setOption("UseVisibilityCulling", &mUseVisibilityCulling);
-	mSceneMgr->setOption("ShowOctree", &mShowOctree);
-	mSceneMgr->setOption("CullCamera", &mCullCamera);
-	mSceneMgr->setOption("ShowVisualization", &mShowVisualization);
-	
-	pOver->show();
-} 
-//-----------------------------------------------------------------------
-MouseQueryListener::~MouseQueryListener()
-{
-	delete mRayQueryExecutor;
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::mouseMoved(MouseEvent *e)
-{
-	// Update CEGUI with the mouse motion
-    CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * 
-		mGUIRenderer->getWidth(), e->getRelY() * mGUIRenderer->getHeight());
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::mousePressed(MouseEvent* e)
-{
-     // Left mouse button down
-     if (e->getButtonID() & InputEvent::BUTTON0_MASK)
-     {
-		 CEGUI::MouseCursor::getSingleton().hide();
-
-		 // Setup the ray scene query
-         Ray mouseRay = mCamera->getCameraToViewportRay(e->getX(), e->getY());
-   
-		 Vector3 queryResult;
-		 
-		 // Get results, create a node/entity on the position
-		 mCurrentObject = mTerrainContentGenerator->GenerateSceneObject(
-			 mouseRay.getOrigin(), Vector3(0,0,0), "robot");
-		
-         mLMouseDown = true; 
-     }
-     // Right mouse button down
-     else if (e->getButtonID() & InputEvent::BUTTON1_MASK)
-     {
-         CEGUI::MouseCursor::getSingleton().hide();
-         mRMouseDown = true;
-     }
-} // mousePressed
-//-----------------------------------------------------------------------
-void MouseQueryListener::mouseReleased(MouseEvent* e)
-{
-    // Left mouse button up
-    if (e->getButtonID() & InputEvent::BUTTON0_MASK)
-    {
-		CEGUI::MouseCursor::getSingleton().show();
-        mLMouseDown = false;
-    }
-    // Right mouse button up
-    else if (e->getButtonID() & InputEvent::BUTTON1_MASK)
-    {
-        CEGUI::MouseCursor::getSingleton().show();
-        mRMouseDown = false;
-    }
-} 
-//-----------------------------------------------------------------------
-void MouseQueryListener::mouseDragged(MouseEvent *e)
- {
-	 // If we are dragging the left mouse button.	 	 
-	 if (mLMouseDown)
-     {
-		 Vector3 queryResult;
-		 Ray mouseRay = mCamera->getCameraToViewportRay(e->getX(), e->getY());
-
-		 if (mRayQueryExecutor->executeRayQuery(&queryResult, mouseRay))
-		 {
-			 if (mCurrentObject)
-			 {
-				 mCurrentObject->setPosition(queryResult);
-			 }
-		 }
-     }
-	 // If we are dragging the right mouse button.
-	 if (mRMouseDown)
-	 {
-		 //mCamera->yaw(-e->getRelX() * mRotateSpeed);
-		 //mCamera->pitch(-e->getRelY() * mRotateSpeed);
-		 mCamNode->yaw(-e->getRelX() * mRotateSpeed);
-		 mCamNode->pitch(-e->getRelY() * mRotateSpeed);
-	 }
-}
-//-----------------------------------------------------------------------
-bool MouseQueryListener::frameStarted(const FrameEvent &evt)
-{
-	switch (mAppState)
-	{
-	case REPLAY:
-		setCurrentFrameInfo(evt.timeSinceLastFrame);
-		break;
-	case WALKTHROUGH:
-		if (mRecord)
-		{
-			addFrameInfo(mCamNode, evt.timeSinceLastFrame);
-			// print recording message
-			mWindow->setDebugText("Recording frame " + 
-				StringConverter::toString(mFrameInfo.size() - 1));
-		}	
-	
-		Clamp2Terrain();
-		break;
-	default:
-		break;
-	};	
-	
-	if (mShowVisualization)
-	{
-		// important for visualization => draw octree bounding boxes
-		mSceneMgr->setOption("ShowOctree", &mShowVisualization);
-		// also render nodew content?
-		//mSceneMgr->setOption("RenderNodesForViz", &mRenderNodesForViz);
-
-		// -- setup visualization camera
-		mVizCamera->setPosition(0, 0, 0);
-		mVizCamera->setOrientation(Quaternion::IDENTITY);
-
-		Vector3 camPos = mCamNode->getPosition();
-		mVizCamera->setPosition(camPos.x, mVizCameraHeight, camPos.z);
-
-		// point down -Z axis
-		mVizCamera->pitch(Radian(Degree(270.0)));
-	
-		// rotation arounnd X axis
-		mVizCamera->yaw(Math::ATan2(-mCamera->getDerivedDirection().x, 
-			-mCamera->getDerivedDirection().z));
-		
-		// move by a constant so view plane is on bottom of viewport
-		mVizCamera->moveRelative(Vector3(0, 800, 0));
-	}
-
-	return ExampleFrameListener::frameStarted(evt);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::Clamp2Terrain()
-{
-	// clamp to terrain
-	Vector3 camPos = mCamNode->getPosition();
-	Vector3 queryResult;
-
-	if (mRayQueryExecutor->executeRayQuery(&queryResult, 
-			Vector3(camPos.x, 5000.0f, camPos.z), Vector3::NEGATIVE_UNIT_Y))
-	{
-		mCamNode->setPosition(camPos.x, queryResult.y + 10, camPos.z);
-	}
-}
-//-----------------------------------------------------------------------
-bool MouseQueryListener::frameEnded(const FrameEvent& evt)
-{
-	if (mShutdownRequested)
-		return false;
-
-    if (timeDelay >= 0) 
-        timeDelay -= evt.timeSinceLastFrame;
-
-	KEY_PRESSED(KC_SPACE, 0.3, nextAlgorithm());
-
-	KEY_PRESSED(KC_O, 0.3, toggleUseOptimization());
-	KEY_PRESSED(KC_T, 0.3, toggleShowOctree());
-	KEY_PRESSED(KC_C, 0.3, toggleUseVisibilityCulling());
-	KEY_PRESSED(KC_1, 0.3, toggleShowViz());
-	KEY_PRESSED(KC_2, 0.3, nextNodeVizMode());
-	
-	KEY_PRESSED(KC_SUBTRACT, 0, changeThreshold(-10));
-	KEY_PRESSED(KC_ADD, 0, changeThreshold(10));
-	
-	KEY_PRESSED(KC_4, 0, zoomVizCamera(50));
-	KEY_PRESSED(KC_5, 0, zoomVizCamera(-50));
-
-	KEY_PRESSED(KC_F1, 0.3, nextAppState());
-	KEY_PRESSED(KC_F2, 0.3, toggleRecord());
-	KEY_PRESSED(KC_F3, 0.3, mTerrainContentGenerator->WriteObjects(objects_outfile));
-	KEY_PRESSED(KC_F4, 0.3, toggleUseShadows());
-	//KEY_PRESSED(KC_F3, 0.3, writeFrames());
-	//KEY_PRESSED(KC_F4, 0.3, loadFrames());
-
-	updateStats();
-
-	//return ExampleFrameListener::frameStarted(evt) && ExampleFrameListener::frameEnded(evt);
-	return ExampleFrameListener::frameEnded(evt);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::moveCamera()
-{
-	mCamNode->yaw(mRotX);
-	mCamNode->pitch(mRotY);
-	mCamNode->translate(mCamNode->getLocalAxes(), mTranslateVector);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::writeFrames()
-{
-	std::ofstream ofstr(frame_outfile);
-	
-	std::vector<frame_info>::const_iterator it, it_end;
-
-	it_end = mFrameInfo.end();
-	for(it = mFrameInfo.begin(); it < it_end; ++it)
-	{
-		ofstr << StringConverter::toString((*it).position) << " " 
-			<< StringConverter::toString((*it).orientation) << " "
-			<< StringConverter::toString((*it).timeElapsed) << "\n";
-	}
-	ofstr.close();
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::loadFrames()
-{
-	std::ifstream ifstr(frame_outfile);
-	char line[256];
-	frame_info info;
-
-	// reset current values
-	mFrameInfo.clear();
-	mCurrentFrame = 0;
-	
-	while (!ifstr.eof()) 
-	{
-		ifstr.getline(line, 256);
-		sscanf(line, "%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);
-		
-		mFrameInfo.push_back(info);
-		
-		/*
-		std::stringstream d;
-		d << StringConverter::toString(info.position) << " " << StringConverter::toString(info.orientation);
-		LogManager::getSingleton().logMessage(d.str());
-		*/
-	}
-	ifstr.close();
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::setAppState(int state)
-{
-	mAppState = state;
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::nextAppState()
-{
-	mCurrentFrame = 0;
-
-	// if last state was replay state
-	if (mAppState == REPLAY)
-	{
-		// reset debug text and write frame info to file
-		mWindow->setDebugText("");
-		writeFrames();
-		
-		//-- write out stats
-		std::stringstream d;
-		d << "Algorithm: " << mCurrentAlgorithmCaptions[mCurrentAlgorithm] << "\n"
-		  << "avg. FPS: " << mWindow->getAverageFPS() << "\n"
-		  << "best FPS: " << mWindow->getBestFPS() << "\n"
-		  << "worst FPS: " << mWindow->getWorstFPS() << "\n"
-		  << "best frame time: " <<	mWindow->getBestFrameTime() << "\n"
-		  << "worst frame time: " << mWindow->getWorstFrameTime();
- 		
-		LogManager::getSingleton().logMessage(d.str());
-	}
-	
-	//-- 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
-		if (mFrameInfo.size() == 0)
-		{
-			loadFrames();
-		}
-
-		// if there are no recorded frames => set next state
-		if (mFrameInfo.size() == 0) 
-		{
-			nextAppState();
-		}
-		else
-		{
-			mWindow->setDebugText("Replay");
-			
-			// reset, because we measure fps stats during walkthrough
-			mWindow->resetStatistics();
-
-			//-- initialise frame data
-			mTimeElapsed = 0;
-
-			mCamNode->setPosition(mFrameInfo[0].position);
-			mCamNode->setOrientation(mFrameInfo[0].orientation);
-		}
-	}
-
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleRecord()
-{
-	mRecord = !mRecord;
-
-	// clear previous camera path
-	if (mRecord)
-		mFrameInfo.clear();
-	else
-		mWindow->setDebugText("");
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::changeThreshold(int incr)
-{
-	mVisibilityThreshold += incr; 
-	if(mVisibilityThreshold < 0) mVisibilityThreshold = 0;
-	
-	char str[100]; sprintf(str,": %d", mVisibilityThreshold);
-
-	mSceneMgr->setOption("Threshold", &mVisibilityThreshold); 
-	mThresholdInfo->setCaption(str);
-}
-//-----------------------------------------------------------------------
-bool MouseQueryListener::processUnbufferedKeyInput(const FrameEvent& evt)
-{    
-	if (mInputDevice->isKeyDown(KC_RIGHT))
-	{
-		mCamNode->yaw(-mRotScale);
-		return true;
-	}
-	if (mInputDevice->isKeyDown(KC_LEFT))
-	{
-		mCamNode->yaw(mRotScale);
-		return true;
-	}
-
-	return ExampleFrameListener::processUnbufferedKeyInput(evt);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::zoomVizCamera(int zoom)
-{
-	mVizCameraHeight += zoom; 
-	if(mVizCameraHeight < 0) mVizCameraHeight = 0;
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::nextAlgorithm()
-{
-	mCurrentAlgorithm = (mCurrentAlgorithm + 1) % 
-		GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS,
-
-	setAlgorithm(mCurrentAlgorithm);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::setAlgorithm(int algorithm)
-{
-	mAlgorithmInfo->setCaption(": " + mCurrentAlgorithmCaptions[mCurrentAlgorithm]);
-	mSceneMgr->setOption("Algorithm", &mCurrentAlgorithm);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::updateStats()
-{
-	unsigned int opt = 0;
-	char str[100];
-	
-	mSceneMgr->getOption("NumFrustumCulledNodes", &opt); sprintf(str,": %d", opt); 
-	mFrustumCulledNodesInfo->setCaption(str);
-	
-	mSceneMgr->getOption("NumQueriesIssued", &opt); sprintf(str,": %d", opt); 
-	mQueriesIssuedInfo->setCaption(str);
-	
-	mSceneMgr->getOption("NumQueryCulledNodes", &opt); sprintf(str,": %d", opt); 
-	mQueryCulledNodesInfo->setCaption(str);
-	
-	mSceneMgr->getOption("NumTraversedNodes", &opt); sprintf(str,": %d", opt); 
-	mTraversedNodesInfo->setCaption(str);
-
-	mSceneMgr->getOption("NumHierarchyNodes", &opt); sprintf(str,": %d", opt); 
-	mHierarchyNodesInfo->setCaption(str);
-
-	mSceneMgr->getOption("NumRenderedNodes", &opt); sprintf(str,": %d", opt); 
-	mRenderedNodesInfo->setCaption(str);
-
-	sprintf(str,": %d", mTerrainContentGenerator->GetObjectCount()); 
-	mObjectsInfo->setCaption(str);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleUseOptimization()
-{
-	mUseOptimization = !mUseOptimization;
-
-	mSceneMgr->setOption("UseOptimization", &mUseOptimization);
-
-	if (mUseOptimization)
-		mUseOptimizationInfo->setCaption(": true");
-	else
-		mUseOptimizationInfo->setCaption(": false");
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleShowOctree()
-{
-	mShowOctree = !mShowOctree;
-
-	mSceneMgr->setOption("ShowOctree", &mShowOctree);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleUseVisibilityCulling()
-{
-	mUseVisibilityCulling = !mUseVisibilityCulling;
-
-	mSceneMgr->setOption("UseVisibilityCulling", &mUseVisibilityCulling);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleShowViz()
-{
-	mShowVisualization = !mShowVisualization;
-	mVisualizeCulledNodes = !mVisualizeCulledNodes;
-
-	// create viewport with priority VIZ_VIEWPORT_Z_ORDER: 
-	// will be rendered over standard viewport
-	if (mShowVisualization)
-	{	
-		Viewport *vizvp = mWindow->addViewport(mVizCamera, 
-			VIZ_VIEWPORT_Z_ORDER, 0.6, 0.6, 0.4, 0.4); 
-				
-		vizvp->setBackgroundColour(ColourValue(0.0, 0.3, 0.2, 1));
-
-		vizvp->setOverlaysEnabled(false);
-		// Alter the camera aspect ratio to match the viewport
-        mVizCamera->setAspectRatio(Real(vizvp->getActualWidth()) / 
-			Real(vizvp->getActualHeight()));
-		
-		mSceneMgr->setOption("VisualizeCulledNodes", &mVisualizeCulledNodes);
-		//vizvp->setClearEveryFrame(false);
-
-		// Create a skyplane (for visualization background)
-		/*
-		Plane plane;
-		plane.d = -1000;
-		plane.normal = Vector3::UNIT_Y;
-		mSceneMgr->setSkyPlane(true, plane, "Examples/TransparentTest", 4000, 75, false);
-		*/
-		
-	}
-	else
-	{
-		mWindow->removeViewport(VIZ_VIEWPORT_Z_ORDER);
-		// if octree was enabled for visualization purpose, reset now
-		mSceneMgr->setOption("ShowOctree", &mShowOctree);
-	}
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleUseShadows()
-{
-	mUseShadows = !mUseShadows;
-
-	//mSunLight->setCastShadows(mUseShadows);
-
-	if (mUseShadows)
-	{
-		mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE);
-	}
-	else
-	{
-		mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
-	}
-
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::nextNodeVizMode()
-{
-	mNodeVizMode = (mNodeVizMode + 1) % NODEVIZ_MODES_NUM;
-
-	//bool renderNodesForViz = (mNodeVizMode == NODEVIZ_RENDER_NODES) || (mNodeVizMode == NODEVIZ_RENDER_NODES_AND_CONTENT);
-	bool renderNodesContentForViz = mNodeVizMode == NODEVIZ_RENDER_GEOMETRY;
-
-	//mSceneMgr->setOption("RenderNodesForViz", &renderNodesForViz);
-	mSceneMgr->setOption("RenderNodesContentForViz", &renderNodesContentForViz);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::keyPressed(KeyEvent* e)
-{
-	if(e->getKey() == KC_ESCAPE)
-    {
-		mShutdownRequested = true;
-		e->consume();
-		return;
-	}
-
-	CEGUI::System::getSingleton().injectKeyDown(e->getKey());
-	CEGUI::System::getSingleton().injectChar(e->getKeyChar());
-	e->consume();
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::keyReleased(KeyEvent* e)
-{
-	CEGUI::System::getSingleton().injectKeyUp(e->getKey());
-	e->consume();
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::keyClicked(KeyEvent* e) 
-{
-	// Do nothing
-	e->consume();
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::addFrameInfo(SceneNode *camNode, Real timeElapsed)
-{
-	frame_info info;
-	info.orientation = mCamNode->getOrientation();
-	info.position = mCamNode->getPosition();
-	info.timeElapsed = timeElapsed;
-
-	mFrameInfo.push_back(info);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::setCurrentFrameInfo(Real timeElapsed)
-{
-	//-- find current frame relative to elapsed frame time		
-	mTimeElapsed -= timeElapsed;
-
-	while ((mTimeElapsed <= 0) && (mCurrentFrame < (int)mFrameInfo.size() - 1))
-	{
-		mTimeElapsed += mFrameInfo[mCurrentFrame ++].timeElapsed;
-	}
-
-	frame_info new_frame = mFrameInfo[mCurrentFrame];
-	frame_info old_frame = mFrameInfo[mCurrentFrame - 1];
-		
-	//-- interpolate frames
-	Real factor = 1;
-
-	if (old_frame.timeElapsed > 0)
-		factor = mTimeElapsed / old_frame.timeElapsed;
-
-	Vector3 camPos = old_frame.position + factor * (new_frame.position - old_frame.position);
-	Quaternion camOrienation = Quaternion::Slerp(factor, old_frame.orientation, 
-		new_frame.orientation, true);
-
-	mCamNode->setPosition(camPos);
-	mCamNode->setOrientation(camOrienation);
-	
-	// stop replay after a full walkthrough
-	if (mCurrentFrame == (int)mFrameInfo.size() - 1)
-	{
-		nextAppState();
-	}
-}
+
 
 /**************************************************************/
Index: trunk/VUT/work/TestCullingTerrain/TerrainMouseQueryListener.cpp
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TerrainMouseQueryListener.cpp	(revision 115)
+++ trunk/VUT/work/TestCullingTerrain/TerrainMouseQueryListener.cpp	(revision 115)
@@ -0,0 +1,917 @@
+#include <OgreNoMemoryMacros.h>
+#include <CEGUI/CEGUI.h>
+#include <../CEGUIRenderer/include/OgreCEGUIRenderer.h>
+#include <../CEGUIRenderer/include/OgreCEGUIResourceProvider.h>
+#include <../CEGUIRenderer/include/OgreCEGUITexture.h>
+#include <OgreMemoryMacros.h>
+#include "TerrainMouseQueryListener.h"
+
+// output file for frame info
+const char* frames_out_filename = "frame.out";
+// output file for object positions / orientations
+const char* objects_out_filename = "objects.out";
+
+
+Real timeDelay = 0;
+#define KEY_PRESSED(_key,_timeDelay, _macro) \
+{ \
+    if (mInputDevice->isKeyDown(_key) && timeDelay <= 0) \
+{ \
+    timeDelay = _timeDelay; \
+    _macro ; \
+} \
+}
+
+
+String mCurrentAlgorithmCaptions[GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS] = 
+{
+    "View Frustum Culling", 
+	"Stop and Wait Culling", 
+	"Coherent Hierarchical Culling"
+};
+
+
+//-----------------------------------------------------------------------
+TerrainMouseQueryListener::TerrainMouseQueryListener(RenderWindow* win, Camera* cam, 
+									   SceneManager *sceneManager, 
+									   CEGUI::Renderer *renderer,
+									   TerrainContentGenerator *sceneGenerator,
+									   Camera *vizCamera,
+									   SceneNode *camNode): 
+mCamera(cam),
+mWindow(win),
+mStatsOn(true),
+mNumScreenShots(0),
+mTimeUntilNextToggle(0),
+mSceneDetailIndex(0),
+mMoveScale(0.0f),
+mRotScale(0.0f),
+mTranslateVector(Vector3::ZERO),
+mAniso(1),
+mFiltering(TFO_BILINEAR), 
+mGUIRenderer(renderer), 
+mShutdownRequested(false), 
+mLMouseDown(false),
+mRMouseDown(false),
+mSceneMgr(sceneManager),
+mCurrentObject(NULL),
+mTerrainContentGenerator(sceneGenerator),
+mVisibilityThreshold(0),
+mCurrentAlgorithm(GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING),
+//mCurrentAlgorithm(GtpVisibility::VisibilityEnvironment::FRUSTUM_CULLING),
+mShowOctree(false),
+mUseDepthPass(false),
+mUseOptimization(true),
+mVizCamera(vizCamera),
+mShowVisualization(false),
+mNodeVizMode(NODEVIZ_NONE),
+mVizCameraHeight(Real(2500.0)),
+mCamNode(camNode),
+mCullCamera(false),
+mAppState(WALKTHROUGH),
+mCurrentFrame(0),
+mRecord(false),
+mTimeElapsed(0),
+mUseShadows(false),
+mVisualizeCulledNodes(false),
+mRotateSpeed(72),
+mMoveSpeed(50)
+{
+	mDebugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay");
+	
+    mInputDevice = PlatformManager::getSingleton().createInputReader();
+	mInputDevice->initialise(win, true, true);
+
+    showDebugOverlay(true);
+    
+	// Register this so that we get mouse events.
+	/*mEventProcessor->addMouseListener(this);
+	mEventProcessor->addMouseMotionListener(this);
+	mEventProcessor->addKeyListener(this);
+	*/
+
+	// create ray query executor, used to place objects in terrain
+	mRayQueryExecutor = new RayQueryExecutor(mSceneMgr);
+	
+	//-- show visibility overlay
+	Overlay* pOver = OverlayManager::getSingleton().getByName("Example/VisibilityDemoOverlay"); 
+
+	mAlgorithmInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/AlgorithmInfo");
+	mThresholdInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/ThresholdInfo");
+	
+	mFrustumCulledNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/FrustumCulledNodesInfo");
+	mQueryCulledNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/QueryCulledNodesInfo");
+    mTraversedNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/TraversedNodesInfo");
+	mHierarchyNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/HierarchyNodesInfo");
+	mRenderedNodesInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/RenderedNodesInfo");
+	mObjectsInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/ObjectsInfo");
+	mUseOptimizationInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/UseOptimizationInfo");
+	mUseDepthPassInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/UseDepthPassInfo");
+	mQueriesIssuedInfo = OverlayManager::getSingleton().getOverlayElement("Example/Visibility/QueriesIssuedInfo");
+	
+	mAlgorithmInfo->setCaption(": " + mCurrentAlgorithmCaptions[mCurrentAlgorithm]);
+	mThresholdInfo->setCaption(": 0");
+	mFrustumCulledNodesInfo->setCaption(": 0");
+	mQueryCulledNodesInfo->setCaption(": 0");
+	mTraversedNodesInfo->setCaption(": 0");
+	mHierarchyNodesInfo->setCaption(": 0");
+	mRenderedNodesInfo->setCaption(": 0");
+	mObjectsInfo->setCaption(": 0");
+	mUseOptimizationInfo->setCaption(": true");
+	mUseDepthPassInfo->setCaption(": false");
+	mQueriesIssuedInfo->setCaption(": 0");
+	
+	pOver->show();
+
+
+	// set culling algorithm type
+	setAlgorithm(mCurrentAlgorithm);
+
+
+	// set scene manager options
+	mSceneMgr->setOption("UseOptimization", &mUseOptimization);
+	bool delayedRendering = !mUseOptimization;
+	mSceneMgr->setOption("DelayRenderTransparents", &delayedRendering);
+	mSceneMgr->setOption("UseDepthPass", &mUseDepthPass);
+	mSceneMgr->setOption("ShowOctree", &mShowOctree);
+	mSceneMgr->setOption("CullCamera", &mCullCamera);
+	mSceneMgr->setOption("ShowVisualization", &mShowVisualization);
+} 
+//-----------------------------------------------------------------------
+TerrainMouseQueryListener::~TerrainMouseQueryListener()
+{
+	PlatformManager::getSingleton().destroyInputReader(mInputDevice);
+    
+	delete mRayQueryExecutor;
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::mouseMoved(MouseEvent *e)
+{
+	// Update CEGUI with the mouse motion
+    CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * 
+		mGUIRenderer->getWidth(), e->getRelY() * mGUIRenderer->getHeight());
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::mousePressed(MouseEvent* e)
+{
+     // Left mouse button down
+     if (e->getButtonID() & InputEvent::BUTTON0_MASK)
+     {
+		 CEGUI::MouseCursor::getSingleton().hide();
+
+		 // Setup the ray scene query
+         Ray mouseRay = mCamera->getCameraToViewportRay(e->getX(), e->getY());
+   
+		 Vector3 queryResult;
+		 
+		 // Get results, create a node/entity on the position
+		 mCurrentObject = mTerrainContentGenerator->GenerateSceneObject(
+			 mouseRay.getOrigin(), Vector3(0,0,0), "robot");
+		
+         mLMouseDown = true; 
+     }
+     // Right mouse button down
+     else if (e->getButtonID() & InputEvent::BUTTON1_MASK)
+     {
+         CEGUI::MouseCursor::getSingleton().hide();
+         mRMouseDown = true;
+     }
+} // mousePressed
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::mouseReleased(MouseEvent* e)
+{
+    // Left mouse button up
+    if (e->getButtonID() & InputEvent::BUTTON0_MASK)
+    {
+		CEGUI::MouseCursor::getSingleton().show();
+        mLMouseDown = false;
+    }
+    // Right mouse button up
+    else if (e->getButtonID() & InputEvent::BUTTON1_MASK)
+    {
+        CEGUI::MouseCursor::getSingleton().show();
+        mRMouseDown = false;
+    }
+} 
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::mouseDragged(MouseEvent *e)
+ {
+	 // If we are dragging the left mouse button.	 	 
+	 if (mLMouseDown)
+     {
+		 Vector3 queryResult;
+		 Ray mouseRay = mCamera->getCameraToViewportRay(e->getX(), e->getY());
+
+		 if (mRayQueryExecutor->executeRayQuery(&queryResult, mouseRay))
+		 {
+			 if (mCurrentObject)
+			 {
+				 mCurrentObject->setPosition(queryResult);
+			 }
+		 }
+     }
+	 // If we are dragging the right mouse button.
+	 if (mRMouseDown)
+	 {
+		 //mCamera->yaw(-e->getRelX() * mRotateSpeed);
+		 //mCamera->pitch(-e->getRelY() * mRotateSpeed);
+		 mCamNode->yaw(-e->getRelX() * mRotateSpeed);
+		 mCamNode->pitch(-e->getRelY() * mRotateSpeed);
+	 }
+}
+//-----------------------------------------------------------------------
+bool TerrainMouseQueryListener::frameStarted(const FrameEvent &evt)
+{
+	if (mWindow->isClosed())
+        return false;
+
+	 mInputDevice->capture();
+		 
+	 //-- setup what is needed for immediate mouse/key movement
+	 if (mTimeUntilNextToggle >= 0) 
+		 mTimeUntilNextToggle -= evt.timeSinceLastFrame;
+
+	 // If this is the first frame, pick a speed
+	 if (evt.timeSinceLastFrame == 0)
+	 {
+		 mMoveScale = 1;
+		 mRotScale = 0.1;
+	 }
+	 // Otherwise scale movement units by time passed since last frame
+	 else
+	 {
+		 // Move about 100 units per second,
+		 mMoveScale = mMoveSpeed * evt.timeSinceLastFrame;
+		 // Take about 10 seconds for full rotation
+		 mRotScale = mRotateSpeed * evt.timeSinceLastFrame;
+	 }
+
+	 mRotX = 0;
+	 mRotY = 0;
+	 mTranslateVector = Vector3::ZERO;
+
+	 if (!processUnbufferedKeyInput(evt))
+	 {
+		 return false;
+	 }
+	 if (!processUnbufferedMouseInput(evt))
+	 {
+		 return false;
+	 }
+
+	 if (mShowVisualization)
+	 {
+		// important for visualization => draw octree bounding boxes
+		mSceneMgr->setOption("ShowOctree", &mShowVisualization);
+		// also render nodew content?
+		//mSceneMgr->setOption("RenderNodesForViz", &mRenderNodesForViz);
+
+		// -- setup visualization camera
+		mVizCamera->setPosition(0, 0, 0);
+		mVizCamera->setOrientation(Quaternion::IDENTITY);
+
+		Vector3 camPos = mCamNode->getPosition();
+		mVizCamera->setPosition(camPos.x, mVizCameraHeight, camPos.z);
+
+		// point down -Z axis
+		mVizCamera->pitch(Radian(Degree(270.0)));
+	
+		// rotation arounnd X axis
+		mVizCamera->yaw(Math::ATan2(-mCamera->getDerivedDirection().x, 
+			-mCamera->getDerivedDirection().z));
+		
+		// move by a constant so view plane is on bottom of viewport
+		mVizCamera->moveRelative(Vector3(0, 800, 0));
+	}
+
+	switch (mAppState)
+	{
+	case REPLAY:
+		setCurrentFrameInfo(evt.timeSinceLastFrame);
+		break;
+	case WALKTHROUGH:
+		//-- if we are recording camera status per frame
+		if (mRecord)
+		{
+			addFrameInfo(mCamNode, evt.timeSinceLastFrame);
+			// print recording message
+			mWindow->setDebugText("Recording frame " + 
+				StringConverter::toString(mFrameInfo.size() - 1));
+		}	
+	
+		 moveCamera();
+		 Clamp2Terrain();
+
+		 break;
+	default:
+		break;
+	};	
+	
+	return true;
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::Clamp2Terrain()
+{
+	// clamp to terrain
+	Vector3 camPos = mCamNode->getPosition();
+	Vector3 queryResult;
+
+	if (mRayQueryExecutor->executeRayQuery(&queryResult, 
+			Vector3(camPos.x, 5000.0f, camPos.z), Vector3::NEGATIVE_UNIT_Y))
+	{
+		mCamNode->setPosition(camPos.x, queryResult.y + 10, camPos.z);
+	}
+}
+//-----------------------------------------------------------------------
+bool TerrainMouseQueryListener::frameEnded(const FrameEvent& evt)
+{
+	if (mShutdownRequested)
+		return false;
+
+    if (timeDelay >= 0) 
+        timeDelay -= evt.timeSinceLastFrame;
+
+	KEY_PRESSED(KC_SPACE, 0.3, nextAlgorithm());
+
+	KEY_PRESSED(KC_O, 0.3, toggleUseOptimization());
+	KEY_PRESSED(KC_T, 0.3, toggleShowOctree());
+	KEY_PRESSED(KC_X, 0.3, toggleUseDepthPass());
+	KEY_PRESSED(KC_1, 0.3, toggleShowViz());
+	KEY_PRESSED(KC_2, 0.3, nextNodeVizMode());
+	
+	KEY_PRESSED(KC_SUBTRACT, 0, changeThreshold(-10));
+	KEY_PRESSED(KC_ADD, 0, changeThreshold(10));
+	
+	KEY_PRESSED(KC_4, 0, zoomVizCamera(50));
+	KEY_PRESSED(KC_5, 0, zoomVizCamera(-50));
+
+	KEY_PRESSED(KC_F1, 0.3, nextAppState());
+	KEY_PRESSED(KC_F2, 0.3, toggleRecord());
+	KEY_PRESSED(KC_F3, 0.3, mTerrainContentGenerator->WriteObjects(objects_out_filename));
+	KEY_PRESSED(KC_F4, 0.3, toggleUseShadows());
+	//KEY_PRESSED(KC_F3, 0.3, writeFrames());
+	//KEY_PRESSED(KC_F4, 0.3, loadFrames());
+
+	updateStats();
+
+	return true;
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::moveCamera()
+{
+	// move node rather than camera so orientation is right in the visualization
+	mCamNode->yaw(mRotX);
+	mCamNode->pitch(mRotY);
+	mCamNode->translate(mCamNode->getLocalAxes(), mTranslateVector);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::writeFrames()
+{
+	std::ofstream ofstr(frames_out_filename);
+	
+	std::vector<frame_info>::const_iterator it, it_end;
+
+	it_end = mFrameInfo.end();
+	for(it = mFrameInfo.begin(); it < it_end; ++it)
+	{
+		ofstr << StringConverter::toString((*it).position) << " " 
+			<< StringConverter::toString((*it).orientation) << " "
+			<< StringConverter::toString((*it).timeElapsed) << "\n";
+	}
+	ofstr.close();
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::loadFrames()
+{
+	std::ifstream ifstr(frames_out_filename);
+	char line[256];
+	frame_info info;
+
+	// reset current values
+	mFrameInfo.clear();
+	mCurrentFrame = 0;
+	
+	while (!ifstr.eof()) 
+	{
+		ifstr.getline(line, 256);
+		sscanf(line, "%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);
+		
+		mFrameInfo.push_back(info);
+		
+		/*
+		std::stringstream d;
+		d << StringConverter::toString(info.position) << " " << StringConverter::toString(info.orientation);
+		LogManager::getSingleton().logMessage(d.str());
+		*/
+	}
+	ifstr.close();
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::setAppState(int state)
+{
+	mAppState = state;
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::nextAppState()
+{
+	mCurrentFrame = 0;
+
+	// if last state was replay state
+	if (mAppState == REPLAY)
+	{
+		// reset debug text and write frame info to file
+		mWindow->setDebugText("");
+		writeFrames();
+		
+		//-- write out stats
+		std::stringstream d;
+		d << "Algorithm: " << mCurrentAlgorithmCaptions[mCurrentAlgorithm] << "\n"
+		  << "avg. FPS: " << mWindow->getAverageFPS() << "\n"
+		  << "best FPS: " << mWindow->getBestFPS() << "\n"
+		  << "worst FPS: " << mWindow->getWorstFPS() << "\n"
+		  << "best frame time: " <<	mWindow->getBestFrameTime() << "\n"
+		  << "worst frame time: " << mWindow->getWorstFrameTime();
+ 		
+		LogManager::getSingleton().logMessage(d.str());
+	}
+	
+	//-- 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
+		if (mFrameInfo.size() == 0)
+		{
+			loadFrames();
+		}
+
+		// if there are no recorded frames => set next state
+		if (mFrameInfo.size() == 0) 
+		{
+			nextAppState();
+		}
+		else
+		{
+			mWindow->setDebugText("Replay");
+			
+			// reset, because we measure fps stats during walkthrough
+			mWindow->resetStatistics();
+
+			//-- initialise frame data
+			mTimeElapsed = 0;
+
+			mCamNode->setPosition(mFrameInfo[0].position);
+			mCamNode->setOrientation(mFrameInfo[0].orientation);
+		}
+	}
+
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleRecord()
+{
+	mRecord = !mRecord;
+
+	// clear previous camera path
+	if (mRecord)
+		mFrameInfo.clear();
+	else
+		mWindow->setDebugText("");
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::changeThreshold(int incr)
+{
+	mVisibilityThreshold += incr; 
+	if(mVisibilityThreshold < 0) mVisibilityThreshold = 0;
+	
+	char str[100]; sprintf(str,": %d", mVisibilityThreshold);
+
+	mSceneMgr->setOption("Threshold", &mVisibilityThreshold); 
+	mThresholdInfo->setCaption(str);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::zoomVizCamera(int zoom)
+{
+	mVizCameraHeight += zoom; 
+	if(mVizCameraHeight < 0) mVizCameraHeight = 0;
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::nextAlgorithm()
+{
+	mCurrentAlgorithm = (mCurrentAlgorithm + 1) % 
+		GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS,
+
+	setAlgorithm(mCurrentAlgorithm);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::setAlgorithm(int algorithm)
+{
+	mAlgorithmInfo->setCaption(": " + mCurrentAlgorithmCaptions[mCurrentAlgorithm]);
+	mSceneMgr->setOption("Algorithm", &mCurrentAlgorithm);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::updateStats()
+{
+	unsigned int opt = 0;
+	char str[100];
+	
+	static String currFps = "Current FPS: ";
+	static String avgFps = "Average FPS: ";
+	static String bestFps = "Best FPS: ";
+	static String worstFps = "Worst FPS: ";
+	static String tris = "Triangle Count: ";
+
+	// update stats when necessary
+    try {
+		OverlayElement* guiAvg = OverlayManager::getSingleton().getOverlayElement("Core/AverageFps");
+		OverlayElement* guiCurr = OverlayManager::getSingleton().getOverlayElement("Core/CurrFps");
+		OverlayElement* guiBest = OverlayManager::getSingleton().getOverlayElement("Core/BestFps");
+		OverlayElement* guiWorst = OverlayManager::getSingleton().getOverlayElement("Core/WorstFps");
+
+		const RenderTarget::FrameStats& stats = mWindow->getStatistics();
+
+		guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
+		guiCurr->setCaption(currFps + StringConverter::toString(stats.lastFPS));
+		guiBest->setCaption(bestFps + StringConverter::toString(stats.bestFPS)
+			+" "+StringConverter::toString(stats.bestFrameTime)+" ms");
+		guiWorst->setCaption(worstFps + StringConverter::toString(stats.worstFPS)
+			+" "+StringConverter::toString(stats.worstFrameTime)+" ms");
+
+		OverlayElement* guiTris = OverlayManager::getSingleton().getOverlayElement("Core/NumTris");
+        guiTris->setCaption(tris + StringConverter::toString(stats.triangleCount));
+
+		OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText");
+		guiDbg->setCaption(mWindow->getDebugText());
+
+		//-- culling stats
+		mSceneMgr->getOption("NumFrustumCulledNodes", &opt); sprintf(str,": %d", opt); 
+		mFrustumCulledNodesInfo->setCaption(str);
+	
+		mSceneMgr->getOption("NumQueriesIssued", &opt); sprintf(str,": %d", opt); 
+		mQueriesIssuedInfo->setCaption(str);
+
+		mSceneMgr->getOption("NumQueryCulledNodes", &opt); sprintf(str,": %d", opt); 
+		mQueryCulledNodesInfo->setCaption(str);
+	
+		mSceneMgr->getOption("NumTraversedNodes", &opt); sprintf(str,": %d", opt); 
+		mTraversedNodesInfo->setCaption(str);
+
+		mSceneMgr->getOption("NumHierarchyNodes", &opt); sprintf(str,": %d", opt); 
+		mHierarchyNodesInfo->setCaption(str);
+
+		mSceneMgr->getOption("NumRenderedNodes", &opt); sprintf(str,": %d", opt); 
+		mRenderedNodesInfo->setCaption(str);
+
+		sprintf(str,": %d", mTerrainContentGenerator->GetObjectCount()); 
+		mObjectsInfo->setCaption(str);
+	}
+	catch(...)
+	{
+            // ignore
+	}
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleUseOptimization()
+{
+	mUseOptimization = !mUseOptimization;
+
+	mSceneMgr->setOption("UseOptimization", &mUseOptimization);
+	// delayed rendering (i.e., render transparents afterwards) allows 
+	// no optimization which tests geometry instead of aabb
+	bool delayedRendering = !mUseOptimization;
+	mSceneMgr->setOption("DelayRenderTransparents", &delayedRendering);
+
+	if (mUseOptimization)
+		mUseOptimizationInfo->setCaption(": true");
+	else
+		mUseOptimizationInfo->setCaption(": false");
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleShowOctree()
+{
+	mShowOctree = !mShowOctree;
+
+	mSceneMgr->setOption("ShowOctree", &mShowOctree);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleUseDepthPass()
+{
+	mUseDepthPass = !mUseDepthPass;
+
+	mSceneMgr->setOption("UseDepthPass", &mUseDepthPass);
+	
+	if (mUseDepthPass)
+		mUseDepthPassInfo->setCaption(": true");
+	else
+		mUseDepthPassInfo->setCaption(": false");
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleShowViz()
+{
+	mShowVisualization = !mShowVisualization;
+	mVisualizeCulledNodes = !mVisualizeCulledNodes;
+
+	// create viewport with priority VIZ_VIEWPORT_Z_ORDER: 
+	// will be rendered over standard viewport
+	if (mShowVisualization)
+	{	
+		Viewport *vizvp = mWindow->addViewport(mVizCamera, 
+			VIZ_VIEWPORT_Z_ORDER, 0.6, 0.6, 0.4, 0.4); 
+				
+		vizvp->setBackgroundColour(ColourValue(0.0, 0.3, 0.2, 1));
+
+		vizvp->setOverlaysEnabled(false);
+		// Alter the camera aspect ratio to match the viewport
+        mVizCamera->setAspectRatio(Real(vizvp->getActualWidth()) / 
+			Real(vizvp->getActualHeight()));
+		
+		mSceneMgr->setOption("VisualizeCulledNodes", &mVisualizeCulledNodes);
+		//vizvp->setClearEveryFrame(false);
+
+		// Create a skyplane (for visualization background)
+		/*
+		Plane plane;
+		plane.d = -1000;
+		plane.normal = Vector3::UNIT_Y;
+		mSceneMgr->setSkyPlane(true, plane, "Examples/TransparentTest", 4000, 75, false);
+		*/
+		
+	}
+	else
+	{
+		mWindow->removeViewport(VIZ_VIEWPORT_Z_ORDER);
+		// if octree was enabled for visualization purpose, reset now
+		mSceneMgr->setOption("ShowOctree", &mShowOctree);
+	}
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleUseShadows()
+{
+	mUseShadows = !mUseShadows;
+
+	//mSunLight->setCastShadows(mUseShadows);
+
+	if (mUseShadows)
+	{
+		mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE);
+	}
+	else
+	{
+		mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
+	}
+
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::nextNodeVizMode()
+{
+	mNodeVizMode = (mNodeVizMode + 1) % NODEVIZ_MODES_NUM;
+
+	bool renderNodesForViz = (mNodeVizMode == NODEVIZ_RENDER_NODES) || (mNodeVizMode == NODEVIZ_RENDER_NODES_AND_CONTENT);
+	bool renderNodesContentForViz = (mNodeVizMode == NODEVIZ_RENDER_NODES_AND_CONTENT);
+	//bool renderNodesContentForViz = mNodeVizMode == NODEVIZ_RENDER_GEOMETRY;
+
+	mSceneMgr->setOption("RenderNodesForViz", &renderNodesForViz);
+	mSceneMgr->setOption("RenderNodesContentForViz", &renderNodesContentForViz);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::keyPressed(KeyEvent* e)
+{
+	if(e->getKey() == KC_ESCAPE)
+    {
+		mShutdownRequested = true;
+		e->consume();
+		return;
+	}
+
+	CEGUI::System::getSingleton().injectKeyDown(e->getKey());
+	CEGUI::System::getSingleton().injectChar(e->getKeyChar());
+	e->consume();
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::keyReleased(KeyEvent* e)
+{
+	CEGUI::System::getSingleton().injectKeyUp(e->getKey());
+	e->consume();
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::keyClicked(KeyEvent* e) 
+{
+	// Do nothing
+	e->consume();
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::addFrameInfo(SceneNode *camNode, Real timeElapsed)
+{
+	frame_info info;
+	info.orientation = mCamNode->getOrientation();
+	info.position = mCamNode->getPosition();
+	info.timeElapsed = timeElapsed;
+
+	mFrameInfo.push_back(info);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::setCurrentFrameInfo(Real timeElapsed)
+{
+	//-- find current frame relative to elapsed frame time		
+	mTimeElapsed -= timeElapsed;
+
+	while ((mTimeElapsed <= 0) && (mCurrentFrame < (int)mFrameInfo.size() - 1))
+	{
+		mTimeElapsed += mFrameInfo[mCurrentFrame ++].timeElapsed;
+	}
+
+	frame_info new_frame = mFrameInfo[mCurrentFrame];
+	frame_info old_frame = mFrameInfo[mCurrentFrame - 1];
+		
+	//-- interpolate frames
+	Real factor = 1;
+
+	if (old_frame.timeElapsed > 0)
+		factor = mTimeElapsed / old_frame.timeElapsed;
+
+	Vector3 camPos = old_frame.position + factor * (new_frame.position - old_frame.position);
+	Quaternion camOrienation = Quaternion::Slerp(factor, old_frame.orientation, 
+		new_frame.orientation, true);
+
+	mCamNode->setPosition(camPos);
+	mCamNode->setOrientation(camOrienation);
+	
+	// stop replay after a full walkthrough
+	if (mCurrentFrame == (int)mFrameInfo.size() - 1)
+	{
+		nextAppState();
+	}
+}
+//-----------------------------------------------------------------------    
+bool TerrainMouseQueryListener::processUnbufferedKeyInput(const FrameEvent& evt)
+{
+    if (mInputDevice->isKeyDown(KC_A))
+    {
+        // Move camera left
+        mTranslateVector.x = -mMoveScale;
+    }
+
+    if (mInputDevice->isKeyDown(KC_D))
+    {
+        // Move camera RIGHT
+        mTranslateVector.x = mMoveScale;
+    }
+
+    /* Move camera forward by keypress. */
+    if (mInputDevice->isKeyDown(KC_UP) || mInputDevice->isKeyDown(KC_W) )
+    {
+        mTranslateVector.z = -mMoveScale;
+    }
+
+    /* Move camera backward by keypress. */
+    if (mInputDevice->isKeyDown(KC_DOWN) || mInputDevice->isKeyDown(KC_S) )
+    {
+        mTranslateVector.z = mMoveScale;
+    }
+
+    if (mInputDevice->isKeyDown(KC_PGUP))
+    {
+        // Move camera up
+        mTranslateVector.y = mMoveScale;
+    }
+
+    if (mInputDevice->isKeyDown(KC_PGDOWN))
+    {
+        // Move camera down
+        mTranslateVector.y = -mMoveScale;
+    }
+
+    if (mInputDevice->isKeyDown(KC_RIGHT))
+    {
+        mCamNode->yaw(-mRotScale);
+    }
+	
+    if (mInputDevice->isKeyDown(KC_LEFT))
+    {
+        mCamNode->yaw(mRotScale);
+    }
+
+    if( mInputDevice->isKeyDown( KC_ESCAPE) )
+    {            
+        return false;
+    }
+	
+	if (mInputDevice->isKeyDown(KC_F) && mTimeUntilNextToggle <= 0)
+    {
+        mStatsOn = !mStatsOn;
+        showDebugOverlay(mStatsOn);
+
+        mTimeUntilNextToggle = 1;
+    }
+    if (mInputDevice->isKeyDown(KC_T) && mTimeUntilNextToggle <= 0)
+    {
+        switch(mFiltering)
+        {
+        case TFO_BILINEAR:
+            mFiltering = TFO_TRILINEAR;
+            mAniso = 1;
+            break;
+        case TFO_TRILINEAR:
+            mFiltering = TFO_ANISOTROPIC;
+            mAniso = 8;
+            break;
+        case TFO_ANISOTROPIC:
+            mFiltering = TFO_BILINEAR;
+            mAniso = 1;
+            break;
+        default:
+            break;
+        }
+        MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering);
+        MaterialManager::getSingleton().setDefaultAnisotropy(mAniso);
+
+
+        showDebugOverlay(mStatsOn);
+
+        mTimeUntilNextToggle = 1;
+    }
+
+    if (mInputDevice->isKeyDown(KC_SYSRQ) && mTimeUntilNextToggle <= 0)
+    {
+		char tmp[20];
+		sprintf(tmp, "screenshot_%d.png", ++mNumScreenShots);
+        mWindow->writeContentsToFile(tmp);
+        mTimeUntilNextToggle = 0.5;
+		mWindow->setDebugText(String("Wrote ") + tmp);
+    }
+	
+	if (mInputDevice->isKeyDown(KC_R) && mTimeUntilNextToggle <=0)
+	{
+		mSceneDetailIndex = (mSceneDetailIndex+1)%3 ;
+		switch(mSceneDetailIndex) {
+			case 0 : mCamera->setDetailLevel(SDL_SOLID) ; break ;
+			case 1 : mCamera->setDetailLevel(SDL_WIREFRAME) ; break ;
+			case 2 : mCamera->setDetailLevel(SDL_POINTS) ; break ;
+		}
+		mTimeUntilNextToggle = 0.5;
+	}
+
+    static bool displayCameraDetails = false;
+    if (mInputDevice->isKeyDown(KC_P) && mTimeUntilNextToggle <= 0)
+    {
+        displayCameraDetails = !displayCameraDetails;
+        mTimeUntilNextToggle = 0.5;
+        if (!displayCameraDetails)
+            mWindow->setDebugText("");
+    }
+    if (displayCameraDetails)
+    {
+        // Print camera details
+        mWindow->setDebugText("P: " + StringConverter::toString(mCamera->getDerivedPosition()) + " " + 
+            "O: " + StringConverter::toString(mCamera->getDerivedOrientation()));
+    }
+
+    // Return true to continue rendering
+    return true;
+}
+//-----------------------------------------------------------------------
+bool TerrainMouseQueryListener::processUnbufferedMouseInput(const FrameEvent& evt)
+{
+	/* Rotation factors, may not be used if the second mouse button is pressed. */
+
+	/* If the second mouse button is pressed, then the mouse movement results in 
+	sliding the camera, otherwise we rotate. */
+	if(mInputDevice->getMouseButton(1))
+	{
+		mTranslateVector.x += mInputDevice->getMouseRelativeX() * 0.13;
+		mTranslateVector.y -= mInputDevice->getMouseRelativeY() * 0.13;
+	}
+    else
+    {
+		mRotX = Degree(-mInputDevice->getMouseRelativeX() * 0.13);
+		mRotY = Degree(-mInputDevice->getMouseRelativeY() * 0.13);
+    }
+
+
+	return true;
+}
+
+void TerrainMouseQueryListener::showDebugOverlay(bool show)
+{
+	if (mDebugOverlay)
+	{
+		if (show)
+		{
+			mDebugOverlay->show();
+		}
+		else
+		{
+			mDebugOverlay->hide();
+		}
+	}
+}
+
+
+	
+	
Index: trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.h
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.h	(revision 114)
+++ trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.h	(revision 115)
@@ -1,38 +1,11 @@
-/**
-    \file 
-        TestCullingTerrainApplication.h
-*/
+#ifndef _TestCullingTerrainApplication_H__
+#define _TestCullingTerrainApplication_H__
+
 #include "CEGUIForwardRefs.h"
 #include "ExampleApplication.h"
 #include "OgreTerrainContentGenerator.h"
-#include "VisibilityEnvironment.h"
+
 #include <OgreRenderTargetListener.h>
-#include <vector>
-
-Real timeDelay = 0;
-#define KEY_PRESSED(_key,_timeDelay, _macro) \
-{ \
-    if (mInputDevice->isKeyDown(_key) && timeDelay <= 0) \
-{ \
-    timeDelay = _timeDelay; \
-    _macro ; \
-} \
-}
-
-String mCurrentAlgorithmCaptions[GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS] = 
-{
-    "View Frustum Culling", 
-	"Stop and Wait Culling", 
-	"Coherent Hierarchical Culling"
-};
-
-/** The information about camera position and orienation per frame */
-typedef struct
-{
-	Vector3 position;
-	Quaternion orientation;
-	Real timeElapsed;
-} frame_info;
-
+#include "TerrainMouseQueryListener.h"
 
 class VisualizationRenderTargetListener: public RenderTargetListener
@@ -46,130 +19,4 @@
 
 	SceneManager *mSceneMgr;
-};
-
-class MouseQueryListener : public ExampleFrameListener, public MouseListener, public MouseMotionListener
-{
-public:
-	
-    MouseQueryListener(RenderWindow* win, Camera* cam, SceneManager *sceneManager, 
-		CEGUI::Renderer *renderer, TerrainContentGenerator *contentGenerator, Camera *vizCamera,
-		SceneNode *camNode);
-
-    ~MouseQueryListener();
-
-	bool frameStarted(const FrameEvent& evt);
-	bool frameEnded(const FrameEvent& evt);
-	bool processUnbufferedKeyInput(const FrameEvent& evt);
-    
-
-    /* MouseListener callbacks. */
-    virtual void mouseClicked(MouseEvent* e) { }
-    virtual void mouseEntered(MouseEvent* e) { }
-    virtual void mouseExited(MouseEvent* e)  { }
-
-    // This is when the mouse button goes DOWN.
-    virtual void mousePressed(MouseEvent* e);
-
-    // This is when the mouse button is let UP.
-    virtual void mouseReleased(MouseEvent* e);
-
-    /* MouseMotionListener callbacks */
-    virtual void mouseMoved (MouseEvent *e);
-   
-    // This is when the mouse is clicked, held and dragged.
-    virtual void mouseDragged (MouseEvent *e);
-
-    void keyPressed(KeyEvent* e);
-
-	void keyReleased(KeyEvent* e);
-	void keyClicked(KeyEvent* e);
-
-	enum  {WALKTHROUGH, REPLAY, STATE_NUM};
-
-	// visualization modes for scene nodes
-	//enum {NODEVIZ_NONE, NODEVIZ_RENDER_NODES, 
-	//	  NODEVIZ_RENDER_NODES_AND_CONTENT, NODEVIZ_MODES_NUM};
-	enum {NODEVIZ_NONE, NODEVIZ_RENDER_GEOMETRY, NODEVIZ_MODES_NUM};
-
-	void nextAlgorithm();
-	void changeThreshold(int incr);
-	void updateStats();
-
-	void toggleUseOptimization();
-	void toggleShowOctree();
-	void toggleUseVisibilityCulling();
-	void toggleShowViz();
-	void nextNodeVizMode();
-	void toggleRecord();
-
-	void zoomVizCamera(int zoom);
-	
-	void addFrameInfo(SceneNode *camNode, Real timeElapsed);
-	void setCurrentFrameInfo(Real timeElapsed);
-
-	void setAppState(int state);
-	void nextAppState();
-
-	void setAlgorithm(int algorithm);
-
-	void moveCamera();
-	
-	void writeFrames();
-	void loadFrames();
-
-	void toggleUseShadows();
-
-protected:
-	void Clamp2Terrain();
-	
-    bool mLMouseDown, mRMouseDown;     // True if the mouse buttons are down
-    SceneManager *mSceneMgr;           // A pointer to the scene manager
-    
-	CEGUI::Renderer *mGUIRenderer;     // cegui renderer
-	
-	bool mShutdownRequested;
-	int mCurrentAlgorithm;
-	int mVisibilityThreshold;
-	
-	OverlayElement *mAlgorithmInfo;
-	OverlayElement *mThresholdInfo;
-	OverlayElement *mFrustumCulledNodesInfo;
-	OverlayElement *mQueryCulledNodesInfo;
-    OverlayElement *mTraversedNodesInfo;
-	OverlayElement *mHierarchyNodesInfo;
-	OverlayElement *mUseOptimizationInfo;
-	OverlayElement *mRenderedNodesInfo;
-	OverlayElement *mObjectsInfo;
-	OverlayElement *mQueriesIssuedInfo;
-
-	SceneNode *mCurrentObject;    // the newly created object
-	int mObjectCount;             // The number of objects on the screen
-
-	RayQueryExecutor *mRayQueryExecutor;
-	TerrainContentGenerator *mTerrainContentGenerator;
-
-	bool mUseOptimization;
-	bool mShowOctree;
-	bool mUseVisibilityCulling;
-	bool mShowVisualization;
-	int mNodeVizMode;
-	bool mCullCamera;
-
-	Real mVizCameraHeight;
-
-	Camera *mVizCamera;
-	SceneNode *mCamNode;
-	
-	//std::deque<Vector3> mWalkList;   // The list of points we are walking to
-	std::vector<frame_info> mFrameInfo;
-		
-	int mCurrentFrame;
-	// the current application state
-	int mAppState;
-	bool mRecord;
-	Real mTimeElapsed;
-	bool mUseShadows;
-
-	bool mVisualizeCulledNodes;
 };
 
@@ -209,5 +56,9 @@
 	VisualizationRenderTargetListener *mRenderTargetListener;
 
+	TerrainMouseQueryListener *mTerrainFrameListener;
+
 private:
 	void chooseSceneManager(void);
 };
+
+#endif // TestCullingTerrainApplication
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreHardwareOcclusionQuery.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreHardwareOcclusionQuery.h	(revision 92)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreHardwareOcclusionQuery.h	(revision 115)
@@ -96,32 +96,10 @@
       * Pulls the hardware occlusion query too see if there is a result.
       * @retval NumOfFragments will get the resulting number of fragments.
-	  * @param waitForResult if true, the query will wait until a result is available
-      * @return True if success or false if not.
-	  * @Remarks Hardware occlusion is an assyncronius process the result may take a frame or so.
-	  *			one idea is to test pass1 and if not visible skip pass2. Also note that objects
-	  *			not visible must be tested evrey frame. Visable objects don't need testing every frame.
-	  *			Testing non visable objects can be don unlit, no texture with low LOD object.
-	  *        0 will generate all the levels till 1x1. [default: 0]
-      */
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	  virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult ) = 0;
-#else
-	 virtual bool pullOcclusionQuery( unsigned int* NumOfFragments ) = 0;
-#endif
-	/**
-      * Pulls the hardware occlusion query too see if there is a result.
-      * @retval NumOfFragments will get the resulting number of fragments.
-	  * @param waitForResult if true, the query will wait until a result is available
       * @return True if success or false if not.
 	  * @Remarks In DX9 mode specifying OCCLUSIONQUERY_FLUSH as the flag, will case the driver to flush whatever API calls are batched.
 	  * In OpenGL mode it makes no difference if you specify OCCLUSIONQUERY_FLUSH or OCCLUSIONQUERY_NOFLUSH.
       */
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult,
-									 const HW_OCCLUSIONQUERY flag  ) = 0; 
-#else
-	  virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, 
-									   const HW_OCCLUSIONQUERY flag  ) = 0; 
-#endif
+	virtual bool pullOcclusionQuery(unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH) = 0;
+
 	/**
 	  * Let's you get the last pixel count with out doing the hardware occlusion test
@@ -143,4 +121,19 @@
 	virtual void	setSkipRate( int skip ) = 0;
 	virtual int		getSkipRate() = 0;
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	/**
+		Pulls occlusion query.
+		@param NumOfFragments number of visible fragments if query result was available.
+		Last query result if query result was not yet available.
+
+		@param waitForResult if true, the function waits until the result is available.
+		Otherwise the function returns immediately, not waiting for the result.
+		@returns true if query result was available, false if result was not yet available
+	*/
+	virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
+		const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH ) = 0; 
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+
 //----------------------------------------------------------------------
 // Private members
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h	(revision 115)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h	(revision 115)
@@ -0,0 +1,373 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2005 The OGRE Team
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+#ifndef __RenderQueueSortingGrouping_H__
+#define __RenderQueueSortingGrouping_H__
+
+// Precompiler options
+#include "OgrePrerequisites.h"
+#include "OgreIteratorWrappers.h"
+#include "OgreMaterial.h"
+#include "OgreTechnique.h"
+#include "OgrePass.h"
+#include "OgreMaterialManager.h"
+
+namespace Ogre {
+
+    /** Renderables in the queue grouped by priority.
+    @remarks
+        This class simply groups renderables for rendering. All the 
+        renderables contained in this class are destined for the same
+        RenderQueueGroup (coarse groupings like those between the main
+        scene and overlays) and have the same priority (fine groupings
+        for detailed overlap control).
+    @par
+        This class optimises the grouped renderables by sorting them by
+        material to reduce render state changes, and outsorts transparent
+        objects.
+    */
+    class RenderPriorityGroup
+    {
+        /** Internal struct reflecting a single Pass for a Renderable. 
+        This is used to sort transparent objects.
+        */
+        struct RenderablePass
+        {
+            /// Pointer to the Renderable details
+            Renderable* renderable;
+            /// Pointer to the Pass
+            Pass* pass;
+
+            RenderablePass(Renderable* rend, Pass* p) :renderable(rend), pass(p) {}
+        };
+
+        /// Comparator to order non-transparent object passes
+        struct SolidQueueItemLess
+        {
+            bool _OgreExport operator()(const Pass* a, const Pass* b) const
+            {
+                // Sort by passHash, which is pass, then texture unit changes
+                unsigned long hasha = a->getHash();
+                unsigned long hashb = b->getHash();
+                if (hasha == hashb)
+                {
+                    // Must differentiate by pointer incase 2 passes end up with the same hash
+                    return a < b;
+                }
+                else
+                {
+                    return hasha < hashb;
+                }
+            }
+        };
+        /// Comparator to order transparent object passes
+        struct TransparentQueueItemLess
+        {
+            const Camera* camera;
+            bool _OgreExport operator()(const RenderablePass& a, const RenderablePass& b) const
+            {
+                if (a.renderable == b.renderable)
+                {
+                    // Same renderable, sort by pass hash
+                    return a.pass->getHash() < b.pass->getHash();
+                }
+                else
+                {
+                    // Different renderables, sort by depth
+                    Real adepth = a.renderable->getSquaredViewDepth(camera);
+                    Real bdepth = b.renderable->getSquaredViewDepth(camera);
+				    if (adepth == bdepth)
+				    {
+                        // Must return deterministic result, doesn't matter what
+                        return a.pass < b.pass;
+				    }
+				    else
+				    {
+				        // Sort DESCENDING by depth (ie far objects first)
+					    return (adepth > bdepth);
+				    }
+                }
+
+            }
+        };
+    public:
+        /** Vector of RenderablePass objects, this is built on the assumption that
+         vectors only ever increase in size, so even if we do clear() the memory stays
+         allocated, ie fast */
+        typedef std::vector<RenderablePass> TransparentRenderablePassList;
+        typedef std::vector<Renderable*> RenderableList;
+        /** Map of pass to renderable lists, used for solid objects since ordering within objects not
+        important. */
+        typedef std::map<Pass*, RenderableList*, SolidQueueItemLess> SolidRenderablePassMap;
+    protected:
+        /// Parent queue group
+        RenderQueueGroup* mParent;
+        bool mSplitPassesByLightingType;
+        bool mSplitNoShadowPasses;
+        /// Solid pass list, used when no shadows, modulative shadows, or ambient passes for additive
+        SolidRenderablePassMap mSolidPasses;
+        /// Solid per-light pass list, used with additive shadows
+        SolidRenderablePassMap mSolidPassesDiffuseSpecular;
+        /// Solid decal (texture) pass list, used with additive shadows
+        SolidRenderablePassMap mSolidPassesDecal;
+        /// Solid pass list, used when shadows are enabled but shadow receive is turned off for these passes
+        SolidRenderablePassMap mSolidPassesNoShadow;
+
+		/// Transparent list
+		TransparentRenderablePassList mTransparentPasses;
+
+        /// Totally empties and destroys a solid pass map
+        void destroySolidPassMap(SolidRenderablePassMap& passmap);
+
+        /// remove a pass entry from all solid pass maps
+        void removeSolidPassEntry(Pass* p);
+
+        /// Clear a solid pass map at the end of a frame
+        void clearSolidPassMap(SolidRenderablePassMap& passmap);
+        /// Internal method for adding a solid renderable
+        void addSolidRenderable(Technique* pTech, Renderable* rend, bool toNoShadowMap);
+        /// Internal method for adding a solid renderable
+        void addSolidRenderableSplitByLightType(Technique* pTech, Renderable* rend);
+        /// Internal method for adding a transparent renderable
+        void addTransparentRenderable(Technique* pTech, Renderable* rend);
+
+    public:
+        RenderPriorityGroup(RenderQueueGroup* parent, 
+            bool splitPassesByLightingType, bool splitNoShadowPasses) 
+            :mParent(parent), mSplitPassesByLightingType(splitPassesByLightingType),
+            mSplitNoShadowPasses(splitNoShadowPasses) { }
+
+        ~RenderPriorityGroup() {
+            // destroy all the pass map entries
+            destroySolidPassMap(mSolidPasses);
+            destroySolidPassMap(mSolidPassesDecal);
+            destroySolidPassMap(mSolidPassesDiffuseSpecular);
+            destroySolidPassMap(mSolidPassesNoShadow);
+            mTransparentPasses.clear();
+
+        }
+
+        /** Get the collection of solid passes currently queued */
+        const SolidRenderablePassMap& _getSolidPasses(void) const
+        { return mSolidPasses; }
+        /** Get the collection of solid passes currently queued (per-light) */
+        const SolidRenderablePassMap& _getSolidPassesDiffuseSpecular(void) const
+        { return mSolidPassesDiffuseSpecular; }
+        /** Get the collection of solid passes currently queued (decal textures)*/
+        const SolidRenderablePassMap& _getSolidPassesDecal(void) const
+        { return mSolidPassesDecal; }
+        /** Get the collection of solid passes for which shadow receipt is disabled*/
+        const SolidRenderablePassMap& _getSolidPassesNoShadow(void) const
+        { return mSolidPassesNoShadow; }
+        /** Get the collection of transparent passes currently queued */
+        const TransparentRenderablePassList& _getTransparentPasses(void) const
+        { return mTransparentPasses; }
+
+
+        /** Add a renderable to this group. */
+        void addRenderable(Renderable* pRend);
+
+		/** Sorts the objects which have been added to the queue; transparent objects by their 
+            depth in relation to the passed in Camera. */
+		void sort(const Camera* cam);
+
+        /** Clears this group of renderables. 
+        */
+        void clear(void);
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		/** Clears solids in this group of renderables. Leaves transparents in group.
+        */
+        void clearSolids(void);
+#endif // GTP_VISIBILITY_MODIFIED_OGRE		
+        /** Sets whether or not the queue will split passes by their lighting type,
+        ie ambient, per-light and decal. 
+        */
+        void setSplitPassesByLightingType(bool split)
+        {
+            mSplitPassesByLightingType = split;
+        }
+
+        /** Sets whether or not passes which have shadow receive disabled should
+            be separated. 
+        */
+        void setSplitNoShadowPasses(bool split)
+        {
+            mSplitNoShadowPasses = split;
+        }
+
+
+    };
+
+
+    /** A grouping level underneath RenderQueue which groups renderables
+    to be issued at coarsely the same time to the renderer.
+    @remarks
+        Each instance of this class itself hold RenderPriorityGroup instances, 
+        which are the groupings of renderables by priority for fine control
+        of ordering (not required for most instances).
+    @par
+        This is an internal OGRE class, not intended for apps to use.
+    */
+    class RenderQueueGroup
+    {
+    public:
+        typedef std::map<ushort, RenderPriorityGroup*, std::less<ushort> > PriorityMap;
+        typedef MapIterator<PriorityMap> PriorityMapIterator;
+    protected:
+        RenderQueue* mParent;
+        bool mSplitPassesByLightingType;
+        bool mSplitNoShadowPasses;
+        /// Map of RenderPriorityGroup objects
+        PriorityMap mPriorityGroups;
+		/// Whether shadows are enabled for this queue
+		bool mShadowsEnabled;
+
+
+    public:
+		RenderQueueGroup(RenderQueue* parent, bool splitPassesByLightingType, 
+            bool splitNoShadowPasses) 
+            :mParent(parent), mSplitPassesByLightingType(splitPassesByLightingType),
+            mSplitNoShadowPasses(splitNoShadowPasses), mShadowsEnabled(true) {}
+
+        ~RenderQueueGroup() {
+            // destroy contents now
+            PriorityMap::iterator i;
+            for (i = mPriorityGroups.begin(); i != mPriorityGroups.end(); ++i)
+            {
+                delete i->second;
+            }
+        }
+
+        /** Get an iterator for browsing through child contents. */
+        PriorityMapIterator getIterator(void)
+        {
+            return PriorityMapIterator(mPriorityGroups.begin(), mPriorityGroups.end());
+        }
+
+        /** Add a renderable to this group, with the given priority. */
+        void addRenderable(Renderable* pRend, ushort priority)
+        {
+            // Check if priority group is there
+            PriorityMap::iterator i = mPriorityGroups.find(priority);
+            RenderPriorityGroup* pPriorityGrp;
+            if (i == mPriorityGroups.end())
+            {
+                // Missing, create
+                pPriorityGrp = new RenderPriorityGroup(this, 
+                    mSplitPassesByLightingType, mSplitNoShadowPasses);
+                mPriorityGroups.insert(PriorityMap::value_type(priority, pPriorityGrp));
+            }
+            else
+            {
+                pPriorityGrp = i->second;
+            }
+
+            // Add
+            pPriorityGrp->addRenderable(pRend);
+
+        }
+
+        /** Clears this group of renderables. 
+        @remarks
+            Doesn't delete any priority groups, just empties them. Saves on 
+            memory deallocations since the chances are rougly the same kinds of 
+            renderables are going to be sent to the queue again next time.
+        */
+        void clear(void)
+        {
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->clear();
+            }
+
+        }
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE	
+		/** Clears only solid renderables. Leaves transparents in queue. */
+		void clearSolids(void)
+        {
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->clearSolids();
+            }
+        }
+#endif // GTP_VISIBILITY_MODIFIED_OGRE		
+
+		/** Indicate whether a given queue group will be doing any
+		shadow setup.
+		@remarks
+		This method allows you to inform the queue about a queue group, and to 
+		indicate whether this group will require shadow processing of any sort.
+		In order to preserve rendering order, OGRE has to treat queue groups
+		as very separate elements of the scene, and this can result in it
+		having to duplicate shadow setup for each group. Therefore, if you
+		know that a group which you are using will never need shadows, you
+		should preregister the group using this method in order to improve
+		the performance.
+		*/
+		void setShadowsEnabled(bool enabled) { mShadowsEnabled = enabled; }
+
+		/** Are shadows enabled for this queue? */
+		bool getShadowsEnabled(void) const { return mShadowsEnabled; }
+
+        /** Sets whether or not the queue will split passes by their lighting type,
+        ie ambient, per-light and decal. 
+        */
+        void setSplitPassesByLightingType(bool split)
+        {
+            mSplitPassesByLightingType = split;
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->setSplitPassesByLightingType(split);
+            }
+        }
+        /** Sets whether or not the queue will split passes which have shadow receive
+        turned off (in their parent material), which is needed when certain shadow
+        techniques are used.
+        */
+        void setSplitNoShadowPasses(bool split)
+        {
+            mSplitNoShadowPasses = split;
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->setSplitNoShadowPasses(split);
+            }
+        }
+
+    };
+
+
+
+}
+
+#endif
+
+
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreSceneManager.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreSceneManager.h	(revision 74)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreSceneManager.h	(revision 115)
@@ -128,10 +128,11 @@
 			@param node scene node to be rendered
 			@param cam current camera
+			@param leaveTransparentsInQueue if only solid objects should be rendered
 		*/
-		void _renderSceneNode( Camera *cam, SceneNode *node );
-		/** deletes all queues which we were currently processing
-			@remark clears renderqueue after rendering scene node
+		void _renderSceneNode(Camera *cam, SceneNode *node, bool leaveTransparentsInQueue = false);
+		/** deletes all processed queues
+			@remark clears render queues after rendering scene node
 		*/
-		void _deleteRenderedQueueGroups();
+		void _deleteRenderedQueueGroups(bool leaveTransparentsInQueue);
 		/** Internal method used by _renderVisibleObjects to deal with renderables
             which override the camera's own view / projection materices. 
Index: trunk/VUT/work/ogre_changes/OgreMain/src/OgreRenderQueueSortingGrouping.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/src/OgreRenderQueueSortingGrouping.cpp	(revision 115)
+++ trunk/VUT/work/ogre_changes/OgreMain/src/OgreRenderQueueSortingGrouping.cpp	(revision 115)
@@ -0,0 +1,319 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2005 The OGRE Team
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+#include "OgreStableHeaders.h"
+#include "OgreRenderQueueSortingGrouping.h"
+
+namespace Ogre {
+
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::destroySolidPassMap(SolidRenderablePassMap& passmap)
+    {
+        // destroy all the pass map entries
+        SolidRenderablePassMap::iterator i, iend;
+        iend = passmap.end();
+        for (i = passmap.begin(); i != iend; ++i)
+        {
+            // Free the list associated with this pass
+            delete i->second;
+        }
+        passmap.clear();
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::removeSolidPassEntry(Pass* p)
+    {
+        SolidRenderablePassMap::iterator i;
+
+        i = mSolidPasses.find(p);
+        if (i != mSolidPasses.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPasses.erase(i);
+        }
+
+        i = mSolidPassesDiffuseSpecular.find(p);
+        if (i != mSolidPassesDiffuseSpecular.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPassesDiffuseSpecular.erase(i);
+        }
+        i = mSolidPassesDecal.find(p);
+        if (i != mSolidPassesDecal.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPassesDecal.erase(i);
+        }
+        i = mSolidPassesNoShadow.find(p);
+        if (i != mSolidPassesNoShadow.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPassesNoShadow.erase(i);
+        }
+
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::clearSolidPassMap(SolidRenderablePassMap& passmap)
+    {
+        SolidRenderablePassMap::iterator i, iend;
+        iend = passmap.end();
+        for (i = passmap.begin(); i != iend; ++i)
+        {
+            // Clear the list associated with this pass, but leave the pass entry
+            i->second->clear();
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addRenderable(Renderable* rend)
+    {
+        // Check material & technique supplied (the former since the default implementation
+        // of getTechnique is based on it for backwards compatibility
+        Technique* pTech;
+        if(rend->getMaterial().isNull() || !rend->getTechnique())
+        {
+            // Use default base white
+			MaterialPtr baseWhite = MaterialManager::getSingleton().getByName("BaseWhite");
+            pTech = baseWhite->getTechnique(0);
+        }
+        else
+        {
+            // Get technique
+            pTech = rend->getTechnique();
+        }
+
+        // Transparent and depth settings mean depth sorting is required?
+        if (pTech->isTransparent() && 
+            !(pTech->isDepthWriteEnabled() && pTech->isDepthCheckEnabled()) )
+        {
+            addTransparentRenderable(pTech, rend);
+        }
+        else
+        {
+            if (mSplitNoShadowPasses && !pTech->getParent()->getReceiveShadows())
+            {
+                // Add solid renderable and add passes to no-shadow group
+                addSolidRenderable(pTech, rend, true);
+            }
+            else
+            {
+                if (mSplitPassesByLightingType)
+                {
+                    addSolidRenderableSplitByLightType(pTech, rend);
+                }
+                else
+                {
+                    addSolidRenderable(pTech, rend, false);
+                }
+            }
+        }
+
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addSolidRenderable(Technique* pTech, 
+        Renderable* rend, bool addToNoShadow)
+    {
+        Technique::PassIterator pi = pTech->getPassIterator();
+
+        SolidRenderablePassMap* passMap;
+        if (addToNoShadow)
+        {
+            passMap = &mSolidPassesNoShadow;
+        }
+        else
+        {
+            passMap = &mSolidPasses;
+        }
+
+
+        while (pi.hasMoreElements())
+        {
+            // Insert into solid list
+            Pass* p = pi.getNext();
+            SolidRenderablePassMap::iterator i = passMap->find(p);
+            if (i == passMap->end())
+            {
+                std::pair<SolidRenderablePassMap::iterator, bool> retPair;
+                // Create new pass entry, build a new list
+                // Note that this pass and list are never destroyed until the engine
+                // shuts down, although the lists will be cleared
+                retPair = passMap->insert(
+                    SolidRenderablePassMap::value_type(p, new RenderableList() ) );
+                assert(retPair.second && "Error inserting new pass entry into SolidRenderablePassMap");
+                i = retPair.first;
+            }
+            // Insert renderable
+            i->second->push_back(rend);
+
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addSolidRenderableSplitByLightType(Technique* pTech, Renderable* rend)
+    {
+        // Divide the passes into the 3 categories
+        Technique::IlluminationPassIterator pi = 
+            pTech->getIlluminationPassIterator();
+
+        while (pi.hasMoreElements())
+        {
+            // Insert into solid list
+            IlluminationPass* p = pi.getNext();
+            SolidRenderablePassMap* passMap;
+            switch(p->stage)
+            {
+            case IS_AMBIENT:
+                passMap = &mSolidPasses;
+                break;
+            case IS_PER_LIGHT:
+                passMap = &mSolidPassesDiffuseSpecular;
+                break;
+            case IS_DECAL:
+                passMap = &mSolidPassesDecal;
+                break;
+            };
+
+            SolidRenderablePassMap::iterator i = passMap->find(p->pass);
+            if (i == passMap->end())
+            {
+                std::pair<SolidRenderablePassMap::iterator, bool> retPair;
+                // Create new pass entry, build a new list
+                // Note that this pass and list are never destroyed until the engine
+                // shuts down, although the lists will be cleared
+                retPair = passMap->insert(
+                    SolidRenderablePassMap::value_type(p->pass, new RenderableList() ) );
+                assert(retPair.second && "Error inserting new pass entry into SolidRenderablePassMap");
+                i = retPair.first;
+            }
+            // Insert renderable
+            i->second->push_back(rend);
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addTransparentRenderable(Technique* pTech, Renderable* rend)
+    {
+        Technique::PassIterator pi = pTech->getPassIterator();
+
+        while (pi.hasMoreElements())
+        {
+            // Insert into transparent list
+            mTransparentPasses.push_back(RenderablePass(rend, pi.getNext()));
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::sort(const Camera* cam)
+    {
+        TransparentQueueItemLess transFunctor;
+        transFunctor.camera = cam;
+
+        std::stable_sort(mTransparentPasses.begin(), mTransparentPasses.end(), 
+            transFunctor);
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::clear(void)
+    {
+        SolidRenderablePassMap::iterator i, iend;
+        // Delete queue groups which are using passes which are to be
+        // deleted, we won't need these any more and they clutter up 
+        // the list and can cause problems with future clones
+        const Pass::PassSet& graveyardList = Pass::getPassGraveyard();
+        Pass::PassSet::const_iterator gi, giend;
+        giend = graveyardList.end();
+        for (gi = graveyardList.begin(); gi != giend; ++gi)
+        {
+            removeSolidPassEntry(*gi);
+        }
+
+        // Now remove any dirty passes, these will have their hashes recalculated
+        // by the parent queue after all groups have been processed
+        // If we don't do this, the std::map will become inconsistent for new insterts
+        const Pass::PassSet& dirtyList = Pass::getDirtyHashList();
+        Pass::PassSet::const_iterator di, diend;
+        diend = dirtyList.end();
+        for (di = dirtyList.begin(); di != diend; ++di)
+        {
+            removeSolidPassEntry(*di);
+        }
+        // NB we do NOT clear the graveyard or the dirty list here, because 
+        // it needs to be acted on for all groups, the parent queue takes 
+        // care of this afterwards
+
+        // We do not clear the unchanged solid pass maps, only the contents of each list
+        // This is because we assume passes are reused a lot and it saves resorting
+        clearSolidPassMap(mSolidPasses);
+        clearSolidPassMap(mSolidPassesDecal);
+        clearSolidPassMap(mSolidPassesDiffuseSpecular);
+        clearSolidPassMap(mSolidPassesNoShadow);
+
+        // Always empty the transparents list
+        mTransparentPasses.clear();
+
+    }
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE	
+	//-----------------------------------------------------------------------
+    void RenderPriorityGroup::clearSolids(void)
+    {
+      /*  SolidRenderablePassMap::iterator i, iend;
+        // Delete queue groups which are using passes which are to be
+        // deleted, we won't need these any more and they clutter up 
+        // the list and can cause problems with future clones
+        const Pass::PassSet& graveyardList = Pass::getPassGraveyard();
+        Pass::PassSet::const_iterator gi, giend;
+        giend = graveyardList.end();
+        for (gi = graveyardList.begin(); gi != giend; ++gi)
+        {
+            removeSolidPassEntry(*gi);
+        }
+
+        // Now remove any dirty passes, these will have their hashes recalculated
+        // by the parent queue after all groups have been processed
+        // If we don't do this, the std::map will become inconsistent for new insterts
+        const Pass::PassSet& dirtyList = Pass::getDirtyHashList();
+        Pass::PassSet::const_iterator di, diend;
+        diend = dirtyList.end();
+        for (di = dirtyList.begin(); di != diend; ++di)
+        {
+            removeSolidPassEntry(*di);
+        }*/
+        // NB we do NOT clear the graveyard or the dirty list here, because 
+        // it needs to be acted on for all groups, the parent queue takes 
+        // care of this afterwards
+
+        // We do not clear the unchanged solid pass maps, only the contents of each list
+        // This is because we assume passes are reused a lot and it saves resorting
+        clearSolidPassMap(mSolidPasses);
+        clearSolidPassMap(mSolidPassesDecal);
+        clearSolidPassMap(mSolidPassesDiffuseSpecular);
+        clearSolidPassMap(mSolidPassesNoShadow);
+    }
+#endif // GTP_VISIBILITY_MODIFIED_OGRE		
+//-----------------------------------------------------------------------
+
+}
+
Index: trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp	(revision 99)
+++ trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp	(revision 115)
@@ -59,5 +59,5 @@
 #include "OgreDataStream.h"
 #include "OgreStaticGeometry.h"
-#include <windows.h> //matt: remove later
+
 // This class implements the most basic scene manager
 
@@ -665,7 +665,4 @@
         if (lastUsedVertexProgram)
         {
-			//matt: remove later
-			//OutputDebugString("unbinding vertex program\n");
-
             mDestRenderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
             lastUsedVertexProgram = false;
@@ -990,5 +987,4 @@
                                const String& groupName)
 {
-    mSkyPlaneEnabled = enable;
     if (enable)
     {
@@ -1061,4 +1057,5 @@
 
     }
+	mSkyPlaneEnabled = enable;
 }
 //-----------------------------------------------------------------------
@@ -1071,5 +1068,4 @@
                              const String& groupName)
 {
-    mSkyBoxEnabled = enable;
     if (enable)
     {
@@ -1143,5 +1139,5 @@
 
     }
-
+	mSkyBoxEnabled = enable;
 }
 //-----------------------------------------------------------------------
@@ -1157,5 +1153,4 @@
                               const String& groupName)
 {
-    mSkyDomeEnabled = enable;
     if (enable)
     {
@@ -1164,5 +1159,5 @@
         {
             OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
-                "Sky dome material '" + materialName + " not found.",
+                "Sky dome material '" + materialName + "' not found.",
                 "SceneManager::setSkyDome");
         }
@@ -1208,4 +1203,5 @@
 
     }
+	mSkyDomeEnabled = enable;
 }
 //-----------------------------------------------------------------------
@@ -2658,4 +2654,6 @@
     {
         Light* l = i->second;
+		if (l->isVisible())
+		{
         if (l->getType() == Light::LT_DIRECTIONAL)
         {
@@ -2675,4 +2673,5 @@
 
         }
+    }
     }
 
@@ -4180,5 +4179,5 @@
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 //-----------------------------------------------------------------------
-void SceneManager::_renderSceneNode( Camera *cam, SceneNode *node )
+void SceneManager::_renderSceneNode(Camera *cam, SceneNode *node, bool leaveTransparentsInQueue)
 {
 	node->_findVisibleObjects(cam, getRenderQueue(), false, mDisplayNodes, false);
@@ -4186,8 +4185,8 @@
 	
 	// delete all rendered objects from renderqueue
-	_deleteRenderedQueueGroups();
-}
-//-----------------------------------------------------------------------
-void SceneManager::_deleteRenderedQueueGroups()
+	_deleteRenderedQueueGroups(leaveTransparentsInQueue);
+}
+//-----------------------------------------------------------------------
+void SceneManager::_deleteRenderedQueueGroups(bool leaveTransparentsInQueue)
 {
 	RenderQueue::QueueGroupIterator queueIt = getRenderQueue()->_getQueueGroupIterator();
@@ -4200,5 +4199,14 @@
 
 		if (isRenderQueueToBeProcessed(qId))
+		{
+			if (leaveTransparentsInQueue)
+			{
+				pGroup->clearSolids();
+			}
+			else
+			{
 			pGroup->clear();
+	}
+		}
 	}
 	
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h	(revision 112)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h	(revision 115)
@@ -105,10 +105,14 @@
 	/** Renders one octant of an octree, i.e., renders current octant
 		node and does not traverse deeper into the tree.
+
 		@remark Note that OctreeNode instances are NOT part of the octree 
 		hierarchy, instead one octant of an Octree contains many OctreeNode instances.
-		@param octree the octree to be rendered
+		
 		@param cam current camera
+		@param octree the octant to be rendered (without children)
+		@param onlyShadowCasters if only shadow casters are rendered
+		@param leaveTransparentsInQueue if transparemt should be left in queue for later processing
 	*/
-	void _renderOctant(Camera* cam, Octree *octree, bool onlyShadowCasters);
+	void _renderOctant(Camera* cam, Octree *octree, bool onlyShadowCasters, bool leaveTransparentsInQueue = false);
 
 	/** Returns stored list of boxes */
@@ -214,4 +218,5 @@
     IntersectionSceneQuery* createIntersectionQuery(unsigned long mask);
 
+
 protected:
 
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp	(revision 61)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp	(revision 115)
@@ -109,9 +109,4 @@
 		mDepth = 0;
 
-	//matt: remove later
-	//char msg[100];
-	//sprintf(msg, "creating new octant in depth %d", mDepth);
-	//OutputDebugString(msg);
-
 #endif //GTP_VISIBILITY_MODIFIED_OGRE
     mNumNodes = 0;
@@ -171,9 +166,4 @@
 
 	mWireBoundingBox->setupBoundingBox(mBox);
-
-	// matt: change this back
-	//AxisAlignedBox box; _getCullBounds(&box); 
-	//mWireBoundingBox->setupBoundingBox(box);
-
     return mWireBoundingBox;
 }
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeSceneManager.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeSceneManager.cpp	(revision 112)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeSceneManager.cpp	(revision 115)
@@ -39,5 +39,5 @@
 #include <OgreOctreeCamera.h>
 #include <OgreRenderSystem.h>
-#include <windows.h>
+
 
 extern "C"
@@ -508,8 +508,4 @@
         }
 
-		//matt: remove later
-		//OutputDebugString("adding octree node\n");
-		
-
         _addOctreeNode( n, octant -> mChildren[ x ][ y ][ z ], ++depth );
 
@@ -1173,5 +1169,6 @@
 }
 //-----------------------------------------------------------------------
-void OctreeSceneManager::_renderOctant(Camera *cam, Octree *octant, bool onlyShadowCasters)
+void OctreeSceneManager::_renderOctant(Camera *cam, Octree *octant, bool onlyShadowCasters, 
+									   bool leaveTransparentsInQueue)//, bool useZPassQueue)
 {
 	//Add stuff to be rendered;
@@ -1188,5 +1185,4 @@
 		{
 			sn->_addToRenderQueue(cam, getRenderQueue(), onlyShadowCasters);
-			//node->_findVisibleObjects(cam, getRenderQueue(), false, mDisplayNodes, false);
 			mVisible.push_back(sn);
 
@@ -1207,12 +1203,14 @@
 	if (mShowBoxes)
 	{
+		octant->getWireBoundingBox()->setMaterial("BaseWhiteNoLighting");
+
 		getRenderQueue()->addRenderable(octant->getWireBoundingBox());
 		mBoxes.push_back(octant->getWireBoundingBox());
 	}
 
+	//-- the actual rendering
 	SceneManager::_renderVisibleObjects();
-
 	// delete all rendered objects from the render queue
-	_deleteRenderedQueueGroups();
+	_deleteRenderedQueueGroups(leaveTransparentsInQueue);
 }
 #endif // GTP_VISIBILITY_MODIFIED_OGRE
Index: trunk/VUT/work/ogre_changes/Samples/Common/include/ExampleFrameListener.h
===================================================================
--- trunk/VUT/work/ogre_changes/Samples/Common/include/ExampleFrameListener.h	(revision 100)
+++ trunk/VUT/work/ogre_changes/Samples/Common/include/ExampleFrameListener.h	(revision 115)
@@ -300,9 +300,6 @@
 		return true;
 	}
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	virtual void moveCamera() // made virtual by matt (16.05.05)
-#else
+
 	void moveCamera()
-#endif // GTP_VISIBILTIY_MODIFIED_OGRE
 	{
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h	(revision 92)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h	(revision 115)
@@ -88,15 +88,6 @@
 	void beginOcclusionQuery();
 	void endOcclusionQuery();
-
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult,
-							 const HW_OCCLUSIONQUERY flag  ); 
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult );
-#else
-	bool pullOcclusionQuery( unsigned int* NumOfFragments );
 	bool pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag  ); 
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
-	unsigned int getLastQuerysPixelcount() { return m_uintPixelCount; }
+	unsigned int getLastQuerysPixelcount() { return mPixelCount; }
 
 	// This functions are optional, it's a simple filter that simply skipps some hardware occlusion tests on visable objects only
@@ -115,8 +106,10 @@
 	  */
 
-	void setSkipRate( int skip ) { m_Skip = skip; }		// Using 2 only 50 % of the tests are actully made and 3 results in only 33% of the tests. So on.
-	int	 getSkipRate() { return m_Skip; } 
+	void setSkipRate( int skip ) { mSkipInterval = skip; }		// Using 2 only 50 % of the tests are actully made and 3 results in only 33% of the tests. So on.
+	int	 getSkipRate() { return mSkipInterval; } 
 
-
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH ); 
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 //----------------------------------------------------------------------
 // Protected members
@@ -124,12 +117,11 @@
 protected:
 
-	unsigned int	m_uintPixelCount;
-	unsigned int	m_uintQuery[1];
+	unsigned int	mPixelCount;
+	GLuint			mQueryID;
 	bool			m_bOcclusionQuery;
-	int				m_SkipCounter;		// m_SkipConter =  m_SkipConter % m_Skip; if ( m_SkipConter == 0 && m_uintPixelCount !=0 ) TestHWOcclusion else just return 
-	static int		m_Skip;				// This is shared by all instancies
-	bool			m_bHWOcclusionSupport;
+	int				mSkipCounter;
+	int				mSkipInterval;
+	bool			mHasOcclusionSupport;
 };
-
 
 }
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h	(revision 97)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h	(revision 115)
@@ -70,4 +70,8 @@
 extern GL_SecondaryColorPointerEXT_Func glSecondaryColorPointerEXT_ptr;
 
+// Pointer to glSecondaryColor3fEXT function
+typedef void (APIENTRY *GL_SecondaryColor3fEXT_Func)(GLfloat, GLfloat, GLfloat);
+extern GL_SecondaryColor3fEXT_Func glSecondaryColor3fEXT_ptr;
+
 // Pointer to glGenBuffersARB function
 typedef void (APIENTRY *GL_GenBuffersARB_Func)(GLsizei, GLuint*);
@@ -208,39 +212,4 @@
 extern GL_GetOcclusionQueryuivNV_Func glGetOcclusionQueryuivNV_ptr;
 
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-// Pointer to glGenQueriesARB function
-typedef void (APIENTRY *GL_GenQueriesARB_Func) (GLsizei n, GLuint *ids);
-extern GL_GenQueriesARB_Func glGenQueriesARB_ptr;
-
-// Pointer to glDeleteQueriesARB function
-typedef void (APIENTRY *GL_DeleteQueriesARB_Func) (GLsizei n, const GLuint *ids);
-extern GL_DeleteQueriesARB_Func glDeleteQueriesARB_ptr;
-
-// Pointer to glIsQueryARB function
-typedef GLboolean (APIENTRY *GL_IsQueryARB_Func) (GLuint id);
-extern GL_IsQueryARB_Func glIsQueryARB_ptr;
-
-// Pointer to glBeginQueryARB function
-typedef void (APIENTRY *GL_BeginQueryARB_Func) (GLenum target, GLuint id);
-extern GL_BeginQueryARB_Func glBeginQueryARB_ptr;
-
-// Pointer to glEndQueryARB function
-typedef void (APIENTRY *GL_EndQueryARB_Func) (GLenum target);
-extern GL_EndQueryARB_Func glEndQueryARB_ptr;
-
-// Pointer to glGetQueryivARB function
-typedef void (APIENTRY *GL_GetQueryivARB_Func) (GLuint id, GLenum pname, GLint *params);
-extern GL_GetQueryivARB_Func glGetQueryivARB_ptr;
-
-// Pointer to glGetQueryObjectivARB function
-typedef void (APIENTRY *GL_GetQueryObjectivARB_Func) (GLuint id, GLenum pname, GLint *params);
-extern GL_GetQueryObjectivARB_Func glGetQueryObjectivARB_ptr;
-
-// Pointer to glGetQueryObjectuivARB function
-typedef void (APIENTRY *GL_GetQueryObjectuivARB_Func) (GLuint id, GLenum pname, GLuint *params);
-extern GL_GetQueryObjectuivARB_Func glGetQueryObjectuivARB_ptr;
-
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
 extern PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1DARB_ptr;
 extern PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2DARB_ptr;
@@ -253,4 +222,31 @@
 };
 
+// Pointer to glGenQueriesARB function
+typedef void (APIENTRY *GL_GenQueriesARB_Func) (GLuint n, GLuint *ids);
+extern GL_GenQueriesARB_Func glGenQueriesARB_ptr;
+
+// Pointer to glDeleteQueriesARB function
+typedef void (APIENTRY *GL_DeleteQueriesARB_Func) (GLuint n, const GLuint *ids);
+extern GL_DeleteQueriesARB_Func glDeleteQueriesARB_ptr;
+
+// Pointer to glBeginQueryARB function
+typedef void (APIENTRY *GL_BeginQueryARB_Func) (GLenum target, GLuint id);
+extern GL_BeginQueryARB_Func glBeginQueryARB_ptr;
+
+// Pointer to glEndQueryARB function
+typedef void (APIENTRY *GL_EndQueryARB_Func) (GLenum target);
+extern GL_EndQueryARB_Func glEndQueryARB_ptr;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+// Pointer to glGetQueryivARB function
+typedef void (APIENTRY *GL_GetQueryivARB_Func) (GLuint id, GLenum pname, GLint *params);
+extern GL_GetQueryivARB_Func glGetQueryivARB_ptr;
+
+// Pointer to glGetQueryObjectivARB function
+typedef void (APIENTRY *GL_GetQueryObjectivARB_Func) (GLuint id, GLenum pname, GLint *params);
+extern GL_GetQueryObjectivARB_Func glGetQueryObjectivARB_ptr;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+// Pointer to glGetQueryObjectuivARB function
+typedef void (APIENTRY *GL_GetQueryObjectuivARB_Func) (GLuint id, GLenum pname, GLuint *params);
+extern GL_GetQueryObjectuivARB_Func glGetQueryObjectuivARB_ptr;
 
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp	(revision 99)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp	(revision 115)
@@ -27,7 +27,6 @@
 #include "OgreException.h"
 
+
 namespace Ogre {
-
-int GLHardwareOcclusionQuery::m_Skip = 0;
 
 /**
@@ -36,19 +35,9 @@
   *
   * @author Lee Sandberg email: lee@abcmedia.se
+  *
+  * Updated on 12/7/2004 by Chris McGuirk
+  * - Implemented ARB_occlusion_query
   */
 
-/* Functions used;
-
-glGenOcclusionQueriesNV_ptr( 1, m_uintQuery );
-glDeleteOcclusionQueriesNV_ptr( 1, &m_uintQuery[0] );
-glBeginOcclusionQueryNV_ptr( m_uintQuery[0] );
-glEndOcclusionQueryNV_ptr();
-glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
-
-  TO DO: change this to the new ARB functions...
-
-*/
-
-#ifndef GTP_VISIBILITY_MODIFIED_OGRE
 /**
   * Default object constructor
@@ -57,23 +46,26 @@
 GLHardwareOcclusionQuery::GLHardwareOcclusionQuery() 
 { 
-	m_uintPixelCount = 0; 
-	m_SkipCounter = 0;
+	mPixelCount = 0; 
+	mSkipCounter = 0;
+	mSkipInterval = 0;
 
 	// Check for hardware occlusion support
-    if( glDeleteOcclusionQueriesNV_ptr != 0 )	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
+	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
+	//if (glGenQueriesARB_ptr != 0)
+	if (glGenOcclusionQueriesNV_ptr != 0)
     {
-		m_bHWOcclusionSupport = true;
+		mHasOcclusionSupport = true;
 	}
 	else
 	{
-		m_bHWOcclusionSupport = false;
+		mHasOcclusionSupport = false;
 	}
 
-	if( m_bHWOcclusionSupport )
+	if(mHasOcclusionSupport)
 	{
-		glGenOcclusionQueriesNV_ptr( 1, m_uintQuery );	
+		//glGenQueriesARB_ptr(1, &mQueryID );	
+		glGenOcclusionQueriesNV_ptr(1, &mQueryID);
 	}
 }
-
 
 /**
@@ -82,7 +74,8 @@
 GLHardwareOcclusionQuery::~GLHardwareOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )
+	if( mHasOcclusionSupport )
 	{
-		glDeleteOcclusionQueriesNV_ptr( 1, &m_uintQuery[0] );  
+		//glDeleteQueriesARB_ptr(1, &mQueryID);  
+		glDeleteOcclusionQueriesNV_ptr(1, &mQueryID);  
 	}	
 }
@@ -93,10 +86,21 @@
 void GLHardwareOcclusionQuery::beginOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+	// Make it fail silently if hardware occlusion isn't supported
+	if(mHasOcclusionSupport)
 	{
-		if  ( m_SkipCounter ==  m_Skip ) { m_SkipCounter = 0; };		// Counter starts at 0 again at m_Skip 
-		if ( m_SkipCounter == 0 && m_uintPixelCount != 0 ) // New or none visable objects must allways be tested but visable objects can be skiped
+		// Counter starts at 0 again at mSkipInterval 
+#ifndef GTP_VISIBILITY_MODIFIED_OGRE
+		if(mSkipCounter == mSkipInterval) 
+#else
+		if (mSkipCounter >= mSkipInterval)  // otherwise no query ever issued if mSkipInterval = 0 !
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+	{
+			mSkipCounter = 0; 
+		}
+
+		if (mSkipCounter == 0)
 		{
-			glBeginOcclusionQueryNV_ptr( m_uintQuery[0] );
+			//glBeginQueryARB_ptr(GL_SAMPLES_PASSED_ARB, mQueryID);
+			glBeginOcclusionQueryNV_ptr(mQueryID);
 		}
 	}
@@ -105,40 +109,26 @@
 void GLHardwareOcclusionQuery::endOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+	// Make it fail silently if hardware occlusion isn't supported
+	if(mHasOcclusionSupport)
 	{
-		if( m_SkipCounter == 0 && m_uintPixelCount != 0 ) // New or none visable objects must allways be tested but visable objects can be skiped
+		if( mSkipCounter == 0)
 		{
+			//glEndQueryARB_ptr(GL_SAMPLES_PASSED_ARB);
 			glEndOcclusionQueryNV_ptr();
 		}
-		m_SkipCounter++;
-	}
-}
 
-bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int * NumOfFragments) 
-{
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
+		mSkipCounter++;
 	} 
-	else
-	{
-		*NumOfFragments = 100000;		// Fails quitlly -> every object tested is visable.
-	}
-
-	m_uintPixelCount = *NumOfFragments; 
-
-	return true;
 }
 
 //------------------------------------------------------------------
-// OpenGL dosn't use the flag, but to fulfil the abstract interface we need to include this function.
-// Using this function in OpenGL mode simple works the same way as calling the other function without the flag parameter,
-// but in DX9 it works differentlly, see notes in the DX9 implementation.
-//--
+// OpenGL dosn't use the flag paramter.
+//------------------------------------------------------------------
 bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag  ) 
 {
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+	if( mHasOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
 	{
-		glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
+		//glGetQueryObjectuivARB_ptr(mQueryID, GL_QUERY_RESULT_ARB, NumOfFragments);
+glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_NV, NumOfFragments);
 	}
 	else
@@ -147,83 +137,28 @@
 	}
 
-	m_uintPixelCount = *NumOfFragments; 
+	mPixelCount = *NumOfFragments; 
 	
 	return true;
 }
 
-#else // GTP_VISIBILITY_MODIFIED_OGRE
-
-//------------------------------------------------------------------
-GLHardwareOcclusionQuery::GLHardwareOcclusionQuery() 
-{ 
-	m_uintPixelCount = 0; 
-	m_SkipCounter = 0;
-
-	// Check for hardware occlusion support
-    if ( glDeleteOcclusionQueriesNV_ptr != 0 )	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
-	//if ( glDeleteQueriesARB_ptr != 0 )
-	{
-		m_bHWOcclusionSupport = true;
-	}
-	else
-	{
-		m_bHWOcclusionSupport = false;
-	}
-
-	if ( m_bHWOcclusionSupport )
-	{
-		glGenOcclusionQueriesNV_ptr( 1, m_uintQuery );	
-		//glGenQueriesARB_ptr(1, m_uintQuery);
-	}
-}
-
-
-//------------------------------------------------------------------
-GLHardwareOcclusionQuery::~GLHardwareOcclusionQuery() 
-{ 
-	if ( m_bHWOcclusionSupport )
-	{
-		glDeleteOcclusionQueriesNV_ptr( 1, &m_uintQuery[0] );  
-		//glDeleteQueriesARB_ptr(1, &m_uintQuery[0]);
-	}	
-}
-
-//------------------------------------------------------------------
-void GLHardwareOcclusionQuery::beginOcclusionQuery() 
-{ 
-	if ( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		// do the actual occlusion query for this node
-		glBeginOcclusionQueryNV_ptr( m_uintQuery[0] );
-		//glBeginQueryARB_ptr(GL_SAMPLES_PASSED_ARB, m_uintQuery[0]);
-	}
-}
-	
-void GLHardwareOcclusionQuery::endOcclusionQuery() 
-{ 
-	if ( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		glEndOcclusionQueryNV_ptr();
-		//glEndQueryARB_ptr(GL_SAMPLES_PASSED_ARB);
-	}
-}
-//------------------------------------------------------------------
-bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int * NumOfFragments, const bool waitForResult) 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	//------------------------------------------------------------------
+	bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int * NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag) 
 {
 	unsigned int isAvailable = GL_TRUE;
-	//int isAvailable = GL_TRUE;
 
-	if( m_bHWOcclusionSupport )	
+		if (mHasOcclusionSupport)	
 	{
 		if (!waitForResult)
 		{
-			glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_AVAILABLE_NV, &isAvailable );
-			//glGetQueryivARB_ptr(m_uintQuery[0], GL_QUERY_RESULT_AVAILABLE_ARB, &isAvailable);
+			// use nv queries rather that arb because they are faster (no flush)
+				//glGetQueryivARB_ptr(mQueryID, GL_QUERY_RESULT_AVAILABLE_ARB, &isAvailable);
+				glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_AVAILABLE_NV, &isAvailable);
 		}
 
 		if (isAvailable == GL_TRUE)
 		{
-			glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
-			//glGetQueryObjectuivARB_ptr( m_uintQuery[0], GL_QUERY_RESULT_ARB, NumOfFragments);
+				//glGetQueryObjectuivARB_ptr(mQueryID, GL_QUERY_RESULT_ARB, NumOfFragments);
+				glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_NV, NumOfFragments);
 		}
 	} 
@@ -234,19 +169,9 @@
 	}
 
-	m_uintPixelCount = *NumOfFragments; 
+		mPixelCount = *NumOfFragments; 
 
 	return isAvailable == GL_TRUE;	
 }
 
-//------------------------------------------------------------------
-bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag  ) 
-{
-	return pullOcclusionQuery(NumOfFragments, waitForResult);
+#endif // GTP_VIBILITY_MODIFIED_OGRE
 }
-
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
-
-}
-
-
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp	(revision 97)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp	(revision 115)
@@ -58,4 +58,5 @@
 GL_ClientActiveTextureARB_Func glClientActiveTextureARB_ptr;
 GL_SecondaryColorPointerEXT_Func glSecondaryColorPointerEXT_ptr;
+GL_SecondaryColor3fEXT_Func glSecondaryColor3fEXT_ptr;
 GL_GenBuffersARB_Func glGenBuffersARB_ptr;
 GL_BindBufferARB_Func glBindBufferARB_ptr;
@@ -97,15 +98,13 @@
 GL_EndOcclusionQueryNV_Func glEndOcclusionQueryNV_ptr;
 GL_GetOcclusionQueryuivNV_Func glGetOcclusionQueryuivNV_ptr;
- 
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 GL_GenQueriesARB_Func glGenQueriesARB_ptr;
 GL_DeleteQueriesARB_Func glDeleteQueriesARB_ptr;
-GL_IsQueryARB_Func glIsQueryARB_ptr;
 GL_BeginQueryARB_Func glBeginQueryARB_ptr;
 GL_EndQueryARB_Func glEndQueryARB_ptr;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 GL_GetQueryivARB_Func glGetQueryivARB_ptr;
 GL_GetQueryObjectivARB_Func glGetQueryObjectivARB_ptr;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 GL_GetQueryObjectuivARB_Func glGetQueryObjectuivARB_ptr;
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
 
 namespace Ogre {
@@ -191,4 +190,5 @@
         glClientActiveTextureARB_ptr = 0;
         glSecondaryColorPointerEXT_ptr = 0;
+        glSecondaryColor3fEXT_ptr = 0;
         glGenBuffersARB_ptr = 0;
         glBindBufferARB_ptr = 0;
@@ -220,15 +220,13 @@
         glEndOcclusionQueryNV_ptr = 0;
         glGetOcclusionQueryuivNV_ptr = 0;
-
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		glGenQueriesARB_ptr = 0;
 		glDeleteQueriesARB_ptr = 0;
-		glIsQueryARB_ptr = 0;
 		glBeginQueryARB_ptr = 0;
 		glEndQueryARB_ptr = 0;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryivARB_ptr = 0;
 		glGetQueryObjectivARB_ptr = 0;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryObjectuivARB_ptr = 0;
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
 
         mCurrentLights = 0;
@@ -543,4 +541,6 @@
         glSecondaryColorPointerEXT_ptr = 
             (GL_SecondaryColorPointerEXT_Func)mGLSupport->getProcAddress("glSecondaryColorPointerEXT");
+        glSecondaryColor3fEXT_ptr = 
+            (GL_SecondaryColor3fEXT_Func)mGLSupport->getProcAddress("glSecondaryColor3fEXT");
         glGenBuffersARB_ptr = 
             (GL_GenBuffersARB_Func)mGLSupport->getProcAddress("glGenBuffersARB");
@@ -622,26 +622,21 @@
         glGetOcclusionQueryuivNV_ptr =
             (GL_GetOcclusionQueryuivNV_Func)mGLSupport->getProcAddress("glGetOcclusionQueryuivNV");
-		glGetQueryObjectivARB_ptr = 
-			 (GL_GetQueryObjectivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectivARB");
-		glGetQueryObjectuivARB_ptr = 
-			 (GL_GetQueryObjectuivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectuivARB");
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+
 		glGenQueriesARB_ptr = 
 			 (GL_GenQueriesARB_Func)mGLSupport->getProcAddress("glGenQueriesARB");
 		glDeleteQueriesARB_ptr =
 			(GL_DeleteQueriesARB_Func)mGLSupport->getProcAddress("glDeleteQueriesARB");
-		glIsQueryARB_ptr =
-			(GL_IsQueryARB_Func)mGLSupport->getProcAddress("glIsQueryARB");
 		glBeginQueryARB_ptr =
 			 (GL_BeginQueryARB_Func)mGLSupport->getProcAddress("glBeginQueryARB");
 		glEndQueryARB_ptr =
 			 (GL_EndQueryARB_Func)mGLSupport->getProcAddress("glEndQueryARB");
+	#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryivARB_ptr = 
 			(GL_GetQueryivARB_Func)mGLSupport->getProcAddress("glGetQueryivARB");
 		glGetQueryObjectivARB_ptr = 
 			 (GL_GetQueryObjectivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectivARB");
+	#endif // GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryObjectuivARB_ptr = 
 			 (GL_GetQueryObjectuivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectuivARB");
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
 
         mCapabilities->log(LogManager::getSingleton().getDefaultLog());
@@ -1857,4 +1852,6 @@
 		    cv1[2] = bm.colourArg1.b;
 		    cv1[3] = bm.colourArg1.a;
+			mManualBlendColours[stage][0] = bm.colourArg1;
+
 
 		    cv2[0] = bm.colourArg2.r;
@@ -1862,16 +1859,17 @@
 		    cv2[2] = bm.colourArg2.b;
 		    cv2[3] = bm.colourArg2.a;
+			mManualBlendColours[stage][1] = bm.colourArg2;
         }
 
 		if (bm.blendType == LBT_ALPHA)
         {
-		    cv1[0] = 0;
-		    cv1[1] = 0;
-		    cv1[2] = 0;
+		    cv1[0] = mManualBlendColours[stage][0].r;
+		    cv1[1] = mManualBlendColours[stage][0].g;
+		    cv1[2] = mManualBlendColours[stage][0].b;
 		    cv1[3] = bm.alphaArg1;
 
-		    cv2[0] = 0;
-		    cv2[1] = 0;
-		    cv2[2] = 0;
+		    cv2[0] = mManualBlendColours[stage][1].r;
+		    cv2[1] = mManualBlendColours[stage][1].g;
+		    cv2[2] = mManualBlendColours[stage][1].b;
 		    cv2[3] = bm.alphaArg2;
         }
@@ -2249,4 +2247,5 @@
         }
         glColor4f(1,1,1,1);
+        glSecondaryColor3fEXT_ptr(0.0f, 0.0f, 0.0f);
 
         // UnGuard
@@ -2537,4 +2536,6 @@
         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);        
+        glEnable(GL_COLOR_SUM);
+
         // Check for FSAA
         // Enable the extension if it was enabled by the GLSupport
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h	(revision 92)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h	(revision 115)
@@ -33,8 +33,6 @@
 namespace Ogre {
 
-
-
 // If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered 
-// if the first pass resultet has too few pixels visable.
+	// if the first pass resultet has too few pixels visible.
 
 // Be sure to render all occlluder first and whats out so the RenderQue don't switch places on 
@@ -46,4 +44,6 @@
   *
   * @author Lee Sandberg, email lee@abcmedia.se
+	*
+	* Updated on 12/7/2004 by Chris McGuirk
   */
 class D3D9HardwareOcclusionQuery : public HardwareOcclusionQuery
@@ -71,35 +71,27 @@
 	void beginOcclusionQuery();	
 	void endOcclusionQuery();
+		bool pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH);
+		unsigned int getLastQuerysPixelcount() { return mPixelCount; }
 
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult,
-							 const HW_OCCLUSIONQUERY flag  ); 
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult );
-#else
-	bool pullOcclusionQuery( unsigned int* NumOfFragments );
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag  ); 
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
-	unsigned int getLastQuerysPixelcount() { return m_uintPixelCount; }
-	
-	// This functions are optional, it's a simple filter that simply skips some hardware occlusion tests on visable objects only
-	// It's easy to use if you don't have to keep track on which objects are visable (can be skipped) and what objects arn't visable..
-	// (None visable objects and object you introduce for the first time have allways to be tested allthough the cheepest possible 
-	// LOD (Level Of Detail) mesh and material wize). 
+		// These functions are optional, it's a simple filter that simply skips some hardware occlusion tests on visible objects only
+		// It's easy to use if you don't have to keep track of which objects are visible (can be skipped) and what objects arn't visible..
+		// (None visible objects and object you introduce for the first time have always to be tested although the cheapest possible 
+		// LOD (Level Of Detail) mesh and material-wise). 
 
 	/**
 	  *   
-	  * Remarks This function allows you to set how often the hardware occlusion really are sent to the driver
+		* Remarks This function allows you to set how often the hardware occlusion query is sent to the driver
 	  * if you set it to 0 every hw occlusion test is acctually made. If you set it to 1 only the half of your queries are sent 
-	  * for all visable objects. 2 will result in 25% of all queries to acctualy be sent. 
-	  * New and none visable objects will be tested all the time.
-	  * This functionality is here because this class can keep track on visable and none visable objects for you.
+		* 2 will result in 25% of all queries to acctualy be sent. 
+		* This functionality is here because this class can keep track on visible and none visible objects for you.
 	  * Once you you set the SkipRate for any hardware occlusion instance it effects all others.
 	  */
 
+		void setSkipRate( int skip ) { mSkipInterval = skip; }			// Using 2 only 50 % of the tests are actully made and 3 results in only 33% of the tests. So on.
+		int	 getSkipRate() { return mSkipInterval; } 
 
-	void setSkipRate( int skip ) { m_Skip = skip; }			// Using 2 only 50 % of the tests are actually made and 3 results in only 33% of the tests. So on.
-	int	 getSkipRate() { return m_Skip; } 
-
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH ); 
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 //----------------------------------------------------------------------
 // Protected members
@@ -107,14 +99,10 @@
 protected:
 
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
-						     const DWORD queryFlag );
-
-	unsigned int		m_uintPixelCount;		
-	IDirect3DQuery9*	m_pD3DQuery;
-	IDirect3DDevice9*   m_pD3DDevice;       // d3d device
-	bool				m_bOcclusionQuery;
-	int					m_SkipCounter;		// m_SkipConter =  m_SkipConter % m_Skip; if ( m_SkipConter == 0 && m_uintPixelCount !=0 ) TestHWOcclusion else just return 
-	static int			m_Skip;				// This is shared by all instancies
-	bool				m_bHWOcclusionSupport;
+		unsigned int		mPixelCount;		
+		IDirect3DQuery9*	mpQuery;
+		IDirect3DDevice9*   mpDevice;
+		int					mSkipCounter;
+		int					mSkipInterval;
+		bool				mHasOcclusionSupport;
 };
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp	(revision 97)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp	(revision 115)
@@ -29,6 +29,4 @@
 namespace Ogre {
 
-int D3D9HardwareOcclusionQuery::m_Skip = 0;
-
 /**
   * This is a class that is the DirectX9 implementation of 
@@ -36,30 +34,31 @@
   *
   * @author Lee Sandberg
+	*
+	* Updated on 12/7/2004 by Chris McGuirk
   */
 
 /**
   * Default object constructor
-  * 
   */
 D3D9HardwareOcclusionQuery::D3D9HardwareOcclusionQuery( IDirect3DDevice9* pD3DDevice ) 
 { 
-	m_pD3DDevice = pD3DDevice;
-	m_uintPixelCount = 0; 
-	m_SkipCounter = 0;
-	m_bHWOcclusionSupport = false;
+		mpDevice = pD3DDevice;
+		mPixelCount = 0; 
+		mSkipCounter = 0;
+		mSkipInterval = 0;
+		mHasOcclusionSupport = false;
 
-	HRESULT hr = m_pD3DDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &m_pD3DQuery);
+		// create the occlusion query
+		HRESULT hr = mpDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &mpQuery);
+
 	if ( hr != D3D_OK ) 
 	{
-		//OGRE_EXCEPT(hr, "D3D9HardwareOcclusionQuery couldn't create hardware occlusion query object.", 
-        //        "D3D9HardwareOcclusionQuery::D3D9HardwareOcclusionQuery");
-		m_bHWOcclusionSupport = false;
+			mHasOcclusionSupport = false;
 	}
 	else 
 	{
-		m_bHWOcclusionSupport = true;
+			mHasOcclusionSupport = true;
 	}
 }
-
 
 /**
@@ -68,8 +67,7 @@
 D3D9HardwareOcclusionQuery::~D3D9HardwareOcclusionQuery() 
 { 
-	SAFE_RELEASE( m_pD3DQuery ); 
+		SAFE_RELEASE(mpQuery); 
 }
 
-#ifndef GTP_VISIBILITY_MODIFIED_OGRE
 //------------------------------------------------------------------
 // Occlusion query functions (see base class documentation for this)
@@ -77,61 +75,45 @@
 void D3D9HardwareOcclusionQuery::beginOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )		// Make it fail silently if hardware occlusion isn't supported
+		// Make it fail silently if hardware occlusion isn't supported
+		if(mHasOcclusionSupport)
 	{
-		if  ( m_SkipCounter ==  m_Skip ) { m_SkipCounter = 0; };		// Counter starts at 0 again at m_Skip 
-		
-		if ( m_SkipCounter == 0 && m_uintPixelCount != 0 )	// New or none visable objects must allways be tested but visable objects can be skiped
+#ifndef GTP_VISIBILITY_MODIFIED_OGRE
+			// Counter starts at 0 again at mSkipInterval 
+			if(mSkipCounter == mSkipInterval) 
+#else
+			if (mSkipCounter >= mSkipInterval)  // otherwise no query ever issued if mSkipInterval = 0 !
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 		{
-			m_pD3DQuery->Issue(D3DISSUE_BEGIN); 
+				mSkipCounter = 0; 
+}
+			//std::stringstream d; d << "count: " << mSkipCounter;
+			//LogManager::getSingleton().logMessage(d.str());
+			if (mSkipCounter == 0)
+		{
+				mpQuery->Issue(D3DISSUE_BEGIN); 
 		}
 	}
+	
 }
-	
-void D3D9HardwareOcclusionQuery::endOcclusionQuery() 
-{ 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+
+	void D3D9HardwareOcclusionQuery::endOcclusionQuery() 
 	{
-		if (m_SkipCounter == 0 && m_uintPixelCount != 0 ) // New or none visable objects must allways be tested but visable objects can be skiped
-		{
-			m_pD3DQuery->Issue(D3DISSUE_END); 
-		}
-		m_SkipCounter++;								 // The skip counter is increased 
+		// Make it fail silently if hardware occlusion isn't supported
+		if(mHasOcclusionSupport)
+			{
+			if(mSkipCounter == 0)
+			{ 
+				mpQuery->Issue(D3DISSUE_END); 
+	}
+
+			// The skip counter is increased
+			mSkipCounter++; 
 	}
 }
 
 //------------------------------------------------------------------
-// This version of pullOcclusionQuery cases the DX9 API/Driver to flush all commands to the 3D card
-// to allow a fast result from the query, but at the cost of poorer batching of API calls to the card.
-// Note: OpenGL dosn't use this flag at all so the application running OpenGL won't display any different behaviour.
-//--
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments) 
-{
-	HRESULT hr;
-	
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), D3DGETDATA_FLUSH );
-
-		if ( hr != S_OK ) 
-			{
-				return false; 
-			}
-			else 
-			{ 
-				m_uintPixelCount = *NumOfFragments; 
-				return true; 
-			}
-	}
-	else
-	{
-		m_uintPixelCount = 100000; // Fails quitlly if hardware occlusion is not supported - every object is visable
-		return true;
-	}
-}
-
-//------------------------------------------------------------------
-// This version of pullOcclusionQuery cases the DX9 API/Driver to not flush all commands to the 3D card
+	// This version of pullOcclusionQuery causes the DX9 API/Driver to not flush all commands to the 3D card
 // to allow a fast result from the query, but the batching of API calls to the card will be normal. 
-// But the query wont be processed until the card recives the query in the nexr batch.
+	// But the query wont be processed until the card recives the query in the next batch.
 // Note: OpenGL dosn't use this flag at all so the application running OpenGL won't display any different behaviour.
 //--
@@ -140,97 +122,52 @@
 	HRESULT hr;
 
-	// TO DO: USE lockOpts= D3D9Mappings::get(options); instead of RS_OCCLUSIONQUERY enum
+		// Make it fail silently if hardware occlusion isn't supported
+		if(mHasOcclusionSupport)
+	{
+			DWORD d3dFlags = (flag == HWOCCLUSIONQUERY_FLUSH) ? D3DGETDATA_FLUSH : 0;
+	
+			// run until success (http://www.gamedev.net/reference/programming/features/occlusionculling/page2.asp)
+			while(hr = mpQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), d3dFlags) == S_FALSE);
 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-	
-		switch( flag )
-		{
-			case HWOCCLUSIONQUERY_FLUSH : 	
-				hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), D3DGETDATA_FLUSH );
-			break;
-
-			case HWOCCLUSIONQUERY_NOFLUSH :	
-				hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), 0 );
-			break;
-		};
-
-
-
-		if ( hr != S_OK ) 
-			{
-				return false; 
+			mPixelCount = *NumOfFragments;
 			}
 			else 
 			{ 
-				m_uintPixelCount = *NumOfFragments; 
-				return true; 
+			// fail silently if not supported, assume visible i suppose
+			mPixelCount = 100000;
 			}
-	}
-	else 
-	{
-		m_uintPixelCount = 100000; // Fails quitlly if hardware occlusion is not supported - every object is visable
+
 		return true;
 	}
-}
-#else // GTP_VISIBILITY_MODIFIED_OGRE
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 //------------------------------------------------------------------
-void D3D9HardwareOcclusionQuery::beginOcclusionQuery() 
-{ 
-	if( m_bHWOcclusionSupport )		// Make it fail silently if hardware occlusion isn't supported
+	bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
+													     const HW_OCCLUSIONQUERY flag ) 
 	{
-		m_pD3DQuery->Issue(D3DISSUE_BEGIN); 
+		HRESULT hr = S_OK;
+		DWORD queryFlag = (flag == HWOCCLUSIONQUERY_FLUSH) ? D3DGETDATA_FLUSH : 0;
+
+		if (mHasOcclusionSupport)	// In case hardware occlusion isn't supported
+		{	
+			do
+			{
+				hr = mpQuery->GetData(NumOfFragments, sizeof(NumOfFragments), queryFlag);
+	    	}
+			while(waitForResult && (hr == S_FALSE));
+		
+			mPixelCount = *NumOfFragments;
+		}
+		else
+		{
+			mPixelCount = 100000; // every object is visible
+		}
+	
+		return hr == S_OK;
 	}
-}
-//------------------------------------------------------------------
-void D3D9HardwareOcclusionQuery::endOcclusionQuery() 
-{ 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		m_pD3DQuery->Issue(D3DISSUE_END); 
-	}
-}
-//------------------------------------------------------------------
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult ) 
-{
-	return pullOcclusionQuery(NumOfFragments, waitForResult, HWOCCLUSIONQUERY_FLUSH);
-}
-
-//------------------------------------------------------------------
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
-												     const HW_OCCLUSIONQUERY flag  ) 
-{
-	DWORD queryFlag = flag == HWOCCLUSIONQUERY_FLUSH ? D3DGETDATA_FLUSH : 0;
-	// TO DO: USE lockOpts= D3D9Mappings::get(options); instead of RS_OCCLUSIONQUERY enum
-
-	return pullOcclusionQuery(NumOfFragments, waitForResult, queryFlag);
-}
-
-//------------------------------------------------------------------
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
-												     const DWORD queryFlag ) 
-{
-	HRESULT hr = S_OK;
-
-	if( m_bHWOcclusionSupport )	// In case hardware occlusion isn't supported
-	{	
-		do
-		{
-			hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), queryFlag );
-	    	}
-		while(waitForResult && (hr == S_FALSE));
-		
-		m_uintPixelCount = *NumOfFragments; 
-	}
-	else
-	{
-		m_uintPixelCount = 100000; // every object is visible
-	}
-	
-	return hr == S_OK;
-}
 
 
 #endif // GTP_VISIBILITY_MODIFIED_OGRE
 
-} // namespace OGre
+
+}
Index: trunk/VUT/work/TestCulling/TestCulling.vcproj
===================================================================
--- trunk/VUT/work/TestCulling/TestCulling.vcproj	(revision 107)
+++ trunk/VUT/work/TestCulling/TestCulling.vcproj	(revision 115)
@@ -13,5 +13,5 @@
 		<Configuration
 			Name="Debug|Win32"
-			OutputDirectory=".\bin\$(ConfigurationName)"
+			OutputDirectory=".\lib\$(ConfigurationName)"
 			IntermediateDirectory=".\obj\$(ConfigurationName)"
 			ConfigurationType="1"
@@ -21,5 +21,5 @@
 				Name="VCCLCompilerTool"
 				Optimization="0"
-				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\Dependencies\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;../include;../../GtpVisibility/include"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\Dependencies\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;../include;../../GtpVisibility/include;../../Ogre/include"
 				PreprocessorDefinitions="_WINDOWS;_STLP_USE_DYNAMIC_LIB;OGRE_LIBRARY_IMPORTS;_DEBUG;WIN32;_STLP_DEBUG;PLUGIN_TERRAIN_IMPORTS;GTP_VISIBILITY_MODIFIED_OGRE"
 				MinimalRebuild="TRUE"
@@ -34,8 +34,8 @@
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="Plugin_OctreeSceneManager.lib OGREMain_d.LIB CEGUIBase_d.lib OgreGUIRenderer_d.lib Plugin_DotSceneManager.lib"
+				AdditionalDependencies="Plugin_OctreeSceneManager.lib OGREMain_d.LIB CEGUIBase_d.lib OgreGUIRenderer_d.lib Plugin_DotSceneManager.lib Plugin_VisibilitySceneManager.lib"
 				OutputFile="$(OGRE_PATH)/Samples/Common/bin/Debug/TestCulling.exe"
 				LinkIncremental="2"
-				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\Dependencies\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\Dependencies\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;$(GAMETOOLS_PATH)\trunk\VUT\Ogre\lib\$(ConfigurationName)&quot;"
 				GenerateDebugInformation="TRUE"
 				ProgramDatabaseFile="$(OutDir)/TestCulling.pdb"
Index: trunk/VUT/work/TestCulling/TestCullingApplication.cpp
===================================================================
--- trunk/VUT/work/TestCulling/TestCullingApplication.cpp	(revision 112)
+++ trunk/VUT/work/TestCulling/TestCullingApplication.cpp	(revision 115)
@@ -81,5 +81,5 @@
 void TestCullingApplication::createFrameListener()
 {
-	mFrameListener= new MouseQueryListener(mWindow, mCamera, mSceneMgr, 
+	mFrameListener= new TerrainMouseQueryListener(mWindow, mCamera, mSceneMgr, 
 		mGUIRenderer, mSceneContentGenerator);
 	mFrameListener->showDebugOverlay(true);
@@ -94,8 +94,8 @@
 
 /***********************************************/
-/* MouseQueryListener implementation           */
+/* TerrainMouseQueryListener implementation           */
 /***********************************************/
 //-----------------------------------------------------------------------
-MouseQueryListener::MouseQueryListener(RenderWindow* win, Camera* cam, 
+TerrainMouseQueryListener::TerrainMouseQueryListener(RenderWindow* win, Camera* cam, 
 									   SceneManager *sceneManager, 
 									   CEGUI::Renderer *renderer,
@@ -111,5 +111,5 @@
 mCurrentAlgorithm(GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING),
 mShowOctree(false),
-mUseVisibilityCulling(true),
+mUseDepthPass(false),
 mUseOptimization(true),
 mShowVisualization(false),
@@ -154,5 +154,5 @@
 	
 	mSceneMgr->setOption("UseOptimization", &mUseOptimization);
-	mSceneMgr->setOption("UseVisibilityCulling", &mUseVisibilityCulling);
+	mSceneMgr->setOption("UseDepthPass", &mUseDepthPass);
 	mSceneMgr->setOption("ShowVizualisation", &mShowVisualization);
 	mSceneMgr->setOption("ShowOctree", &mShowOctree);
@@ -161,9 +161,9 @@
 } 
 //-----------------------------------------------------------------------
-MouseQueryListener::~MouseQueryListener( )
-{
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::mouseMoved (MouseEvent *e)
+TerrainMouseQueryListener::~TerrainMouseQueryListener( )
+{
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::mouseMoved (MouseEvent *e)
 {
 	// Update CEGUI with the mouse motion
@@ -171,5 +171,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::mousePressed(MouseEvent* e)
+void TerrainMouseQueryListener::mousePressed(MouseEvent* e)
 {
      // Left mouse button down
@@ -187,5 +187,5 @@
 
  //-----------------------------------------------------------------------
-void MouseQueryListener::mouseReleased(MouseEvent* e)
+void TerrainMouseQueryListener::mouseReleased(MouseEvent* e)
 {
     // Left mouse button up
@@ -203,5 +203,5 @@
 } 
 //-----------------------------------------------------------------------
-void MouseQueryListener::mouseDragged (MouseEvent *e)
+void TerrainMouseQueryListener::mouseDragged (MouseEvent *e)
  {
 	 // If we are dragging the left mouse button.	 	 
@@ -218,10 +218,10 @@
 }
 //-----------------------------------------------------------------------
-bool MouseQueryListener::frameStarted(const FrameEvent &evt)
+bool TerrainMouseQueryListener::frameStarted(const FrameEvent &evt)
 {	 
 	return ExampleFrameListener::frameStarted(evt);
 }
 //-----------------------------------------------------------------------
-bool MouseQueryListener::frameEnded(const FrameEvent& evt)
+bool TerrainMouseQueryListener::frameEnded(const FrameEvent& evt)
 {
 	if (mShutdownRequested)
@@ -236,5 +236,5 @@
 	KEY_PRESSED(KC_ADD, 0, changeThreshold(10));
 	KEY_PRESSED(KC_O, 0.3, toggleUseOptimization());
-	KEY_PRESSED(KC_C, 0.3, toggleUseVisibilityCulling());
+	KEY_PRESSED(KC_C, 0.3, toggleUseDepthPass());
 	KEY_PRESSED(KC_V, 0.3, toggleShowViz());
 
@@ -244,5 +244,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::changeThreshold(int incr)
+void TerrainMouseQueryListener::changeThreshold(int incr)
 {
 	mVisibilityThreshold += incr; 
@@ -255,5 +255,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::nextAlgorithm()
+void TerrainMouseQueryListener::nextAlgorithm()
 {
 	mCurrentAlgorithm = ++mCurrentAlgorithm % 
@@ -263,5 +263,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::toggleUseOptimization()
+void TerrainMouseQueryListener::toggleUseOptimization()
 {
 	mUseOptimization = !mUseOptimization;
@@ -275,5 +275,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::toggleShowOctree()
+void TerrainMouseQueryListener::toggleShowOctree()
 {
 	mShowOctree = !mShowOctree;
@@ -282,12 +282,12 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::toggleUseVisibilityCulling()
-{
-	mUseVisibilityCulling = !mUseVisibilityCulling;
-
-	mSceneMgr->setOption("UseVisibilityCulling", &mUseVisibilityCulling);
-}
-//-----------------------------------------------------------------------
-void MouseQueryListener::toggleShowViz()
+void TerrainMouseQueryListener::toggleUseDepthPass()
+{
+	mUseDepthPass = !mUseDepthPass;
+
+	mSceneMgr->setOption("UseDepthPass", &mUseDepthPass);
+}
+//-----------------------------------------------------------------------
+void TerrainMouseQueryListener::toggleShowViz()
 {
 	mShowVisualization = !mShowVisualization;
@@ -297,5 +297,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::setAlgorithm(int algorithm)
+void TerrainMouseQueryListener::setAlgorithm(int algorithm)
 {
 	mAlgorithmInfo->setCaption(": " + mCurrentAlgorithmCaptions[mCurrentAlgorithm]);
@@ -303,5 +303,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::updateStats()
+void TerrainMouseQueryListener::updateStats()
 {
 	unsigned int opt = 0;
@@ -330,5 +330,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::keyPressed(KeyEvent* e)
+void TerrainMouseQueryListener::keyPressed(KeyEvent* e)
 {
 	if(e->getKey() == KC_ESCAPE)
@@ -344,5 +344,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::keyReleased(KeyEvent* e)
+void TerrainMouseQueryListener::keyReleased(KeyEvent* e)
 {
 	CEGUI::System::getSingleton().injectKeyUp(e->getKey());
@@ -350,5 +350,5 @@
 }
 //-----------------------------------------------------------------------
-void MouseQueryListener::keyClicked(KeyEvent* e) 
+void TerrainMouseQueryListener::keyClicked(KeyEvent* e) 
 {
 	// Do nothing
Index: trunk/VUT/work/TestCulling/TestCullingApplication.h
===================================================================
--- trunk/VUT/work/TestCulling/TestCullingApplication.h	(revision 112)
+++ trunk/VUT/work/TestCulling/TestCullingApplication.h	(revision 115)
@@ -25,13 +25,13 @@
 };
 
-class MouseQueryListener : public ExampleFrameListener, public MouseListener, public MouseMotionListener
+class TerrainMouseQueryListener : public ExampleFrameListener, public MouseListener, public MouseMotionListener
 {
 public:
 
-    MouseQueryListener(RenderWindow* win, Camera* cam, SceneManager *sceneManager, 
+    TerrainMouseQueryListener(RenderWindow* win, Camera* cam, SceneManager *sceneManager, 
 			CEGUI::Renderer *renderer, SceneContentGenerator *sceneContentGenerator);
 
 
-    ~MouseQueryListener( );
+    ~TerrainMouseQueryListener( );
 
 	bool frameStarted(const FrameEvent& evt);
@@ -66,5 +66,5 @@
 	void toggleUseOptimization();
 	void toggleShowOctree();
-	void toggleUseVisibilityCulling();
+	void toggleUseDepthPass();
 	void toggleShowViz();
 
@@ -94,5 +94,5 @@
 	bool mUseOptimization;
 	bool mShowOctree;
-	bool mUseVisibilityCulling;
+	bool mUseDepthPass;
 	bool mShowVisualization;
 
