Index: trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h	(revision 139)
+++ trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h	(revision 153)
@@ -80,4 +80,8 @@
 	GtpVisibility::VisibilityManager *GetVisibilityManager();
 
+	/** Returns hierarchy interface.
+	*/
+	OctreeHierarchyInterface *GetHierarchyInterface();
+
 protected:
 	
@@ -107,4 +111,5 @@
 	bool mRenderDepthPass;
 	bool mRenderItemBuffer;
+	bool mUseItemBuffer;
 	bool mEnableDepthWrite;
 	bool mSkipTransparents;
@@ -115,6 +120,4 @@
 	int mCurrentEntityId;
 
-	PlatformQueryManager *mQueryManager;
-
 	int mLeavePassesInQueue;
 	ShadowTechnique mSavedShadowTechnique;
Index: trunk/VUT/Ogre/include/OgreItemBufferQueryManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreItemBufferQueryManager.h	(revision 153)
+++ trunk/VUT/Ogre/include/OgreItemBufferQueryManager.h	(revision 153)
@@ -0,0 +1,43 @@
+#ifndef _ItemBufferQueryManager_H__
+#define _ItemBufferQueryManager_H__
+
+#include "OgrePlatformQueryManager.h"
+
+namespace Ogre {
+  
+/**
+	Class which implements the QueryManager for Ogre scene queries.
+*/
+class __declspec(dllexport) ItemBufferQueryManager: public PlatformQueryManager
+{
+public:
+    /** Constructor taking a hierarchy interface as an argument. This allows to operate
+	onm different hierarchy types, while reusing the implementation of the query methods.
+    */
+	ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp);
+    
+    void ComputeCameraVisibility(const Camera &camera,
+			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+			    bool relativeVisibility = false);
+    
+    /** 
+	Uses the specified point to execute the visibility query in all directions. 
+	@sa ComputeCameraVisibility()
+    */
+    void ComputeFromPointVisibility(const Vector3 &point,
+			       InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			       InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+			       bool relativeVisibility = false);
+    
+	bool ShootRay(const Ray &ray, std::vector<Mesh *> *visibleMeshes, bool isGlobalLine = false);  
+	
+protected:
+	void InitItemBuffer( InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry);
+	bool mWasInitialised;
+};
+
+} // namespace Ogre
+
+#endif // ItemBufferQueryManager
Index: trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 150)
+++ trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 153)
@@ -13,8 +13,7 @@
 
 //-----------------------------------------------------------------------
-VisibilityTerrainSceneManager::VisibilityTerrainSceneManager(
-	GtpVisibility::VisibilityManager *visManager): 
+VisibilityTerrainSceneManager::VisibilityTerrainSceneManager(GtpVisibility::
+															 VisibilityManager *visManager): 
 mVisibilityManager(visManager), 
-mRenderDepthPass(false),
 mShowVisualization(false),
 mRenderNodesForViz(false),
@@ -24,5 +23,8 @@
 mDelayRenderTransparents(true),
 mUseDepthPass(false),
-mRenderItemBuffer(true),
+mRenderDepthPass(false),
+//mUseItemBuffer(false),
+mUseItemBuffer(true),
+mRenderItemBuffer(false),
 mCurrentEntityId(0),
 mEnableDepthWrite(true),
@@ -31,7 +33,4 @@
 {
 	mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
-	mQueryManager = new PlatformQueryManager(mHierarchyInterface, mCurrentViewport);
-
-	mVisibilityManager->SetQueryManager(mQueryManager);
 	
 	//mDisplayNodes = true;
@@ -94,9 +93,4 @@
 		mHierarchyInterface = NULL;
 	}
-	if (mQueryManager)
-	{
-		delete mQueryManager;
-		mQueryManager = NULL;
-	}
 }
 //-----------------------------------------------------------------------
@@ -259,7 +253,13 @@
 		mIlluminationStage = savedStage;
 	}
