Index: trunk/VUT/Ogre/include/OgreOcclusionQueriesQueryManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreOcclusionQueriesQueryManager.h	(revision 154)
+++ trunk/VUT/Ogre/include/OgreOcclusionQueriesQueryManager.h	(revision 159)
@@ -7,5 +7,5 @@
   
 /**
-	Class which implements the QueryManager for Ogre scene queries.
+	Class which implements the QueryManager for Ogre scene queries using occlusion queries.
 */
 class __declspec(dllexport) OcclusionQueriesQueryManager: public PlatformQueryManager
@@ -13,5 +13,5 @@
 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.
+		on different hierarchy types, while reusing the implementation of the query methods.
     */
 	OcclusionQueriesQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp);
@@ -20,4 +20,5 @@
 			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			    bool relativeVisibility = false);
     
@@ -29,4 +30,5 @@
 			       InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			       InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				   InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			       bool relativeVisibility = false);
     
Index: trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h	(revision 158)
+++ trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h	(revision 159)
@@ -75,5 +75,5 @@
 	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
 	*/
-	Entity* createEntity(const String& entityName, const String& meshName);
+	//Entity* createEntity(const String& entityName, const String& meshName);
 
 	/** Returns pointer to visibility manager.
@@ -84,4 +84,7 @@
 	*/
 	OctreeHierarchyInterface *GetHierarchyInterface();
+
+	void endFrame();
+
 
 protected:
@@ -142,4 +145,9 @@
 	int mLeavePassesInQueue;
 	ShadowTechnique mSavedShadowTechnique;
+
+	/// if transparent object are considered for item buffer visibility
+	bool mRenderTransparentsForItemBuffer;
+	/// Always execute the vertex program of a pass, e.g., for the depth pass or item buffer
+	bool mExecuteVertexProgramForAllPasses;
 };
 
Index: trunk/VUT/Ogre/include/OgreVisibilityOctreeSceneManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreVisibilityOctreeSceneManager.h	(revision 139)
+++ trunk/VUT/Ogre/include/OgreVisibilityOctreeSceneManager.h	(revision 159)
@@ -17,5 +17,5 @@
 	occlusion queries for visibility culling.
 */
-class VisibilityOctreeSceneManager: public OctreeSceneManager
+class __declspec(dllexport) VisibilityOctreeSceneManager: public OctreeSceneManager
 {
 public:
@@ -59,27 +59,91 @@
 	void WriteLog();
 
-	/** Override pass so we can do the z-fail pass */
+	/** Override pass so we can do the z-fail pass. 
+	*/
 	Pass* setPass(Pass* pass);
 
+	/** Override from SceneManager so we can skip all but first pass for depth pass. 
+	*/
+	bool validatePassForRendering(Pass* pass);
+
+	void RenderItemBuffer(RenderPriorityGroup* pGroup);
+	void RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass);
+	void renderQueueGroupObjects(RenderQueueGroup* pGroup);
+
+	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
+	*/
+	//Entity* createEntity(const String& entityName, const String& meshName);
+
+	/** Returns pointer to visibility manager.
+	*/
+	GtpVisibility::VisibilityManager *GetVisibilityManager();
+
+	/** Returns hierarchy interface.
+	*/
+	OctreeHierarchyInterface *GetHierarchyInterface();
+
+
 protected:
-	/** Creates material for depth pass, e.g., a pass that only fills the depth buffer */
+	
+	/** Creates material for depth pass, e.g., a pass that only fills the depth buffer. 
+	*/
 	void InitDepthPass();
+	/** Creates material for item buffer. 
+	*/
+	void InitItemBufferPass();
+	/** Fills render queue so that a visualization can be rendered. 
+	*/
+	void PrepareVisualization(Camera *cam);
+	/** Initialises necessary parameters for hierarchical visibility culling.
+	*/
+	void InitVisibilityCulling(Camera *cam);
 	
-	/** Prepares visualization of hierarchical culling. */
-	void PrepareVisualization(Camera *cam);
+	/// the interface to the scene hierarchy.
 	OctreeHierarchyInterface *mHierarchyInterface;
+	/// manages all visibility options
 	GtpVisibility::VisibilityManager *mVisibilityManager;
 	
+	/// if a visualization of the hierarchical culling is shown
 	bool mShowVisualization;
-	bool mSkipTransparents;
+
+	/// if the culled nodes are indicated in the visualization
 	bool mVisualizeCulledNodes;
 
+	/// if symbols for the nodes are shown in the visualization
 	bool mRenderNodesForViz;
+	/// if content of the nodes is shown in the visualization
 	bool mRenderNodesContentForViz;
+
+	/// render transparents after the hierarchical traversal
 	bool mDelayRenderTransparents;
+
+	/// use a depth pass (i.e., fill only the depth buffer in the first pass)
 	bool mUseDepthPass;
+	/// flag indicating if we currently render the depth pass
 	bool mRenderDepthPass;
 
+	/// if we use an item buffer for rendering (i.e., object ids as color codes
+	bool mUseItemBuffer;
+	/// if we currently render the item buffer 
+	bool mRenderItemBuffer;
+
+	/// if depth write should be enabled
+	bool mEnableDepthWrite;
+	/// if transparents are skipped during rendering
+	bool mSkipTransparents;
+
+	/// the depth pass (no lighting, just filling the depth buffer)
 	Pass *mDepthPass;
+	Pass *mItemBufferPass;
+
+	int mCurrentEntityId;
+	/// flag for passes which should not be deleted from queue during first traversal
+	int mLeavePassesInQueue;
+	ShadowTechnique mSavedShadowTechnique;
+
+	/// if transparent object are considered for item buffer visibility
+	bool mRenderTransparentsForItemBuffer;
+	/// Always execute the vertex program of a pass, e.g., for the depth pass or item buffer
+	bool mExecuteVertexProgramForAllPasses;
 };
 
