Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchyCamera.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchyCamera.h	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchyCamera.h	(revision 1318)
@@ -0,0 +1,46 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBvHierarchyCamera_H_
+#define _OgreBvHierarchyCamera_H_
+
+#include <OgreCamera.h>
+
+#define KDCAMPTR_CAST(cam) (static_cast<BvHierarchyCamera *>(cam))
+
+namespace Ogre
+{
+
+class BvHierarchyCamera : public Camera
+{
+public:
+	enum NodeVisibility
+	{
+		KDNV_NONE,
+		KDNV_PART,
+		KDNV_FULL
+	};
+
+	// default constructor
+	BvHierarchyCamera(const String& name, SceneManager *sm);
+	// default destructor
+	~BvHierarchyCamera();
+
+	// regular visibility, like isVisible
+	NodeVisibility getVisibilitySimple(const AxisAlignedBox& box ) const;
+	// enhanced visibility
+	NodeVisibility getVisibilityEnhanced(const AxisAlignedBox& box) const;
+
+	// statistical info
+	mutable unsigned int mNumVisQueries;
+};
+
+} // namespace Ogre
+
+#endif // _OgreBvHierarchyCamera_H_
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchySceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchySceneManager.h	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchySceneManager.h	(revision 1318)
@@ -0,0 +1,349 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _KdTreeSceneManager_H__
+#define _KdTreeSceneManager_H__
+
+#include <OgreSceneManager.h>
+#include <VisibilityManager.h>
+#include <ViewCellsManager.h>
+
+#include "OgreBvHierarchy.h"
+#include "OgreBvHierarchyCamera.h"
+#include "OgreBvHierarchyInterface.h"
+
+#define KDTREE_MAX_DEPTH 12
+
+namespace Ogre
+{
+
+class KdTreeSceneNode;
+
+class KdTreeSceneManager : public SceneManager
+{
+public:
+	KdTreeSceneManager(const String& name, GtpVisibility::VisibilityManager *vm);
+	~KdTreeSceneManager(void);
+
+	virtual const String& getTypeName(void) const;
+
+	//typedef std::list<KdTreeSceneNode *> NodeList;
+	//typedef std::list<WireBoundingBox *> BoxList;
+
+	/************************************************************************/
+	/* Functions overridden form SceneManager for KdTree                    */
+	/************************************************************************/
+
+	/** Override from Scenemanager to create Camera as instance of BvHierarchyCamera
+	*/
+	virtual Camera* createCamera(const String& name);
+
+	/** Override from SceneManager to create SceneNodes as instance of KdTreeSceneNode
+	*/
+	virtual SceneNode* createSceneNode(void);
+	/** Override from SceneManager to create SceneNodes as instance of KdTreeSceneNode
+	*/
+	virtual SceneNode* createSceneNode(const String& name);
+
+	/** Override from Scenemanager, employ kd-tree based culling or CHC
+	*/
+	virtual void _findVisibleObjects(Camera *cam, bool onlyShadowCasters);
+
+	virtual bool setOption(const String& strKey, const void* pValue);
+	virtual bool getOption(const String& strKey, void* pDestValue);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
+
+	/** Overide from scene manager to destroy kdtree properly (before the scene graph is destroyed)
+	*/
+	virtual void clearScene();
+
+	/************************************************************************/
+	/* Functions overridden from SceneManager for CHC                       */
+	/************************************************************************/
+
+	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
+	*/
+	Entity* createEntity(const String& entityName, const String& meshName);
+
+	/** Override from scene manager to set up culling manager
+	*/
+	virtual void _updateSceneGraph(Camera* cam);
+
+	/** Override from SceneManager, employ normal rendering or CHC
+	*/
+	virtual void _renderVisibleObjects();
+
+	/** Override pass so we can do the z-fail pass.
+	*/
+	virtual const Pass* _setPass(const Pass* pass, bool evenIfSuppressed = false);
+
+	/** Render a queue group. 
+	Override so we can handle delayed rendering of transparent objects
+	*/
+	void renderBasicQueueGroupObjects(RenderQueueGroup* pGroup, 
+		QueuedRenderableCollection::OrganisationMode om);
+
+	/** Override from scene manager
+	*/
+	void _renderQueueGroupObjects(RenderQueueGroup* pGroup,
+		QueuedRenderableCollection::OrganisationMode om);
+
+	/** Override from SceneManager so we can skip all but first pass for depth pass. 
+	*/
+	bool validatePassForRendering(Pass* pass);
+
+	/** Override from SceneManager because idontknow
+	*/
+	void renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup,
+		QueuedRenderableCollection::OrganisationMode om);
+	void renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup,
+		QueuedRenderableCollection::OrganisationMode om);
+
+
+	/************************************************************************/
+	/* Functions which are specific to the KdTree                           */
+	/************************************************************************/
+	
+	/** Update the KdTree with the node (more or less disabled now)
+	*/
+	virtual void _updateNode(KdTreeSceneNode *node); // TODO: 
+
+	/** Show or hide the bounding boxes of KdTree nodes - obsolete, use options
+	*/
+	virtual void setShowBoxes(bool showboxes);
+	/** Tell if show boxes is enabled - obsolete, use options
+	*/
+	virtual bool getShowBoxes(void) const;
+
+	/** Recurses the kdtree, adding any nodes intersecting with the 
+	box/sphere/volume/ray into the given list.
+	It ignores the exclude scene node.
+	*/
+	void findNodesIn( const AxisAlignedBox &box, std::list < SceneNode * > &list, SceneNode *exclude = 0 )
+	{
+		if (mBvHierarchy)
+			mBvHierarchy->findNodesIn(box, list, exclude);
+	}
+	void findNodesIn( const Sphere &sphere, std::list < SceneNode * > &list, SceneNode *exclude = 0 )
+	{
+		if (mBvHierarchy)
+			mBvHierarchy->findNodesIn(sphere, list, exclude);
+	}
+	void findNodesIn( const PlaneBoundedVolume &volume, std::list < SceneNode * > &list, SceneNode *exclude=0 )
+	{
+		if (mBvHierarchy)
+			mBvHierarchy->findNodesIn(volume, list, exclude);
+	}
+	void findNodesIn( const Ray &ray, std::list < SceneNode * > &list, SceneNode *exclude=0 )
+	{
+		if (mBvHierarchy)
+			mBvHierarchy->findNodesIn(ray, list, exclude);
+	}
+
+	/************************************************************************/
+	/* Functions for PVS                                                    */
+	/************************************************************************/
+	/** Loads view cells for this particular scene.
+	*/
+	bool LoadViewCells(const String &filename);
+
+	/************************************************************************/
+	/* Functions for CHC                                                    */
+	/************************************************************************/
+
+	/** Render a list of scenenodes
+	*/
+	//virtual void _renderNodes(const BvRenderableList& nodelist, Camera * cam,
+	//	bool onlyShadowCasters, int leavePassesInQueue);
+	virtual void _renderNode(KdTree::NodePtr node, Camera * cam,
+		bool onlyShadowCasters, int leavePassesInQueue);
+
+	/** Sets the visibility manager.
+	@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::VisibilityManager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::VisibilityManager *getVisibilityManager();
+
+	/** Returns pointer to visibility manager.
+	*/
+	GtpVisibility::VisibilityManager *GetVisibilityManager();
+
+	/** Returns hierarchy interface.
+	*/
+	KdTreeHierarchyInterface *GetHierarchyInterface();
+
+protected:
+	/** 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);
+
+	/** Writes out stats into the Ogre log file.
+	*/
+	void WriteLog();
+
+	/************************************************************************/
+	/* Functions for PVS                                                    */
+	/************************************************************************/
+	/** Loads / unloads pvs of the view cell to set the visibility in the scene.
+	*/
+	void applyViewCellPvs(GtpVisibilityPreprocessor::ViewCell *vc, const bool load);
+
+	/** updates pvs in current frame.
+	*/
+	void updatePvs(Camera *cam);
+
+	/** Sets all objects invisible.
+	*/
+	void SetObjectsVisible(const bool visible);
+
+	/************************************************************************/
+	/* CHC-specific options & members                                       */
+	/************************************************************************/
+	// pointer to the visibility manager
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+
+	// the hierarchy interface for CHC
+	KdTreeHierarchyInterface *mHierarchyInterface;
+
+	// if hierarchical culling is currently in use
+	bool mIsHierarchicalCulling;
+
+	// if a visualization of the hierarchical culling is shown
+	bool mShowVisualization;
+	
+	// if the culled nodes are indicated in the visualization
+	bool mVisualizeCulledNodes;
+
+	// consecutive number for sub-entities
+	int mCurrentEntityId;
+
+	// flag for passes which should not be deleted from queue during first traversal
+	int mLeavePassesInQueue;
+
+	// 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;
+	
+	// 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;
+
+	// the depth pass (no lighting, just filling the depth buffer)
+	Pass *mDepthPass;
+	// 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 mIsDepthPassPhase;
+	// if depth write should be enabled
+	bool mEnableDepthWrite;
+	// if transparents are skipped during rendering
+	bool mSkipTransparents;
+	// the item buffer pass (render items color-coded)
+	Pass *mItemBufferPass;
+	// 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 mIsItemBufferPhase;
+	// delete or clear the renderqueue after each rame?
+	bool mDeleteQueueAfterRendering;
+
+
+	// remember visited scene nodes for viz
+	KdTree::NodeList mVisibleNodes;
+
+	/************************************************************************/
+	/* Kd-Tree specific options & members                                   */
+	/************************************************************************/
+	// maximum depth of the kdtree
+	int mMaxDepth;
+
+	// the kdtree which holds the scene
+	KdTree *mBvHierarchy;
+
+	// if bounding boxes of kdtree nodes are shown
+	bool mShowBoxes;
+	// bounding boxes of kd nodes will be highlighted on this level of the kd tree
+	int mHiLiteLevel;
+	// if all bounding boxes shall be displayed, not only the highlighted level
+	bool mShowAllBoxes;
+	// visualize kdtree nodes or bounding boxes of objects in nodes
+	bool mShowNodes;
+
+	// vis mode
+	bool mEnhancedVisiblity;
+
+	// the method/algorithm used when rendering the scene
+	KdTree::RenderMethod mRenderMethod;
+
+	// the method of building the tree
+	KdTree::BuildMethod mBuildMethod;
+
+	/************************************************************************/
+	/* PVS specific options and members                                     */
+	/************************************************************************/
+
+	// The view cell manager
+	GtpVisibilityPreprocessor::ViewCellsManager *mViewCellsManager;
+
+	/// Used to assign Ogre meshes to view cell entries.
+	GtpVisibilityPreprocessor::ObjectContainer mObjects;
+
+	GtpVisibilityPreprocessor::ViewCell *mElementaryViewCell;
+	GtpVisibilityPreprocessor::ViewCell *mCurrentViewCell;
+
+	/// If view cells are loaded.
+	bool mViewCellsLoaded;
+
+	/// If view cells are used.
+	bool mUseViewCells;
+
+	/// if the view cells are filtered
+	bool mUseVisibilityFilter;
+};
+
+
+
+/// Factory for KdTreeSceneManager
+class BvHierarchySceneManagerFactory : public SceneManagerFactory
+{
+protected:
+	void initMetaData(void) const;
+	GtpVisibility::VisibilityManager *visManager;
+public:
+	BvHierarchySceneManagerFactory(GtpVisibility::VisibilityManager * vm)
+	{
+		visManager = vm;
+	};
+	~BvHierarchySceneManagerFactory(void) {};
+	/// Factory type name
+	static const String FACTORY_TYPE_NAME;
+	SceneManager* createInstance(const String& instanceName);
+	void destroyInstance(SceneManager* instance);
+};
+
+} // namespace Ogre
+
+#endif // _KdTreeSceneManager_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchy.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchy.h	(revision 1317)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchy.h	(revision 1318)
@@ -8,6 +8,6 @@
 */
 
-#ifndef _OgreKdTree_H__
-#define _OgreKdTree_H__
+#ifndef _OgreBvHierarchy_H__
+#define _OgreBvHierarchy_H__
 
 #define KDNODE_CAST(a) (static_cast<KdTree::Node>(a))
@@ -29,5 +29,5 @@
 #include <stack>
 
-#include "OgreKdTreeCamera.h"
+#include "OgreBvHierarchyCamera.h"
 #include "HierarchyInterface.h"
 
@@ -35,6 +35,6 @@
 namespace Ogre
 {
-	class KdTreeCamera;
-	class KdRenderable;
+	class BvHierarchyCamera;
+	class BvRenderable;
 	struct SplitInfo;
 
@@ -66,5 +66,5 @@
 		{ };
 
-		PlaneEvent(KdRenderable *rend, const Vector3& pos, PlaneEvent::Dimension dim, PlaneEvent::Type type):
+		PlaneEvent(BvRenderable *rend, const Vector3& pos, PlaneEvent::Dimension dim, PlaneEvent::Type type):
 			mRenderable(rend), mPosition(pos), mDimension(dim), mType(type) 
 		{ };
@@ -125,5 +125,5 @@
 		}
 