-	else // the hierarchical culling algorithm
-	{
-		//-- hierarchical culling
+	else // -- the hierarchical culling algorithm
+	{
+		// don't render backgrounds for item buffer
+		if (mUseItemBuffer)
+		{
+			clearSpecialCaseRenderQueues();
+			getRenderQueue()->clear();
+		}
+
 		// the objects of different layers (e.g., background, scene, 
 		// overlay) must be identified and rendered one after another
@@ -272,6 +272,8 @@
 
 		TerrainSceneManager::_renderVisibleObjects();
+		
 
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		// delete previously rendered contenbt
 		_deleteRenderedQueueGroups();
 #endif
@@ -284,11 +286,12 @@
 
 
-		//-- set all necessary parameters for hierarchical visibility culling and rendering
+		// set all necessary parameters for 
+		// hierarchical visibility culling and rendering
 		InitVisibilityCulling(mCameraInProgress);
 
 		/** 
 		* the hierarchical culling algorithm
-		* if using depth pass: will just find objects and update depth buffer
-		* for "delayed" rendering: will render some passes afterwards, e.g. transparents
+		* if we use a depth pass: will just find objects and update depth buffer
+		* for "delayed" rendering: will render some passes afterwards, e.g., transparents
 		**/
 		
@@ -302,8 +305,9 @@
 		//-- reset parameters
 		mRenderDepthPass = false;
+		mRenderItemBuffer = false;
 		mSkipTransparents = false;
 		mLeavePassesInQueue = 0;
 		mShadowTechnique = mSavedShadowTechnique;
-		mRenderItemBuffer = false;
+		
 
 		// add visible nodes found by the visibility culling algorithm
@@ -326,8 +330,8 @@
 	TerrainRenderable::setCurrentRenderLevelIndex(levelIdx);
 
-	getRenderQueue()->clear();
-
 	// reset ambient light
 	setAmbientLight(savedAmbient);
+
+	getRenderQueue()->clear();
 	//WriteLog(); // write out stats
 }
@@ -404,7 +408,7 @@
 		return true;
 	}
-	if (key == "ItemBuffer")
-	{
-		mRenderItemBuffer = (*static_cast<const bool *>(val));
+	if (key == "UseItemBuffer")
+	{
+		mUseItemBuffer = (*static_cast<const bool *>(val));
 		return true;
 	}
@@ -425,5 +429,6 @@
 }
 //-----------------------------------------------------------------------
-bool VisibilityTerrainSceneManager::getOptionValues(const String & key, StringVector &refValueList)
+bool VisibilityTerrainSceneManager::getOptionValues(const String & key, 
+													StringVector &refValueList)
 {
 	return TerrainSceneManager::getOptionValues( key, refValueList);
@@ -436,5 +441,6 @@
 }
 //-----------------------------------------------------------------------
-void VisibilityTerrainSceneManager::setVisibilityManager(GtpVisibility::VisibilityManager *visManager)
+void VisibilityTerrainSceneManager::setVisibilityManager(GtpVisibility::
+														 VisibilityManager *visManager)
 {
 	mVisibilityManager = visManager;
@@ -634,10 +640,21 @@
 	InitItemBufferPass(); // create material for item buffer pass
 
+	// reset culling manager stats
+	mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
+
 	// save shadow technique. It will be reset after hierarchical culling
 	mSavedShadowTechnique = mShadowTechnique;
 
-
-	mLeavePassesInQueue = 0;
-	
+	// render standard solids without shadows during hierarchical culling pass
+	if ((mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE) ||
+	    (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE))
+	{
+	
+		mShadowTechnique = SHADOWTYPE_NONE;
+	}
+
+	// set depth pass flag before rendering
+	mRenderDepthPass = mUseDepthPass;
+
 	// item buffer needs full ambient lighting to use item colors as unique id
 	if (mUseItemBuffer) 
@@ -649,14 +666,13 @@
 
 	// set passes which should be stored in render queue 
-	// for rendering after hierarchical culling
-
-	if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
-	{
-		// render standard solids without shadows during hierarchical culling pass
-		mShadowTechnique = SHADOWTYPE_NONE;
-
-		if (!mUseDepthPass)
-		{
-			// TODO: remove this because should be processed in first pass
+	// for rendering AFTER hierarchical culling, i.e., passes which need 
+	// a special rendering order
+	mLeavePassesInQueue = 0;
+
+	if (!mUseDepthPass || !mUseItemBuffer)
+	{
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
+		{
+			// TODO: remove this pass because it should be processed during hierarchical culling
 			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
 
@@ -664,23 +680,27 @@
 			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DIFFUSE_SPECULAR;
 			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
-		}
-	}
-	if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
-	{
-		// render standard solids without shadows during hierarchical culling pass
-		mShadowTechnique = SHADOWTYPE_NONE;
-
-		if (!mUseDepthPass)
+
+			// just render ambient stuff
+			mIlluminationStage = IRS_AMBIENT;
+		}
+	
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
 		{
 			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
 			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
 		}
-	}
-	
-	if (mDelayRenderTransparents && (!mUseDepthPass))
-	{
-		mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
-	}
-	//std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;LogManager::getSingleton().logMessage(d.str());
+	
+		// transparents should be rendered after hierarchical culling to 
+		// provide front-to-back ordering
+		if (mDelayRenderTransparents)
+		{
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+		}
+	}
+
+	// skip rendering transparents in the hierarchical culling
+	// (because they will be rendered afterwards)
+	mSkipTransparents = mUseDepthPass || 
+		(mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES);
 
 	// possible two cameras (one for culling, one for rendering)
@@ -689,20 +709,15 @@
 						mLeavePassesInQueue);
 		