Index: trunk/VUT/Ogre/include/OgrePlatformQueryManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgrePlatformQueryManager.h	(revision 154)
+++ trunk/VUT/Ogre/include/OgrePlatformQueryManager.h	(revision 159)
@@ -26,4 +26,5 @@
 			       InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			       InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				   InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			       bool relativeVisibility = false);
     
Index: trunk/VUT/Ogre/include/OgreItemBufferQueryManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreItemBufferQueryManager.h	(revision 154)
+++ trunk/VUT/Ogre/include/OgreItemBufferQueryManager.h	(revision 159)
@@ -7,5 +7,7 @@
   
 /**
-	Class which implements the QueryManager for Ogre scene queries.
+	Class which implements the QueryManager for Ogre scene queries using an item buffer,
+	i.e., the objects are rendered with their id used as unique color code. After reading
+	back the frame buffer, the visibility information can be established for each object.
 */
 class __declspec(dllexport) ItemBufferQueryManager: public PlatformQueryManager
@@ -13,11 +15,14 @@
 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.
+		on different hierarchy types, while reusing the implementation of the query methods.
+		@param renderPatches determines if the visibility of either patches or meshes is computed.
     */
-	ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp);
+	ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp,
+						   const bool renderPatches);
     
     void ComputeCameraVisibility(const Camera &camera,
 			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			    bool relativeVisibility = false);
     
@@ -25,7 +30,13 @@
 	
 protected:
-	void InitItemBuffer( InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
-			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry);
+	/** Helper function used to initialise item buffer.
+	*/
+	void InitItemBuffer( 
+				InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches);
 	
+	/// if patches are used instead of meshes (only one at a time)
+	bool mRenderPatchesForItemBuffer;
 };
 
Index: trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 158)
+++ trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 159)
@@ -31,5 +31,7 @@
 mEnableDepthWrite(true),
 mSkipTransparents(false),
-mSavedShadowTechnique(SHADOWTYPE_NONE)
+mSavedShadowTechnique(SHADOWTYPE_NONE),
+mRenderTransparentsForItemBuffer(false),
+mExecuteVertexProgramForAllPasses(false)
 {
 	mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
@@ -37,4 +39,6 @@
 	//mDisplayNodes = true;
 	//mShowBoundingBoxes = true;
+	//mShowBoxes = true;
+	//mShowBoxes = true;
 
 	// TODO: set maxdepth to reasonable value
@@ -48,8 +52,8 @@
 	if (depthMat.isNull())
     {
-		// Init
 		depthMat = MaterialManager::getSingleton().create(
                 "Visibility/DepthPass",
                 ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
         mDepthPass = depthMat->getTechnique(0)->getPass(0);
 		mDepthPass->setColourWriteEnabled(false);
@@ -60,4 +64,13 @@
 	{
 		mDepthPass = depthMat->getTechnique(0)->getPass(0);
+	}
+}
+//-----------------------------------------------------------------------
+VisibilityTerrainSceneManager::~VisibilityTerrainSceneManager()
+{
+	if (mHierarchyInterface)
+	{
+		delete mHierarchyInterface;
+		mHierarchyInterface = NULL;
 	}
 }
@@ -85,13 +98,4 @@
 	}
 	//mItemBufferPass->setAmbient(1, 1, 0);
-}
-//-----------------------------------------------------------------------
-VisibilityTerrainSceneManager::~VisibilityTerrainSceneManager()
-{
-	if (mHierarchyInterface)
-	{
-		delete mHierarchyInterface;
-		mHierarchyInterface = NULL;
-	}
 }
 //-----------------------------------------------------------------------
@@ -160,26 +164,25 @@
 	}
 	
-	if (mRenderDepthPass)
-	{
-		// --- set vertex program of current pass so z-buffer is updated correctly
-        if (pass->hasVertexProgram())
-		{
-			mDepthPass->setVertexProgram(pass->getVertexProgramName());
-
-			if (mDepthPass->hasVertexProgram())
-			{
-				const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
-				// Load this program if not done already
-				if (!prg->isLoaded())
-					prg->load();
-				// Copy params
-				mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
-			}
-		}
-		else if (mDepthPass->hasVertexProgram())
-		{
-			mDepthPass->setVertexProgram("");
-		}
-	}
+	// --- set vertex program of current pass in order to set correct depth
+	if (mExecuteVertexProgramForAllPasses && mRenderDepthPass && pass->hasVertexProgram())
+	{
+		// add vertex program of current pass to depth pass
+		mDepthPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mDepthPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mDepthPass->hasVertexProgram())
+	{
+		mDepthPass->setVertexProgram("");
+	}
+	
 
 	bool IsDepthWrite = usedPass->getDepthWriteEnabled();
@@ -228,5 +231,5 @@
 		// mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
 	}
-	//TerrainSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
+	
 	
 	// -- delete lists stored for visualization
@@ -240,5 +243,5 @@
 	ColourValue savedAmbient = mAmbientLight;
 
-	// --- apply standard rendering for some cases (e.g., visualization, shadow pass)
+	//-- apply standard rendering for some modes (e.g., visualization, shadow pass)
 
 	if (mShowVisualization ||
@@ -257,5 +260,5 @@
 		mIlluminationStage = savedStage;
 	}
-	else // -- the hierarchical culling algorithm
+	else //-- the hierarchical culling algorithm
 	{
 		// don't render backgrounds for item buffer
@@ -266,4 +269,5 @@
 		}
 
+		//-- hierarchical culling
 		// the objects of different layers (e.g., background, scene, 
 		// overlay) must be identified and rendered one after another
@@ -279,5 +283,5 @@
 
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
-		// delete previously rendered contenbt
+		// delete previously rendered content
 		_deleteRenderedQueueGroups();
 #endif
@@ -296,6 +300,7 @@
 		/** 
 		* the hierarchical culling algorithm
-		* 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
+		* for depth pass: we just find objects and update depth buffer
+		* for "delayed" rendering: we render some passes afterwards
+		* e.g., transparents, because they need front-to-back sorting
 		**/
 		