-		KdRenderable * getRenderable() const //??
+		BvRenderable * getRenderable() const //??
 		{
 			return mRenderable;
@@ -139,5 +139,5 @@
 	protected:
 		// event info
-		KdRenderable *			mRenderable;
+		BvRenderable *			mRenderable;
 		Vector3					mPosition;
 		PlaneEvent::Dimension	mDimension;
@@ -186,5 +186,5 @@
 
 	typedef std::list<PlaneEvent> PlaneEventList;
-	typedef std::list<KdRenderable *> KdRenderableList;
+	typedef std::list<BvRenderable *> BvRenderableList;
 	
 	class KdTree
@@ -397,8 +397,8 @@
 
 			// a leaf is empty when it does not posses renderables
-			virtual bool isEmpty() const { return mKdRenderables.empty(); }
+			virtual bool isEmpty() const { return mBvRenderables.empty(); }
 
 			// a leaf has geometry when it has renderables
-			virtual bool hasGeometry() const { return !mKdRenderables.empty(); }
+			virtual bool hasGeometry() const { return !mBvRenderables.empty(); }
 
 			// a leaf adds itself to the leaf set
@@ -417,16 +417,16 @@
 			virtual void _updateBounds(bool recurse = true);
 
-			virtual void remove(KdRenderable * rend)
-			{
-				mKdRenderables.remove(rend);
-				//mKdRenderables.erase(find(mKdRenderables.begin(), mKdRenderables.end(), rend));
+			virtual void remove(BvRenderable * rend)
+			{
+				mBvRenderables.remove(rend);
+				//mBvRenderables.erase(find(mBvRenderables.begin(), mBvRenderables.end(), rend));
 			};
 
-			virtual void insert(KdRenderable * rend)
-			{
-				mKdRenderables.push_back(rend);
+			virtual void insert(BvRenderable * rend)
+			{
+				mBvRenderables.push_back(rend);
 			};
 
-			KdRenderableList mKdRenderables;
+			BvRenderableList mBvRenderables;
 		};
 
@@ -562,12 +562,12 @@
 
 		// insert a new scene node into an existing kd-tree
-		void insert(KdRenderable * rend);
+		void insert(BvRenderable * rend);
 		// remove a scene node from the tree
-		void remove(KdRenderable * rend);
+		void remove(BvRenderable * rend);
 		// function to initialize a kd-tree based on the contents of the scene
-		void build(KdRenderable * sceneRoot);
+		void build(BvRenderable * sceneRoot);
 
 		// test visibility of objects and add to render	queue
-		void queueVisibleObjects(KdTreeCamera* cam, RenderQueue* queue, bool onlyShadowCasters, 
+		void queueVisibleObjects(BvHierarchyCamera* cam, RenderQueue* queue, bool onlyShadowCasters, 
 			bool showBoxes, KdTree::NodeList& visibleNodes);
 
@@ -594,12 +594,12 @@
 		void init();
 		// recursive insert funciton
-		void recInsert(KdTree::Node * node, KdRenderable * rend);
+		void recInsert(KdTree::Node * node, BvRenderable * rend);
 		// helper functions for insert
-		void recInsertNew(KdTree::Branch * parent, PlaneEvent::Side side, KdRenderable * rend);
+		void recInsertNew(KdTree::Branch * parent, PlaneEvent::Side side, BvRenderable * rend);
 		void splitBox(const KdTree::Branch& parent, AxisAlignedBox& left, AxisAlignedBox& right);
-		void rebuildSubtree(KdTree::Node * node, KdRenderable * rend);
+		void rebuildSubtree(KdTree::Node * node, BvRenderable * rend);
 		// build scene from a list of nodes rather than a hierarchy
-		KdTree::Node * buildFromList(KdRenderableList& nodelist, KdTree::Branch * parent, AxisAlignedBox& aabb);
-		void addRendToList(KdTree::Node * node, KdRenderableList& nodelist);
+		KdTree::Node * buildFromList(BvRenderableList& nodelist, KdTree::Branch * parent, AxisAlignedBox& aabb);
+		void addRendToList(KdTree::Node * node, BvRenderableList& nodelist);
 
 		// recursively delete empty nodes
@@ -615,5 +615,5 @@
 
 		// recursive rendering function
-		void recQueueVisibleObjects(KdTree::Node * node, unsigned long currentFrame, KdTreeCamera* cam,
+		void recQueueVisibleObjects(KdTree::Node * node, unsigned long currentFrame, BvHierarchyCamera* cam,
 			RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, 
 			KdTree::NodeList& visibleNodes, bool fullVis = false);
@@ -659,5 +659,5 @@
 		// allows choosing between regular vis (NONE/PART, same es isVisible)
 		// and enhaced vis (NONE/PART/FULL) for early traversal abort
-		KdTreeCamera::NodeVisibility (KdTreeCamera::*getVisibility)(const AxisAlignedBox& box) const;
+		BvHierarchyCamera::NodeVisibility (BvHierarchyCamera::*getVisibility)(const AxisAlignedBox& box) const;
 
 		// DEBUG
@@ -668,3 +668,3 @@
 } // namespace Ogre
 
-#endif // _OgreKdTree_H__
+#endif // _OgreBvHierarchy_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchyInterface.h	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchyInterface.h	(revision 1318)
@@ -0,0 +1,99 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBvHierarchyInterface_H_
+#define _OgreBvHierarchyInterface_H_
+
+#include "OgrePlatformHierarchyInterface.h"
+
+namespace Ogre
+{
+
+class KdTreeSceneManager;
+
+class KdTreeHierarchyInterface : public PlatformHierarchyInterface
+{
+public:
+	KdTreeHierarchyInterface(KdTreeSceneManager *sm, RenderSystem *rsys);
+
+	virtual ~KdTreeHierarchyInterface() {};
+
+	/** Returns true if current node is leaf of the hierarchy. 
+	@param node hierarchy node
+	@returns true if node is leaf
+	*/
+	virtual bool IsLeaf(GtpVisibility::HierarchyNode *node) const;
+	/** Traverses and renders the hierarchy from the given node. 
+	@param node the hierarchy node
+	*/
+	virtual void TraverseNode(GtpVisibility::HierarchyNode *node);
+	/** Renders the given hierarchy node.
+	@param node current hierarchy node to be rendered
+	*/
+	virtual void RenderNode(GtpVisibility::HierarchyNode *node);
+	/** Pulls up the visibility from the current node recursively to the parent nodes. 
+	@param node the current node 
+	*/
+	virtual void PullUpVisibility(GtpVisibility::HierarchyNode *node) const;
+
+	/** Returns distance of the node to the view plane.
+	@param node the hierarchy node
+	*/			
+	virtual float GetSquaredDistance(GtpVisibility::HierarchyNode *node) const;
+	/** Returns pointer to bounding box of node.
+	@param node current hierarchy node
+	@returns bounding box of current node
+	*/
+	virtual AxisAlignedBox *GetBoundingBox(GtpVisibility::HierarchyNode *node);
+	/** Returns true if there is renderable geometry attached to this node
+	@param node the current node
+	@returns if the node has renderable geometry
+	*/
+	virtual bool HasGeometry(GtpVisibility::HierarchyNode *node) const;
+	/** Sets the visible flag for this node.
+	@param node the current node
+	@param visible the visible flag
+	*/
+	virtual void SetNodeVisible(GtpVisibility::HierarchyNode *node, const bool visible) const;
+	/** Returns true if node has the visible flag set. See set
+	*/
+	virtual bool IsNodeVisible(GtpVisibility::HierarchyNode *node) const;
+	/** Sets the last visited frame id for this node.
+	@param node the current node
+	@param frameId the current frame id
+	*/
+	virtual void SetLastVisited(GtpVisibility::HierarchyNode *node, const unsigned int frameId) const;
+	/** Returns frame id when this node was last visited by the traverser. See set
+	*/
+	virtual unsigned int LastVisited(GtpVisibility::HierarchyNode *node) const;
+
+
+	/** Visualization of a culled node, dependent on the culling type. 
+	@param node the hierarchy node to be visualized
+	@param type can be one of FRUSTUM_CULLED, QUERY_CULLED
+	*/
+	virtual void VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+		GtpVisibility::CullingType type) const;
+
+
+	/** Returns the geometry of a given hierarchy node. 
+	@param node the hierarchy node containing the geometry
+	@param geometryList geometry is returned in this list
+	@param includeChildren if the geometry of the children should be taken into account
+	*/
+	virtual void GetNodeGeometryList(GtpVisibility::HierarchyNode *node,	
+		GtpVisibility::GeometryVector *geometryList, 
+		bool includeChildren);
+
+
+};
+
+} // namespace Ogre
+
+#endif // _OgreBvHierarchyInterface_H_
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchySceneNode.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchySceneNode.h	(revision 1317)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvHierarchySceneNode.h	(revision 1318)
@@ -8,14 +8,14 @@
 */
 
-#ifndef _OgreKdTreeSceneNode_H__
-#define _OgreKdTreeSceneNode_H__
+#ifndef _OgreBvHierarchySceneNode_H__
+#define _OgreBvHierarchySceneNode_H__
 
 #include <OgreSceneNode.h>
-#include "OgreKdRenderable.h"
+#include "OgreBvRenderable.h"
 
 namespace Ogre
 {
 
-	class KdTreeSceneNode : public SceneNode, public KdRenderable
+	class KdTreeSceneNode : public SceneNode, public BvRenderable
 	{
 	public:
@@ -52,3 +52,3 @@
 } // namespace Ogre
 
-#endif // _OgreKdTreeSceneNode_H__
+#endif // _OgreBvHierarchySceneNode_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvRenderable.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvRenderable.h	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/include/OgreBvRenderable.h	(revision 1318)
@@ -0,0 +1,128 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBvRenderable_H__
+#define _OgreBvRenderable_H__
+
+#include "OgreBvHierarchy.h"
+
+namespace Ogre
+{
+
+	// interface which must be implemented by all objects which desire to be
+	// placed in the kd-tree
+	class BvRenderable
+	{
+	public:
+		BvRenderable():mSide(PlaneEvent::PES_BOTH), mClassified(false), mLastQueued(0), mBvHierarchy(0) {};
+		virtual ~BvRenderable()
+		{
+			if (mBvHierarchy)
+				mBvHierarchy->remove(this);
+		}
+
+		// gather the information required for the creation of the kd-tree
+		virtual void computeScene(PlaneEventList& events, AxisAlignedBox& aabb, int& nObjects, bool includeChildren = true) = 0;
+
+		// put all objects this element holds in the renedering queue
+		virtual void queueObjects(Camera* cam, RenderQueue* queue, bool onlyShadowCasters) = 0;
+
+		// place all entities in geometry queue (for CHC)
+		virtual void getGeometryList(GtpVisibility::GeometryVector *geometryList) = 0;
+
+		// return a bounding box enclosing all objects
+		virtual AxisAlignedBox getBoundingBox() const = 0;
+
+		// TODO: reconsider getters/setters !!!
+		inline bool isClassified()
+		{
+			return mClassified;
+		};
+		inline void setClassified(bool q)
+		{
+			mClassified = q;
+		};
+
+		inline PlaneEvent::Side getSide()
+		{
+			return mSide;
+		};
+		inline void setSide(PlaneEvent::Side s)
+		{
+			mSide = s;
+		};
+
+		// funcions for attachment/detachment of renderables to/from the kd-tree
+		inline bool isAttached()
+		{
+			return mLeaves.size() != 0;
+		};
+		// the following functions should work in O(log N)
+		inline bool isAttached(KdTree::LeafPtr leaf)
+		{
+			return mLeaves.find(leaf) != mLeaves.end();
+		};
+		inline bool attachTo(KdTree::LeafPtr leaf, KdTree * kdTree)
+		{
+			if (mBvHierarchy == 0 || mBvHierarchy == kdTree)
+				mBvHierarchy = kdTree;
+			else
+				return false;
+
+			KdTree::LeafSet::_Pairib p = mLeaves.insert(leaf);
+			return p.second;
+		};
+		inline bool detachFrom(KdTree::LeafPtr leaf)
+		{
+			bool success = (mLeaves.erase(leaf) == 1);
+			if (mLeaves.size() == 0)
+				mBvHierarchy = 0;
+
+			return success;
+		};
+
+		inline bool isQueued(unsigned long currentFrame, Camera * currentCam)
+		{
+			if (mLastQueued == currentFrame && mLastCam == currentCam)
+			{
+				return true;
+			}
+			else
+			{
+				mLastQueued = currentFrame;
+				mLastCam = currentCam;
+				return false;
+			}
+		};
+
+		KdTree::LeafSet& getLeaves()
+		{
+			return mLeaves;
+		};
+
+	protected:
+		// number of the frame in which this renderable was last queued for rendering
+		unsigned long mLastQueued;
+		// the camera for which this renderable was last queued for rendering
+		Camera * mLastCam;
+		
+		// kdtree to which this renderable is attached
+		KdTree * mBvHierarchy;
+		// kdtree leaves which overlap this renderable
+		KdTree::LeafSet mLeaves;
+
+		// Flag for the SAH determining the "cheaper" side of the split plane
+		PlaneEvent::Side mSide;
+		// Flag for the SAH which marks if this renderable was already placed in the list after a split
+		bool mClassified;
+	}; // class BvRenderable
+
+} // namespace Ogre
+
+#endif // _OgreBvRenderable_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvhSceneManagerDll.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvhSceneManagerDll.cpp	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvhSceneManagerDll.cpp	(revision 1318)
@@ -0,0 +1,76 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright © 2000-2002 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 "OgreBvHierarchySceneManager.h"
+#include <OgreRoot.h>
+#include <OgreLogManager.h>
+
+#include "VisibilityManager.h"
+#include "VisibilityEnvironment.h"
+		
+GtpVisibility::VisibilityEnvironment *visEnv;
+GtpVisibility::VisibilityManager *visManager;
+
+
+namespace Ogre {
+
+BvHierarchySceneManagerFactory *bvHierarchyFactory;
+
+//-----------------------------------------------------------------------
+extern "C" void __declspec(dllexport) dllStartPlugin(void)
+{
+	// load visibility environment
+	visEnv = new GtpVisibility::VisibilityEnvironment();
+	visManager = new GtpVisibility::VisibilityManager(visEnv);
+
+	// Create new scene manager
+	bvHierarchyFactory = new BvHierarchySceneManagerFactory(visManager);
+	
+	// Construct listener manager singleton
+	
+	// Register
+	Root::getSingleton().addSceneManagerFactory(bvHierarchyFactory);
+}
+//-----------------------------------------------------------------------
+extern "C" void __declspec(dllexport) dllShutdownPlugin()
+{
+	Root::getSingleton().removeSceneManagerFactory(bvHierarchyFactory);
+
+	// destroy listener manager
+}
+//-----------------------------------------------------------------------
+extern "C" void __declspec(dllexport) dllStopPlugin()
+{
+	//delete heightmapTerrainPageSource;
+	// BUG: crashes on delete!!!! FIX this 
+	delete bvHierarchyFactory;
+
+	delete visManager;
+	delete visEnv;
+}
+
+
+
+} //namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchy.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchy.cpp	(revision 1317)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchy.cpp	(revision 1318)
@@ -8,8 +8,8 @@
 */
 
-#include "OgreKdTree.h"
-#include "OgreKdRenderable.h"
-#include "OgreKdTreeSceneNode.h"
-#include "OgreKdTreeSceneManager.h"
+#include "OgreBvHierarchy.h"
+#include "OgreBvRenderable.h"
+#include "OgreBvHierarchySceneNode.h"
+#include "OgreBvHierarchySceneManager.h"
 
 #include <OgreStringConverter.h>
@@ -589,5 +589,5 @@
 /************************************************************************/
 
-void KdTree::remove(KdRenderable * rend)
+void KdTree::remove(BvRenderable * rend)
 {
 	// DEBUG
@@ -621,5 +621,5 @@
 	{
 		OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
-			"SNAFU while inserting KdRenderable into KdTree.",
+			"SNAFU while inserting BvRenderable into KdTree.",
 			"KdTree::recInsert" );
 		return;
@@ -648,5 +648,5 @@
 }
 
-void KdTree::insert(KdRenderable * rend)
+void KdTree::insert(BvRenderable * rend)
 {
 	// make sure the tree exists
@@ -663,5 +663,5 @@
 		{
 			//LogManager::getSingleton().logMessage("Inserted node outside of world AABB.");
-			KdRenderableList nodelist;
+			BvRenderableList nodelist;
 			nodelist.push_back(rend);
 			addRendToList(mKdRoot, nodelist);
@@ -677,10 +677,10 @@
 }
 
-void KdTree::recInsert(KdTree::Node * node, KdRenderable * rend)
+void KdTree::recInsert(KdTree::Node * node, BvRenderable * rend)
 {
 	if (node == 0) // DEBUG
 	{
 		OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
-			"SNAFU while inserting KdRenderable into KdTree.",
+			"SNAFU while inserting BvRenderable into KdTree.",
 			"KdTree::recInsert" );
 		return;
@@ -744,5 +744,5 @@
 }
 
-void KdTree::recInsertNew(KdTree::Branch * parent, PlaneEvent::Side side, KdRenderable * rend)
+void KdTree::recInsertNew(KdTree::Branch * parent, PlaneEvent::Side side, BvRenderable * rend)
 {
 	//LogManager::getSingleton().logMessage("## Inserting into new subtree");
@@ -789,5 +789,5 @@
 }
 
-void KdTree::rebuildSubtree(KdTree::Node * node, KdRenderable * rend)
+void KdTree::rebuildSubtree(KdTree::Node * node, BvRenderable * rend)
 {
 	//LogManager::getSingleton().logMessage("## Rebuilding subtree");
@@ -795,5 +795,5 @@
 	AxisAlignedBox aabb = node->mAABB;
 	
-	KdRenderableList nodelist;
+	BvRenderableList nodelist;
 	nodelist.push_back(rend);
 	addRendToList(node, nodelist);
@@ -821,5 +821,5 @@
 		{
 			OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
-				"SNAFU while inserting KdRenderable into KdTree.",
+				"SNAFU while inserting BvRenderable into KdTree.",
 				"KdTree::recInsert" );
 		}
@@ -845,11 +845,11 @@
 }
 
-void KdTree::addRendToList(KdTree::Node * node, KdRenderableList& nodelist)
+void KdTree::addRendToList(KdTree::Node * node, BvRenderableList& nodelist)
 {
 	if (node->isLeaf())
 	{
 		KdTree::Leaf * leaf = KDLEAFPTR_CAST(node);
-		KdRenderableList::iterator it  = leaf->mKdRenderables.begin();
-		KdRenderableList::iterator end = leaf->mKdRenderables.end();
+		BvRenderableList::iterator it  = leaf->mBvRenderables.begin();
+		BvRenderableList::iterator end = leaf->mBvRenderables.end();
 		while (it != end)
 		{
@@ -872,5 +872,5 @@
 /************************************************************************/
 
-void KdTree::build(KdRenderable * sceneRoot)
+void KdTree::build(BvRenderable * sceneRoot)
 {
 	Timer *timer = Root::getSingleton().getTimer();
@@ -931,5 +931,5 @@
 }
 
-KdTree::Node * KdTree::buildFromList(KdRenderableList& nodelist, KdTree::Branch * parent, AxisAlignedBox& aabb)
+KdTree::Node * KdTree::buildFromList(BvRenderableList& nodelist, KdTree::Branch * parent, AxisAlignedBox& aabb)
 {
 	// data we want to collect
@@ -938,6 +938,6 @@
 	int nObjects = 0;
 
-	KdRenderableList::iterator it = nodelist.begin();
-	KdRenderableList::iterator end = nodelist.end();
+	BvRenderableList::iterator it = nodelist.begin();
+	BvRenderableList::iterator end = nodelist.end();
 	while (it != end)
 	{
@@ -1031,5 +1031,5 @@
 		// Terminating condition reached, create leaf and add renderables to list
 		KdTree::Leaf * leaf = new KdTree::Leaf(this, level, aabb, parent);
-		KdRenderable *rend;
+		BvRenderable *rend;
 		it = begin;
 		while (it != end)
@@ -1178,5 +1178,5 @@
 			// Terminating condition reached, create leaf and add renderables to list
 			KdTree::Leaf * leaf = new KdTree::Leaf(this, level, sc.aabb, sc.parent);
-			KdRenderable *rend;
+			BvRenderable *rend;
 			PlaneEventList::iterator begin = sc.events->begin();
 			PlaneEventList::iterator end = sc.events->end();
@@ -1396,5 +1396,5 @@
 
 //-------------------------------------------------------------------------
-void KdTree::queueVisibleObjects(KdTreeCamera* cam, RenderQueue* queue, bool onlyShadowCasters, 
+void KdTree::queueVisibleObjects(BvHierarchyCamera* cam, RenderQueue* queue, bool onlyShadowCasters, 
 	bool showBoxes, KdTree::NodeList& visibleNodes)
 {
@@ -1411,16 +1411,16 @@
 //-------------------------------------------------------------------------
 void KdTree::recQueueVisibleObjects(KdTree::Node * node, unsigned long currentFrame, 
-	KdTreeCamera* cam, RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, 
+	BvHierarchyCamera* cam, RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, 
 	KdTree::NodeList& visibleNodes, bool fullVis)
 {
-	KdTreeCamera::NodeVisibility vis = KdTreeCamera::KDNV_PART;
+	BvHierarchyCamera::NodeVisibility vis = BvHierarchyCamera::KDNV_PART;
 	// test visibility
 	//if (cam->isVisible(node->mAABB))
 	if (fullVis || 
-		((vis = (cam->*getVisibility)(node->mAABB)) != KdTreeCamera::KDNV_NONE))
+		((vis = (cam->*getVisibility)(node->mAABB)) != BvHierarchyCamera::KDNV_NONE))
 	{
 		visibleNodes.push_back(node);
 
-		bool v = (fullVis || vis == KdTreeCamera::KDNV_FULL);
+		bool v = (fullVis || vis == BvHierarchyCamera::KDNV_FULL);
 
 		node->queueVisibleObjects(currentFrame, cam, queue, onlyShadowCasters, showBoxes, v);
@@ -1450,7 +1450,7 @@
 {
 	if (enh)
-		getVisibility = &KdTreeCamera::getVisibilityEnhanced;
+		getVisibility = &BvHierarchyCamera::getVisibilityEnhanced;
 	else
-		getVisibility = &KdTreeCamera::getVisibilitySimple;
+		getVisibility = &BvHierarchyCamera::getVisibilitySimple;
 }
 
@@ -1458,5 +1458,5 @@
 bool KdTree::getEnhancedVis()
 {
-	return getVisibility == &KdTreeCamera::getVisibilityEnhanced;
+	return getVisibility == &BvHierarchyCamera::getVisibilityEnhanced;
 }
 
@@ -1523,6 +1523,6 @@
 	{
 		LeafPtr leaf = KDLEAFPTR_CAST(node);
-		for (KdRenderableList::iterator it = leaf->mKdRenderables.begin();
-			it != leaf->mKdRenderables.end(); it ++)
+		for (BvRenderableList::iterator it = leaf->mBvRenderables.begin();
+			it != leaf->mBvRenderables.end(); it ++)
 		{
 			SceneNode *sn = dynamic_cast<SceneNode *>(*it);
@@ -1600,6 +1600,6 @@
 	{
 		KdTree::Leaf * leaf = KDLEAFPTR_CAST(node);
-		KdRenderableList::iterator it  = leaf->mKdRenderables.begin();
-		KdRenderableList::iterator end = leaf->mKdRenderables.end();
+		BvRenderableList::iterator it  = leaf->mBvRenderables.begin();
+		BvRenderableList::iterator end = leaf->mBvRenderables.end();
 		while (it != end)
 		{
@@ -1649,5 +1649,5 @@
 		KdTree::Leaf * leaf = KDLEAFPTR_CAST(node);
 		return (PlaneEvent::surfaceArea(node->mAABB)/vs) *
-			PlaneEvent::KI * leaf->mKdRenderables.size();
+			PlaneEvent::KI * leaf->mBvRenderables.size();
 	}
 	else
@@ -1668,6 +1668,6 @@
 	// detach all scene nodes in the case that we are rebuilding
 	// the tree but not the scene
-	KdRenderableList::iterator it = mKdRenderables.begin();
-	KdRenderableList::iterator end = mKdRenderables.end();
+	BvRenderableList::iterator it = mBvRenderables.begin();
+	BvRenderableList::iterator end = mBvRenderables.end();
 	while (it != end)
 	{
@@ -1675,5 +1675,5 @@
 		it++;
 	}
-	mKdRenderables.clear();
+	mBvRenderables.clear();
 }
 
@@ -1682,6 +1682,6 @@
 	Camera* cam, RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, bool fullVis)
 {
-	KdRenderableList::iterator it  = mKdRenderables.begin();
-	KdRenderableList::iterator end = mKdRenderables.end();
+	BvRenderableList::iterator it  = mBvRenderables.begin();
+	BvRenderableList::iterator end = mBvRenderables.end();
 	while (it != end)
 	{			
@@ -1701,6 +1701,6 @@
 void KdTree::Leaf::getGeometryList(GtpVisibility::GeometryVector *geometryList)
 {
-	KdRenderableList::iterator it = mKdRenderables.begin();
-	KdRenderableList::iterator end = mKdRenderables.end();
+	BvRenderableList::iterator it = mBvRenderables.begin();
+	BvRenderableList::iterator end = mBvRenderables.end();
 	while (it != end)
 	{
@@ -1718,6 +1718,6 @@
 
 	// merge boxes from attached geometry
-	KdRenderableList::iterator it = mKdRenderables.begin();
-	KdRenderableList::iterator end = mKdRenderables.end();
+	BvRenderableList::iterator it = mBvRenderables.begin();
+	BvRenderableList::iterator end = mBvRenderables.end();
 	while (it != end)
 	{
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchyInterface.cpp	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchyInterface.cpp	(revision 1318)
@@ -0,0 +1,144 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#include "OgreBvRenderable.h"
+#include "OgreBvHierarchySceneManager.h"
+#include "OgreBvHierarchyInterface.h"
+
+namespace Ogre
+{
+
+KdTreeHierarchyInterface::KdTreeHierarchyInterface(KdTreeSceneManager *sm, RenderSystem *rsys):
+PlatformHierarchyInterface(sm, rsys)
+{
+
+}
+
+bool KdTreeHierarchyInterface::IsLeaf(GtpVisibility::HierarchyNode *node) const
+{
+	return KDNODEPTR_CAST(node)->isLeaf();
+}
+
+void KdTreeHierarchyInterface::TraverseNode(GtpVisibility::HierarchyNode *node)
+{
+	++ mNumTraversedNodes;
+
+	KdTree::Node * kdnode = KDNODEPTR_CAST(node);
+
+	// if the node is a leaf and has geometry => render it
+	if (kdnode->isLeaf())
+	{
+		if (!kdnode->isEmpty())
+		{
+			RenderNode(node);
+		}
+	}
+	else
+	{
+		if (kdnode->getLeftChild())
+			mDistanceQueue->push(kdnode->getLeftChild());
+		if (kdnode->getRightChild())
+			mDistanceQueue->push(kdnode->getRightChild());
+	}
+}
+
+void KdTreeHierarchyInterface::RenderNode(GtpVisibility::HierarchyNode *node)
+{
+	KdTree::Node * kdnode = KDNODEPTR_CAST(node);
+	if (kdnode->lastRendered() != mFrameId)
+	{
+		kdnode->setLastRendered(mFrameId);
+		KdTreeSceneManager * ksm = static_cast<KdTreeSceneManager *>(mSceneManager);
+
+		ksm->_renderNode(kdnode, mCamera, mOnlyShadowCasters, mLeavePassesInQueue);
+
+		mVisibleNodes.push_back(node);
+	}
+}
+
+void KdTreeHierarchyInterface::PullUpVisibility(GtpVisibility::HierarchyNode *node) const
+{
+	KdTree::Node * kdnode = KDNODEPTR_CAST(node);
+
+	while (kdnode && !kdnode->isNodeVisible())
+	{
+		kdnode->setNodeVisible(true);
+		kdnode = kdnode->getParent();
+	}
+}
+
+float KdTreeHierarchyInterface::GetSquaredDistance(GtpVisibility::HierarchyNode *node) const
+{
+	const Vector3 pos = KDNODEPTR_CAST(node)->mAABB.getCenter();
+	return (mCameraPosition - pos).squaredLength();
+}
+
+AxisAlignedBox * KdTreeHierarchyInterface::GetBoundingBox(GtpVisibility::HierarchyNode *node)
+{
+	// reuse box if node is the same
+	// only create renderable bounding box for new node
+	if (node != mSavedNode)
+	{
+		mSavedNode = node;
+		mBox = KDNODEPTR_CAST(node)->_getWorldAABB();
+	}
+
+	return &mBox;
+}
+
+bool KdTreeHierarchyInterface::HasGeometry(GtpVisibility::HierarchyNode *node) const
+{
+	return KDNODEPTR_CAST(node)->hasGeometry();
+}
+
+void KdTreeHierarchyInterface::SetNodeVisible(GtpVisibility::HierarchyNode *node, const bool visible) const
+{
+	KDNODEPTR_CAST(node)->setNodeVisible(visible);
+}
+
+bool KdTreeHierarchyInterface::IsNodeVisible(GtpVisibility::HierarchyNode *node) const
+{
+	return KDNODEPTR_CAST(node)->isNodeVisible();
+}
+
+void KdTreeHierarchyInterface::SetLastVisited(GtpVisibility::HierarchyNode *node, const unsigned int frameId) const
+{
+	KDNODEPTR_CAST(node)->setLastVisited(frameId);
+}
+
+unsigned int KdTreeHierarchyInterface::LastVisited(GtpVisibility::HierarchyNode *node) const
+{
+	return KDNODEPTR_CAST(node)->lastVisited();
+}
+
+void KdTreeHierarchyInterface::VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+												   GtpVisibility::CullingType type) const
+{
+	WireBoundingBox *box = KDNODEPTR_CAST(node)->getWireBoundingBox();
+
+	if (type == GtpVisibility::FRUSTUM_CULLED)
+	{
+		box->setMaterial("FrustumCulledNodesMaterial");
+	}
+	else // type == GtpVisibility::QUERY_CULLED
+	{
+		box->setMaterial("QueryCulledNodesMaterial");
+	}
+
+	dynamic_cast<KdTreeSceneManager *>(mSceneManager)->getRenderQueue()->addRenderable(box);
+}
+
+void KdTreeHierarchyInterface::GetNodeGeometryList(GtpVisibility::HierarchyNode *node, 
+												   GtpVisibility::GeometryVector *geometryList, 
+												   bool includeChildren) 
+{
+	KDNODEPTR_CAST(node)->getGeometryList(geometryList);
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchySceneNode.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchySceneNode.cpp	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchySceneNode.cpp	(revision 1318)
@@ -0,0 +1,191 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#include "OgreBvHierarchySceneNode.h"
+#include "OgreBvHierarchySceneManager.h"
+
+#include <OgreStringConverter.h>
+#include <OgreLogManager.h>
+
+namespace Ogre
+{
+	// TRIVIA: this function is _not_ called for nodes which did not change since the last frame
+	// only exception: the root node ... it's aabb should be null however, so we don't care
+	void KdTreeSceneNode::_updateBounds(void)
+	{
+		// Reset bounds first
+		mWorldAABB.setNull();
+
+		// Update bounds from own attached objects
+		ObjectMap::iterator i;
+		for (i = mObjectsByName.begin(); i != mObjectsByName.end(); ++i)
+		{
+			// Merge world bounds of each object
+			mWorldAABB.merge(i->second->getWorldBoundingBox(true));
+		}
+
+		if (!mWorldAABB.isNull())
+		{
+			static_cast<KdTreeSceneManager *>(mCreator)->_updateNode(this);
+		}
+	}
+
+	void KdTreeSceneNode::computeScene(PlaneEventList& events, AxisAlignedBox& aabb, int& nObjects, bool includeChildren)
+	{
+		/**************************************************************************************/
+		/* HACK: do not include camera node, FUCKS UP world AABB really BAD, dunno why        */
+		/* TODO: find a generic solution where MOVABLE nodes are NOT INSERTED into the KDTREE */
+		/**************************************************************************************/
+		//if (mName == "PlayerCamNode")
+		//	return;
+
+		// first compute nodes AABB
+		mWorldAABB.setNull();
+		// Update bounds from own attached objects
+		ObjectMap::iterator i;
+		for (i = mObjectsByName.begin(); i != mObjectsByName.end(); ++i)
+		{
+			// ignore objects with no actual geometry like frustums & lights
+			if (getExcludedMovables().find(i->second->getMovableType()) == getExcludedMovables().end())
+			{
+				//LogManager::getSingleton().getLog(KDTREE_LOGNAME)->logMessage("Adding movable type " + i->second->getMovableType() + " to KdTree");
+				// Merge world bounds of each object
+				mWorldAABB.merge(i->second->getWorldBoundingBox(true));
+			}
+		}
+
+		// create information for KdTree/SAH
+		if (!mWorldAABB.isNull())
+		{
+			// merge aabb with global AABB
+			aabb.merge(mWorldAABB);
+
+			// increase object count
+			nObjects++;
+
+			// generate events
+			PlaneEvent::Dimension axes[] = 
+				{PlaneEvent::PED_X, PlaneEvent::PED_Y, PlaneEvent::PED_Z};
+			Vector3 min = mWorldAABB.getMinimum();
+			Vector3 max = mWorldAABB.getMaximum();
+			for (int i = 0; i < 3; i++)
+			{
+				// 1-D and 2-D objects
+				if (min[i] == max[i])
+				{	
+					//e = new PlaneEvent(this, min, axes[i], PlaneEvent::PET_ON);
+					//sceneinfo.events.push_back(*e);
+					events.push_back(PlaneEvent(this, min, axes[i], PlaneEvent::PET_ON));
+				}
+				else
+				{
+					//e = new PlaneEvent(this, min, axes[i], PlaneEvent::PET_START);
+					//sceneinfo.events.push_back(*e);
+					//e = new PlaneEvent(this, max, axes[i], PlaneEvent::PET_END);
+					//sceneinfo.events.push_back(*e);
+					events.push_back(PlaneEvent(this, min, axes[i], PlaneEvent::PET_START));
+					events.push_back(PlaneEvent(this, max, axes[i], PlaneEvent::PET_END));
+				}
+			}
+		}
+
+		// Merge with children
+		if (includeChildren)
+		{
+			ChildNodeMap::iterator child;
+			for (child = mChildren.begin(); child != mChildren.end(); ++child)
+			{
+				KdTreeSceneNode* sceneChild = static_cast<KdTreeSceneNode*>(child->second);
+				sceneChild->computeScene(events, aabb, nObjects);
+			}
+		}
+	}
+
+	//void KdTreeSceneNode::_findVisibleObjects(Camera* cam, RenderQueue* queue, 
+	//	bool includeChildren, bool displayNodes, bool onlyShadowCasters)
+	void KdTreeSceneNode::queueObjects(Camera* cam, RenderQueue* queue, bool onlyShadowCasters)
+	{
+		//SceneNode::_findVisibleObjects(cam, queue, includeChildren, displayNodes, onlyShadowCasters);
+
+		// Add all entities
+		ObjectMap::iterator iobj;
+		ObjectMap::iterator iobjend = mObjectsByName.end();
+		for (iobj = mObjectsByName.begin(); iobj != iobjend; ++iobj)
+		{
+			// Tell attached objects about camera position (incase any extra processing they want to do)
+			iobj->second->_notifyCurrentCamera(cam);
+			if (iobj->second->isVisible() &&
+				(!onlyShadowCasters || iobj->second->getCastShadows()))
+			{
+				iobj->second->_updateRenderQueue(queue);
+			}
+		}
+
+		// Check if the bounding box should be shown.
+		// See if our flag is set or if the scene manager flag is set.
+		if (mShowBoundingBox || (mCreator && mCreator->getShowBoundingBoxes())) 
+		{ 
+			_addBoundingBoxToQueue(queue);
+		}
+	}
+
+	void KdTreeSceneNode::getGeometryList(GtpVisibility::GeometryVector *geometryList)
+	{
+		SceneNode::ObjectIterator objIt = getAttachedObjectIterator();
+
+		while (objIt.hasMoreElements())
+		{
+			MovableObject *movable = objIt.getNext();
+
+			// we are interested only in the entities, i.e., instances of geometry
+			if (movable->getMovableType() == "Entity")
+			{
+				Entity *ent = static_cast<Entity *>(movable);
+				geometryList->push_back(ent);
+			}
+		}
+	}
+
+	// recalculate the world aabb
+	AxisAlignedBox KdTreeSceneNode::getBoundingBox(void) const
+	{
+		return mWorldAABB;
+	}
+
+	KdTreeSceneNode::StringSet& KdTreeSceneNode::getExcludedMovables(void)
+	{
+		static StringSet sExluded;
+
+		// initialise once
+		if (sExluded.empty())
+		{
+			sExluded.insert("Camera");
+			sExluded.insert("Frustum");
+			sExluded.insert("Light");
+		}
+
+		return sExluded;
+	}
+
+	// DEBUG
+	String KdTreeSceneNode::dumpToString(void)
+	{
+		String objects;
+		// Add all entities
+		ObjectMap::iterator iobj = mObjectsByName.begin();
+		ObjectMap::iterator iobjend = mObjectsByName.end();
+		while (iobj != iobjend)
+		{
+			objects += " " + iobj->second->getName();
+			iobj++;
+		}
+		objects += " Attached to " + StringConverter::toString(mLeaves.size()) + " KdLeaves.";
+		return objects;
+	}
+}
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/Plugin_BvhSceneManager.vcproj
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/Plugin_BvhSceneManager.vcproj	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/Plugin_BvhSceneManager.vcproj	(revision 1318)
@@ -0,0 +1,400 @@
+<?xml version="1.0" encoding="windows-1250"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="Plugin_BvhSceneManager"
+	ProjectGUID="{80DECC17-BDDD-4412-8CF8-F7C1C17A7436}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="..\lib\$(ConfigurationName)"
+			IntermediateDirectory="..\obj\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\..\..\OnlineCullingCHC\include;..\..\..\..\Preprocessing\src"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PLUGIN_KD_TERRAIN_EXPORTS;GTP_VISIBILITY_MODIFIED_OGRE"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="2"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain_d.lib CEGUIBase_d.lib OgreGUIRenderer_d.lib Plugin_OctreeSceneManager.lib GtpVisibility.lib zdll.lib zziplibd.lib Preprocessor.lib devil.lib glut32.lib xerces-c_2D.lib OpenGL32.Lib glu32.lib cg.lib cgGL.lib glew32.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="1"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;..\lib\$(ConfigurationName)&quot;;&quot;..\..\lib\$(ConfigurationName)&quot;;&quot;..\..\..\Preprocessing\lib\$(ConfigurationName)&quot;;..\..\..\Preprocessing\src\GL;..\..\..\..\..\..\..\NonGTP\Xerces\xercesc\lib;&quot;$(CG_LIB_PATH)&quot;"
+				ModuleDefinitionFile="..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/Plugin_VisibilitySceneManager.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="..\lib\$(ConfigurationName)"
+			IntermediateDirectory="..\obj\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2"
+			WholeProgramOptimization="TRUE">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				GlobalOptimizations="TRUE"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="TRUE"
+				ImproveFloatingPointConsistency="TRUE"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="TRUE"
+				EnableFiberSafeOptimizations="TRUE"
+				OptimizeForProcessor="0"
+				OptimizeForWindowsApplication="TRUE"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\..\OGRE\include;..\..\..\..\Preprocessing\src;..\..\..\include"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PLUGIN_KD_TERRAIN_EXPORTS;GTP_VISIBILITY_MODIFIED_OGRE"
+				StringPooling="TRUE"
+				RuntimeLibrary="2"
+				BufferSecurityCheck="FALSE"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain.lib CEGUIBase.lib OgreGUIRenderer.lib Plugin_OctreeSceneManager.lib GtpVisibility.lib zdll.lib zziplib.lib Preprocessor.lib xerces-c_2.lib devil.lib glut32.lib OpenGL32.Lib glu32.lib glew32.lib glew32s.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="1"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;;&quot;..\..\..\..\Preprocessing\lib\$(ConfigurationName)&quot;;..\..\..\..\..\..\..\..\NonGTP\Xerces\xercesc\lib;..\..\..\..\Preprocessing\src\GL;..\..\..\..\..\..\..\..\NonGTP\Zlib\lib;&quot;..\..\..\lib\$(ConfigurationName)&quot;"
+				ModuleDefinitionFile="..\..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="mlrt|Win32"
+			OutputDirectory="$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2"
+			WholeProgramOptimization="TRUE">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				GlobalOptimizations="TRUE"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="TRUE"
+				ImproveFloatingPointConsistency="TRUE"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="TRUE"
+				EnableFiberSafeOptimizations="TRUE"
+				OptimizeForProcessor="2"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\..\OnlineCullingCHC\include;..\..\..\Preprocessing\src"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;GTP_VISIBILITY_MODIFIED_OGRE"
+				StringPooling="TRUE"
+				RuntimeLibrary="2"
+				BufferSecurityCheck="FALSE"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain.lib CEGUIBase.lib OgreGUIRenderer.lib Plugin_OctreeSceneManager.lib GtpVisibility.lib zdll.lib zziplib.lib Preprocessor.lib xerces-c_2.lib devil.lib glut32.lib OpenGL32.Lib glu32.lib cg.lib cgGL.lib glew32.lib glew32s.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="1"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;..\..\GtpVisibility\lib\$(ConfigurationName)&quot;;&quot;..\..\lib\$(ConfigurationName)&quot;;&quot;..\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;;&quot;..\..\..\Preprocessing\lib\$(ConfigurationName)&quot;;..\..\..\..\..\..\..\NonGTP\Xerces\xercesc\lib;..\..\..\Preprocessing\src\GL;&quot;$(CG_LIB_PATH)&quot;;..\..\..\..\..\..\..\NonGTP\Zlib\lib"
+				ModuleDefinitionFile="..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release_Internal|Win32"
+			OutputDirectory="$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2"
+			WholeProgramOptimization="TRUE">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				GlobalOptimizations="TRUE"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="TRUE"
+				ImproveFloatingPointConsistency="TRUE"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="TRUE"
+				EnableFiberSafeOptimizations="TRUE"
+				OptimizeForProcessor="2"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\..\OnlineCullingCHC\include;..\..\..\Preprocessing\src"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;GTP_VISIBILITY_MODIFIED_OGRE"
+				StringPooling="TRUE"
+				RuntimeLibrary="2"
+				BufferSecurityCheck="FALSE"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain.lib CEGUIBase.lib OgreGUIRenderer.lib Plugin_OctreeSceneManager.lib GtpVisibility.lib zdll.lib zziplib.lib Preprocessor.lib xerces-c_2.lib devil.lib glut32.lib OpenGL32.Lib glu32.lib cg.lib cgGL.lib glew32.lib glew32s.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="1"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;..\..\GtpVisibility\lib\$(ConfigurationName)&quot;;&quot;..\..\lib\$(ConfigurationName)&quot;;&quot;..\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;;&quot;..\..\..\Preprocessing\lib\$(ConfigurationName)&quot;;..\..\..\..\..\..\..\NonGTP\Xerces\xercesc\lib;..\..\..\Preprocessing\src\GL;&quot;$(CG_LIB_PATH)&quot;;..\..\..\..\..\..\..\NonGTP\Zlib\lib"
+				ModuleDefinitionFile="..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release Internal|Win32"
+			OutputDirectory="$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2"
+			WholeProgramOptimization="TRUE">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				GlobalOptimizations="TRUE"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="TRUE"
+				ImproveFloatingPointConsistency="TRUE"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="TRUE"
+				EnableFiberSafeOptimizations="TRUE"
+				OptimizeForProcessor="2"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\..\OnlineCullingCHC\include;..\..\..\Preprocessing\src"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;GTP_VISIBILITY_MODIFIED_OGRE"
+				StringPooling="TRUE"
+				RuntimeLibrary="2"
+				BufferSecurityCheck="FALSE"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain.lib CEGUIBase.lib OgreGUIRenderer.lib Plugin_OctreeSceneManager.lib GtpVisibility.lib zdll.lib zziplib.lib Preprocessor.lib xerces-c_2.lib devil.lib glut32.lib OpenGL32.Lib glu32.lib cg.lib cgGL.lib glew32.lib glew32s.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="1"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;..\..\GtpVisibility\lib\$(ConfigurationName)&quot;;&quot;..\..\lib\$(ConfigurationName)&quot;;&quot;..\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;;&quot;..\..\..\Preprocessing\lib\$(ConfigurationName)&quot;;..\..\..\..\..\..\..\NonGTP\Xerces\xercesc\lib;..\..\..\Preprocessing\src\GL;&quot;$(CG_LIB_PATH)&quot;;..\..\..\..\..\..\..\NonGTP\Zlib\lib"
+				ModuleDefinitionFile="..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="src"
+			Filter="">
+			<File
+				RelativePath=".\OgreBvHierarchy.cpp">
+			</File>
+			<File
+				RelativePath=".\OgreBvHierarchyCamera.cpp">
+			</File>
+			<File
+				RelativePath=".\OgreBvHierarchyInterface.cpp">
+			</File>
+			<File
+				RelativePath=".\OgreBvHierarchySceneManager.cpp">
+			</File>
+			<File
+				RelativePath=".\OgreBvHierarchySceneNode.cpp">
+			</File>
+			<File
+				RelativePath=".\OgreBvhSceneManagerDll.cpp">
+			</File>
+		</Filter>
+		<Filter
+			Name="include"
+			Filter="">
+			<File
+				RelativePath="..\include\OgreBvHierarchy.h">
+			</File>
+			<File
+				RelativePath="..\include\OgreBvHierarchyCamera.h">
+			</File>
+			<File
+				RelativePath="..\include\OgreBvHierarchyInterface.h">
+			</File>
+			<File
+				RelativePath="..\include\OgreBvHierarchySceneManager.h">
+			</File>
+			<File
+				RelativePath="..\include\OgreBvHierarchySceneNode.h">
+			</File>
+			<File
+				RelativePath="..\include\OgreBvRenderable.h">
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/Plugin_BvhSceneManager.dsp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/Plugin_BvhSceneManager.dsp	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/Plugin_BvhSceneManager.dsp	(revision 1318)
@@ -0,0 +1,137 @@
+# Microsoft Developer Studio Project File - Name="Plugin_OcclusionCullingSceneManager" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=Plugin_OcclusionCullingSceneManager - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE 
+!MESSAGE NMAKE /f "Plugin_OcclusionCullingSceneManager.mak".
+!MESSAGE 
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE 
+!MESSAGE NMAKE /f "Plugin_OcclusionCullingSceneManager.mak" CFG="Plugin_OcclusionCullingSceneManager - Win32 Debug"
+!MESSAGE 
+!MESSAGE Possible choices for configuration are:
+!MESSAGE 
+!MESSAGE "Plugin_OcclusionCullingSceneManager - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "Plugin_OcclusionCullingSceneManager - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
+!MESSAGE 
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF  "$(CFG)" == "Plugin_OcclusionCullingSceneManager - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "..\bin\Release"
+# PROP Intermediate_Dir "..\obj\Release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\include" /I "$(OGRE_PATH)\OgreMain\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x418 /d "NDEBUG"
+# ADD RSC /l 0x418 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib OgreMain.lib /nologo /dll /machine:I386 /libpath:"$(OGRE_PATH)\OgreMain\lib\Release"
+# SUBTRACT LINK32 /pdb:none
+# Begin Special Build Tool
+SOURCE="$(InputPath)"
+PostBuild_Cmds=copy ..\bin\Release\*.dll $(OGRE_PATH)\Samples\Common\bin\Release
+# End Special Build Tool
+
+!ELSEIF  "$(CFG)" == "Plugin_OcclusionCullingSceneManager - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "..\bin\Debug"
+# PROP Intermediate_Dir "..\obj\Debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /GZ /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\include" /I "$(OGRE_PATH)\OgreMain\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /GZ /Zm200 /c
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x418 /d "_DEBUG"
+# ADD RSC /l 0x418 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib OgreMain_d.lib /nologo /dll /debug /machine:I386 /pdbtype:sept /libpath:"$(OGRE_PATH)\OgreMain\lib\Debug"
+# SUBTRACT LINK32 /pdb:none
+# Begin Special Build Tool
+SOURCE="$(InputPath)"
+PostBuild_Cmds=copy ..\bin\Debug\*.dll $(OGRE_PATH)\Samples\Common\bin\Debug
+# End Special Build Tool
+
+!ENDIF 
+
+# Begin Target
+
+# Name "Plugin_OcclusionCullingSceneManager - Win32 Release"
+# Name "Plugin_OcclusionCullingSceneManager - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\src\OgreOcclusionCullingResourceManager.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\OgreOcclusionCullingSceneManager.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\misc\OgreOcclusionCullingSceneManager.def
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\OgreOcclusionCullingSceneManagerDll.cpp
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# Begin Source File
+
+SOURCE=..\include\OgreOcclusionCullingResourceManager.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\include\OgreOcclusionCullingSceneManager.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchyCamera.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchyCamera.cpp	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchyCamera.cpp	(revision 1318)
@@ -0,0 +1,104 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#include "OgreBvHierarchyCamera.h"
+
+namespace Ogre
+{
+
+BvHierarchyCamera::BvHierarchyCamera(const String& name, SceneManager *sm):
+Camera(name, sm)
+{
+
+}
+
+BvHierarchyCamera::~BvHierarchyCamera()
+{
+
+}
+
+//-----------------------------------------------------------------------
+// enhanced vis calculation - borrowed from OctreeCamera - indicate when entire box inside the frustum
+BvHierarchyCamera::NodeVisibility BvHierarchyCamera::getVisibilityEnhanced(const AxisAlignedBox& box) const
+{
+	++ mNumVisQueries;
+	
+	// Null boxes always invisible
+	if ( box.isNull() )
+		return KDNV_NONE;
+
+	// Make any pending updates to the calculated frustum planes
+	updateFrustumPlanes();
+
+	// Get corners of the box
+	const Vector3* pCorners = box.getAllCorners();
+
+	// For each plane, see if all points are on the negative side
+	// If so, object is not visible.
+	// If one or more are, it's partial.
+	// If all aren't, full
+
+	int corners[ 8 ] = {0, 4, 3, 5, 2, 6, 1, 7};
+
+	int planes[ 6 ] = {FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_BOTTOM,
+		FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_RIGHT,
+		FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_NEAR };
+
+	bool all_inside = true;
+
+	for ( int plane = 0; plane < 6; ++plane )
+	{
+
+		// Skip far plane if infinite view frustum
+		if (mFarDist == 0 && planes[ plane ] == FRUSTUM_PLANE_FAR)
+			continue;
+
+		bool all_outside = true;
+
+		float distance = 0;
+
+		for ( int corner = 0; corner < 8; ++corner )
+		{
+			distance = mFrustumPlanes[ planes[ plane ] ].getDistance( pCorners[ corners[ corner ] ] );
+			all_outside = all_outside && ( distance < 0 );
+			all_inside = all_inside && ( distance >= 0 );
+
+			if ( !all_outside && !all_inside )
+				break;
+		}
+
+		if ( all_outside )
+			return KDNV_NONE;
+	}
+
+	if ( all_inside )
+		return KDNV_FULL;
+	else
+		return KDNV_PART;
+}
+
+//-----------------------------------------------------------------------
+// simple vis calculation - does the same as isVisible, only different return type
+BvHierarchyCamera::NodeVisibility BvHierarchyCamera::getVisibilitySimple(const AxisAlignedBox& box) const
+{
+	++ mNumVisQueries;
+
+	// dummy
+	FrustumPlane* culledBy = 0;
+	if (mCullFrustum)
+	{
+		return mCullFrustum->isVisible(box, culledBy) ? KDNV_PART : KDNV_NONE;
+	}
+	else
+	{
+		return Frustum::isVisible(box, culledBy) ? KDNV_PART : KDNV_NONE;
+	}
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchySceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchySceneManager.cpp	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/BvHierarchySceneManager/src/OgreBvHierarchySceneManager.cpp	(revision 1318)
@@ -0,0 +1,1455 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#include <OgreCamera.h>
+#include <OgreSubEntity.h>
+#include <OgreMaterialManager.h>
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+
+#include "OgreBvHierarchySceneManager.h"
+#include "OgreBvHierarchySceneNode.h"
+#include "OgreBvHierarchy.h"
+
+#include <OgreMeshInstance.h>
+#include <OgreBoundingBoxConverter.h>
+#include <OgreTypeConverter.h>
+#include <VisibilityEnvironment.h>
+#include "OgreVisibilityOptionsManager.h"
+
+namespace Ogre
+{
+
+KdTreeSceneManager::KdTreeSceneManager(const String& name, GtpVisibility::VisibilityManager *vm):
+SceneManager(name), 
+mVisibilityManager(vm), 
+mBvHierarchy(0), 
+mMaxDepth(KDTREE_MAX_DEPTH),
+mShowBoxes(false),
+mHiLiteLevel(0),
+mShowAllBoxes(false),
+mEnhancedVisiblity(true),
+mBuildMethod(KdTree::KDBM_RECURSIVE),
+mRenderMethod(KdTree::KDRM_INTERNAL),
+mShowVisualization(false),
+mRenderNodesForViz(false),
+mRenderNodesContentForViz(false),
+mVisualizeCulledNodes(false),
+mLeavePassesInQueue(0),
+mDelayRenderTransparents(true),
+mUseDepthPass(false),
+mIsDepthPassPhase(false),
+mUseItemBuffer(false),
+mIsItemBufferPhase(false),
+mCurrentEntityId(1),
+mEnableDepthWrite(true),
+mSkipTransparents(false),
+mRenderTransparentsForItemBuffer(true),
+mExecuteVertexProgramForAllPasses(false),
+mIsHierarchicalCulling(false),
+mDeleteQueueAfterRendering(true),
+mViewCellsLoaded(false),
+mUseViewCells(false),
+mUseVisibilityFilter(false),
+mViewCellsManager(0),
+mElementaryViewCell(0),
+mCurrentViewCell(0)
+{
+	// Replace root node with my node
+	OGRE_DELETE(mSceneRoot);
+	mSceneRoot = new KdTreeSceneNode(this, "root node");
+	mSceneRoot->_notifyRootNode();
+
+	// init heirarchy interface
+	mHierarchyInterface = new KdTreeHierarchyInterface(this, mDestRenderSystem);
+}
+
+KdTreeSceneManager::~KdTreeSceneManager(void)
+{
+	delete mHierarchyInterface;
+	delete mBvHierarchy;
+}
+
+void KdTreeSceneManager::clearScene()
+{
+	// DEBUG
+	//if (mBvHierarchy)
+	//	mBvHierarchy->dump();
+
+	// must happen before actual scene is cleared
+	OGRE_DELETE(mBvHierarchy);
+
+	SceneManager::clearScene();
+}
+
+
+const String& KdTreeSceneManager::getTypeName(void) const
+{
+	return BvHierarchySceneManagerFactory::FACTORY_TYPE_NAME;
+}
+
+void KdTreeSceneManager::setShowBoxes(bool showboxes)
+{
+	mShowBoxes = showboxes;
+}
+
+bool KdTreeSceneManager::getShowBoxes(void) const
+{
+	return mShowBoxes;
+}
+
+bool KdTreeSceneManager::setOption(const String& strKey, const void* pValue)
+{
+	// change max depth of the kdtree
+	// rebuild the tree if already exists
+	if (strKey == "KdTreeMaxDepth")
+	{
+		int maxdepth = *static_cast<const int *>(pValue);
+
+		// no negative depth, plz!
+		if (maxdepth < 0)
+		{
+			return false;
+		}
+		else
+		{
+			mMaxDepth = maxdepth;
+			if (mHiLiteLevel > mMaxDepth)
+				mHiLiteLevel = mMaxDepth;
+			return true;
+		}
+		return true;
+	}
+	else if (strKey == "KT")
+	{
+		Real kt = *static_cast<const Real *>(pValue);
+		if (kt > 0)
+		{
+			PlaneEvent::KT = kt;
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+	else if (strKey == "KI")
+	{
+		Real ki = *static_cast<const Real *>(pValue);
+		if (ki > 0)
+		{
+			PlaneEvent::KI = ki;
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+	else if (strKey == "RebuildKdTree")
+	{
+		OGRE_DELETE(mBvHierarchy);
+		mBvHierarchy = new KdTree(mMaxDepth, mBuildMethod, mHiLiteLevel, mShowAllBoxes, mShowNodes);
+		mBvHierarchy->build(static_cast<KdTreeSceneNode *>(mSceneRoot));
+		mBvHierarchy->setEnhancedVis(mEnhancedVisiblity);
+		return true;
+	}
+	else if (strKey == "EnhancedVisibility")
+	{
+		bool enh = *static_cast<const bool *>(pValue);
+		mEnhancedVisiblity = enh;
+		if (mBvHierarchy)
+			mBvHierarchy->setEnhancedVis(mEnhancedVisiblity);
+		//setEnhancedVis(enh);
+		return true;
+	}
+	else if (strKey == "BuildMethod")
+	{
+		KdTree::BuildMethod bm = *static_cast<const KdTree::BuildMethod *>(pValue);
+		if (bm == KdTree::KDBM_RECURSIVE || bm == KdTree::KDBM_PRIORITYQUEUE)
+		{
+			mBuildMethod = bm;
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+	else if (strKey == "RenderMethod")
+	{
+		KdTree::RenderMethod rm = *static_cast<const KdTree::RenderMethod *>(pValue);
+		if (rm == KdTree::KDRM_INTERNAL)
+		{
+			mRenderMethod = rm;
+			return true;
+		}
+		else if (rm == KdTree::KDRM_GTP_VFC)
+		{
+			mRenderMethod = rm;
+			int cmt = GtpVisibility::VisibilityEnvironment::FRUSTUM_CULLING;
+			return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+				.setOption("Algorithm", &cmt);
+		}
+		else if (rm == KdTree::KDRM_GTP_SWC)
+		{
+			mRenderMethod = rm;
+			int cmt = GtpVisibility::VisibilityEnvironment::STOP_AND_WAIT_CULLING;
+			return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+				.setOption("Algorithm", &cmt);
+		}
+		else if (rm == KdTree::KDRM_GTP_CHC)
+		{
+			mRenderMethod = rm;
+			int cmt = GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING;
+			return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+				.setOption("Algorithm", &cmt);
+		}
+		else
+		{
+			return false;
+		}
+	}
+	// little hack in case someone uses "Algorithm" option from VisOptMan directly
+	else if (strKey == "Algorithm")
+	{
+		bool success = VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+			.setOption(strKey, pValue);
+		// change setting only if change in VisOptMan was successful
+		if (success)
+		{
+			int val = *static_cast<const int *>(pValue);
+			if (val == GtpVisibility::VisibilityEnvironment::FRUSTUM_CULLING)
+				mRenderMethod = KdTree::KDRM_GTP_VFC;
+			else if (val == GtpVisibility::VisibilityEnvironment::STOP_AND_WAIT_CULLING)
+				mRenderMethod = KdTree::KDRM_GTP_SWC;
+			else if (val == GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING)
+				mRenderMethod = KdTree::KDRM_GTP_CHC;
+			// default, should never happen
+			else
+				mRenderMethod = KdTree::KDRM_INTERNAL;
+		}
+		else
+		{
+			mRenderMethod = KdTree::KDRM_INTERNAL;
+		}
+		return success;
+	}
+	else if (strKey == "ShowKdTree")
+	{
+		bool sk = *static_cast<const bool *>(pValue);
+		mShowBoxes = sk;
+		return true;
+	}
+	else if (strKey == "HiLiteLevel")
+	{
+		int hl = *static_cast<const int *>(pValue);
+		if (hl >= 0 && hl <= mMaxDepth)
+		{
+			mHiLiteLevel = hl;
+			if (mBvHierarchy)
+				mBvHierarchy->setHiLiteLevel(mHiLiteLevel);
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+	else if (strKey == "ShowAllBoxes")
+	{
+		bool sa = *static_cast<const bool *>(pValue);
+		mShowAllBoxes = sa;
+		if (mBvHierarchy)
+			mBvHierarchy->setShowAllBoxes(mShowAllBoxes);
+		return true;
+	}
+	else if (strKey == "ShowNodes")
+	{
+		bool sn = *static_cast<const bool *>(pValue);
+		mShowNodes = sn;
+		if (mBvHierarchy)
+			mBvHierarchy->setShowNodes(mShowNodes);
+		return true;
+	}
+	// options for CHC
+	else if (strKey == "UseDepthPass")
+	{
+		mUseDepthPass = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "PrepareVisualization")
+	{
+		mShowVisualization = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "RenderNodesForViz")
+	{
+		mRenderNodesForViz = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "RenderNodesContentForViz")
+	{
+		mRenderNodesContentForViz = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "SkyBoxEnabled")
+	{
+		mSkyBoxEnabled = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "SkyPlaneEnabled")
+	{
+		mSkyPlaneEnabled = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "SkyDomeEnabled")
+	{
+		mSkyDomeEnabled = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "VisualizeCulledNodes")
+	{
+		mVisualizeCulledNodes = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "DelayRenderTransparents")
+	{
+		mDelayRenderTransparents = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+
+	else if (strKey == "DepthWrite")
+	{
+		mEnableDepthWrite = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "UseItemBuffer")
+	{
+		mUseItemBuffer = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "ExecuteVertexProgramForAllPasses")
+	{ 
+		mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "RenderTransparentsForItemBuffer")
+	{ 
+		mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	else if (strKey == "DeleteRenderQueue")
+	{
+		mDeleteQueueAfterRendering = (*static_cast<const bool *>(pValue));
+		return true;
+	}
+	// options for viewcells
+	else if (strKey == "LoadViewCells")
+	{ 
+		if (!mViewCellsLoaded)
+		{
+			String filename(static_cast<const char *>(pValue));
+			mViewCellsLoaded = LoadViewCells(filename);	
+		}
+
+		return mViewCellsLoaded;
+	}
+	else if (strKey == "UseViewCells")
+	{ 
+		if (mViewCellsLoaded)
+		{
+			mUseViewCells = *static_cast<const bool *>(pValue);
+
+			// reset view cell
+			OGRE_DELETE(mCurrentViewCell);
+
+			if (mUseViewCells)
+				mCurrentViewCell = mViewCellsManager->GenerateViewCell();
+
+			mElementaryViewCell = NULL;
+
+			// if using view cells, all objects are set to false initially
+			SetObjectsVisible(!mUseViewCells);
+
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+
+	}
+	else if (strKey == "UseVisibilityFilter")
+	{
+		if (mViewCellsLoaded)
+		{
+			mUseVisibilityFilter = *static_cast<const bool *>(pValue);
+			// set null =>recomputation of the pvs
+			mElementaryViewCell = NULL;
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+		.setOption(strKey, pValue) || SceneManager::setOption(strKey, pValue);
+}
+
+bool KdTreeSceneManager::getOption(const String& strKey, void* pDestValue)
+{
+	if (strKey == "KdTreeMaxDepth")
+	{
+		*static_cast<int *>(pDestValue) = mMaxDepth;
+		return true;
+	}
+	else if (strKey == "KT")
+	{
+		*static_cast<Real *>(pDestValue) = PlaneEvent::KT;
+		return true;
+	}
+	else if (strKey == "KI")
+	{
+		*static_cast<Real *>(pDestValue) = PlaneEvent::KI;
+		return true;
+	}
+	else if (strKey == "EnhancedVisibility")
+	{
+		if (mBvHierarchy)
+			*static_cast<bool *>(pDestValue) = mBvHierarchy->getEnhancedVis();
+		else
+			*static_cast<bool *>(pDestValue) = mEnhancedVisiblity;
+		return true;
+	}
+	else if (strKey == "BuildMethod")
+	{
+		*static_cast<KdTree::BuildMethod *>(pDestValue) = mBuildMethod;
+		return true;
+	}
+	else if (strKey == "RenderMethod")
+	{
+		*static_cast<KdTree::RenderMethod *>(pDestValue) = mRenderMethod;
+		return true;
+	}
+	else if (strKey == "ShowKdTree")
+	{
+		*static_cast<bool *>(pDestValue) = mShowBoxes;
+		return true;
+	}	
+	else if (strKey == "HiLiteLevel")
+	{
+		*static_cast<int *>(pDestValue) = mHiLiteLevel;
+		return true;
+	}
+	else if (strKey == "ShowAllBoxes")
+	{
+		*static_cast<bool *>(pDestValue) = mShowAllBoxes;
+		return true;
+	}
+	else if (strKey == "ShowNodes")
+	{
+		*static_cast<bool *>(pDestValue) = mShowNodes;
+		return true;
+	}
+	// vis options
+	else if (strKey == "NumFrustumCulledNodes")
+	{
+		if (mRenderMethod == KdTree::KDRM_INTERNAL)
+		{
+			unsigned int numnodes = 0;
+			if (mBvHierarchy)
+				numnodes = mBvHierarchy->getFramesStats().mFrustumCulledNodes;
+
+			* static_cast<unsigned int *>(pDestValue) = (unsigned int)numnodes;
+			return true;
+		}
+		// otherwise let fall through to VisibilityOptionsManager
+	}
+	else if (strKey == "NumQueryCulledNodes")
+	{
+		if (mRenderMethod == KdTree::KDRM_INTERNAL)
+		{
+			* static_cast<unsigned int *>(pDestValue) = 0;
+			return true;
+		}
+		// otherwise let fall through to VisibilityOptionsManager
+	}
+	else if (strKey == "NumHierarchyNodes")
+	{
+		unsigned int numnodes = 0;
+		if (mBvHierarchy)
+			numnodes = mBvHierarchy->getTreeStats().mNumNodes;
+
+		* static_cast<unsigned int *>(pDestValue) = (unsigned int)numnodes;
+		return true;
+	}
+	else if (strKey == "NumRenderedNodes")
+	{
+		if (mRenderMethod == KdTree::KDRM_INTERNAL)
+		{
+			unsigned int numnodes = 0;
+			if (mBvHierarchy)
+				numnodes = mBvHierarchy->getFramesStats().mRenderedNodes;
+
+			* static_cast<unsigned int *>(pDestValue) = (unsigned int)numnodes;
+			return true;
+		}
+		// otherwise let fall through to VisibilityOptionsManager
+	}
+	else if (strKey == "NumQueriesIssued")
+	{
+		if (mRenderMethod == KdTree::KDRM_INTERNAL)
+		{
+			* static_cast<unsigned int *>(pDestValue) = 0;
+			return true;
+		}
+		// otherwise let fall through to VisibilityOptionsManager
+	}
+	else if (strKey == "NumTraversedNodes")
+	{
+		if (mRenderMethod == KdTree::KDRM_INTERNAL)
+		{
+			unsigned int numnodes = 0;
+			if (mBvHierarchy)
+				numnodes = mBvHierarchy->getFramesStats().mTraversedNodes;
+
+			* static_cast<unsigned int *>(pDestValue) = (unsigned int)numnodes;
+			return true;
+		}
+		// otherwise let fall through to VisibilityOptionsManager
+	}
+	else if (strKey == "VisibilityManager")
+	{
+		* static_cast<GtpVisibility::VisibilityManager **>(pDestValue) = 
+			(GtpVisibility::VisibilityManager *)mVisibilityManager;
+		return true;
+	}
+	else if (strKey == "HierarchInterface")
+	{
+		* static_cast<GtpVisibility::HierarchyInterface **>(pDestValue) = 
+			(GtpVisibility::HierarchyInterface *)mHierarchyInterface;
+		return true;
+	}
+	// view cell options
+
+	else if (strKey == "UseViewCells")
+	{ 
+		*static_cast<bool *>(pDestValue) = mUseViewCells;
+		return mViewCellsLoaded;
+	}
+	else if (strKey == "UseVisibilityFilter")
+	{
+		*static_cast<bool *>(pDestValue) = mUseVisibilityFilter;
+		return mViewCellsLoaded;
+	}
+
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+		.getOption(strKey, pDestValue) || SceneManager::getOption(strKey, pDestValue);
+}
+
+bool KdTreeSceneManager::getOptionKeys(StringVector &refKeys)
+{
+	refKeys.push_back("Algorithm");
+	refKeys.push_back("BuildMethod");
+	refKeys.push_back("DelayRenderTransparents");
+	refKeys.push_back("DeleteRenderQueue");
+	refKeys.push_back("DepthWrite");
+	refKeys.push_back("EnhancedVisibility");
+	refKeys.push_back("ExecuteVertexProgramForAllPasses");
+	refKeys.push_back("HiLiteLevel");
+	refKeys.push_back("HierarchInterface");
+	refKeys.push_back("KI");
+	refKeys.push_back("KT");
+	refKeys.push_back("KdTreeMaxDepth");
+	refKeys.push_back("LoadViewCells");
+	refKeys.push_back("NumHierarchyNodes");
+	refKeys.push_back("PrepareVisualization");
+	refKeys.push_back("RebuildKdTree");
+	refKeys.push_back("RenderMethod");
+	refKeys.push_back("RenderNodesContentForViz");
+	refKeys.push_back("RenderNodesForViz");
+	refKeys.push_back("RenderTransparentsForItemBuffer");
+	refKeys.push_back("ShowAllBoxes");
+	refKeys.push_back("ShowKdTree");
+	refKeys.push_back("ShowNodes");
+	refKeys.push_back("SkyBoxEnabled");
+	refKeys.push_back("SkyDomeEnabled");
+	refKeys.push_back("SkyPlaneEnabled");
+	refKeys.push_back("UseDepthPass");
+	refKeys.push_back("UseItemBuffer");
+	refKeys.push_back("UseViewCells");
+	refKeys.push_back("UseVisibilityFilter");
+	refKeys.push_back("VisibilityManager");
+	refKeys.push_back("VisualizeCulledNodes");
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface)
+		.getOptionKeys(refKeys);
+}
+
+bool KdTreeSceneManager::getOptionValues(const String & key, StringVector &refValueList)
+{
+	return SceneManager::getOptionValues(key, refValueList);
+}
+
+void KdTreeSceneManager::setVisibilityManager(GtpVisibility::VisibilityManager *visManager)
+{
+	mVisibilityManager = visManager;
+}
+
+GtpVisibility::VisibilityManager * KdTreeSceneManager::getVisibilityManager()
+{
+	return mVisibilityManager;
+}
+
+GtpVisibility::VisibilityManager * KdTreeSceneManager::GetVisibilityManager()
+{
+	return mVisibilityManager;
+}
+
+KdTreeHierarchyInterface * KdTreeSceneManager::GetHierarchyInterface()
+{
+	return mHierarchyInterface;
+}
+
+Camera* KdTreeSceneManager::createCamera(const String& name)
+{
+	// Check name not used
+	if (mCameras.find(name) != mCameras.end())
+	{
+		OGRE_EXCEPT(
+			Exception::ERR_DUPLICATE_ITEM,
+			"A camera with the name " + name + " already exists",
+			"SceneManager::createCamera" );
+	}
+
+	Camera *c = new BvHierarchyCamera(name, this);
+	mCameras.insert(CameraList::value_type(name, c));
+
+	return c;
+}
+
+SceneNode* KdTreeSceneManager::createSceneNode(void)
+{
+	SceneNode* sn = new KdTreeSceneNode(this);
+	assert(mSceneNodes.find(sn->getName()) == mSceneNodes.end());
+	mSceneNodes[sn->getName()] = sn;
+	return sn;
+}
+
+SceneNode* KdTreeSceneManager::createSceneNode(const String& name)
+{
+	// Check name not used
+	if (mSceneNodes.find(name) != mSceneNodes.end())
+	{
+		OGRE_EXCEPT(
+			Exception::ERR_DUPLICATE_ITEM,
+			"A scene node with the name " + name + " already exists",
+			"KdTreeSceneManager::createSceneNode" );
+	}
+
+	SceneNode* sn = new KdTreeSceneNode(this, name);
+	mSceneNodes[sn->getName()] = sn;
+	return sn;
+}
+
+Entity * KdTreeSceneManager::createEntity(const String& entityName, const String& meshName)
+{
+	Entity *ent = SceneManager::createEntity(entityName, meshName);
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+	{
+		ent->getSubEntity(i)->setId(mCurrentEntityId);
+	}
+
+	// increase counter of entity id values
+	++ mCurrentEntityId;
+#endif
+	return ent;
+}
+
+// make sure it's called only for non-empty nodes .. avoids one uneccessary funciton call
+void KdTreeSceneManager::_updateNode(KdTreeSceneNode *node)
+{
+	//LogManager::getSingleton().logMessage("### _updateNode called for " + node->getName());
+
+	/* Rebuild kdtree when it was wiped out
+		* Usually this happens only before the first frame
+		* The initial AABB shall enclose all objects present
+		* in the scene at the time of construction
+		* TODO: find a more appropriate place for it,
+		* e.g., before the first render call
+		* teh stupid thing is I can't find any other place so far ...
+		*/
+	if (!mBvHierarchy)
+	{
+		mBvHierarchy = new KdTree(mMaxDepth, mBuildMethod);
+		mBvHierarchy->build(static_cast<KdTreeSceneNode *>(mSceneRoot));
+		mBvHierarchy->setEnhancedVis(mEnhancedVisiblity);
+	}
+
+	// if the node is in the tree and _updateNode was called, then the node was moved/rotated/resized/wahtever
+	if (node->isAttached())
+	{
+		// TEST: perfomance when adding & removing for every frame
+		//mBvHierarchy->remove(node);
+		//mBvHierarchy->insert(node);
+	}
+	// there's a new node in town ... 
+	else
+	{			
+		// inserting single nodes yields sub-optimal results
+		// rebuilding tree takes too long
+		// "What now?", spoke Zeus ...
+
+		//mBvHierarchy->insert(node);
+		
+		//delete mBvHierarchy;
+		//mBvHierarchy = new KdTree(mMaxDepth);
+		//mBvHierarchy->build(static_cast<KdTreeSceneNode *>(mSceneRoot));
+	}
+
+}
+
+void KdTreeSceneManager::_updateSceneGraph(Camera* cam)
+{
+	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
+	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
+
+	SceneManager::_updateSceneGraph(cam);
+}
+
+void KdTreeSceneManager::_findVisibleObjects(Camera *cam, bool onlyShadowCasters)
+{
+	if (mRenderMethod == KdTree::KDRM_INTERNAL)
+	{
+		getRenderQueue()->clear();
+		if (mShowVisualization)
+		{
+			PrepareVisualization(cam);
+		}
+		else
+		{
+			mVisibleNodes.clear();
+			if (mBvHierarchy)
+			{
+				// determine visibility
+				mBvHierarchy->queueVisibleObjects(KDCAMPTR_CAST(cam), getRenderQueue(), onlyShadowCasters, mShowBoxes, mVisibleNodes);
+				// apply view cell pvs
+				updatePvs(cam);
+			}
+		}
+	}
+	else
+	{
+		//-- show visible scene nodes and octree bounding boxes from last frame
+		if (mShowVisualization)
+		{
+			PrepareVisualization(cam);
+		}
+		else 
+		{	
+			// 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)
+			{
+				getRenderQueue()->clear();
+				if (mBvHierarchy)
+					mBvHierarchy->queueVisibleObjects(KDCAMPTR_CAST(cam), getRenderQueue(), onlyShadowCasters, mShowBoxes, mVisibleNodes);
+			}
+
+			// only shadow casters will be rendered in shadow texture pass
+			if (0) mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
+
+
+			//-- apply view cell pvs -
+			updatePvs(cam);
+		}
+		mVisibleNodes.clear();	
+	}
+}
+
+void KdTreeSceneManager::_renderVisibleObjects()
+{
+	if (mRenderMethod == KdTree::KDRM_INTERNAL)
+	{
+		SceneManager::_renderVisibleObjects();
+	}
+	else
+	{
+		InitDepthPass(); 	  // create material for depth pass
+		InitItemBufferPass(); // create material for item buffer pass
+
+		// 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
+			SceneManager::_renderVisibleObjects();
+
+			mIlluminationStage = savedStage;
+		}
+		else //-- the hierarchical culling algorithm
+		{
+			// this is also called in TerrainSceneManager: really necessary?
+			//mDestRenderSystem -> setLightingEnabled(false);
+
+			// 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);
+
+			SceneManager::_renderVisibleObjects();
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+			// delete previously rendered content
+			_deleteRenderedQueueGroups();
+#endif
+
+			//-- prepare queue for visible objects (i.e., all but overlay and skies late)
+			clearSpecialCaseRenderQueues();
+			addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
+			addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+
+			// exclude this queues from hierarchical rendering
+			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 which are not in mLeavePassesInQueue
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+			_deleteRenderedQueueGroups(mLeavePassesInQueue);
+#endif
+
+			//-- reset parameters
+			mIsDepthPassPhase = false;
+			mIsItemBufferPhase = false;
+			mSkipTransparents = false;
+			mIsHierarchicalCulling = false;
+
+			mLeavePassesInQueue = 0;
+
+			// add visible nodes found by the visibility culling algorithm
+			if (mUseDepthPass)
+			{
+				KdTree::NodeList::const_iterator it, end = mVisibleNodes.end();
+				for (it = mVisibleNodes.begin(); it != end; it++)
+				{
+					(*it)->queueVisibleObjects(mHierarchyInterface->GetFrameId(), mCameraInProgress,
+						getRenderQueue(), false, mShowBoxes);
+				}
+			}
+
+			//-- now we can render all remaining queue objects
+			//-- used for depth pass, transparents, overlay
+			clearSpecialCaseRenderQueues();
+
+			SceneManager::_renderVisibleObjects();
+		} // hierarchical culling
+
+
+		// reset ambient light
+		setAmbientLight(savedAmbient);
+
+
+		// almost same effect as below
+		getRenderQueue()->clear(mDeleteQueueAfterRendering);
+
+		//if (!mDeleteQueueAfterRendering)
+		//	getRenderQueue()->clear(true); // finally clear render queue
+		//else
+		//	OGRE_DELETE(mRenderQueue); // HACK: should rather only be cleared ...
+
+		if (0) WriteLog(); // write out stats
+	}
+}
+
+
+void KdTreeSceneManager::_renderNode(KdTree::NodePtr node, Camera * cam, 
+									 bool onlyShadowCasters, int leavePassesInQueue)
+{
+	RenderQueueGroup *currentGroup = 
+		getRenderQueue()->getQueueGroup(getRenderQueue()->getDefaultQueueGroup());
+	currentGroup->clear(leavePassesInQueue);
+
+	node->queueVisibleObjects(mHierarchyInterface->GetFrameId(), cam, getRenderQueue(),
+		onlyShadowCasters, mShowBoxes);
+	mVisibleNodes.push_back(node);
+
+	_renderQueueGroupObjects(currentGroup, QueuedRenderableCollection::OM_PASS_GROUP);
+}
+
+//-----------------------------------------------------------------------
+const Pass *KdTreeSceneManager::_setPass(const Pass* pass, bool evenIfSuppressed)
+{
+	if (mRenderMethod == KdTree::KDRM_INTERNAL)
+	{
+		return SceneManager::_setPass(pass);
+	}
+
+	// TODO: setting vertex program is not efficient
+	//Pass *usedPass = ((mIsDepthPassPhase && !pass->hasVertexProgram()) ? mDepthPass : pass); 
+
+	// set depth fill pass if we currently do not make an aabb occlusion query
+	const bool useDepthPass = 
+		(mIsDepthPassPhase && !mHierarchyInterface->IsBoundingBoxQuery());
+
+	const IlluminationRenderStage savedStage = mIlluminationStage; 
+
+	// set illumination stage to NONE so no shadow material is used 
+	// for depth pass or for occlusion query
+	if (mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery())
+	{
+		mIlluminationStage = IRS_NONE;
+	}
+
+	// --- set vertex program of current pass in order to set correct depth
+	if (mExecuteVertexProgramForAllPasses && 
+		mIsDepthPassPhase && 
+		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()) // reset vertex program
+	{
+		mDepthPass->setVertexProgram("");
+	}
+
+	const Pass *usedPass = useDepthPass ? mDepthPass : pass;
+
+	// save old depth write: needed for item buffer
+	const bool IsDepthWrite = usedPass->getDepthWriteEnabled();
+
+	// global option which enables / disables depth writes
+	if (!mEnableDepthWrite)
+	{
+		//	usedPass->setDepthWriteEnabled(false);
+	}
+	//else if (mIsItemBufferPass) {usedPass = mItemBufferPass;}
+
+
+	//-- set actual pass here
+	const Pass *result = SceneManager::_setPass(usedPass);
+
+
+	// reset depth write
+	if (!mEnableDepthWrite)
+	{
+		//	usedPass->setDepthWriteEnabled(IsDepthWrite);
+	}
+
+	// reset illumination stage
+	mIlluminationStage = savedStage;
+
+	return result;
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup,
+													  QueuedRenderableCollection::OrganisationMode om)
+{
+	// 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
+		renderObjects(pPriorityGrp->getSolidsBasic(), om, true);
+
+		// for correct rendering, transparents must be rendered after hierarchical culling
+		// => do nothing
+
+		// Do transparents (always descending)
+		if (mRenderMethod == KdTree::KDRM_INTERNAL || !mSkipTransparents)
+		{
+			renderObjects(pPriorityGrp->getTransparents(), 
+				QueuedRenderableCollection::OM_SORT_DESCENDING, true);
+		}
+
+
+	}// for each priority
+}
+//-----------------------------------------------------------------------
+bool KdTreeSceneManager::validatePassForRendering(Pass* pass)
+{
+	if (mRenderMethod == KdTree::KDRM_INTERNAL)
+	{
+		return SceneManager::validatePassForRendering(pass);
+	}
+
+	// skip all but first pass if we are doing the depth pass
+	if ((mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() > 0))
+	{
+		return false;
+	}
+	// all but first pass
+	/*else if ((!mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() != 0))
+	{
+	return false;
+	}*/
+
+	return SceneManager::validatePassForRendering(pass);
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::_renderQueueGroupObjects(RenderQueueGroup* pGroup, 
+												  QueuedRenderableCollection::OrganisationMode om)
+{
+	if (mRenderMethod == KdTree::KDRM_INTERNAL || !mIsItemBufferPhase)
+	{
+		SceneManager::_renderQueueGroupObjects(pGroup, om);
+		return;
+	}
+#ifdef  ITEM_BUFFER
+	//-- item buffer
+	//-- item buffer: render objects using false colors
+
+	// Iterate through priorities
+	RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+	while (groupIt.hasMoreElements())
+	{
+		RenderItemBuffer(groupIt.getNext());
+	}
+#endif // ITEM_BUFFER
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(
+	RenderQueueGroup* pGroup, QueuedRenderableCollection::OrganisationMode om)
+{
+	// only render solid passes during hierarchical culling
+	if (mIsHierarchicalCulling)
+	{
+		RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+		LightList lightList;
+
+		while (groupIt.hasMoreElements())
+		{
+			RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+			// Sort the queue first
+			pPriorityGrp->sort(mCameraInProgress);
+
+			// Clear light list
+			lightList.clear();
+
+			// Render all the ambient passes first, no light iteration, no lights
+			/*** msz: no more IRS_AMBIENT, see OgreSceneManager.h ***/
+			// mIlluminationStage = IRS_AMBIENT;
+
+			SceneManager::renderObjects(pPriorityGrp->getSolidsBasic(), om, false, &lightList);
+			// Also render any objects which have receive shadows disabled
+			SceneManager::renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, true);
+		}
+	}
+	else // render the rest of the passes
+	{
+		SceneManager::renderAdditiveStencilShadowedQueueGroupObjects(pGroup, om);
+	}
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::renderModulativeStencilShadowedQueueGroupObjects(
+	RenderQueueGroup* pGroup, QueuedRenderableCollection::OrganisationMode om)
+{
+	if (mIsHierarchicalCulling)
+	{
+		// Iterate through priorities
+		RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+		while (groupIt.hasMoreElements())
+		{
+			RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+			// Sort the queue first
+			pPriorityGrp->sort(mCameraInProgress);
+
+			// Do (shadowable) solids
+			SceneManager::renderObjects(pPriorityGrp->getSolidsBasic(), om, true);
+		}
+	}
+	else
+	{
+		SceneManager::renderModulativeStencilShadowedQueueGroupObjects(pGroup, om);
+	}
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::InitDepthPass()
+{
+	MaterialPtr depthMat = MaterialManager::getSingleton().getByName("Visibility/DepthPass");
+
+	if (depthMat.isNull())
+	{
+		depthMat = MaterialManager::getSingleton().create(
+			"Visibility/DepthPass",
+			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+		mDepthPass = depthMat->getTechnique(0)->getPass(0);
+		mDepthPass->setColourWriteEnabled(false);
+		mDepthPass->setDepthWriteEnabled(true);
+		mDepthPass->setLightingEnabled(false);
+	}
+	else
+	{
+		mDepthPass = depthMat->getTechnique(0)->getPass(0);
+	}
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::InitItemBufferPass()
+{
+	MaterialPtr itemBufferMat = MaterialManager::getSingleton().
+		getByName("Visibility/ItemBufferPass");
+
+	if (itemBufferMat.isNull())
+	{
+		// 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);
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::PrepareVisualization(Camera *cam)
+{
+	// add player camera for visualization purpose
+	try 
+	{
+		Camera *c;
+		if ((c = getCamera("PlayerCam")) != NULL)
+		{
+			getRenderQueue()->addRenderable(c);
+		}   
+	}
+	catch (...)
+	{
+		// ignore
+	}
+
+	if (mRenderNodesForViz || mRenderNodesContentForViz)
+	{
+		RenderQueue * queue = getRenderQueue();
+		unsigned long frameid = 0;
+
+		if (mRenderMethod == KdTree::KDRM_INTERNAL)
+			frameid = Root::getSingleton().getCurrentFrameNumber();
+		else
+			frameid = mHierarchyInterface->GetFrameId();
+
+		for (KdTree::NodeList::iterator it = mVisibleNodes.begin(); it != mVisibleNodes.end(); ++it)
+		{
+			if (mRenderNodesForViz && (*it)->isLeaf())
+			{
+				WireBoundingBox * wirebox = (*it)->getWireBoundingBox();
+				wirebox->setMaterial("KdTree/BoxViz");
+				getRenderQueue()->addRenderable(wirebox);
+			}
+			// add renderables itself
+			if (mRenderNodesContentForViz) 
+			{
+				(*it)->queueVisibleObjects(frameid, cam, queue, false, false);
+			}
+		}
+	}	
+}
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::InitVisibilityCulling(Camera *cam)
+{
+	// reset culling manager stats
+	mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
+
+	// set depth pass flag before rendering
+	mIsDepthPassPhase = mUseDepthPass;
+
+	mIsHierarchicalCulling = true; // during hierarchical culling
+
+	// item buffer needs full ambient lighting to use item colors as unique id
+	if (mUseItemBuffer) 
+	{
+		mIsItemBufferPhase = 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 we have the depth pass or use an item buffer, no passes are left in the queue
+	if (1 && !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
+			/*** msz: no more IRS_AMBIENT, see OgreSceneManager.h ***/
+			// mIlluminationStage = IRS_AMBIENT; 
+			//getRenderQueue()->setSplitPassesByLightingType(true);
+		}
+
+		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 during the hierarchical culling
+	// (because they will be rendered afterwards)
+	mSkipTransparents = 
+		(mIsDepthPassPhase || (mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES));
+
+	// -- initialise interface for rendering traversal of the hierarchy
+	mHierarchyInterface->SetHierarchyRoot(mBvHierarchy->getRoot());
+
+	// possible two cameras (one for culling, one for rendering)
+	mHierarchyInterface->InitTraversal(mCameraInProgress, 
+		/*mCullCamera ? getCamera("CullCamera") : */NULL,
+		mLeavePassesInQueue);
+
+}
+
+//-------------------------------------------------------------------------
+void KdTreeSceneManager::SetObjectsVisible(const bool visible)
+{
+	GtpVisibilityPreprocessor::ObjectContainer::iterator it, it_end = mObjects.end();
+
+	for (it = mObjects.begin(); it != it_end; ++ it)
+	{
+		OgreMeshInstance *omi = static_cast<OgreMeshInstance *>(*it);
+		Entity *ent = omi->GetMesh();
+
+		ent->setVisible(visible);
+	}
+}
+//-----------------------------------------------------------------------
+bool KdTreeSceneManager::LoadViewCells(const String &filename)
+{
+	// objects are set to invisible initially
+	SetObjectsVisible(false);
+
+	const string bboxesFilename = mVisibilityManager->GetVisibilityEnvironment()->getViewCellsFileName();
+
+	// converter between view cell ids and Ogre entites 
+	GtpVisibilityPreprocessor::IndexedBoundingBoxContainer iboxes;
+	OgreBoundingBoxConverter bconverter(this);
+
+	// load the view cells assigning the found objects to the pvss
+	mViewCellsManager = 
+		GtpVisibilityPreprocessor::ViewCellsManager::LoadViewCells(filename, &mObjects, false, &bconverter);
+
+	return (mViewCellsManager != NULL);
+}
+//-------------------------------------------------------------------------
+void KdTreeSceneManager::applyViewCellPvs(GtpVisibilityPreprocessor::ViewCell *vc, 
+													const bool load)
+{	// NOTE: should not happen, rather apply view cell representing unbounded space then
+	if (!vc) 
+	{	
+		// set everything visible for savety
+		SetObjectsVisible(true);
+
+		return;
+	}
+
+	GtpVisibilityPreprocessor::ObjectPvsMap::const_iterator oit,
+		oit_end = vc->GetPvs().mEntries.end();
+
+	//-- PVS of view cell
+	for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
+	{
+		if (!(*oit).first) continue;
+
+		OgreMeshInstance *omi = dynamic_cast<OgreMeshInstance *>((*oit).first);
+		omi->GetMesh()->setVisible(load);
+		//GtpVisibilityPreprocessor::Debug << "assigned id " << omi->GetId() << endl;
+	}
+}
+//-------------------------------------------------------------------------
+void KdTreeSceneManager::updatePvs(Camera *cam)
+{
+	if (!(mViewCellsLoaded && mUseViewCells))
+		return;
+
+	const GtpVisibilityPreprocessor::Vector3 viewPoint = 
+		OgreTypeConverter::ConvertFromOgre(cam->getDerivedPosition());
+
+	GtpVisibilityPreprocessor::ViewCell *newElementary = 
+		mViewCellsManager->GetViewCell(viewPoint);
+
+	// elementary view cell did not change => apply same pvs
+	if (mElementaryViewCell == newElementary)
+		return;
+
+	mElementaryViewCell = newElementary;
+	//LogManager::getSingleton().logMessage("unloading");
+	//-- unload old pvs
+	applyViewCellPvs(mCurrentViewCell, false);
+
+
+	//-- the new view cell
+
+	GtpVisibilityPreprocessor::ViewCell *viewCell;
+
+
+	if (mUseVisibilityFilter)
+	{
+		//-- compute new filtered cell
+		GtpVisibilityPreprocessor::PrVs prvs;
+		mViewCellsManager->GetPrVS(viewPoint, prvs, 5);
+		viewCell = prvs.mViewCell;
+	}
+	else
+	{
+		viewCell = newElementary;
+	}
+	//LogManager::getSingleton().logMessage("loading");
+	//-- load new pvs
+	applyViewCellPvs(viewCell, true);
+
+	// store pvs
+	mCurrentViewCell->SetPvs(viewCell->GetPvs());
+
+	// delete merge tree of filtered view cell
+	if (mUseVisibilityFilter)
+		mViewCellsManager->DeleteLocalMergeTree(viewCell);
+}
+
+//-----------------------------------------------------------------------
+void KdTreeSceneManager::WriteLog()
+{
+	std::stringstream d;
+
+	d << "Depth pass: " << StringConverter::toString(mUseDepthPass) << ", "
+		<< "Delay transparents: " << StringConverter::toString(mDelayRenderTransparents) << ", "
+		<< "Use optimization: " << StringConverter::toString(mHierarchyInterface->GetTestGeometryForVisibleLeaves()) << ", "
+		<< "Algorithm type: " << mVisibilityManager->GetCullingManagerType() << ", "
+		<< "Hierarchy nodes: " << (mBvHierarchy ? mBvHierarchy->getTreeStats().mNumNodes : 0) << ", " 
+		<< "Traversed nodes: " << mHierarchyInterface->GetNumTraversedNodes() << ", "
+		<< "Rendered nodes: " << mHierarchyInterface->GetNumRenderedNodes() << ", "
+		<< "Query culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes() << ", "
+		<< "Frustum culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes() << ", "
+		<< "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << ", "
+		<< "Found objects: " << (int)mVisibleNodes.size() << "\n"
+		;
+
+	LogManager::getSingleton().logMessage(d.str());
+}
+
+/************************************************************************/
+/* Factory for KdTreeSceneManager                                       */
+/************************************************************************/
+//-----------------------------------------------------------------------
+//-----------------------------------------------------------------------
+const String BvHierarchySceneManagerFactory::FACTORY_TYPE_NAME = "KdTreeSceneManager";
+//-----------------------------------------------------------------------
+void BvHierarchySceneManagerFactory::initMetaData(void) const
+{
+	mMetaData.typeName = FACTORY_TYPE_NAME;
+	mMetaData.description = "Scene manager that organises the scene based on a kd-tree";
+	mMetaData.sceneTypeMask = 0xFFFF; // support all types of scenes (hopefully)
+	mMetaData.worldGeometrySupported = false;
+}
+//-----------------------------------------------------------------------
+SceneManager* BvHierarchySceneManagerFactory::createInstance(
+	const String& instanceName)
+{
+	return new KdTreeSceneManager(instanceName, visManager);
+}
+//-----------------------------------------------------------------------
+void BvHierarchySceneManagerFactory::destroyInstance(SceneManager* instance)
+{
+	delete instance;
+}
+
+} // namespace Ogre
+
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/misc/OgreBvHierarchySceneManager.def
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/misc/OgreBvHierarchySceneManager.def	(revision 1318)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/misc/OgreBvHierarchySceneManager.def	(revision 1318)
@@ -0,0 +1,4 @@
+LIBRARY Plugin_VisibilitySceneManager
+EXPORTS	
+	dllStartPlugin
+	dllStopPlugin