-	
-	// reset culling manager stats
-	mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
-
-	// set depth pass flag before rendering
-	mRenderDepthPass = mUseDepthPass;
-	// set flag for skipping transparents in the hierarchical culling pass
-	mSkipTransparents = mUseDepthPass || 
-		(mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES);
-}
-
+	//std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;LogManager::getSingleton().logMessage(d.str());
+}
+//-----------------------------------------------------------------------
+OctreeHierarchyInterface *VisibilityTerrainSceneManager::GetHierarchyInterface()
+{
+	return mHierarchyInterface;
+}
 //-----------------------------------------------------------------------
 /*void VisibilityTerrainSceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup)
 {
-    // Basic render loop
-    // Iterate through priorities
+    // Basic render loop: Iterate through priorities
     RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
 
@@ -714,6 +729,6 @@
         pPriorityGrp->sort(mCameraInProgress);
 
-		//TODO: render other splid passes for shadows
-        // Do solids
+		// Do solids
+		// TODO: render other solid passes for shadows
         renderObjects(pPriorityGrp->_getSolidPassesNoShadows(), true);
 
Index: trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 150)
+++ trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 153)
@@ -37,4 +37,6 @@
 	bool overlayEnabled = mViewport->getOverlaysEnabled();
 	mViewport->setOverlaysEnabled(false);
+
+	//-- render the scene once to update depth buffer
 	pfHierarchyInterface->GetSceneManager()->_renderScene(pCam, mViewport, false);
 
@@ -234,5 +236,5 @@
 	mViewport->setCamera(savedCam);
 
-	// --- remove duplicates (happens if an object is on the edge of the viewport)
+	// --- remove duplicates (duplicates occur if an object is on the edge of the viewport)
 
 	// before duplicates can be deleted we have to add up their visibility
@@ -259,5 +261,5 @@
 	}
 	
-	// really delete duplicates
+	// physically delete duplicates
 	visibleNodes->erase( std::unique(visibleNodes->begin(), 
 		visibleNodes->end(), nodeinfo_eq), visibleNodes->end());
@@ -284,5 +286,5 @@
 	}
 
-	// really delete duplicates
+	// physically delete duplicates
 	visibleGeometry->erase(std::unique(visibleGeometry->begin(), visibleGeometry->end(), 
 		meshinfo_eq), visibleGeometry->end());
Index: trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp	(revision 153)
+++ trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp	(revision 153)
@@ -0,0 +1,175 @@
+#include "OgreItemBufferQueryManager.h"
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+#include <vector>
+
+
+namespace Ogre {
+//----------------------------------------------------------------------- 
+ItemBufferQueryManager::ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp):
+PlatformQueryManager(hierarchyInterface, vp), mWasInitialised(false)
+{
+}
+//-----------------------------------------------------------------------
+bool ItemBufferQueryManager::ShootRay(const Ray &ray, std::vector<Mesh *> *visibleMeshes, bool isGlobalLine)
+{
+    // run OGRE ray shooting query
+    return false;
+}
+//-----------------------------------------------------------------------
+void ItemBufferQueryManager::ComputeCameraVisibility(const Camera &camera,
+			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+			    bool relativeVisibility)
+{
+	// initialise item buffer if necessary
+	InitItemBuffer(visibleNodes, visibleGeometry);
+
+	// we need access to the scene manager and the rendersystem
+	PlatformHierarchyInterface *pfHierarchyInterface = 
+		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+
+	SceneManager *sm = pfHierarchyInterface->GetSceneManager();
+
+	//-- Render scene as item buffer (e.g., color coded objects)
+
+	// const_cast allowed because camera is not changed in renderScene
+	Camera *pCam = const_cast<Camera *>(&camera); 
+
+	// disable overlays, reset them later
+	bool overlayEnabled = mViewport->getOverlaysEnabled();
+	mViewport->setOverlaysEnabled(false);
+
+	// set item buffer (must be provided by scene manager)
+	bool useItemBuffer = true;
+	sm->setOption("UseItemBuffer", &useItemBuffer);
+	
+	// clear background with black
+	ColourValue bg = mViewport->getBackgroundColour();
+	mViewport->setBackgroundColour(ColourValue(0, 0, 0, 0));
+
+	//pfHierarchyInterface->GetRenderSystem()->clearFrameBuffer(FBT_COLOUR);
+	// render item buffer
+	pfHierarchyInterface->GetSceneManager()->_renderScene(pCam, mViewport, false);
+	
+	// reset old overlay status
+	mViewport->setOverlaysEnabled(overlayEnabled);
+	
+	mViewport->setBackgroundColour(bg);
+
+	// don't need item buffer anymore
+	useItemBuffer = false;
+	sm->setOption("UseItemBuffer", &useItemBuffer);
+
+
+	//---- collect results
+	int dimx = 0;
+	int dimy = 0;
+
+	// get frame buffer
+	uchar *buf = mViewport->getTarget()->getBufferContents(dimx, dimy);
+
+	// loop through frame buffer & collect visible pixels
+	for (int idx = 0; idx < dimy * dimx * 3; idx += 3)
+	{
+		int id = buf[idx] << 16;
+		id += buf[idx + 1] << 8;
+		id += buf[idx + 2];
+
+		// if valid id <= add visibility
+		if ((id >= 0) && (id < (int)visibleGeometry->size()))
+		{
+			((*visibleGeometry)[id]).AddVisibility(1, 1);
+		}
+	/*	else
+		{ 
+			std::stringstream d; 
+			d << "id: " << id << ", buf 1: " << (int)buf[idx] << ", buf 2: " << (int)buf[idx + 1] << ", buf 3: " << (int)buf[idx + 2];
+			LogManager::getSingleton().logMessage(d.str());
+		}*/
+	}
+
+	// reset initialised - flag
+	mWasInitialised = false;
+
+	delete [] buf;
+}
+//-----------------------------------------------------------------------
+void ItemBufferQueryManager::InitItemBuffer(InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry)
+{
+	if (mWasInitialised)
+		return;
+
+	mWasInitialised = true;
+
+	SceneManager::EntityIterator it = dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->
+		GetSceneManager()->getEntityIterator();
+
+	// TODO: make this more efficient
+	visibleGeometry->clear();
+
+	while (it.hasMoreElements())
+	{
+		visibleGeometry->push_back(GtpVisibility::MeshInfo(it.getNext(), 0, 0));
+	}
+}
+//-----------------------------------------------------------------------
+void ItemBufferQueryManager::ComputeFromPointVisibility(const Vector3 &point,
+			       InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			       InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+			       bool relativeVisibility)
+{
+	SceneManager *sm = dynamic_cast<PlatformHierarchyInterface *>
+		(mHierarchyInterface)->GetSceneManager();
+
+	Camera *cam = sm->createCamera("PointQueryCam");	
+
+	//save old camera
+	Camera *savedCam = mViewport->getCamera();
+	
+	// --- initialise new camera
+	mViewport->setCamera(cam);
+	cam->setPosition(point);
+
+	cam->setNearClipDistance(savedCam->getNearClipDistance());
+	cam->setFarClipDistance(savedCam->getFarClipDistance());
+
+	// set frustum to 45 degrees so all the scene can be captured with 6 shots
+	cam->setAspectRatio(1.0);
+	cam->setFOVy(Radian(Math::HALF_PI));
+
+	int sign = -1;
+	
+	// ---- capture visibility from all 6 directions
+	for (int i=0; i < 6; i++)	
+	{
+		sign *= -1;
+		
+		// Print camera details
+      	std::stringstream d;
+		d << "Point query camera: " + StringConverter::toString(cam->getDerivedPosition()) + 
+			" " + "O: " + StringConverter::toString(cam->getDerivedOrientation());
+		LogManager::getSingleton().logMessage(d.str());
+
+		// prevent from initialising array again
+		if (i > 0)
+			mWasInitialised = true;
+		
+		// compute camera visibility for this direction
+		ComputeCameraVisibility(*cam, visibleNodes, visibleGeometry, relativeVisibility);
+
+		//mViewport->getTarget()->update(); for(int j=0; j<10000000; j++)	printf("wait"); // HACK: DISPLAY CAMERA VIEW
+
+		// --- permute directions
+		Vector3 dir(0,0,0);
+		dir[i/2] = sign;
+
+		cam->setDirection(dir);
+	}
+	
+	// reset camera
+	mViewport->setCamera(savedCam);
+}
+
+} // namespace Ogre