@@ -325,17 +330,16 @@
 		
 		//-- now we can render all remaining queue objects
-		// for depth pass, transparents, overlay 
+		// used for depth pass, transparents, overlay 
 		clearSpecialCaseRenderQueues();
 		TerrainSceneManager::_renderVisibleObjects();
 	}
 		
-	// set the new render level index afterwards => new level in the next frame 
-	int levelIdx = TerrainRenderable::getCurrentRenderLevelIndex() + 1;
-	TerrainRenderable::setCurrentRenderLevelIndex(levelIdx);
-
+	// set the new render level index 
+	TerrainRenderable::NextRenderLevelIndex();
+	
 	// reset ambient light
 	setAmbientLight(savedAmbient);
 
-	getRenderQueue()->clear();
+	getRenderQueue()->clear(); // finally clear render queue
 	//WriteLog(); // write out stats
 }
@@ -397,11 +401,5 @@
 		return true;
 	}
-	// notifiy that frame has ended so terrain render level can be reset for correct
-	// terrain rendering
-	if (key == "TerrainLevelIdx")
-	{
-		TerrainRenderable::setCurrentRenderLevelIndex((*static_cast<const int *>(val)));
-		return true;
-	}
+
 	if (key == "DepthWrite")
 	{
@@ -414,5 +412,15 @@
 		return true;
 	}
-	
+	if (key == "ExecuteVertexProgramForAllPasses")
+	{ 
+		mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderTransparentsForItemBuffer")
+	{ 
+		mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(val));
+		return true;
+	}
+
 	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
 		setOption(key, val) || TerrainSceneManager::setOption(key, val);
@@ -547,19 +555,24 @@
 	}
 
-	// ----- TRANSPARENT LOOP: must be handled differently 
-	// TODO: HOW TO HANDLE OCCLUDED OBJECTS ????
-	RenderPriorityGroup::TransparentRenderablePassList
-		transpObjs = pGroup->_getTransparentPasses();
-	RenderPriorityGroup::TransparentRenderablePassList::const_iterator itrans, itransend;
-
-	itransend = transpObjs.end();
-	for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
-	{
-		// like for solids, render only first pass
-		if (itrans->pass->getIndex() == 0)
-		{	
-			RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
-		}
-	} 
+	// -- TRANSPARENT LOOP: must be handled differently 
+
+	// transparents are treated either as solids or completely discarded
+	if (mRenderTransparentsForItemBuffer)
+	{
+		RenderPriorityGroup::TransparentRenderablePassList transpObjs = 
+			pGroup->_getTransparentPasses();
+		RenderPriorityGroup::TransparentRenderablePassList::const_iterator 
+			itrans, itransend;
+
+		itransend = transpObjs.end();
+		for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
+		{
+			// like for solids, render only first pass
+			if (itrans->pass->getIndex() == 0)
+			{	
+				RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
+			}
+		}
+	}
 }
 //-----------------------------------------------------------------------
@@ -583,5 +596,5 @@
 
 	// set vertex program of current pass
-	if (pass->hasVertexProgram())
+	if (mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
 	{
 		mItemBufferPass->setVertexProgram(pass->getVertexProgramName());
@@ -614,20 +627,4 @@
 }
 //-----------------------------------------------------------------------
-Entity* VisibilityTerrainSceneManager::createEntity(const String& entityName, 
-													const String& meshName)
-{
-	Entity *ent = SceneManager::createEntity(entityName, meshName);
-
-	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
-	{
-		ent->getSubEntity(i)->setId(mCurrentEntityId);
-	}
-
-	// increase counter of entity id values
-	++ mCurrentEntityId;
-
-	return ent;
-}
-//-----------------------------------------------------------------------
 void VisibilityTerrainSceneManager::InitVisibilityCulling(Camera *cam)
 {
@@ -644,6 +641,5 @@
 	if ((mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE) ||
 	    (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE))
-	{
-	
+	{	
 		mShadowTechnique = SHADOWTYPE_NONE;
 	}
@@ -660,5 +656,5 @@
 
 
-	// set passes which should be stored in render queue 
+	// set passes which are stored in render queue 
 	// for rendering AFTER hierarchical culling, i.e., passes which need 
 	// a special rendering order
@@ -715,4 +711,9 @@
 }
 //-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::endFrame()
+{
+	TerrainRenderable::ResetRenderLevelIndex();
+}
+//-----------------------------------------------------------------------
 /*void VisibilityTerrainSceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup)
 {
@@ -742,3 +743,21 @@
 }
 */
+//-----------------------------------------------------------------------
+/*
+Entity* VisibilityTerrainSceneManager::createEntity(const String& entityName, 
+													const String& meshName)
+{
+	Entity *ent = SceneManager::createEntity(entityName, meshName);
+
+	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+	{
+		ent->getSubEntity(i)->setId(mCurrentEntityId);
+	}
+
+	// increase counter of entity id values
+	++ mCurrentEntityId;
+
+	return ent;
+}
+*/
 } // namespace Ogre
Index: trunk/VUT/Ogre/src/OgreSceneContentGenerator.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreSceneContentGenerator.cpp	(revision 130)
+++ trunk/VUT/Ogre/src/OgreSceneContentGenerator.cpp	(revision 159)
@@ -65,4 +65,5 @@
 {
 	char name[25];
+
 	sprintf(name, "%s Entity%d", objName.c_str(), GetObjectCount());
 		
Index: trunk/VUT/Ogre/src/OgreOctreeHierarchyInterface.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreOctreeHierarchyInterface.cpp	(revision 158)
+++ trunk/VUT/Ogre/src/OgreOctreeHierarchyInterface.cpp	(revision 159)
@@ -26,6 +26,5 @@
 	}
 	
-	// if not all subtrees are empty
-	//if (octree->numNodes() > (int)octree->mNodes.size())
+	//if (octree->numNodes() > (int)octree->mNodes.size()) // if not all subtrees are empty
 	if (!IsLeaf(node))
 	{
Index: trunk/VUT/Ogre/src/OgreVisibilityOctreeSceneManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreVisibilityOctreeSceneManager.cpp	(revision 156)
+++ trunk/VUT/Ogre/src/OgreVisibilityOctreeSceneManager.cpp	(revision 159)
@@ -7,4 +7,6 @@
 #include <OgreLogManager.h>
 #include <OgreStringConverter.h>
+#include <OgreEntity.h>
+#include <OgreSubEntity.h>
 
 
@@ -16,12 +18,21 @@
 : 
 mVisibilityManager(visManager), 
-mRenderDepthPass(false),
 mShowVisualization(false),
 mRenderNodesForViz(false),
 mRenderNodesContentForViz(false),
 mVisualizeCulledNodes(false),
+mLeavePassesInQueue(0),
 mDelayRenderTransparents(true),
-mUseDepthPass(true),
-mSkipTransparents(false)
+mUseDepthPass(false),
+mRenderDepthPass(false),
+mUseItemBuffer(false),
+//mUseItemBuffer(true),
+mRenderItemBuffer(false),
+mCurrentEntityId(1),
+mEnableDepthWrite(true),
+mSkipTransparents(false),
+mSavedShadowTechnique(SHADOWTYPE_NONE),
+mRenderTransparentsForItemBuffer(false),
+mExecuteVertexProgramForAllPasses(false)
 {
 	mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
@@ -31,5 +42,5 @@
 	//mShowBoxes = true;
 
-	// TODO: find reasonable value for max depth
+	// TODO: set maxdepth to reasonable value
 	mMaxDepth = 50;
 }
@@ -65,37 +76,26 @@
 }
 //-----------------------------------------------------------------------
-Pass *VisibilityOctreeSceneManager::setPass(Pass* pass)
-{
-	// setting vertex program is not efficient
-	Pass *usedPass = ((mRenderDepthPass && pass->getDepthWriteEnabled() && 
-		!pass->hasVertexProgram()) ? mDepthPass : pass);		
-
-	/*
-	// set depth fill pass only if depth write enabled
-	Pass *usedPass = (mRenderDepthPass && pass->getDepthWriteEnabled() ? mDepthPass : pass);
-
-    if (mRenderDepthPass && pass->hasVertexProgram())
+void VisibilityOctreeSceneManager::InitItemBufferPass()
+{
+	MaterialPtr itemBufferMat = MaterialManager::getSingleton().
+		getByName("Visibility/ItemBufferPass");
+
+	if (itemBufferMat.isNull())
     {
-		// set vertex program of current pass to depth pass
-		mDepthPass->setVertexProgram(pass->getVertexProgramName());
-
-		if (mDepthPass->hasVertexProgram())
-		{
-			const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
-			// Load this program if not done already
-			if (!prg->isLoaded())
-				prg->load();
-			// Copy params
-			mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
-		}
-		else if (mDepthPass->hasVertexProgram())
-		{
-			mDepthPass->setVertexProgram("");
-		}
-	}*/
-
-	SceneManager::setPass(usedPass);
-
-	return usedPass;
+		// Init
+		itemBufferMat = MaterialManager::getSingleton().create("Visibility/ItemBufferPass",
+                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+		mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
+		mItemBufferPass->setColourWriteEnabled(true);
+		mItemBufferPass->setDepthWriteEnabled(true);
+		mItemBufferPass->setLightingEnabled(true);
+		//mItemBufferPass->setLightingEnabled(false);
+	}
+	else
+	{
+		mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
+	}
+	//mItemBufferPass->setAmbient(1, 1, 0);
 }
 //-----------------------------------------------------------------------
@@ -131,5 +131,8 @@
 			if (mRenderNodesForViz)
 			{
-				getRenderQueue()->addRenderable(*it);
+				if (((*it)->numAttachedObjects() > 0) && ((*it)->numChildren() == 0)
+					&& (*it)->getAttachedObject(0)->getMovableType() == "Entity")
+				getRenderQueue()->addRenderable((*it));
+
 				// addbounding boxes instead of node itself
 				//(*it)->_addBoundingBoxToQueue(getRenderQueue());
@@ -141,5 +144,64 @@
 		}
 	}
-	
+}
+//-----------------------------------------------------------------------
+Pass *VisibilityOctreeSceneManager::setPass(Pass* pass)
+{
+	// set depth fill pass if we currently do not make an aabb occlusion query
+	Pass *usedPass = (mRenderDepthPass && !mHierarchyInterface->IsBoundingBoxQuery() ? 
+					  mDepthPass : pass);
+
+	IlluminationRenderStage savedStage = mIlluminationStage; 
+	
+	// set illumination stage to NONE so no shadow material is used 
+	// for depth pass or for occlusion query
+	if (mRenderDepthPass || mHierarchyInterface->IsBoundingBoxQuery())
+	{
+		mIlluminationStage = IRS_NONE;
+	}
+
+	//-- set vertex program of current pass in order to set correct depth
+	if (mRenderDepthPass && mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
+    {
+		// add vertex program of current pass to depth pass
+		mDepthPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mDepthPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mDepthPass->hasVertexProgram())
+	{
+		mDepthPass->setVertexProgram("");
+	}
+
+	// store depth write flag to reset later
+	bool IsDepthWrite = usedPass->getDepthWriteEnabled();
+
+	// global option which enables / disables depth writes
+	if (!mEnableDepthWrite)
+	{
+		usedPass->setDepthWriteEnabled(false);
+	}
+	//else if (mIsItemBufferPass) {usedPass = mItemBufferPass;}
+
+	Pass *result = SceneManager::setPass(usedPass);
+
+	// reset depth write
+	if (!mEnableDepthWrite)
+	{
+		usedPass->setDepthWriteEnabled(IsDepthWrite);
+	}
+
+	// reset illumination stage
+	mIlluminationStage = savedStage;
+
+	return result;
 }
 //-----------------------------------------------------------------------
@@ -153,107 +215,131 @@
 	else 
 	{	
-		mVisible.clear();
-	    mBoxes.clear();
-	
-		// if there is no depth pass =>
-		// we interleave identification and rendering of objects 
-		// in _renderVisibibleObjects
-
+		// for hierarchical culling, we interleave identification 
+		// and rendering of objects in _renderVisibibleObjects
+
+		// for the shadow pass we use only standard rendering
+		// because of low occlusion
+		if (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && 
+			mIlluminationStage == IRS_RENDER_TO_TEXTURE)
+		{
+			OctreeSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
+		}
 		// only shadow casters will be rendered in shadow texture pass
-		mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
-	}
+		// mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
+	}
+	
+	
+	// -- delete lists stored for visualization
+	mVisible.clear();
+	mBoxes.clear();
 }
 //-----------------------------------------------------------------------
 void VisibilityOctreeSceneManager::_renderVisibleObjects()
 {
-	// create material for depth pass
-	InitDepthPass();
-	
-	// visualization: apply standard rendering
-	if (mShowVisualization)
+	// save ambient light to reset later
+	ColourValue savedAmbient = mAmbientLight;
+
+	//-- apply standard rendering for some modes (e.g., visualization, shadow pass)
+
+	if (mShowVisualization ||
+	   (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && 
+	    mIlluminationStage == IRS_RENDER_TO_TEXTURE))
+	{
+		IlluminationRenderStage savedStage = mIlluminationStage; 
+	
+		if (mShowVisualization)
+		{
+			// disable illumination stage to prevent rendering shadows
+			mIlluminationStage = IRS_NONE;
+		}
+
+		// standard rendering for shadow maps because of performance
+		OctreeSceneManager::_renderVisibleObjects();
+
+		mIlluminationStage = savedStage;
+	}
+	else //-- the hierarchical culling algorithm
 	{	
+		// don't render backgrounds for item buffer
+		if (mUseItemBuffer)
+		{
+			clearSpecialCaseRenderQueues();
+			getRenderQueue()->clear();
+		} 	
+
+		//-- hierarchical culling
+		// the objects of different layers (e.g., background, scene, 
+		// overlay) must be identified and rendered one after another
+
+		//-- render all early skies
+		clearSpecialCaseRenderQueues();
+		addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
+		addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
+		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
+
 		OctreeSceneManager::_renderVisibleObjects();
-		return;
-	} 	
-
-	//-- hierarchical culling
-	// the objects of different layers (e.g., background, scene, 
-	// overlay) must be identified and rendered one after another
-
-	bool leaveTransparentsInQueue = mDelayRenderTransparents && !mUseDepthPass;
-
-    // -- initialise interface for rendering traversal of the hierarchy
-	mHierarchyInterface->SetHierarchyRoot(mOctree);
-	
-	// possible two cameras (one for culling, one for rendering)
-	mHierarchyInterface->InitTraversal(mCameraInProgress, 
-							mCullCamera ? getCamera("CullCamera") : NULL,
-							leaveTransparentsInQueue);
-		
-
-	// reset culling manager stats
-	mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
-	
-	mSkipTransparents = false;
-
-	//-- render background, in case there is one
-	clearSpecialCaseRenderQueues();
-	addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
-	addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
-	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
-
-	SceneManager::_renderVisibleObjects();
 
 
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	_deleteRenderedQueueGroups();
+		// delete previously rendered content
+		_deleteRenderedQueueGroups();
 #endif
 
-	//-- render visible objects (i.e., all but overlay)
-	clearSpecialCaseRenderQueues();
-	addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
-	addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
-	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
-	
-	// transparents are skipped from hierarchical rendering
-	// => they need sorting, thus we render them afterwards
-	mSkipTransparents = mDelayRenderTransparents;
-
-	// set state for depth pass
-    mRenderDepthPass = mUseDepthPass;
-	
-	/** 
-	* the hierarchical culling algorithm
-	  * for depth pass: will just find objects and update depth buffer
-	  * for delayed rendering: will render all but transparents
-	**/
-	
-	mVisibilityManager->ApplyVisibilityCulling();
-	
-	//-- now we can savely render all remaining objects, e.g., transparents, overlay
-	mSkipTransparents = false;
-
-	clearSpecialCaseRenderQueues();
-	SceneManager::_renderVisibleObjects();
-
-	// for depth pass: add visible nodes found with the visibility culling
-	if (mUseDepthPass)
-	{
-		for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
-		{
-			(*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
-		}
+		//-- prepare queue for visible objects (i.e., all but overlay and skies late)
+		clearSpecialCaseRenderQueues();
+		addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
+		addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
+	
+
+		// set all necessary parameters for 
+		// hierarchical visibility culling and rendering
+		InitVisibilityCulling(mCameraInProgress);
+	
+		/** 
+		* the hierarchical culling algorithm
+		* for depth pass: we just find objects and update depth buffer
+		* for "delayed" rendering: we render some passes afterwards
+		* e.g., transparents, because they need front-to-back sorting
+		**/
+	
+		mVisibilityManager->ApplyVisibilityCulling();
+	
+		// delete remaining renderables from queue (all not in mLeavePassesInQueue)
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		_deleteRenderedQueueGroups(mLeavePassesInQueue);
+#endif
+
+		//-- reset parameters
 		mRenderDepthPass = false;
-    }
-	mSkipTransparents = false;
-		
-	//-- now we can render all remaining queue objects
-	// for depth pass: all
-	// for delayed rendering: transparents, overlay 
-	clearSpecialCaseRenderQueues();
-	OctreeSceneManager::_renderVisibleObjects();
-	
-	WriteLog(); // write out stats
-}
+		mRenderItemBuffer = false;
+		mSkipTransparents = false;
+		mLeavePassesInQueue = 0;
+		mShadowTechnique = mSavedShadowTechnique;
+
+
+		// add visible nodes found by the visibility culling algorithm
+		if (mUseDepthPass)
+		{
+			for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
+			{
+				(*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
+			}
+		}
+	
+		//-- we render all remaining queue objects
+		// used for depth pass, transparents, overlay 
+		clearSpecialCaseRenderQueues();
+		OctreeSceneManager::_renderVisibleObjects();
+	
+	}   // hierarchical culling
+
+	// reset ambient light
+	setAmbientLight(savedAmbient);
+	
+	getRenderQueue()->clear(); // finally clear render queue
+	//WriteLog(); // write out stats
+}
+
 //-----------------------------------------------------------------------
 void VisibilityOctreeSceneManager::_updateSceneGraph(Camera* cam)
@@ -312,4 +398,26 @@
 		return true;
 	}
+
+	if (key == "DepthWrite")
+	{
+		mEnableDepthWrite = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "UseItemBuffer")
+	{
+		mUseItemBuffer = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "ExecuteVertexProgramForAllPasses")
+	{ 
+		mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderTransparentsForItemBuffer")
+	{ 
+		mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(val));
+		return true;
+	}
+
 	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
 		setOption(key, val) || OctreeSceneManager::setOption(key, val);
@@ -372,7 +480,9 @@
 }
 //-----------------------------------------------------------------------
-void VisibilityOctreeSceneManager::renderObjects(const RenderPriorityGroup::TransparentRenderablePassList& objs, 
+void VisibilityOctreeSceneManager::renderObjects(
+	const RenderPriorityGroup::TransparentRenderablePassList& objs, 
             bool doLightIteration, const LightList* manualLightList)
 {
+	// for correct rendering, transparents must be rendered after hierarchical culling
 	if (!mSkipTransparents)
 	{
@@ -380,4 +490,269 @@
 	}
 }
-
+//-----------------------------------------------------------------------
+bool VisibilityOctreeSceneManager::validatePassForRendering(Pass* pass)
+{
+	// skip all but first pass if we are doing the depth pass
+	if ((mRenderDepthPass || mRenderItemBuffer) && pass->getIndex() > 0)
+	{
+		return false;
+	}
+	return SceneManager::validatePassForRendering(pass);
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::renderQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+	if (!mRenderItemBuffer)
+	{
+		OctreeSceneManager::renderQueueGroupObjects(pGroup);
+		return;
+	}
+
+	// --- item buffer
+
+    // Iterate through priorities
+    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+	while (groupIt.hasMoreElements())
+    {
+		RenderItemBuffer(groupIt.getNext());
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::RenderItemBuffer(RenderPriorityGroup* pGroup)
+{
+	// Do solids
+	RenderPriorityGroup::SolidRenderablePassMap solidObjs = pGroup->_getSolidPasses();
+
+	// ----- SOLIDS LOOP -----
+	RenderPriorityGroup::SolidRenderablePassMap::const_iterator ipass, ipassend;
+	ipassend = solidObjs.end();
+
+	for (ipass = solidObjs.begin(); ipass != ipassend; ++ipass)
+	{
+		// Fast bypass if this group is now empty
+		if (ipass->second->empty()) 
+			continue;
+
+		// Render only first pass
+		if (ipass->first->getIndex() > 0)
+			continue;
+
+		RenderPriorityGroup::RenderableList* rendList = ipass->second;
+		
+		RenderPriorityGroup::RenderableList::const_iterator irend, irendend;
+		irendend = rendList->end();
+			
+		for (irend = rendList->begin(); irend != irendend; ++irend)
+		{
+			std::stringstream d; d << "itembuffer, pass name: " << 
+				ipass->first->getParent()->getParent()->getName();
+				
+			LogManager::getSingleton().logMessage(d.str());
+			
+			RenderSingleObjectForItemBuffer(*irend, ipass->first);
+		}
+	}
+
+	// -- TRANSPARENT LOOP: must be handled differently 
+
+	// transparents are treated either as solids or completely discarded
+	if (mRenderTransparentsForItemBuffer)
+	{
+		RenderPriorityGroup::TransparentRenderablePassList transpObjs = 
+			pGroup->_getTransparentPasses();
+		RenderPriorityGroup::TransparentRenderablePassList::const_iterator 
+			itrans, itransend;
+
+		itransend = transpObjs.end();
+		for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
+		{
+			// like for solids, render only first pass
+			if (itrans->pass->getIndex() == 0)
+			{	
+				RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
+			}
+		} 
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass)
+{
+	static LightList nullLightList;
+	
+	int col[4];
+	
+	// -- create color code out of object id
+	col[0] = (rend->getId() >> 16) & 255;
+	col[1] = (rend->getId() >> 8) & 255;
+	col[2] = rend->getId() & 255;
+//	col[3] = 255;
+
+	//mDestRenderSystem->setColour(col[0], col[1], col[2], col[3]);
+    
+	mItemBufferPass->setAmbient(ColourValue(col[0] / 255.0f,
+										    col[1] / 255.0f, 
+											col[2] / 255.0f, 1));
+
+	// set vertex program of current pass
+	if (mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
+	{
+		mItemBufferPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mItemBufferPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mItemBufferPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mItemBufferPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mItemBufferPass->hasVertexProgram())
+	{
+		mItemBufferPass->setVertexProgram("");
+	}
+
+	Pass *usedPass = setPass(mItemBufferPass); 
+
+
+	// Render a single object, this will set up auto params if required
+	renderSingleObject(rend, usedPass, false, &nullLightList);
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilityOctreeSceneManager::GetVisibilityManager()
+{
+	return mVisibilityManager;
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::InitVisibilityCulling(Camera *cam)
+{
+	InitDepthPass(); 	  // create material for depth pass
+	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;
+
+	// 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) 
+	{
+		mRenderItemBuffer = true;
+		setAmbientLight(ColourValue(1,1,1,1));
+	}
+
+
+	// set passes which are stored in render queue 
+	// 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;
+
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DECAL;
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DIFFUSE_SPECULAR;
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+
+			// just render ambient passes
+			mIlluminationStage = IRS_AMBIENT;
+		}
+	
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
+		{
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+		}
+	
+		// 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);
+
+	// -- initialise interface for rendering traversal of the hierarchy
+	mHierarchyInterface->SetHierarchyRoot(mOctree);
+	
+	// possible two cameras (one for culling, one for rendering)
+	mHierarchyInterface->InitTraversal(mCameraInProgress, 
+							mCullCamera ? getCamera("CullCamera") : NULL,
+							mLeavePassesInQueue);
+		
+	//std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;LogManager::getSingleton().logMessage(d.str());
+}
+//-----------------------------------------------------------------------
+OctreeHierarchyInterface *VisibilityOctreeSceneManager::GetHierarchyInterface()
+{
+	return mHierarchyInterface;
+}
+//-----------------------------------------------------------------------
+/*void VisibilityOctreeSceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+    // Basic render loop: Iterate through priorities
+    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+    while (groupIt.hasMoreElements())
+    {
+        RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+        // Sort the queue first
+        pPriorityGrp->sort(mCameraInProgress);
+
+		// Do solids
+		// TODO: render other solid passes for shadows
+        renderObjects(pPriorityGrp->_getSolidPassesNoShadows(), true);
+
+		// do solid passes no shadows if addititive stencil shadows
+		if (mSavedShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
+			renderObjects(pPriorityGrp->_getSolidPassesNoShadows(), true);
+		
+        // Do transparents
+        renderObjects(pPriorityGrp->_getTransparentPasses(), true);
+
+
+    }// for each priority
+}
+*/
+//-----------------------------------------------------------------------
+/*
+Entity* VisibilityTerrainSceneManager::createEntity(const String& entityName, 
+													const String& meshName)
+{
+	Entity *ent = SceneManager::createEntity(entityName, meshName);
+
+	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+	{
+		ent->getSubEntity(i)->setId(mCurrentEntityId);
+	}
+
+	// increase counter of entity id values
+	++ mCurrentEntityId;
+
+	return ent;
+}*/
 }   // namespace Ogre
Index: trunk/VUT/Ogre/src/OgrePlatformHierarchyInterface.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgrePlatformHierarchyInterface.cpp	(revision 158)
+++ trunk/VUT/Ogre/src/OgrePlatformHierarchyInterface.cpp	(revision 159)
@@ -200,5 +200,6 @@
 }
 //-----------------------------------------------------------------------
-GtpVisibility::OcclusionQuery *PlatformHierarchyInterface::IssueOcclusionQuery(GtpVisibility::Mesh *mesh)
+GtpVisibility::OcclusionQuery *PlatformHierarchyInterface::IssueOcclusionQuery(
+	GtpVisibility::Mesh *mesh)
 {
 	// get next available test id
Index: trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 156)
+++ trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 159)
@@ -23,7 +23,11 @@
 			       InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			       InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				   InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			       bool relativeVisibility)
 {
-	SceneManager *sm = dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->GetSceneManager();
+	SceneManager *sm = dynamic_cast<PlatformHierarchyInterface *>
+		(mHierarchyInterface)->GetSceneManager();
+
+	// create a camera for the point query
 	Camera *cam = sm->createCamera("PointQueryCam");	
 
@@ -61,7 +65,7 @@
 		}
 
-		ComputeCameraVisibility(*cam, visibleNodes, visibleGeometry, relativeVisibility);
+		ComputeCameraVisibility(*cam, visibleNodes, visibleGeometry, visiblePatches, relativeVisibility);
 		
-		mViewport->getTarget()->update(); for(int j=0; j<10000000; j++)	printf("wait");
+		//mViewport->getTarget()->update(); for(int j=0; j<10000000; j++)	printf("wait");
 
 		// permute directions
Index: trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp	(revision 158)
+++ trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp	(revision 159)
@@ -3,10 +3,11 @@
 #include <OgreStringConverter.h>
 #include <vector>
-
+#include <OgreSubEntity.h>
 
 namespace Ogre {
 //----------------------------------------------------------------------- 
-ItemBufferQueryManager::ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp):
-PlatformQueryManager(hierarchyInterface, vp)
+ItemBufferQueryManager::ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp,
+											   const bool renderPatches):
+PlatformQueryManager(hierarchyInterface, vp), mRenderPatchesForItemBuffer(renderPatches)
 {
 }
@@ -21,8 +22,9 @@
 			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			    bool relativeVisibility)
 {
 	// initialise item buffer (if not already initialised)
-	InitItemBuffer(visibleNodes, visibleGeometry);
+	InitItemBuffer(visibleNodes, visibleGeometry, visiblePatches);
 
 	// we need access to the scene manager and the rendersystem
@@ -32,5 +34,5 @@
 	SceneManager *sm = pfHierarchyInterface->GetSceneManager();
 
-	// ---- Render scene with item buffer (i.e., objects with their id as color codes)
+	// --- Render scene with item buffer (i.e., objects with their id as color codes)
 
 	// const_cast allowed because camera is not changed in renderScene
@@ -61,4 +63,5 @@
 	uchar *buf = mViewport->getTarget()->getBufferContents(dimx, dimy);
 
+	int n = mRenderPatchesForItemBuffer ? (int)visiblePatches->size() : (int)visibleGeometry->size();
 	
 	// loop through frame buffer & collect visible pixels
@@ -71,7 +74,14 @@
 
 		// if valid id <= add visibility (id values start at 1
-		if ((id > 0) && (id < (int)visibleGeometry->size()))
+		if ((id > 0) && (id < n))
 		{
-			((*visibleGeometry)[id]).AddVisibility(1, 1);
+			if (mRenderPatchesForItemBuffer)
+			{
+				((*visiblePatches)[id]).AddVisibility(1, 1);
+			}
+			else
+			{
+				((*visibleGeometry)[id]).AddVisibility(1, 1);
+			}
 		}
 	}
@@ -93,6 +103,8 @@
 }
 //-----------------------------------------------------------------------
-void ItemBufferQueryManager::InitItemBuffer(InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
-			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry)
+void ItemBufferQueryManager::InitItemBuffer(
+				InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches)
 {
 	if (mWasInitialised)
@@ -109,10 +121,54 @@
 	visibleGeometry->clear();
 	visibleNodes->clear();
+	visiblePatches->clear();
 
+	int id = 0;
+
+	/* We can either use patches or meshes. If patches are used, an unique id must
+	   be given each patch. Otherwise the same id must be given to all patches belonging
+	   to the same mesh.
+    */
 	while (it.hasMoreElements())
 	{
-		visibleGeometry->push_back(GtpVisibility::MeshInfo(it.getNext(), 0, 0));
+		Entity *ent = it.getNext();
+
+		for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+		{
+			SubEntity *subEnt = ent->getSubEntity(i);
+
+			if (mRenderPatchesForItemBuffer)
+			{
+				++ id;
+				visiblePatches->push_back(GtpVisibility::PatchInfo(subEnt, 0, 0));
+			}
+				
+			subEnt->setId(id);
+		}
+			
+		if (!mRenderPatchesForItemBuffer)
+		{
+			visibleGeometry->push_back(GtpVisibility::MeshInfo(ent, 0, 0));
+			++ id;
+		}
 	}
 }
 
+/*
+//-----------------------------------------------------------------------
+Entity* VisibilityOctreeSceneManager::createEntity(const String& entityName, 
+													const String& meshName)
+{
+	Entity *ent = SceneManager::createEntity(entityName, meshName);
+
+	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+	{
+		ent->getSubEntity(i)->setId(mCurrentEntityId);
+	}
+
+	// increase counter of entity id values
+	++ mCurrentEntityId;
+
+	return ent;
+}
+*/
 } // namespace Ogre
Index: trunk/VUT/Ogre/src/OgreOcclusionQueriesQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreOcclusionQueriesQueryManager.cpp	(revision 155)
+++ trunk/VUT/Ogre/src/OgreOcclusionQueriesQueryManager.cpp	(revision 159)
@@ -21,4 +21,5 @@
 			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			    bool relativeVisibility)
 {
@@ -188,7 +189,9 @@
 			       InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
 			       InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				   InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
 			       bool relativeVisibility)
 {
-	PlatformQueryManager::ComputeFromPointVisibility(point, visibleNodes, visibleGeometry, relativeVisibility);
+	PlatformQueryManager::ComputeFromPointVisibility(point, visibleNodes, 
+		visibleGeometry, visiblePatches, relativeVisibility);
 
 	// --- remove duplicates (duplicates occur if an object is on the edge of the viewport)
Index: trunk/VUT/Ogre/resources/VisibilityDemo.overlay
===================================================================
--- trunk/VUT/Ogre/resources/VisibilityDemo.overlay	(revision 155)
+++ trunk/VUT/Ogre/resources/VisibilityDemo.overlay	(revision 159)
@@ -452,4 +452,20 @@
 			caption [F] toggle filtering method (trilinear, anisotropic, bilinear)
 		}
+		element TextArea(Example/Visibility/Help/FromCameraQueryInfo): Example/Visibility/Templates/BasicText
+		{
+			left 5
+			top 285
+			width 180
+			height 30
+			caption [F5] From camera visible pixels (+ SHIFT: relative visibility)
+		}
+		element TextArea(Example/Visibility/Help/FromPointQueryInfo): Example/Visibility/Templates/BasicText
+		{
+			left 5
+			top 60
+			width 300
+			height 30
+			caption [F6] From camera visible pixels (+ SHIFT: relative visibility)
+		}
 	}
 }
@@ -465,5 +481,5 @@
 		vert_align top
 		width 600
-		height 120
+		height 145
 		left 200
 		top 300
@@ -558,8 +574,26 @@
 		}
 
+
+		element TextArea(Example/Visibility/Query/VisiblePatches): Example/Visibility/Templates/BasicText
+		{
+			left 5
+			top 75
+			width 90
+			height 30
+			caption Visible patches
+		}
+		element TextArea(Example/Visibility/Query/VisiblePatchInfo): Example/Visibility/Templates/BasicText
+		{
+			left 180
+			top 75
+			width 90
+			height 30
+			caption :
+		}
+
 		element TextArea(Example/Visibility/Query/NodeVisibility): Example/Visibility/Templates/BasicText
 		{
 			left 5
-			top 75
+			top 90
 			width 90
 			height 30
@@ -570,8 +604,8 @@
 		{
 			left 180
-			top 75
-			width 90
-			height 30
-			caption:
+			top 90
+			width 90
+			height 30
+			caption :
 		}
 
@@ -579,5 +613,5 @@
 		{
 			left 5
-			top 90
+			top 105
 			width 90
 			height 30
@@ -588,9 +622,27 @@
 		{
 			left 180
-			top 90
-			width 90
-			height 30
-			caption:
-		}
+			top 105
+			width 90
+			height 30
+			caption :
+		}
+		element TextArea(Example/Visibility/Query/PatchVisibility): Example/Visibility/Templates/BasicText
+		{
+			left 5
+			top 120
+			width 90
+			height 30
+			caption Avg. patch visibility
+		}
+
+		element TextArea(Example/Visibility/Query/PatchVisibilityInfo): Example/Visibility/Templates/BasicText
+		{
+			left 180
+			top 120
+			width 90
+			height 30
+			caption :
+		}
+			
 
 	}
