Index: GTP/trunk/Lib/Vis/Preprocessing/src/run_test2
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/run_test2	(revision 1900)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/run_test2	(revision 1942)
@@ -2,5 +2,5 @@
 
 #COMMAND="./release/preprocessor.exe -preprocessor_quit_on_finish+"
-COMMAND="../scripts/preprocessor.sh -preprocessor_quit_on_finish+ -preprocessor_use_gl_renderer- -preprocessor_evaluate_filter-"
+COMMAND="../scripts/preprocessor.sh -preprocessor_quit_on_finish+ -preprocessor_use_gl_renderer- -preprocessor_evaluate_filter+"
 
 #SCENE="../data/vienna/vienna-buildings.x3d;../data/vienna/vienna-roofs.x3d;../data/vienna/vienna-roads.x3d"
@@ -65,7 +65,12 @@
 
 $COMMAND -scene_filename=$SCENE -view_cells_filename=$VIEWCELLS \
--rss_distributions=object_direction+spatial+object+direction -view_cells_filter_max_size=1 \
--preprocessor_stats=$PREFIX-i-mixed-b1-n225678.log \
--preprocessor_histogram_file=$PREFIX-i-mixed-b1-n225678.hlog
+-rss_distributions=rss+object_direction+spatial+object+direction -view_cells_filter_max_size=1 \
+-preprocessor_stats=$PREFIX-i-mixed-b1-n4.log \
+-preprocessor_histogram_file=$PREFIX-i-mixed-b1-n4.hlog
+
+# $COMMAND -scene_filename=$SCENE -view_cells_filename=$VIEWCELLS \
+# -rss_distributions=rss+object_direction+spatial+object+direction -view_cells_filter_max_size=1 \
+# -preprocessor_stats=$PREFIX-i-mixed-b1-n2.log \
+# -preprocessor_histogram_file=$PREFIX-i-mixed-b1-n2.hlog
 
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 1932)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 1942)
@@ -81,5 +81,11 @@
 {
 public:
-	struct PvsStatistics 
+
+  struct PerViewCellStat {
+	float pvsSize;
+	float relPvsIncrease;
+  };
+  
+  struct PvsStatistics 
 	{
 	  float minPvs;
@@ -90,8 +96,9 @@
 	  float avgFilterRadius;
 	  float avgFilterRatio;
+	  float avgRelPvsIncrease;
+	  float devRelPvsIncrease;
 	  int viewcells;
-	  
 	};
-
+  
 	/// view cell container types
 	enum {BSP, KD, VSP_KD, VSP_BSP, VSP_OSP};
@@ -789,4 +796,8 @@
 	/// if view cells geometry should be used from other sources
 	bool mUsePredefinedViewCells;
+
+  
+  vector<PerViewCellStat> mPerViewCellStat;
+
 };
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Ray.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Ray.h	(revision 1883)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Ray.h	(revision 1942)
@@ -93,5 +93,5 @@
     mType = _type;
     depth = 0;
-		Init();
+	Init();
   }
   // dummy constructor
@@ -239,5 +239,8 @@
 
   Vector3 GetInvDir() const { return invDir; }
-  
+
+  // precompute some values that are necessary
+  void Precompute();
+
 private:
   Vector3 loc, dir;		// Describes ray origin and vector
@@ -271,6 +274,4 @@
   void Init();
 
-  // precompute some values that are necessary
-  void Precompute();
 
   friend class AxisAlignedBox3;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.h	(revision 1932)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.h	(revision 1942)
@@ -98,4 +98,10 @@
         			 const AxisAlignedBox3 &box,
 					 Intersection &hit);
+
+  bool
+  ClipToViewSpaceBox(const Vector3 &origin,
+					 const Vector3 &termination,
+					 Vector3 &clippedOrigin,
+					 Vector3 &clippedTermination);
 	
   	const Preprocessor &mPreprocessor;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 1934)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 1942)
@@ -1742,15 +1742,15 @@
 	RegisterOption("Preprocessor.loadMeshes",
 					optBool,
-					"preprocessor_load_meshes=",
+					"preprocessor_load_meshes",
 					"true");
 
 	RegisterOption("Preprocessor.evaluateFilter",
 				   optBool,
-				   "preprocessor_evaluate_filter=",
+				   "preprocessor_evaluate_filter",
 				   "false");
 
 	RegisterOption("Preprocessor.delayVisibilityComputation",
 				   optBool,
-				   "preprocessor_delay_computation=",
+				   "preprocessor_delay_computation",
 				   "true");
 
@@ -1762,30 +1762,30 @@
 	RegisterOption("Preprocessor.useGlRenderer",
 					optBool,
-					"preprocessor_use_gl_renderer=",
+					"preprocessor_use_gl_renderer",
 					"false");
 
 	RegisterOption("Preprocessor.useGlDebugger",
 					optBool,
-					"preprocessor_use_gl_debugger=",
+					"preprocessor_use_gl_debugger",
 					"false");
 
 	RegisterOption("Preprocessor.detectEmptyViewSpace",
 				   optBool,
-				   "preprocessor_detect_empty_viewspace=",
+				   "preprocessor_detect_empty_viewspace",
 				   "false");
 	
 	RegisterOption("Preprocessor.quitOnFinish",
 				   optBool,
-				   "preprocessor_quit_on_finish=",
+				   "preprocessor_quit_on_finish",
 				   "true");
 
 	RegisterOption("Preprocessor.computeVisibility",
 				   optBool,
-				   "preprocessor_compute_visibility=",
+				   "preprocessor_compute_visibility",
 				   "true");
 
 	RegisterOption("Preprocessor.exportVisibility",
 				   optBool,
-				   "preprocessor_export_visibility=",
+				   "preprocessor_export_visibility",
 				   "true");
 
@@ -1797,10 +1797,10 @@
 	RegisterOption("Preprocessor.applyVisibilityFilter",
 				   optBool,
-				   "preprocessor_apply_filter=",
+				   "preprocessor_apply_filter",
 				   "false");
 	
 	RegisterOption("Preprocessor.applyVisibilitySpatialFilter",
 				   optBool,
-				   "preprocessor_apply_spatial_filter=",
+				   "preprocessor_apply_spatial_filter",
 				   "false");
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/PreprocessorFactory.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/PreprocessorFactory.cpp	(revision 1891)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/PreprocessorFactory.cpp	(revision 1942)
@@ -49,4 +49,5 @@
 	}
 
+
 	return NULL;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.cpp	(revision 1940)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.cpp	(revision 1942)
@@ -10,6 +10,16 @@
 #include "KdTree.h"
 #include "Environment.h"
+#include "RssPreprocessor.h"
+#include "RssTree.h"
+#include "Trackball.h"
+#include "QtPreprocessorThread.h"
+
+#define USE_CG 1
+
+
+#if USE_CG
 #include <Cg/cg.h>
 #include <Cg/cgGL.h>
+#endif
 
 #include <QVBoxLayout>
@@ -17,15 +27,14 @@
 namespace GtpVisibilityPreprocessor {
 
+
+  
 class ViewCellsManager;
 
 static CGcontext sCgContext = NULL;
 static CGprogram sCgFragmentProgram = NULL;
-static CGprogram sCgDepthPeelingProgram = NULL;
 static CGprofile sCgFragmentProfile;
 
-static GLuint frontDepthMap;
-static GLuint backDepthMap;
-
-const int depthMapSize = 512;
+
+//static vector<OcclusionQuery *> sQueries;
 
 QtGlRendererWidget *rendererWidget = NULL;
@@ -38,5 +47,5 @@
 }
 
-
+#if USE_CG
 static void handleCgError() 
 {
@@ -44,149 +53,18 @@
     exit(1);
 }
-
-void
-QtGlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
-										 const bool useOcclusionQueries,
-										 const int threshold
-										 )
-{
-	// choose a random view point
-	mViewCellsManager->GetViewPoint(mViewPoint);
-	sample.mPosition = mViewPoint;
-
-	// take a render cost sample by rendering a cube
-	Vector3 directions[6];
-
-	directions[0] = Vector3(1,0,0);
-	directions[1] = Vector3(0,1,0);
-	directions[2] = Vector3(0,0,1);
-	directions[3] = Vector3(-1,0,0);
-	directions[4] = Vector3(0,-1,0);
-	directions[5] = Vector3(0,0,-1);
-
-	sample.mVisibleObjects = 0;
-
-	// reset object counters
-	ObjectContainer::const_iterator it, it_end = mObjects.end();
-
-	for (it = mObjects.begin(); it != it_end; ++ it) 
-	{
-		(*it)->mCounter = 0;
-	}
-
-	++ mFrame;
-
-	//glCullFace(GL_FRONT);
-	glCullFace(GL_BACK);
-	glDisable(GL_CULL_FACE);
-	
-
-	// query all 6 directions for a full point sample
-	for (int i = 0; i < 6; ++ i) 
-	{
-		mViewDirection = directions[i];
-		SetupCamera();
-
-		glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
-		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-		//glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);	glDepthMask(GL_TRUE);
-		glDepthFunc(GL_LESS);
-
-		mUseFalseColors = true;
-
-		// the actual scene rendering fills the depth (for occlusion queries)
-		// and the frame buffer (for item buffer)
-		RenderScene();
-
-
-		if (0) 
-		{
-			char filename[256];
-			sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
-			QImage im = toImage();
-			im.save(filename, "PNG");
-		}
-         
-		// evaluate the sample
-		if (useOcclusionQueries) 
-		{
-			EvalQueryWithOcclusionQueries();
-		}
-		else 
-		{
-			EvalQueryWithItemBuffer();
-		}
-	}  
-
-	// now evaluate the statistics over that sample
-	// currently only the number of visible objects is taken into account
-	sample.Reset();
-
-	for (it = mObjects.begin(); it != it_end; ++ it) 
-	{
-		Intersectable *obj = *it;
-		if (obj->mCounter >= threshold) 
-		{
-			++ sample.mVisibleObjects;
-			sample.mVisiblePixels += obj->mCounter;
-		}
-	}
-
-	//cout << "RS=" << sample.mVisibleObjects << " ";
-}
-
-
-QtGlRendererBuffer::~QtGlRendererBuffer()
-{
-	if (sCgFragmentProgram)
-		cgDestroyProgram(sCgFragmentProgram);
-	if (sCgDepthPeelingProgram)
-		cgDestroyProgram(sCgDepthPeelingProgram);
-	if (sCgContext)
-		cgDestroyContext(sCgContext);
-}
-
-
-void
-QtGlRendererBuffer::SampleRenderCost(const int numSamples,
-									 vector<RenderCostSample> &samples,
-									 const bool useOcclusionQueries,
-									 const int threshold
-									 )
+#endif
+
+void
+QtGlRendererBuffer::MakeCurrent()
 {
   makeCurrent();
-
-  if (mPixelBuffer == NULL)
-	  mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
-  
-  // using 90 degree projection to capture 360 view with 6 samples
-  SetupProjection(GetHeight(), GetHeight(), 90.0f);
-
-  //samples.resize(numSamples);
-  halton.Reset();
-  
-  // the number of queries queried in batch mode
-  const int numQ = 500;
-
-  //const int numQ = (int)mObjects.size();
-  if (useOcclusionQueries)
-  {
-	  cout << "\ngenerating " << numQ << " queries ... ";
-	  OcclusionQuery::GenQueries(mOcclusionQueries, numQ);
-	  cout << "finished" << endl;
-  }
-
-  // sampling queries 
-  for (int i = 0; i < numSamples; ++ i)
-  {
-	  cout << ".";
-	  EvalRenderCostSample(samples[i], useOcclusionQueries, threshold);
-  }
-
+}
+
+void
+QtGlRendererBuffer::DoneCurrent()
+{
   doneCurrent();
-
-}
-  
-
+}
+  
 
 QtGlRendererBuffer::QtGlRendererBuffer(const int w,
@@ -196,693 +74,188 @@
 									   KdTree *tree):
   QGLPixelBuffer(QSize(w, h)),
-GlRendererBuffer(sceneGraph, viewcells, tree) {
- 
-  Environment::GetSingleton()->GetIntValue("Preprocessor.pvsRenderErrorSamples", mPvsStatFrames);
-  mPvsErrorBuffer.resize(mPvsStatFrames);
-  ClearErrorBuffer();
-
-  mPixelBuffer = NULL;
-  
-  makeCurrent();
+  //QGLWidget(NULL, w, h),
+  GlRendererBuffer(sceneGraph, viewcells, tree)
+{
+  MakeCurrent();
   InitGL();
-  doneCurrent();
-  
-}
+  DoneCurrent();
+}
+
+
 
 float
 QtGlRendererBuffer::GetPixelError(int &pvsSize)
 {
-	float pErrorPixels = -1.0f;
-
-	glReadBuffer(GL_BACK);
-
-	mUseFalseColors = false;
-	unsigned int pixelCount;
-
-	OcclusionQuery query;
-
-	if (mDetectEmptyViewSpace) 
-	{
-		// now check whether any backfacing polygon would pass the depth test
-		SetupCamera();
-		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-		glEnable( GL_CULL_FACE );
-
-		RenderScene();
-
-		glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
-		glDepthMask(GL_FALSE);
-		glDisable( GL_CULL_FACE );
-
-
-		query.BeginQuery();
-
-		RenderScene();
-
-		query.EndQuery();
-
-		// at this point, if possible, go and do some other computation
-		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-		glDepthMask(GL_TRUE);
-		glEnable( GL_CULL_FACE );
-
-		// reenable other state
-		pixelCount = query.GetQueryResult();
-
-		if (pixelCount > 0)
-			return -1.0f; // backfacing polygon found -> not a valid viewspace sample
-	} 
-	else
-	{
-		glDisable( GL_CULL_FACE );
-	}
-
-	ViewCell *viewcell = NULL;
-
-	PrVs prvs;
-
-	mViewCellsManager->SetMaxFilterSize(0);
-	mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
-	viewcell = prvs.mViewCell;
-
-	// ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
-	pvsSize = 0;
-	if (viewcell) 
-	{
-		SetupCamera();
-		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
-		glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
-
-		// Render PVS
-		ObjectPvsIterator pit = viewcell->GetPvs().GetIterator();
-
-		while (pit.HasMoreEntries())
-		{		
-			const ObjectPvsEntry &entry = pit.Next();
-			Intersectable *obj = entry.mObject;
-
-			RenderIntersectable(obj);
-		}
-
-		// glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
-		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-		mUseFalseColors = true;
-
-		query.BeginQuery();
-
-		SetupCamera();
-
-		RenderScene();
-
-		query.EndQuery();
-
-		unsigned int pixelCount;
-		// reenable other state
-		pixelCount = query.GetQueryResult();
-
-		pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
-		if (mSnapErrorFrames && pErrorPixels > 0.01) 
-		{
-            char filename[256];
-
-			sprintf(filename, "error-frame-%04d-%0.5f.png", mFrame, pErrorPixels);
-			QImage im = toImage();
-			string str = mSnapPrefix + filename;
-			QString qstr(str.c_str());
-
-			im.save(qstr, "PNG");
-			if (1) 
-			{
-				int x,y;
-				int lastIndex = -1;
-				for (y=0; y < im.height(); y++)
-				{
-					for (x=0; x < im.width(); x++) 
-					{
-						QRgb p = im.pixel(x,y);
-
-						int index = qRed(p) + (qGreen(p)<<8) + (qBlue(p)<<16);
-						
-						if (qGreen(p) != 255 && index!=0) 
-						{
-							if (index != lastIndex) 
-							{
-								lastIndex = index;
-							}
-						}
-					}
-				}
+  float pErrorPixels = -1.0f;
+  
+  glReadBuffer(GL_BACK);
+  
+  //  mUseFalseColors = true;
+  
+  mUseFalseColors = false;
+  unsigned int pixelCount;
+
+  //static int query = -1;
+  //if (query == -1)
+  //	  glGenOcclusionQueriesNV(1, (unsigned int *)&query);
+
+  OcclusionQuery query;
+
+  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
+  if (viewcell == NULL)
+	return 0.0f;
+
+  if (mDetectEmptyViewSpace) {
+	// now check whether any backfacing polygon would pass the depth test
+	SetupCamera();
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+	glEnable( GL_CULL_FACE );
+	glCullFace(GL_BACK);
+
+	cout<<"RS ";
+	RenderScene();
+	
+	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+	glDepthMask(GL_FALSE);
+	glDisable( GL_CULL_FACE );
+
+	query.BeginQuery();
+	
+	cout<<"RS ";
+	RenderScene();
+	cout<<"RS3 ";
+	
+	query.EndQuery();
+	
+	// at this point, if possible, go and do some other computation
+	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+	glDepthMask(GL_TRUE);
+	glEnable( GL_CULL_FACE );
+	
+	// reenable other state
+	pixelCount = query.GetQueryResult();
+	cout<<"RS4 ";
+	
+	if (pixelCount > 0)
+	  return -1.0f; // backfacing polygon found -> not a valid viewspace sample
+
+  } else
+	glDisable( GL_CULL_FACE );
+	
+
+  //  ViewCell *viewcell = NULL;
+  
+  //  PrVs prvs;
+  
+  //  mViewCellsManager->SetMaxFilterSize(0);
+  //  mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
+  //  viewcell = prvs.mViewCell;
+  
+  ObjectPvs pvs;
+  if (1) {
+	pvs = viewcell->GetPvs();
+  } else {
+	mViewCellsManager->ApplyFilter2(viewcell,
+									false,
+									1.0f,
+									pvs);
+  }
+  
+  SetupCamera();
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
+  
+  
+  // 	// Render PVS
+  ObjectPvsIterator it = pvs.GetIterator();
+  
+  pvsSize = pvs.GetSize();
+  Intersectable::NewMail();
+  for (; it.HasMoreEntries(); ) {
+	ObjectPvsEntry entry = it.Next();
+	Intersectable *object = entry.mObject;
+	RenderIntersectable(object);
+  }
+  
+  //	glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
+  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+  
+  mUseFalseColors = true;
+  
+  query.BeginQuery();
+  
+  SetupCamera();
+  
+  RenderScene();
+  
+  query.EndQuery();
+  
+  
+  // reenable other state
+  pixelCount = query.GetQueryResult();
+  
+  
+  pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
+
+  
+  if (mSnapErrorFrames && pErrorPixels > 0.001f) {
+	
+	char filename[256];
+	sprintf(filename, "error-frame-%04d-%0.5f.png", mFrame, pErrorPixels);
+	QImage im = toImage();
+	string str = mSnapPrefix + filename;
+	QString qstr(str.c_str());
+	
+	im.save(qstr, "PNG");
+	if (1) { //0 && mFrame == 1543) {
+	  int x,y;
+	  int lastIndex = -1;
+	  for (y=0; y < im.height(); y++)
+		for (x=0; x < im.width(); x++) {
+		  QRgb p = im.pixel(x,y);
+		  int index = qRed(p) + (qGreen(p)<<8) + (qBlue(p)<<16);
+		  if (qGreen(p) != 255 && index!=0) {
+			if (index != lastIndex) {
+			  //				Debug<<"ei="<<index<<" ";
+			  lastIndex = index;
 			}
-
-			mUseFalseColors = false;
-			glPushAttrib(GL_CURRENT_BIT);
-			glColor3f(0,1,0);
-			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-			SetupCamera();
-			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
-			// Render PVS
-			ObjectPvsIterator pit = viewcell->GetPvs().GetIterator();
-
-			while (pit.HasMoreEntries())
-			{		
-				const ObjectPvsEntry &entry = pit.Next();
-				Intersectable *obj = entry.mObject;
-
-				RenderIntersectable(obj);
-			}
-
-			im = toImage();
-			sprintf(filename, "error-frame-%04d-%0.5f-pvs.png", mFrame, pErrorPixels);
-			str = mSnapPrefix + filename;
-			qstr = str.c_str();
-			im.save(qstr, "PNG");
-			glPopAttrib();
-		}
-		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-	}
-
-	if (viewcell && mViewCellsManager->GetMaxFilterSize() > 0)
-		mViewCellsManager->DeleteLocalMergeTree(viewcell);
-
-	return pErrorPixels;
-}
-
-
-void
-QtGlRendererBuffer::ClearErrorBuffer()
-{
-  for (int i=0; i < mPvsStatFrames; i++) {
-	mPvsErrorBuffer[i].mError = 1.0f;
-  }
-}
-
-
-void
-QtGlRendererBuffer::EvalPvsStat()
-{
-  mPvsStat.Reset();
-  halton.Reset();
-
-  makeCurrent();
-
-
-  SetupProjection(GetWidth(), GetHeight());
-
-  
-  for (int i=0; i < mPvsStatFrames; i++) {
-	float err;
-	// set frame id for saving the error buffer
-	mFrame = i;
-	RandomViewPoint();
-
-	// atlanta problematic frames: 325 525 691 1543
-#if 0
-	if (mFrame != 325 &&
-		mFrame != 525 &&
-		mFrame != 691 &&
-		mFrame != 1543)
-	  mPvsErrorBuffer[i] = -1;
-	else {
-	  Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
-	}
-#endif
-	if (mPvsErrorBuffer[i].mError > 0.0f) {
-	  int pvsSize;
-
-
-	  float error = GetPixelError(pvsSize);
-	  mPvsErrorBuffer[i].mError = error;
-	  mPvsErrorBuffer[i].mPvsSize = pvsSize;
-
-	  emit UpdatePvsErrorItem(i,
-							  mPvsErrorBuffer[i]);
-	  
-	  cout<<"("<<i<<","<<mPvsErrorBuffer[i].mError<<")";
-	  //	  swapBuffers();
-	}
-	
-	err = mPvsErrorBuffer[i].mError;
-	
-	if (err >= 0.0f) {
-	  if (err > mPvsStat.maxError)
-		mPvsStat.maxError = err;
-	  mPvsStat.sumError += err;
-	  mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
-	  
-	  if (err == 0.0f)
-		mPvsStat.errorFreeFrames++;
-	  mPvsStat.frames++;
-	}
-  }
-
-  glFinish();
-  doneCurrent();
-
-  cout<<endl<<flush;
-  //  mRenderingFinished.wakeAll();
-}
-
-
-
-
-
-
-
-void QtGlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
-											   Beam &beam,
-											   const int desiredSamples,
-											   BeamSampleStatistics &stat)
-{
-	// TODO: should be moved out of here (not to be done every time)
-	// only back faces are interesting for the depth pass
-	glShadeModel(GL_FLAT);
-	glDisable(GL_LIGHTING);
-
-	// needed to kill the fragments for the front buffer
-	glEnable(GL_ALPHA_TEST);
-	glAlphaFunc(GL_GREATER, 0);
-
-	// assumes that the beam is constructed and contains kd-tree nodes
-	// and viewcells which it intersects
-  
-  
-	// Get the number of viewpoints to be sampled
-	// Now it is a sqrt but in general a wiser decision could be made.
-	// The less viewpoints the better for rendering performance, since less passes
-	// over the beam is needed.
-	// The viewpoints could actually be generated outside of the bounding box which
-	// would distribute the 'efective viewpoints' of the object surface and thus
-	// with a few viewpoints better sample the viewpoint space....
-
-	//TODO: comment in
-	//int viewPointSamples = sqrt((float)desiredSamples);
-	int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
-	
-	// the number of direction samples per pass is given by the number of viewpoints
-	int directionalSamples = desiredSamples / viewPointSamples;
-	
-	Debug << "directional samples: " << directionalSamples << endl;
-	for (int i = 0; i < viewPointSamples; ++ i) 
-	{
-		Vector3 viewPoint = beam.mBox.GetRandomPoint();
-		
-		// perhaps the viewpoint should be shifted back a little bit so that it always lies
-		// inside the source object
-		// 'ideally' the viewpoints would be distributed on the soureObject surface, but this
-        // would require more complicated sampling (perhaps hierarchical rejection sampling of
-		// the object surface is an option here - only the mesh faces which are inside the box
-		// are considered as candidates) 
-		
-		SampleViewpointContributions(sourceObject,
-									 viewPoint,
-									 beam,
-									 directionalSamples,
-									 stat);
-	}
-
-
-	// note:
-	// this routine would be called only if the number of desired samples is sufficiently
-	// large - for other rss tree cells the cpu based sampling is perhaps more efficient
-	// distributing the work between cpu and gpu would also allow us to place more sophisticated
-	// sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
-	// in order that thios scheme is working well the gpu render buffer should run in a separate
-	// thread than the cpu sampler, which would not be such a big problem....
-
-	// disable alpha test again
-	glDisable(GL_ALPHA_TEST);
-}
-
-
-
-void QtGlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
-													  const Vector3 viewPoint,
-													  Beam &beam,
-													  const int samples,
-													  BeamSampleStatistics &stat)
-{
-    // 1. setup the view port to match the desired samples
-	glViewport(0, 0, samples, samples);
-
-	// 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
-	SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
-
-
-	// 3. reset z-buffer to 0 and render the source object for the beam
-	//    with glCullFace(Enabled) and glFrontFace(GL_CW)
-	//    save result to the front depth map
-	//    the front depth map holds ray origins
-
-
-	// front depth buffer must be initialised to 0
-	float clearDepth;
-	
-	glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
-	glClearDepth(0.0f);
-	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
-
-
-	//glFrontFace(GL_CW);
-	glEnable(GL_CULL_FACE);
-	glCullFace(GL_FRONT);
-	glColorMask(0, 0, 0, 0);
-	
-
-	// stencil is increased where the source object is located
-	glEnable(GL_STENCIL_TEST);	
-	glStencilFunc(GL_ALWAYS, 0x1, 0x1);
-	glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
-
-
-#if 0
-	static int glSourceObjList = -1;	 
-	if (glSourceObjList != -1) 
-	{
-		glSourceObjList = glGenLists(1);
-		glNewList(glSourceObjList, GL_COMPILE);
-
-		RenderIntersectable(sourceObject);
-	
-		glEndList();
-	}
-	glCallList(glSourceObjList);
-
-#else
-	RenderIntersectable(sourceObject);
-
-#endif	
-
-	 // copy contents of the front depth buffer into depth texture
-	glBindTexture(GL_TEXTURE_2D, frontDepthMap);	
-	glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
-
-
-	// reset clear function
-	glClearDepth(clearDepth);
-
-	
-	
-	// 4. set up the termination depth buffer (= standard depth buffer)
-	//    only rays which have non-zero entry in the origin buffer are valid since
-	//    they realy start on the object surface (this is tagged by setting a
-	//    stencil buffer bit at step 3).
-	
-	glStencilFunc(GL_EQUAL, 0x1, 0x1);
-	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
-
-	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-	glDepthMask(1);
-
-	glEnable(GL_DEPTH_TEST);
-		
-	glEnable(GL_CULL_FACE);
-	glCullFace(GL_BACK);
-
-	// setup front depth buffer
-	glEnable(GL_TEXTURE_2D);
-	
-	// bind pixel shader implementing the front depth buffer functionality
-	cgGLBindProgram(sCgFragmentProgram);
-	cgGLEnableProfile(sCgFragmentProfile);
-
-
-	// 5. render all objects inside the beam 
-	//    we can use id based false color to read them back for gaining the pvs
-
-	glColorMask(1, 1, 1, 1);
-
-	
-	// if objects not stored in beam => extract objects
-	if (beam.mFlags & !Beam::STORE_OBJECTS)
-	{
-		vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
-
-		Intersectable::NewMail();
-		for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
-		{
-			mKdTree->CollectObjects(*it, beam.mObjects);
+		  }
 		}
 	}
-
-
-	//    (objects can be compiled to a gl list now so that subsequent rendering for
-	//    this beam is fast - the same hold for step 3)
-	//    Afterwards we have two depth buffers defining the ray origin and termination
-	
-
-#if 0
-	static int glObjList = -1; 
-	if (glObjList != -1) 
-	{
-		glObjList = glGenLists(1);
-		glNewList(glObjList, GL_COMPILE);
-	
-		ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
-		for (it = beam.mObjects.begin(); it != it_end; ++ it)
-		{
-			// render all objects except the source object
-			if (*it != sourceObject)
-				RenderIntersectable(*it);
-		}
-		
-		glEndList();
+	
+	
+	mUseFalseColors = false;
+	glPushAttrib(GL_CURRENT_BIT);
+	glColor3f(0,1,0);
+	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+	SetupCamera();
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+	
+	// Render PVS
+	Intersectable::NewMail();
+
+	ObjectPvsIterator it = pvs.GetIterator();
+	for (; it.HasMoreEntries(); ) {
+	  ObjectPvsEntry entry = it.Next();
+	  Intersectable *object = entry.mObject;
+	  RenderIntersectable(object);
 	}
-
-	glCallList(glObjList);
-#else
-	ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
-	for (it = beam.mObjects.begin(); it != it_end; ++ it)
-	{	
-		// render all objects except the source object
-		if (*it != sourceObject)
-			RenderIntersectable(*it);
-	}
-#endif
-	
-   
-
-	// 6. Use occlusion queries for all viewcell meshes associated with the beam ->
-	//     a fragment passes if the corresponding stencil fragment is set and its depth is
-	//     between origin and termination buffer
-
-	// create new queries if necessary
-	OcclusionQuery::GenQueries(mOcclusionQueries, (int)beam.mViewCells.size());
-
-	// check whether any backfacing polygon would pass the depth test?
-	// matt: should check both back /front facing because of dual depth buffer
-	// and danger of cutting the near plane with front facing polys.
-	
-	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
-	glDepthMask(GL_FALSE);
-	glDisable(GL_CULL_FACE);
-
-  
-	ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
-
-	int queryIdx = 0;
-
-	for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
-	{
-		mOcclusionQueries[queryIdx ++]->BeginQuery();
-
-		RenderIntersectable(*vit);
-		
-		mOcclusionQueries[queryIdx]->EndQuery();
-
-		++ queryIdx;
-	}
-
-	// at this point, if possible, go and do some other computation
-	
-	// 7. The number of visible pixels is the number of sample rays which see the source
-	//    object from the corresponding viewcell -> remember these values for later update
-	//   of the viewcell pvs - or update immediately?
-
-	queryIdx = 0;
-
-	for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
-	{
-		// fetch queries
-		unsigned int pixelCount = mOcclusionQueries[queryIdx ++]->GetQueryResult();
-
-		if (pixelCount)
-			Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
-	}
-	
-
-	// 8. Copmpute rendering statistics
-	// In general it is not neccessary to remember to extract all the rays cast. I hope it
-	// would be sufficient to gain only the intergral statistics about the new contributions
-	// and so the rss tree would actually store no new rays (only the initial ones)
-	// the subdivision of the tree would only be driven by the statistics (the glrender could
-	// evaluate the contribution entropy for example)
-	// However might be an option to extract/store only those the rays which made a contribution
-	// (new viewcell has been discovered) or relative contribution greater than a threshold ... 
-
-	ObjectContainer pvsObj;
-	stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
-	
-	// to gain ray source and termination
-	// copy contents of ray termination buffer into depth texture
-	// and compare with ray source buffer
-#if 0
-	VssRayContainer rays;
-
-	glBindTexture(GL_TEXTURE_2D, backDepthMap);	
-	glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
-
-	ComputeRays(Intersectable *sourceObj, rays);
-
-#endif
-
-	////////
-	//-- cleanup
-
-	// reset gl state
-	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-	glDepthMask(GL_TRUE);
-	glEnable(GL_CULL_FACE);
-	glDisable(GL_STENCIL_TEST);
-	cgGLDisableProfile(sCgFragmentProfile);
-	glDisable(GL_TEXTURE_2D);
-
-	// remove objects from beam
-	if (beam.mFlags & !Beam::STORE_OBJECTS)
-		beam.mObjects.clear();
-}
-
-
-void QtGlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint, 
-												   const Beam &beam, 
-												   Intersectable *sourceObject)
-{
-	float left, right, bottom, top, znear, zfar;
-
-	beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
-								   mSceneGraph->GetBox());
-
-	//Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	glFrustum(left, right, bottom, top, znear, zfar);
-	//glFrustum(-1, 1, -1, 1, 1, 20000);
-
-    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
-	const Vector3 up = 
-		Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
-
-#ifdef _DEBUG
-	Debug << "view point: " << viewPoint << endl;
-	Debug << "eye: " << center << endl;
-	Debug << "up: " << up << endl;
-#endif
-
-	glMatrixMode(GL_MODELVIEW);
-	glLoadIdentity();
-	gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z, 
-			  center.x, center.y, center.z,			  
-			  up.x, up.y, up.z);
-}		
-
-
-void QtGlRendererBuffer::InitGL()
-{
-	makeCurrent(); 
-	GlRenderer::InitGL();
-
-#if 1
-	// initialise dual depth buffer textures
-	glGenTextures(1, &frontDepthMap);
-	glBindTexture(GL_TEXTURE_2D, frontDepthMap);
-	
-	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize, 
-		depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-
-	glGenTextures(1, &backDepthMap);
-	glBindTexture(GL_TEXTURE_2D, backDepthMap);
-	
-	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize, 
-		depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-
-	// cg initialization
-	cgSetErrorCallback(handleCgError);
-	sCgContext = cgCreateContext();
-	
-	if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
-		sCgFragmentProfile = CG_PROFILE_ARBFP1;
-	else 
-	{
-	  // try FP30
-	  if (cgGLIsProfileSupported(CG_PROFILE_FP30))
-            sCgFragmentProfile = CG_PROFILE_FP30;
-	  else 
-	  {
-		  Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
-		  exit(1);
-	  }
-  }
-
-
- sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
-											   CG_SOURCE, "../src/dual_depth.cg",
-											   sCgFragmentProfile,
-											   NULL, 
-											   NULL);
-
-  if (!cgIsProgramCompiled(sCgFragmentProgram))
-	  cgCompileProgram(sCgFragmentProgram);
-
-  cgGLLoadProgram(sCgFragmentProgram);
-  cgGLBindProgram(sCgFragmentProgram);
-
-  Debug << "---- PROGRAM BEGIN ----\n" <<
-	  cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
-
-
-  sCgDepthPeelingProgram = 
-	  cgCreateProgramFromFile(sCgContext,
-							  CG_SOURCE, 
-							  "../src/depth_peeling.cg",
-							  sCgFragmentProfile,
-							  NULL, 
-							  NULL);
-
-  if (!cgIsProgramCompiled(sCgDepthPeelingProgram))
-  	  cgCompileProgram(sCgDepthPeelingProgram);
-
-  cgGLLoadProgram(sCgDepthPeelingProgram);
-  cgGLBindProgram(sCgDepthPeelingProgram);
-
-  Debug << "---- PROGRAM BEGIN ----\n" 
-	    << cgGetProgramString(sCgDepthPeelingProgram, CG_COMPILED_PROGRAM) 
-		<< "---- PROGRAM END ----\n";
-
-#endif
-  doneCurrent();
-}
-
-
-void QtGlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
-{
-	for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
-	{
-		//todo glGetTexImage()
-	}
-}
-
-
-
-int QtGlRendererBuffer::ComputePvs(ObjectContainer &objects, 
-								   ObjectContainer &pvs) const
+	
+	im = toImage();
+	sprintf(filename, "error-frame-%04d-%0.5f-pvs.png", mFrame, pErrorPixels);
+	str = mSnapPrefix + filename;
+	qstr = str.c_str();
+	im.save(qstr, "PNG");
+	glPopAttrib();
+  }
+  
+  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+  
+  return pErrorPixels;
+}
+
+int
+QtGlRendererBuffer::ComputePvs(ObjectContainer &objects, 
+							   ObjectContainer &pvs) const
 {
 	int pvsSize = 0;
@@ -924,84 +297,134 @@
 }
 
-
-
-void
-QtGlRendererWidget::SetupProjection(const int w, const int h, const float angle)
-{
-  if (!mTopView)
-	GlRenderer::SetupProjection(w, h, angle);
-  else {
-	glViewport(0, 0, w, h);
+///////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////
+
+
+
+
+
+void
+QtGlRendererWidget::SetupCameraProjection(const int w, const int h, const float angle)
+{
+  if (!mTopView) {
+	int ww = w;
+	int hh = h;
+	glViewport(0, 0, ww, hh);
 	glMatrixMode(GL_PROJECTION);
 	glLoadIdentity();
-	gluPerspective(50.0, 1.0, 0.1, 20.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
+	gluPerspective(angle, ww/(float)hh, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
 	glMatrixMode(GL_MODELVIEW);
-  }
-}
+  } else {
+	int ww = w;
+	int hh = h;
+	glViewport(0, 0, ww, hh);
+	glMatrixMode(GL_PROJECTION);
+	glLoadIdentity();
+	gluPerspective(50.0, ww/(float)hh, 0.1, 20.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
+	glMatrixMode(GL_MODELVIEW);
+  }
+}
+
+
 
 void
 QtGlRendererWidget::RenderPvs()
 {
-  SetupCamera();
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  
+	
+  Intersectable::NewMail();
+
   ViewCell *viewcell = NULL;
 
   PrVs prvs;
   
-  if (!mUseFilter) {
+  if (1 || !mUseFilter) {
 	viewcell = mViewCellsManager->GetViewCell(mViewPoint, true);
   } else {
-	  //  mViewCellsManager->SetMaxFilterSize(1);
-	  mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
-	  viewcell = prvs.mViewCell;
-  }
-
-  if (viewcell) 
-  {
-	  // copy the pvs so that it can be filtered...
-	  ObjectPvs pvs = viewcell->GetPvs();
-
+	//  mViewCellsManager->SetMaxFilterSize(1);
+	mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
+	viewcell = prvs.mViewCell;
+  }
+  
+  if (viewcell) {
+	// copy the pvs so that it can be filtered...
+	
+	//	mPvsCache.mPvs;
+	
+	if (mPvsCache.mViewCell != viewcell) {
+	  mPvsCache.Reset();
+	  mPvsCache.mViewCell = viewcell;
+	  
 	  if (mUseSpatialFilter) {
-		  mViewCellsManager->ApplySpatialFilter(mKdTree,
-			  mSpatialFilterSize*
-			  Magnitude(mViewCellsManager->GetViewSpaceBox().Size()),
-			  pvs);
-	  }
-
-	  // read back the texture
-	  mPvsSize = pvs.GetSize();
-
-	  ObjectPvsIterator pit = pvs.GetIterator();
-
-	  while (pit.HasMoreEntries())
-	  {		
-		  const ObjectPvsEntry &entry = pit.Next();
-		  Intersectable *obj = entry.mObject;
-
-		  float visibility = log10(entry.mData.mSumPdf + 1) / 5.0f;
-		  glColor3f(visibility, 0.0f, 0.0f);
-		  mUseForcedColors = true;
-		  RenderIntersectable(obj);
-		  mUseForcedColors = false;
-	  }
-
-	  if (mRenderFilter) 
-	  {
-		  mWireFrame = true;
-		  RenderIntersectable(viewcell);
-		  mWireFrame = false;
-	  }
-
-	  if (mUseFilter)
-	  {
-		  mViewCellsManager->DeleteLocalMergeTree(viewcell);
-	  }
-  } 
-  else 
-  {
-	  ObjectContainer::const_iterator oi = mObjects.begin();
-	  for (; oi != mObjects.end(); oi++)
-		  RenderIntersectable(*oi);
+		// 9.11. 2006 -> experiment with new spatial filter
+#if 0
+		mViewCellsManager->ApplySpatialFilter(mKdTree,
+											  mSpatialFilterSize*
+											  Magnitude(mViewCellsManager->GetViewSpaceBox().Size()),
+											  mPvsCache.mPvs);
+#else
+		// mSpatialFilter size is in range 0.001 - 0.1
+		mViewCellsManager->ApplyFilter2(viewcell,
+										mUseFilter,
+										100*mSpatialFilterSize,
+										mPvsCache.mPvs,
+										&mPvsCache.filteredBoxes
+										);
+#endif
+	  } else
+		mPvsCache.mPvs = viewcell->GetPvs();
+	  
+	  emit PvsUpdated();
+	}
+
+	// Render PVS
+	if (mUseSpatialFilter && mRenderBoxes) {
+		for (int i=0; i < mPvsCache.filteredBoxes.size(); i++)
+			RenderBox(mPvsCache.filteredBoxes[i]);
+	} else {
+		ObjectPvsIterator it = mPvsCache.mPvs.GetIterator();
+		
+		mPvsSize = mPvsCache.mPvs.GetSize();
+		for (; it.HasMoreEntries(); ) {
+			ObjectPvsEntry entry = it.Next();
+			Intersectable *object = entry.mObject;
+			
+			if (mRenderVisibilityEstimates) {
+				
+				float visibility = mTransferFunction*log10(entry.mData.mSumPdf + 1); // /5.0f
+				glColor3f(visibility, 0.0f, 0.0f);
+				mUseForcedColors = true;
+				RenderIntersectable(object);
+				mUseForcedColors = false;
+			} else {
+				mUseForcedColors = false;
+				RenderIntersectable(object);
+			}
+		}
+	}
+
+	if (mRenderFilter) {
+	  mWireFrame = true;
+	  RenderIntersectable(viewcell);
+	  glPushMatrix();
+	  glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
+	  glScalef(5.0f,5.0f,5.0f);
+	  glPushAttrib(GL_CURRENT_BIT);
+	  glColor3f(1.0f, 0.0f, 0.0f);
+	  gluSphere((::GLUquadric *)mSphere,
+							1e-3*Magnitude(mViewCellsManager->GetViewSpaceBox().Size()), 6, 6);
+	  glPopAttrib();
+	  glPopMatrix();
+	  mWireFrame = false;
+	}
+	
+	if (0 && mUseFilter)
+	  mViewCellsManager->DeleteLocalMergeTree(viewcell);
+
+  } else {
+		ObjectContainer::const_iterator oi = mObjects.begin();
+		for (; oi != mObjects.end(); oi++)
+			RenderIntersectable(*oi);
   }
 }
@@ -1016,5 +439,4 @@
   mUseFalseColors = true;
 
-  SetupCamera();
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
@@ -1154,4 +576,7 @@
   int x = e->pos().x();
   int y = e->pos().y();
+
+  int diffx = -(mousePoint.x - x);
+  int diffy = -(mousePoint.y - y);
   
   if (e->modifiers() & Qt::ControlModifier) {
@@ -1182,5 +607,5 @@
 QtGlRendererWidget::resizeGL(int w, int h)
 {
-  SetupProjection(w, h);
+  SetupCameraProjection(w, h);
   updateGL();
 }
@@ -1191,22 +616,20 @@
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
-  
-  if (!mRenderViewCells) {
-	if (mRenderErrors)
+  if (1) {
+	SetupCameraProjection(width(), height());
+	SetupCamera();
+	
+	if (mRenderErrors) {
 	  RenderErrors();
-	else
+	} else {
 	  RenderPvs();
-	RenderInfo();
-  } else {
-	RenderViewCells();
-	
-	mWireFrame = true;
-	RenderScene();
-	mWireFrame = false;
-	
-	RenderInfo();
-  }
+	}
+	
+  }
+
+  RenderInfo();
 
   mFrame++;
+  
 }
 
@@ -1250,4 +673,5 @@
 }
 
+
 void
 QtGlRendererWidget::keyPressEvent ( QKeyEvent * e )
@@ -1256,5 +680,5 @@
   case Qt::Key_T:
 	mTopView = !mTopView;
-	SetupProjection(width(), height());
+	SetupCameraProjection(width(), height());
 	updateGL();
 	break;
@@ -1277,14 +701,16 @@
   
 
-QtGlRendererWidget::QtGlRendererWidget(SceneGraph *sceneGraph,
-								   ViewCellsManager *viewcells,
-								   KdTree *tree,
-								   QWidget * parent,
-								   const QGLWidget * shareWidget,
-								   Qt::WFlags f
-								   )
+QtGlRendererWidget::QtGlRendererWidget(
+									   SceneGraph *sceneGraph,
+									   ViewCellsManager *viewcells,
+									   KdTree *tree,
+									   QWidget * parent,
+									   const QGLWidget * shareWidget,
+									   Qt::WFlags f
+									   )
   :
   GlRendererWidget(sceneGraph, viewcells, tree), QGLWidget(parent, shareWidget, f)
 {
+  mPreprocessorThread = NULL;
   mTopView = false;
   mRenderViewCells = false;
@@ -1293,5 +719,8 @@
   mCutScene = false;
   mRenderErrors = false;
+  mRenderBoxes = false;
   mRenderFilter = true;
+  mRenderVisibilityEstimates = false;
+  mTransferFunction = 0.2f;
 
   bool tmp;
@@ -1302,5 +731,4 @@
   Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
 							tmp );
-
   mUseSpatialFilter = tmp;
 
@@ -1310,7 +738,19 @@
   mPvsSize = 0;
   mRenderError = 0.0f;
+  mShowRays = false;
+  
   mControlWidget = new QtRendererControlWidget(NULL);
   
   connect(mControlWidget, SIGNAL(SetViewCellGranularity(int)), this, SLOT(SetViewCellGranularity(int)));
+  connect(mControlWidget,
+		  SIGNAL(SetTransferFunction(int)),
+		  this,
+		  SLOT(SetTransferFunction(int)));
+  connect(mControlWidget, SIGNAL(UpdateAllPvs()), this, SLOT(UpdateAllPvs()));
+  connect(mControlWidget, SIGNAL(ComputeVisibility()), this, SLOT(ComputeVisibility()));
+  connect(mControlWidget, SIGNAL(StopComputation()), this, SLOT(StopComputation()));
+  connect(mControlWidget, SIGNAL(SetRandomViewPoint()), this,
+		  SLOT(SetRandomViewPoint()));
+
   connect(mControlWidget, SIGNAL(SetSceneCut(int)), this, SLOT(SetSceneCut(int)));
   connect(mControlWidget, SIGNAL(SetTopDistance(int)), this, SLOT(SetTopDistance(int)));
@@ -1326,46 +766,55 @@
   connect(mControlWidget, SIGNAL(SetCutScene(bool)), this, SLOT(SetCutScene(bool)));
   connect(mControlWidget, SIGNAL(SetRenderErrors(bool)), this, SLOT(SetRenderErrors(bool)));
+  connect(mControlWidget, SIGNAL(SetRenderBoxes(bool)), this, SLOT(SetRenderBoxes(bool)));
   connect(mControlWidget, SIGNAL(SetRenderFilter(bool)), this, SLOT(SetRenderFilter(bool)));
+  connect(mControlWidget, SIGNAL(SetRenderVisibilityEstimates(bool)),
+		  this, SLOT(SetRenderVisibilityEstimates(bool)));
   connect(mControlWidget, SIGNAL(SetUseFilter(bool)), this, SLOT(SetUseFilter(bool)));
   connect(mControlWidget, SIGNAL(SetUseSpatialFilter(bool)),
 		  this, SLOT(SetUseSpatialFilter(bool)));
 
-  
+  connect(mControlWidget,
+		  SIGNAL(SetShowRays(bool)),
+		  this,
+		  SLOT(SetShowRays(bool)));
+
+  resize(1000, 500);
   mControlWidget->show();
 }
 
-
-void
-QtGlRendererWidget::RenderInfo()
-{
-  QString s;
-  int vc = 0;
-  
-  if (mViewCellsManager)
-	  vc = (int)mViewCellsManager->GetViewCells().size();
-
-  int filter = 0;
-  if (mViewCellsManager)
-	filter = mViewCellsManager->GetMaxFilterSize();
-
-  s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f) viewcells:%04d filter:%04d pvs:%04d error:%5.5f %",
-			mFrame,
-			mViewPoint.x,
-			mViewPoint.y,
-			mViewPoint.z,
-			mViewDirection.x,
-			mViewDirection.y,
-			mViewDirection.z,
-			vc,
-
-			filter,
-			mPvsSize,
-			mRenderError*100.0f
-			);
-  
-  glColor3f(0.0f,0.0f,0.0f);
-  renderText(0,20,s);
-  
-  if (mShowRenderCost) {
+void
+QtGlRendererWidget::UpdateAllPvs()
+{
+  // $$ does not work so far:(
+  mViewCellsManager->UpdatePvsForEvaluation();
+  //	mViewCellsManager->FinalizeViewCells(false);
+}
+
+void
+QtGlRendererWidget::ComputeVisibility()
+{
+  cerr<<"Compute Visibility called!\n"<<endl;
+  if (!mPreprocessorThread->isRunning())
+	mPreprocessorThread->RunThread();
+}
+
+void
+QtGlRendererWidget::StopComputation()
+{
+  cerr<<"stop computation called!\n"<<endl;
+  mViewCellsManager->GetPreprocessor()->mStopComputation = true;
+}
+
+void
+QtGlRendererWidget::SetRandomViewPoint()
+{
+  cerr<<"stop computation called!\n"<<endl;
+  mViewCellsManager->GetViewPoint(mViewPoint);
+  updateGL();
+}
+
+void
+QtGlRendererWidget::RenderRenderCost()
+{
 	static vector<float> costFunction;
 	static float maxCost = -1;
@@ -1377,4 +826,6 @@
 		for (int i=0;  i < costFunction.size(); i++) {
 		  //		  cout<<i<<":"<<costFunction[i]<<" ";
+		  // update cost function to an absolute value based on the total geometry count
+		  costFunction[i]*=mSceneGraph->GetRoot()->mGeometry.size();
 		  if (costFunction[i] > maxCost)
 			maxCost = costFunction[i];
@@ -1389,5 +840,5 @@
 	if (currentPos < costFunction.size())
 	  currentCost = costFunction[currentPos];
-#if 0	
+#if 1	
 	cout<<"costFunction.size()="<<costFunction.size()<<endl;
 	cout<<"CP="<<currentPos<<endl;
@@ -1396,7 +847,11 @@
 #endif
 	if (costFunction.size()) {
+	  float scaley = 1.0f/log10(maxCost);
+	  float scalex = 1.0f/(float)costFunction.size();
+
 	  glDisable(GL_DEPTH_TEST);
 	  // init ortographic projection
 	  glMatrixMode(GL_PROJECTION);
+	  
 	  glPushMatrix();
 	  
@@ -1414,6 +869,6 @@
 	  
 	  for (int i=0;  i < costFunction.size(); i++) {
-		float x =  i/(float)costFunction.size();
-		float y = costFunction[i]/(maxCost*0.5f);
+		float x =  i*scalex;
+		float y = log10(costFunction[i])*scaley;
 		glVertex3f(x,y,0.0f);
 	  }
@@ -1422,5 +877,5 @@
 	  glColor3f(1.0f,0,0);
 	  glBegin(GL_LINES);
-	  float x =  currentPos/(float)costFunction.size();
+	  float x =  currentPos*scalex;
 	  glVertex3f(x,0.0,0.0f);
 	  glVertex3f(x,1.0f,0.0f);
@@ -1437,14 +892,17 @@
 
 	  glBegin(GL_LINES);
-	  for (int i=0;  i < 50000 && i < costFunction.size(); i+=10000) {
-		float x =  i/(float)costFunction.size();
+	  for (int i=0;  i < costFunction.size(); i += 1000) {
+		float x =  i*scalex;
 		glVertex3f(x,0.0,0.0f);
 		glVertex3f(x,1.0f,0.0f);
 	  }
 
-	  for (int i=0;  i < maxCost; i+=100) {
-		float y = i/(maxCost*0.5f);
-		glVertex3f(0,y,0.0f);
-		glVertex3f(1,y,0.0f);
+	  for (int i=0;  pow(10.0f, i) < maxCost; i+=1) {
+		float y = i*scaley;
+		//		QString s;
+		//		s.sprintf("%d", (int)pow(10,i));
+		//		renderText(width()/2+5, y*height(), s);
+		glVertex3f(0.0f, y, 0.0f);
+		glVertex3f(1.0f, y, 0.0f);
 	  }
 
@@ -1459,5 +917,47 @@
 
 	}
-  }
+  
+
+
+}
+
+void
+QtGlRendererWidget::RenderInfo()
+{
+  
+  QString s;
+  int vc = 0;
+  if (mViewCellsManager)
+	vc = mViewCellsManager->GetViewCells().size();
+  int filter = 0;
+  if (mViewCellsManager)
+	filter = mViewCellsManager->GetMaxFilterSize();
+
+  glColor3f(1.0f,1.0f,1.0f);
+
+  s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f)",
+			mFrame,
+			mViewPoint.x,
+			mViewPoint.y,
+			mViewPoint.z,
+			mViewDirection.x,
+			mViewDirection.y,
+			mViewDirection.z
+			);
+
+  renderText(20,20,s);
+
+  s.sprintf("viewcells:%04d filter:%04d pvs:%04d error:%5.5f\%",
+			vc,
+			filter,
+			mPvsSize,
+			mRenderError*100.0f);
+
+
+  renderText(20,40,s);
+
+  
+
+  
 }
 
@@ -1466,8 +966,12 @@
 QtGlRendererWidget::SetViewCellGranularity(int number)
 {
-  if (mViewCellsManager) 
+  if (mViewCellsManager) {
 	//  	mViewCellsManager->SetMaxFilterSize(number);
     mViewCellsManager->CollectViewCells(number);
 
+	// $$ does not work so far:(
+	//	mViewCellsManager->UpdatePvsForEvaluation();
+	//	mViewCellsManager->FinalizeViewCells(false);
+  }
   updateGL();
 }
@@ -1478,4 +982,5 @@
   if (mViewCellsManager) 
   	mViewCellsManager->SetMaxFilterSize(number);
+  mPvsCache.Reset();
   updateGL();
 }
@@ -1485,4 +990,5 @@
 {
   mSpatialFilterSize = 1e-3*number;
+  mPvsCache.Reset();
   updateGL();
 }
@@ -1513,57 +1019,61 @@
 QtGlRendererWidget::RenderViewCells()
 {
-	mUseFalseColors = true;
-
-	SetupCamera();
-	glEnable(GL_CULL_FACE);
-	//glDisable(GL_CULL_FACE);
-	glCullFace(GL_FRONT);
-	double eq[4];
-	eq[0] = mSceneCutPlane.mNormal.x;
-	eq[1] = mSceneCutPlane.mNormal.y;
-	eq[2] = mSceneCutPlane.mNormal.z;
-	eq[3] = mSceneCutPlane.mD;
-
-	if (mCutViewCells) 
-	{
-		glClipPlane(GL_CLIP_PLANE0, eq);
-		glEnable(GL_CLIP_PLANE0);
+  mUseFalseColors = true;
+
+  glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT);
+  
+  glEnable(GL_CULL_FACE);
+  //glDisable(GL_CULL_FACE);
+  glCullFace(GL_FRONT);
+  double eq[4];
+  eq[0] = mSceneCutPlane.mNormal.x;
+  eq[1] = mSceneCutPlane.mNormal.y;
+  eq[2] = mSceneCutPlane.mNormal.z;
+  eq[3] = mSceneCutPlane.mD;
+
+  if (mCutViewCells) {
+	glClipPlane(GL_CLIP_PLANE0, eq);
+	glEnable(GL_CLIP_PLANE0);
+  }
+  
+  int i;
+  ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
+  int maxPvs = -1;
+  for (i=0; i < viewcells.size(); i++) 
+  {
+	ViewCell *vc = viewcells[i];
+
+	//const int p = vc->GetPvs().CountObjectsInPvs();
+	const int p = vc->GetPvs().GetSize();
+	if (p > maxPvs)
+	  maxPvs = p;
+  }
+
+
+  for (i=0; i < viewcells.size(); i++) {
+	ViewCell *vc = viewcells[i];
+	//	Mesh *m = vc->GetMesh();
+
+
+	RgbColor c;
+
+	if (!mShowPvsSizes) {
+	  mWireFrame = true;
+	  c = vc->GetColor();
+	} else {
+	  //	  const float importance = 5.0f*mTransferFunction * ((float)vc->GetPvs().CountObjectsInPvs() / (float)maxPvs);
+	  const float importance = 5.0f*mTransferFunction * ((float)vc->GetPvs().GetSize() / (float)maxPvs);
+	  c = RgbColor(importance, 1.0f - importance, 0.0f);
 	}
-
-	//int i;
-	ViewCellContainer &viewCells = mViewCellsManager->GetViewCells();
-	float maxPvs = -1;
-	ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
-
-	for (vit = viewCells.begin(); vit != vit_end; ++ vit)
-	{
-		ViewCell *vc = *vit;
-		const float p = vc->GetPvs().EvalPvsCost();
-		if (p > maxPvs)
-			maxPvs = p;
-	}
-
-	for (vit = viewCells.begin(); vit != vit_end; ++ vit) 
-	{
-		ViewCell *vc = *vit;
-
-		RgbColor c;
-
-		if (!mShowPvsSizes) 
-		{
-			c = vc->GetColor();
-		}
-		else 
-		{
-			const float importance = (float)vc->GetPvs().EvalPvsCost() / (float)maxPvs;
-			c = RgbColor(importance, 1.0f - importance, 0.0f);
-		}
-
-		glColor3f(c.r, c.g, c.b);
-
-		RenderViewCell(vc);
-	}
-
-	glDisable(GL_CLIP_PLANE0);
+	glColor3f(c.r, c.g, c.b);
+	
+	RenderViewCell(vc);
+  }
+
+  mUseFalseColors = false;
+  mWireFrame = false;
+
+  glPopAttrib();
+  
 }
 
@@ -1573,5 +1083,5 @@
 
 /***********************************************************************/
-/*                     QtGlDebuggerWidget implementation			   */
+/*                     QtGlDebuggerWidget implementation				   */
 /***********************************************************************/
 
@@ -1612,5 +1122,5 @@
   QLabel *label = new QLabel("Granularity");
   vbox->layout()->addWidget(label);
-
+  
   QSlider *slider = new QSlider(Qt::Horizontal, vbox);
   vl->addWidget(slider);
@@ -1620,6 +1130,27 @@
   slider->setValue(200);
 
+  
   connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
 
+  label = new QLabel("Transfer function");
+  vbox->layout()->addWidget(label);
+  
+  slider = new QSlider(Qt::Horizontal, vbox);
+  vl->addWidget(slider);
+  slider->show();
+  slider->setRange(1, 1000);
+  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
+  slider->setValue(100);
+
+  
+  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransferFunction(int)));
+
+  {
+	QPushButton *button = new QPushButton("Update all PVSs", vbox);
+	vbox->layout()->addWidget(button);
+	connect(button, SIGNAL(clicked()), SLOT(UpdateAllPvs()));
+  }
+  
+  
   label = new QLabel("Filter size");
   vbox->layout()->addWidget(label);
@@ -1659,13 +1190,18 @@
   connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
 
+  cb = new QCheckBox("Render cost curve", hbox);
+  hlayout->addWidget(cb);
+  cb->setChecked(false);
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
+
   cb = new QCheckBox("Show render cost", hbox);
   hlayout->addWidget(cb);
   cb->setChecked(false);
-  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
-
-  cb = new QCheckBox("Show pvs sizes", hbox);
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
+
+  cb = new QCheckBox("Show rays", hbox);
   hlayout->addWidget(cb);
   cb->setChecked(false);
-  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRays(bool)));
 
   vbox->resize(800,100);
@@ -1678,4 +1214,10 @@
   vbox->setLayout(vl);
 
+
+
+  cb = new QCheckBox("Cut view cells", vbox);
+  vbox->layout()->addWidget(cb);
+  cb->setChecked(false);
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
 
 
@@ -1689,4 +1231,21 @@
   connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
 
+
+  cb = new QCheckBox("Cut scene", vbox);
+  vbox->layout()->addWidget(cb);
+  cb->setChecked(false);
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
+
+  cb = new QCheckBox("Render boxes", vbox);
+  vbox->layout()->addWidget(cb);
+  cb->setChecked(false);
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderBoxes(bool)));
+
+  cb = new QCheckBox("Render visibility estimates", vbox);
+  vbox->layout()->addWidget(cb);
+  cb->setChecked(false);
+  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderVisibilityEstimates(bool)));
+
+  
   cb = new QCheckBox("Render errors", vbox);
   vbox->layout()->addWidget(cb);
@@ -1694,12 +1253,19 @@
   connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
 
+  
+  bool tmp;
+
   cb = new QCheckBox("Use filter", vbox);
   vbox->layout()->addWidget(cb);
-  cb->setChecked(true);
+  Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp );
+  cb->setChecked(tmp);
   connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
 
+  
   cb = new QCheckBox("Use spatial filter", vbox);
   vbox->layout()->addWidget(cb);
-  cb->setChecked(true);
+  Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
+											tmp );
+  cb->setChecked(tmp);
   connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
 
@@ -1710,13 +1276,4 @@
 
 
-  cb = new QCheckBox("Cut view cells", vbox);
-  vbox->layout()->addWidget(cb);
-  cb->setChecked(false);
-  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
-
-  cb = new QCheckBox("Cut scene", vbox);
-  vbox->layout()->addWidget(cb);
-  cb->setChecked(false);
-  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
 
   
@@ -1735,22 +1292,45 @@
   connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
 
+
+
   vbox = new QGroupBox("PVS Errors", this);
   layout()->addWidget(vbox);
-
+  
   vl = new QVBoxLayout;
   vbox->setLayout(vl);
 
-  mPvsErrorWidget = new QListWidget(vbox);
-  vbox->layout()->addWidget(mPvsErrorWidget);
-  
-  connect(mPvsErrorWidget,
-  		  SIGNAL(doubleClicked(const QModelIndex &)),
-  		  this,
-  		  SLOT(PvsErrorClicked(const QModelIndex &)));
-  
-  QPushButton *button = new QPushButton("Next Error Frame", vbox);
+  QPushButton *button = new QPushButton("Compute Visibility", vbox);
   vbox->layout()->addWidget(button);
-  connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
-
+  connect(button, SIGNAL(clicked()), SLOT(ComputeVisibility()));
+
+  button = new QPushButton("Stop Computation", vbox);
+  vbox->layout()->addWidget(button);
+  connect(button, SIGNAL(clicked()), SLOT(StopComputation()));
+
+  button = new QPushButton("Set Random View Point", vbox);
+  vbox->layout()->addWidget(button);
+  connect(button, SIGNAL(clicked()), SLOT(SetRandomViewPoint()));
+
+
+  if (0) {
+	vbox = new QGroupBox("PVS Errors", this);
+	layout()->addWidget(vbox);
+	
+	vl = new QVBoxLayout;
+	vbox->setLayout(vl);
+	
+	mPvsErrorWidget = new QListWidget(vbox);
+	vbox->layout()->addWidget(mPvsErrorWidget);
+	
+	connect(mPvsErrorWidget,
+			SIGNAL(doubleClicked(const QModelIndex &)),
+			this,
+			SLOT(PvsErrorClicked(const QModelIndex &)));
+	
+	QPushButton *button = new QPushButton("Next Error Frame", vbox);
+	vbox->layout()->addWidget(button);
+	connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
+  }
+  
   setWindowTitle("Preprocessor Control Widget");
   adjustSize();
@@ -1758,4 +1338,6 @@
 
 
+
+
 void
 QtRendererControlWidget::FocusNextPvsErrorFrame(void)
@@ -1767,5 +1349,5 @@
 void
 QtRendererControlWidget::UpdatePvsErrorItem(int row,
-											GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
+										  GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
 {
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.h	(revision 1940)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.h	(revision 1942)
@@ -4,4 +4,6 @@
 #include <QtOpenGL>
 #include <QWaitCondition>
+
+//#include <QGLPixelBuffer>
 
 #include "Vector3.h"
@@ -11,6 +13,7 @@
 #include "GlRenderer.h"
 #include "Beam.h"
-
+#include "QtPreprocessorThread.h"
 class QWidget;
+//class QtPreprocessorThread;
 
 namespace GtpVisibilityPreprocessor {
@@ -29,4 +32,5 @@
 class TransformedMeshInstance;
 
+
 struct VssRayContainer;
 struct PvsRenderStatistics; 
@@ -34,268 +38,272 @@
 
 
-class __declspec(dllexport) QtGlRendererBuffer: public QObject, public QGLPixelBuffer, public GlRendererBuffer
+class QtGlRendererBuffer : public QObject, public QGLPixelBuffer, public GlRendererBuffer
 {
 	Q_OBJECT
-
 public:
 	QtGlRendererBuffer(const int w,
-					   const int h,
-					   SceneGraph *sceneGraph,
-					   ViewCellsManager *viewcells,
-					   KdTree *tree);
-
-	~QtGlRendererBuffer();
-
-	/** Evaluates render cost of a point sample.
-	@param sample the render cost sample to be evaluated
-	@param useOcclusionQueries if occlusion queries should be used or item buffer
-	@param threshold number of pixels / samples from where an object is considered visible.
-	*/
-	void EvalRenderCostSample(RenderCostSample &sample,
-		const bool useOcclusionQueries,
-		const int threshold);
-
-	/** Evaluates render cost of a number of point samples. The point samples
-	are distributed uniformly over the defined view space.
-
-	@param numSamples the number of point samples taken
-	@param samples stores the taken point samples in a container
-	@param useOcclusionQueries if occlusion queries should be used or item buffer
-	@param threshold number of pixels / samples from where an object is considered visible.
-	*/
-	void SampleRenderCost(const int numSamples, 
-		vector<RenderCostSample> &samples,
-		const bool useOcclusionQueries,
-		const int threshold = 0);
-
-	void
-		EvalPvsStat();
-
-	void
-		ClearErrorBuffer();
-
-	virtual int GetWidth() const { return width(); }
-	virtual int GetHeight() const { return height(); }
-
-	void SampleBeamContributions(
-			Intersectable *sourceObject,
-			Beam &beam,
-			const int samples,
-			BeamSampleStatistics &stat
-		);
-
-	void
-		SampleViewpointContributions(
-			Intersectable *sourceObject,
-			const Vector3 viewPoint,
-			Beam &beam,
-			const int desiredSamples,
-			BeamSampleStatistics &stat
-		);
-
-	void InitGL();
-
-	/** Computes rays from information gained with hw sampling
-	*/
-	void ComputeRays(Intersectable *sourceObj, VssRayContainer &rays);
-
-	float GetPixelError(int &pvsSize);
-
-	int ComputePvs(ObjectContainer &objects, ObjectContainer &pvs) const;
-
-
-private:
-
-	void SetupProjectionForViewPoint(const Vector3 &viewPoint, 
-									 const Beam &beam, 
-									 Intersectable *sourceObject);
-
-
-public:
-signals:
-	void UpdatePvsErrorItem(int i, GlRendererBuffer::PvsErrorEntry &);
-};
-
-
-class __declspec(dllexport) QtRendererControlWidget : public QWidget
+		const int h,
+		SceneGraph *sceneGraph,
+		ViewCellsManager *viewcells,
+		KdTree *tree);
+
+  ~QtGlRendererBuffer() {}
+
+  virtual void MakeCurrent();
+  virtual void DoneCurrent();
+
+  virtual int GetWidth() const { return width(); }
+  virtual int GetHeight() const { return height(); }
+
+  int ComputePvs() const { return 0; }
+  
+  float
+  GetPixelError(int &pvsSize);
+  
+  int ComputePvs(ObjectContainer &objects, ObjectContainer &pvs) const;
+     
+  
+  
+  
+public:
+  signals:
+  void UpdatePvsErrorItem(int i, GlRendererBuffer::PvsErrorEntry &);
+};
+
+
+class QtRendererControlWidget : public QWidget
 {
-	Q_OBJECT
-public:
-
-	QListWidget *mPvsErrorWidget;
-
-	QtRendererControlWidget(QWidget * parent = 0, Qt::WFlags f = 0);
-
-public slots:
-
-	void FocusNextPvsErrorFrame();
-	void UpdatePvsErrorItem(int i,
-		GlRendererBuffer::PvsErrorEntry &);
-
-signals:
-
-	void SetViewCellGranularity(int);
-	void SetSceneCut(int);
-	void SetTopDistance(int);
-	void SetVisibilityFilterSize(int);
-	void SetSpatialFilterSize(int);
-
-	void SetRenderFilter(bool);
-	void SetUseFilter(bool);
-	void SetUseSpatialFilter(bool);
-	void SetRenderErrors(bool);
-	void SetShowViewCells(bool);
-	void SetShowRenderCost(bool);
-	void SetShowPvsSizes(bool);
-	void SetTopView(bool);
-	void SetCutViewCells(bool);
-	void SetCutScene(bool);
-
-
-};
-
-
-class __declspec(dllexport) QtGlRendererWidget : public QGLWidget, public GlRendererWidget
+  Q_OBJECT
+public:
+
+  QListWidget *mPvsErrorWidget;
+
+  QtRendererControlWidget(QWidget * parent = 0, Qt::WFlags f = 0);
+
+  public slots:
+
+  void FocusNextPvsErrorFrame();
+  void UpdatePvsErrorItem(int i,
+						  GlRendererBuffer::PvsErrorEntry &);
+
+  signals:
+
+  void ComputeVisibility();
+  void StopComputation();
+  void SetRandomViewPoint();
+  void UpdateAllPvs();
+  void SetViewCellGranularity(int);
+  void SetTransferFunction(int);
+  void SetSceneCut(int);
+  void SetTopDistance(int);
+  void SetVisibilityFilterSize(int);
+  void SetSpatialFilterSize(int);
+
+  void SetShowRays(bool);
+  void SetRenderFilter(bool);
+  void SetRenderVisibilityEstimates(bool);
+  void SetUseFilter(bool);
+  void SetUseSpatialFilter(bool);
+  void SetRenderErrors(bool);
+  void SetRenderBoxes(bool);
+  void SetShowViewCells(bool);
+  void SetShowRenderCost(bool);
+  void SetShowPvsSizes(bool);
+  void SetTopView(bool);
+  void SetCutViewCells(bool);
+  void SetCutScene(bool);
+
+};
+
+
+class QtGlRendererWidget : public QGLWidget, public GlRendererWidget
 {
-	Q_OBJECT
-public:
-
-	// point of the last mouse click used for movement in the scene
-	Vector3 mousePoint;
-
-	bool mTopView;
-	bool mRenderViewCells;
-	bool mCutViewCells;
-	bool mCutScene;
-	bool mRenderErrors;
-	bool mRenderFilter;
-	bool mUseFilter;
-	bool mUseSpatialFilter;
-	bool mShowRenderCost;
-
-	bool mShowPvsSizes;
-	float mSpatialFilterSize;
-
-	Plane3 mSceneCutPlane;
-	float mTopDistance;
-
-	// some statistics
-	int mPvsSize;
-	float mRenderError;
-
-	QtRendererControlWidget *mControlWidget;
-
-	QtGlRendererWidget(SceneGraph *sceneGraph,
-		ViewCellsManager *viewcells,
-		KdTree *tree,
-		QWidget * parent = 0, const QGLWidget * shareWidget = 0, Qt::WFlags f = 0
-		);
-
-	QtGlRendererWidget() {};
-
-	virtual void SetupCamera();
-
-	void initializeGL() {
-		InitGL();
-	}
-	void resizeGL(int w, int h);
-	void paintGL();
-	void timerEvent(QTimerEvent *) {
-		update();
-	}
-
-	void mousePressEvent(QMouseEvent *);
-	void mouseReleaseEvent(QMouseEvent *);
-	void mouseMoveEvent(QMouseEvent *);
-
-	void keyPressEvent ( QKeyEvent * e ) ;
-
-	void
-		RenderPvs();
-
-	float
-		RenderErrors();
-	void
-		RenderInfo();
-
-	virtual int GetWidth() const { return width(); }
-	virtual int GetHeight() const { return height(); }
-
-	virtual void
-		SetupProjection(const int w, const int h, const float angle = 70.0f);
-
-	void
-		RenderViewCells();
-
-public slots:
-
-	void SetRenderErrors(bool b) {
-		mRenderErrors = b;
-		updateGL();
-	}
-
-	void SetRenderFilter(bool b) {
-		mRenderFilter = b;
-		updateGL();
-	}
-
-	void SetUseFilter(bool b) {
-		mUseFilter = b;
-		updateGL();
-	}
-
-	void SetUseSpatialFilter(bool b) {
-		mUseSpatialFilter = b;
-		updateGL();
-	}
-
-
-	void
-		SetViewCellGranularity(int number);
-
-	void
-		SetVisibilityFilterSize(int number);
-
-	void
-		SetSpatialFilterSize(int number);
-
-	void
-		SetSceneCut(int cut);
-
-	void
-		SetTopDistance(int dist);
-
-	void SetShowViewCells(bool b) {
-		mRenderViewCells = b;
-		updateGL();
-	}
-
-	void SetShowRenderCost(bool b) {
-		mShowRenderCost = b;
-		updateGL();
-	}
-
-	void SetShowPvsSizes(bool b) {
-		mShowPvsSizes = b;
-		updateGL();
-	}
-
-	void SetTopView(bool b) {
-		mTopView = b;
-		updateGL();
-	}
-
-	void SetCutViewCells(bool b) {
-		mCutViewCells = b;
-		updateGL();
-	}
-	void SetCutScene(bool b) {
-		mCutScene = b;
-		updateGL();
-	}
-
-	// matt: dummy function, must be provided by bittner
-	void RenderRenderCost() {}
-
+  Q_OBJECT
+public:
+
+  // point of the last mouse click used for movement in the scene
+  Vector3 mousePoint;
+
+  bool mTopView;
+  bool mRenderViewCells;
+  bool mCutViewCells;
+  bool mCutScene;
+  bool mRenderErrors;
+  bool mRenderFilter;
+  bool mRenderVisibilityEstimates;
+  bool mUseFilter;
+  bool mUseSpatialFilter;
+  bool mShowRenderCost;
+  bool mShowRays;
+
+  bool mShowPvsSizes;
+  float mSpatialFilterSize;
+  
+  Plane3 mSceneCutPlane;
+  float mTopDistance;
+
+  // some statistics
+  int mPvsSize;
+  float mRenderError;
+  float mTransferFunction;
+
+  
+  QtRendererControlWidget *mControlWidget;
+
+  QtPreprocessorThread *mPreprocessorThread;
+  
+  QtGlRendererWidget(SceneGraph *sceneGraph,
+					 ViewCellsManager *viewcells,
+					 KdTree *tree,
+					 QWidget * parent = 0, const QGLWidget * shareWidget = 0, Qt::WFlags f = 0
+					 );
+  
+  QtGlRendererWidget() {};
+
+  void SetThread(QtPreprocessorThread *t) {
+	mPreprocessorThread = t;
+  }
+  void
+  RenderRenderCost();
+
+  virtual void SetupCamera();
+
+  void initializeGL() {
+	InitGL();
+  }
+  void resizeGL(int w, int h);
+  void paintGL();
+  void timerEvent(QTimerEvent *) {
+	  update();
+  }
+
+  void mousePressEvent(QMouseEvent *);
+  void mouseReleaseEvent(QMouseEvent *);
+  void mouseMoveEvent(QMouseEvent *);
+
+  void keyPressEvent ( QKeyEvent * e ) ;
+
+  void
+  RenderPvs();
+
+  float
+  RenderErrors();
+  void
+  RenderInfo();
+
+  virtual int GetWidth() const { return width(); }
+  virtual int GetHeight() const { return height(); }
+
+  // virtual void
+  //  SetupProjection(const int w, const int h, const float angle = 70.0f);
+
+  virtual void
+  SetupCameraProjection(const int w, const int h, const float angle = 70.0f);
+
+  void
+  RenderViewCells();
+
+
+  virtual void Show() {
+	show();
+  }
+
+ public slots:
+
+ void UpdateAllPvs();
+  void ComputeVisibility();
+  void StopComputation();
+  void SetRandomViewPoint();
+
+ void SetRenderErrors(bool b) {
+   mRenderErrors = b;
+   updateGL();
+ }
+
+  void SetRenderBoxes(bool b) {
+	mRenderBoxes = b;
+	updateGL();
+  }
+
+ void SetRenderFilter(bool b) {
+   mRenderFilter = b;
+   updateGL();
+ }
+
+  void SetRenderVisibilityEstimates(bool b) {
+	mRenderVisibilityEstimates = b;
+   updateGL();
+ }
+
+  void SetUseFilter(bool b) {
+   mUseFilter = b;
+   mPvsCache.Reset();
+   updateGL();
+ }
+
+  void SetUseSpatialFilter(bool b) {
+	mUseSpatialFilter = b;
+	mPvsCache.Reset();
+	updateGL();
+  }
+
+  
+  void
+  SetViewCellGranularity(int number);
+
+  void
+  SetTransferFunction(int number) {
+	mTransferFunction = number/1000.0f;
+	updateGL();
+  }
+
+  void
+  SetVisibilityFilterSize(int number);
+
+  void
+  SetSpatialFilterSize(int number);
+  
+  void
+  SetSceneCut(int cut);
+  
+  void
+  SetTopDistance(int dist);
+  
+  void SetShowViewCells(bool b) {
+	mRenderViewCells = b;
+	updateGL();
+  }
+
+  void SetShowRays(bool b) {
+	mShowRays = b;
+	updateGL();
+  }
+
+  void SetShowRenderCost(bool b) {
+	mShowRenderCost = b;
+	updateGL();
+  }
+
+  void SetShowPvsSizes(bool b) {
+	mShowPvsSizes = b;
+	updateGL();
+  }
+
+  void SetTopView(bool b) {
+	mTopView = b;
+	updateGL();
+  }
+
+  void SetCutViewCells(bool b) {
+	mCutViewCells = b;
+	updateGL();
+  }
+  void SetCutScene(bool b) {
+	mCutScene = b;
+	updateGL();
+  }
+
+  signals:
+  void PvsUpdated();
 };
 
@@ -305,27 +313,26 @@
 	Q_OBJECT
 public:
-	QtGlDebuggerWidget(QtGlRendererBuffer *buf, QWidget *parent = NULL);
-	~QtGlDebuggerWidget();
-	void initializeGL();
-	void resizeGL(int w, int h);
-	void paintGL();
-	void timerEvent(QTimerEvent *) { update(); }
-	void mousePressEvent(QMouseEvent *) { killTimer(timerId); }
-	void mouseReleaseEvent(QMouseEvent *) { timerId = startTimer(20); }
-
-	void initCommon();
-	void initPbuffer();
-
-
-	QtGlRendererBuffer *mRenderBuffer;
-
-	Beam mBeam;
-	int mSamples;
-	Intersectable *mSourceObject;
+    QtGlDebuggerWidget(QtGlRendererBuffer *buf, QWidget *parent = NULL);
+    ~QtGlDebuggerWidget();
+    void initializeGL();
+    void resizeGL(int w, int h);
+    void paintGL();
+    void timerEvent(QTimerEvent *) { update(); }
+    void mousePressEvent(QMouseEvent *) { killTimer(timerId); }
+    void mouseReleaseEvent(QMouseEvent *) { timerId = startTimer(20); }
+
+    void initCommon();
+    void initPbuffer();
+
+  
+	 QtGlRendererBuffer *mRenderBuffer;
+
+	 Beam mBeam;
+	 int mSamples;
+	 Intersectable *mSourceObject;
 
 private:
-
-	GLuint dynamicTexture;
-	int timerId;
+    GLuint dynamicTexture;
+    int timerId;
 };
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlViewer.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlViewer.cpp	(revision 1942)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlViewer.cpp	(revision 1942)
@@ -0,0 +1,190 @@
+// ===================================================================
+// $Id$
+#ifdef USE_QT
+
+// Qt headers
+#include <QtGui>
+#include <QtOpenGL>
+
+// C++ standard headers
+#include <cmath>
+
+// local headers
+#include "common.h"
+#include "QtGlViewer.h"
+#include "QtGlRenderer.h"
+#include "Trackball.h"
+#include "RssPreprocessor.h"
+#include "SceneGraph.h"
+
+
+namespace GtpVisibilityPreprocessor {
+
+QtGlRendererWidget *renderer;
+
+QtGlViewer::QtGlViewer(QWidget *parent,
+					   QtGlRendererWidget *renderer):
+  QGLWidget(parent), mRenderer(renderer)
+{
+	scale = 1.0f;
+	mWireframe = false;
+	trackball(manipulatorLastQuat, 0.0f, 0.0f, 0.0f, 0.0f);
+	connect(renderer, SIGNAL(PvsUpdated()), this, SLOT(updateGL()));
+}
+  
+QSize
+QtGlViewer::minimumSizeHint() const
+{
+  return QSize(100, 100);
+}
+
+QSize
+QtGlViewer::sizeHint() const {
+  return QSize(500, 500);
+}
+  
+// This method has to be rendefined by all renderer implementations
+void
+QtGlViewer::RenderScene()
+{
+	mRenderer->mFrame++;
+	
+	// render into the right side of the window buffer
+	if (mRenderer->mRenderViewCells) 
+	  mRenderer->RenderViewCells();
+	
+	mRenderer->RenderPvs();
+	
+// 	if (mRenderer->mShowRays) {
+// 	  RssPreprocessor *p = (RssPreprocessor *)
+// 			mRenderer->mViewCellsManager->GetPreprocessor();
+// 	  if (p->mRssTree) {
+// 			VssRayContainer rays;
+// 			p->mRssTree->CollectRays(rays, 10000);
+// 			mRenderer->RenderRays(rays);
+// 	  }
+// 	}
+	
+	if (mRenderer->mShowRenderCost) 
+	  mRenderer->RenderRenderCost();
+
+	glColor3f(1.0f, 1.0f, 1.0f);
+	mRenderer->RenderInfo();
+}
+
+
+void
+QtGlViewer::initializeGL()
+{  
+  const char *vendorString, *rendererString, *versionString, *extString;
+
+  // get GL info
+  vendorString = (const char *) glGetString(GL_VENDOR);
+  rendererString = (const char *) glGetString(GL_RENDERER);
+  versionString = (const char *) glGetString(GL_VERSION);
+  extString = (const char *) glGetString(GL_EXTENSIONS);
+  
+  Debug << "Info: GL Vendor = "<<vendorString<<endl
+        << "Info: GL Renderer = "<<rendererString<<endl
+        << "Info: GL Version = "<<versionString<<endl
+        << "Info: GL Extensions = "<<extString<<endl<<flush;
+
+
+  return;
+}
+
+void
+QtGlViewer::paintGL()
+{
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  glLoadIdentity();
+
+  float m[4][4];
+
+  glLoadIdentity();
+  gluLookAt(0.0, 0.0, 1.0,  /* eye is at (0,0,30) */
+						0.0, 0.0, 0.0,      /* center is at (0,0,0) */
+						0.0, 1.0, 0.);      /* up is in positive Y direction */
+  
+  build_rotmatrix(m, manipulatorLastQuat);
+  glMultMatrixf(&m[0][0]);
+
+  float s = scale*20.0f/Magnitude(mRenderer->mSceneGraph->GetBox().Diagonal());
+  glScalef(s, s, s);
+  
+  Vector3 t = -mRenderer->mSceneGraph->GetBox().Center();
+  glTranslatef(t.x, t.y, t.z);
+
+	RenderScene();
+}
+
+void
+QtGlViewer::resizeGL(int width, int height)
+{
+  glViewport(0, 0, width, height);
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70.0, 1.0, 0.1, 100.0);
+  //  glOrtho(-0.5*width/height, +0.5*width/height, 0.5, -0.5, 4.0, 15.0);
+  glMatrixMode(GL_MODELVIEW);
+}
+
+
+void
+QtGlViewer::mousePressEvent(QMouseEvent *event)
+{
+  lastPos = event->pos();
+}
+
+void
+QtGlViewer::keyPressEvent ( QKeyEvent * e )
+{
+  switch (e->key()) {
+  case Qt::Key_W:
+		mWireframe  = !mWireframe;
+		updateGL();
+  default:
+		e->ignore();
+		break;
+  }
+  updateGL();
+}
+
+void
+QtGlViewer::mouseMoveEvent(QMouseEvent *event)
+{
+  int dx = event->x() - lastPos.x();
+  int dy = event->y() - lastPos.y();  
+  
+  if (event->modifiers() & Qt::CTRL)
+		{
+			scale = scale*(1.0f - dy/(float)height());
+			if (scale < 0.01f)
+				scale = 0.01f;
+			updateGL();
+		}
+  else {
+		float W = width();
+		float H = height();
+		int x = event->x();
+		int lastX = lastPos.x();
+		int y = event->y();
+		int lastY = lastPos.y();
+	
+		float quat[4];
+		trackball(quat,
+							(2.0 * lastX - W) / W,
+							(H - 2.0 * lastY) / H,
+							(2.0 * x - W) / W,
+							(H - 2.0 * y) / H
+							);
+		add_quats(quat, manipulatorLastQuat, manipulatorLastQuat);
+  }
+  
+  lastPos = event->pos();
+updateGL();
+}
+}
+
+#endif
Index: GTP/trunk/Lib/Vis/Preprocessing/src/default.env
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/default.env	(revision 1931)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/default.env	(revision 1942)
@@ -43,5 +43,4 @@
 	useGlDebugger false
 # 0 = INTERNAL 		1 = MLRT
-
 	rayCastMethod 1
 	
@@ -62,5 +61,5 @@
 	applyVisibilitySpatialFilter false
 	visibilityFilterWidth	0.01
-	exportVisibility false
+	exportVisibility true
 	visibilityFile visibility.xml
 	loadMeshes false
@@ -98,10 +97,12 @@
 
 #	distributions rss+spatial+object_direction
-	distributions rss+object_direction+spatial+object+direction
+#	distributions rss+object_direction+spatial+object+direction
+	distributions object_direction+spatial+object+direction
+#	distributions rss+object_direction
 #	distributions object_direction
 
 	samplesPerPass 1000000
 	initialSamples 2000000
-	vssSamples 150000000
+	vssSamples 20000000
 	vssSamplesPerPass 5000000
 	useImportanceSampling true
@@ -132,5 +133,5 @@
 #	splitType heuristic
 
-	minRays		50
+	minRays		200
 	minSize		0.001
  	maxCostRatio 1.0
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h	(revision 1932)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h	(revision 1942)
@@ -31,4 +31,5 @@
 
 
+
 /** Namespace for the external visibility preprocessor
 
@@ -230,6 +231,6 @@
 
 	GlRendererBuffer *renderer;
-
-
+  
+  
 protected:
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.h	(revision 1901)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.h	(revision 1942)
@@ -269,4 +269,9 @@
   void ComputeContributions(VssRayContainer &vssRays);
 
+  // update distributions with new rays
+  // warning: some rays can get deleted (if maintained internally by the
+  // particular distribution)!
+  void UpdateDistributions(VssRayContainer &vssRays);
+
   void
   UpdateRatios();
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 1935)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 1942)
@@ -31,7 +31,7 @@
 #define USE_RAY_LENGTH_AS_CONTRIBUTION 0
 #define DIST_WEIGHTED_CONTRIBUTION 0
-#define SUM_RAY_CONTRIBUTIONS 0
-#define AVG_RAY_CONTRIBUTIONS 1
-#define CONTRIBUTION_RELATIVE_TO_PVS_SIZE 1
+#define SUM_RAY_CONTRIBUTIONS 1
+#define AVG_RAY_CONTRIBUTIONS 0
+#define CONTRIBUTION_RELATIVE_TO_PVS_SIZE 0
 #define PVS_ADD_DIRTY 1
 
@@ -1996,6 +1996,20 @@
   stat.avgFilterRadius = 0;
   stat.avgFilterRatio = 0;
+  stat.avgRelPvsIncrease = 0.0f;
+  stat.devRelPvsIncrease = 0.0f;
   
-  for (; it != mViewCells.end(); ++ it) 
+  if (mPerViewCellStat.size() != mViewCells.size()) {
+	// reset the pvs size array after the first call to this routine
+	mPerViewCellStat.resize(mViewCells.size());
+	for (int i=0; i < mPerViewCellStat.size(); i++) {
+	  mPerViewCellStat[i].pvsSize = 0.0f;
+	  mPerViewCellStat[i].relPvsIncrease = 0.0f;
+	}
+  }
+  int i;
+  bool evaluateFilter;
+  Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluateFilter", evaluateFilter);
+
+  for (i=0; it != mViewCells.end(); ++ it, i++) 
 	{
 	  ViewCell *viewcell = *it;
@@ -2010,6 +2024,13 @@
 		stat.avgPvs += pvsCost;
 
-		bool evaluateFilter;
-		Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluateFilter", evaluateFilter);
+
+		if (mPerViewCellStat[i].pvsSize > 0.0f)
+		  mPerViewCellStat[i].relPvsIncrease = (pvsCost - mPerViewCellStat[i].pvsSize)/mPerViewCellStat[i].pvsSize;
+		
+		stat.avgRelPvsIncrease += mPerViewCellStat[i].relPvsIncrease;
+		
+		// update the pvs size
+		mPerViewCellStat[i].pvsSize = pvsCost;
+		
 		
 		
@@ -2040,4 +2061,6 @@
 	  }
 	}
+
+  
   
   if (stat.viewcells) {
@@ -2046,6 +2069,15 @@
 	stat.avgFilterContribution/=stat.viewcells;
 	stat.avgFilterRadius/=stat.viewcells;
-	stat.avgFilterRatio/=stat.viewcells;
+	stat.avgFilterRatio/=stat.viewcells; 
+	stat.avgRelPvsIncrease/=stat.viewcells;
+
+	// evaluate std deviation of relPvsIncrease
+	float sum=0.0f;
+	for (i=0; i < stat.viewcells; i++) {
+	  sum += sqr(mPerViewCellStat[i].relPvsIncrease - stat.avgRelPvsIncrease);
+	}
+	stat.devRelPvsIncrease = sqrt(sum/stat.viewcells);
   }
+  
 }
 
@@ -2063,4 +2095,6 @@
   s<<"#MAX_PVS\n"<<pvsStat.maxPvs<<endl;
   s<<"#MIN_PVS\n"<<pvsStat.minPvs<<endl;
+  s<<"#AVG_REL_PVS_INCREASE\n"<<pvsStat.avgRelPvsIncrease<<endl;
+  s<<"#DEV_REL_PVS_INCREASE\n"<<pvsStat.devRelPvsIncrease<<endl;
 }
 
@@ -2178,48 +2212,59 @@
 												   const bool addRays)
 {
-	// check if we are outside of view space
+  // check if we are outside of view space
 	if (!obj || !viewCell->GetValid())
 		return;
-
+	
 	// if ray not outside of view space
 	float relContribution = 0.0f;
 	float absContribution = 0.0f;
-
-	// todo: maybe not correct for kd node pvs
-	if (viewCell->GetPvs().GetSampleContribution(obj,
-												 ray.mPdf,
-												 relContribution))
-	{
-		absContribution = 1.0f;
-	}
-	
-	// $$ clear the relative contribution as it is currently not correct anyway
-	relContribution = 0.0f;
-
-	if (absContribution == 1.0f)
-	{
-		++ ray.mPvsContribution;
-		relContribution = 1.0f;
-
-		if (addRays) 
-		{
-			AddSampleToPvs(viewCell->GetPvs(), obj, ray.mPdf);
-		}
-
+	
+	if (obj) 
+	  {
+		// todo: maybe not correct for kd node pvs
+		if (addRays) {
+		  float pdf = viewCell->GetPvs().AddSampleDirtyCheck(obj, ray.mPdf);
+		  if (pdf == ray.mPdf) {
+			absContribution = 1.0f;
+			if (viewCell->GetPvs().RequiresResort()) 
+			  viewCell->GetPvs().SimpleSort();
+		  }
+			  } else {
+				if (viewCell->GetPvs().GetSampleContribution(
+															 obj,
+															 ray.mPdf,
+															 relContribution))
+				  absContribution = 1.0f;
+			  }
+		// $$ clear the relative contribution as it is currently not correct anyway
+		relContribution = 0.0f;
+		
+		if (absContribution == 1.0f) {
+		  ++ ray.mPvsContribution;
+		  relContribution = 1.0f;
+		  
+		  
+#if CONTRIBUTION_RELATIVE_TO_PVS_SIZE
+		  relContribution /= viewcell->GetPvs().GetSize();
+#endif
+		  
 #if DIST_WEIGHTED_CONTRIBUTION 
-		// recalculate the contribution - weight the 1.0f contribution by the sqr distance to the
-		// object-> a new contribution in the proximity of the viewcell has a larger weight!
-		relContribution /= SqrDistance(GetViewCellBox(viewcell).Center(), pt);
-				  
+		  // recalculate the contribution - weight the 1.0f contribution by the sqr distance to the
+		  // object-> a new contribution in the proximity of the viewcell has a larger weight!
+		  relContribution /= SqrDistance(GetViewCellBox(viewcell).Center(),
+										 ray.mTermination);
+		  
 #endif
-	}
-
+		}
+		
 #if SUM_RAY_CONTRIBUTIONS || AVG_RAY_CONTRIBUTIONS
-	ray.mRelativePvsContribution += relContribution;
+		ray.mRelativePvsContribution += relContribution;
 #else
-	// recalculate relative contribution - use max of AbsContribution
-	if (ray.mRelativePvsContribution < absContribution)
-		ray.mRelativePvsContribution = absContribution;
+		// recalculate relative contribution - use max of Rel Contribution
+		if (ray.mRelativePvsContribution < relContribution)
+		  ray.mRelativePvsContribution = relContribution;
 #endif
+	  }
+	
 }
 
@@ -2243,6 +2288,8 @@
 	float tmin = 0, tmax = 1.0;
 
-	if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
-		return 0;
+	if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax)) {
+	  //	  cerr<<"ray outside view space box\n";
+	  return 0;
+	}
 
 	Vector3 origin = hray.Extrap(tmin);
@@ -2254,9 +2301,10 @@
 	CastLineSegment(origin, termination, viewCells);
 
+	
 	if (storeViewCells)
 	{	
-		// copy viewcells memory efficiently
-		ray.mViewCells.reserve(viewCells.size());
-		ray.mViewCells = viewCells;
+	  // copy viewcells memory efficiently
+	  ray.mViewCells.reserve(viewCells.size());
+	  ray.mViewCells = viewCells;
 	}
 
@@ -2280,11 +2328,11 @@
 #if USE_RAY_LENGTH_AS_CONTRIBUTION
 	float c = 0.0f;
-	if (obj) 
-		c = ray.Length();
+	if (terminationObj) 
+	  c = ray.Length();
 	ray.mRelativePvsContribution = ray.mPvsContribution = c;
 	return c;
 #else
-	return ABS_CONTRIBUTION_WEIGHT * ray.mPvsContribution +
-		(1.0f - ABS_CONTRIBUTION_WEIGHT) * ray.mRelativePvsContribution;
+	return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
+	  (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
 #endif
 }
@@ -2897,5 +2945,5 @@
 		sqrt((float)objectSamples);
 	  
-	  //	cout<<"lr="<<localRadius<<" gr="<<globalRadius<<endl;
+	  //	  cout<<"os="<<objectSamples<<" lr="<<localRadius<<" gr="<<globalRadius<<endl;
 	  
 	  // now compute the filter size
Index: GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp	(revision 1941)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp	(revision 1942)
@@ -66,5 +66,6 @@
   //  mViewCellsManager->GetViewPoint(mViewPoint);
 
-  mViewPoint = mSceneGraph->GetBox().Center();
+  viewCellsManager->GetViewPoint(mViewPoint);
+	//mSceneGraph->GetBox().Center();
   mViewDirection = Vector3(0,0,1);
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/QtGlViewer.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/QtGlViewer.h	(revision 1936)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/QtGlViewer.h	(revision 1942)
@@ -12,6 +12,5 @@
 class QtGlViewer : public QGLWidget
 {
-	
-	//Q_OBJECT
+  Q_OBJECT
 
 	friend class QtGlRendererWidget;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Pvs.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Pvs.h	(revision 1925)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Pvs.h	(revision 1942)
@@ -615,9 +615,8 @@
   // sample not found yet => search further in the unsorted part
   if (!found && checkDirty) {
-	vector<PvsEntry<T, S> >::const_iterator dit, dit_end = mEntries.end();
-	
-	for (dit = sorted_end; (dit != dit_end) && ((*dit).mObject != sample); ++ dit) ;
-	
-	if (dit != dit_end)
+	
+	for (it = sorted_end; (it != mEntries.end()) && ((*it).mObject != sample); ++ it) ;
+	
+	if (it != mEntries.end())
 	  found = true;
   }
@@ -653,10 +652,10 @@
 	}
 	else 
-	{
+	  {
 		PvsEntry<T, S> entry(sample, pdf);
 		mEntries.insert(it, entry);
 		++ mLastSorted;
 		return pdf;
-	}
+	  }
 }
 
@@ -706,5 +705,5 @@
 
 	vector<PvsEntry<T, S> >::iterator it;
-	const bool entryFound = Find(sample, it);
+	bool entryFound = Find(sample, it);
 
 	if (entryFound) {
Index: GTP/trunk/Lib/Vis/Preprocessing/src/IntelRayCaster.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/IntelRayCaster.cpp	(revision 1867)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/IntelRayCaster.cpp	(revision 1942)
@@ -2,4 +2,5 @@
 #include "VssRay.h"
 #include "Preprocessor.h"
+#include "SceneGraph.h"
 
 #ifdef GTP_INTERNAL
@@ -125,7 +126,7 @@
 	float backward_dist[16];
 
-
-	Vector3 min = sbox.Min();
-	Vector3 max = sbox.Max();
+	
+	Vector3 min = mPreprocessor.mSceneGraph->GetBox().Min();
+	Vector3 max = mPreprocessor.mSceneGraph->GetBox().Max();
 
 	for (i=0; i < num; i++) {
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Makefile
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Makefile	(revision 1931)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Makefile	(revision 1942)
@@ -1,5 +1,5 @@
 #############################################################################
 # Makefile for building: preprocessor
-# Generated by qmake (2.00a) (Qt 4.1.2) on: út 2. I 10:32:48 2007
+# Generated by qmake (2.00a) (Qt 4.1.2) on: pá 5. I 16:16:49 2007
 # Project:  preprocessor.pro
 # Template: app
Index: GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.cpp	(revision 1931)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.cpp	(revision 1942)
@@ -2299,7 +2299,5 @@
 {
   Vector3 origin = sbox.GetPoint(Vector3(params[0], params[1], params[2]));
-
   Vector3 dirVector = sDirBBox.GetPoint(Vector3(params[3], params[4], 0.0f));
-
   Vector3 direction = VssRay::GetInvDirParam(dirVector.x, dirVector.y);
   
@@ -2308,15 +2306,15 @@
   float minT, maxT;
   
-  float boxSize = Magnitude(sbox.Size());
   // compute interection of the ray with the box
 #if 1
   if (sbox.ComputeMinMaxT(origin, direction, &minT, &maxT) && minT < maxT)
-	dist = (maxT + 0.0f*boxSize);
+	dist = (maxT + Limits::Small);
 #else
+  float boxSize = Magnitude(sbox.Size());
   dist = 0.5f*boxSize;
 #endif
   
   origin += direction*dist;
-
+  
   //Debug<<"dir vector.x="<<dirVector.x<<"direction'.x="<<atan2(direction.x, direction.y)<<endl;
   rays.push_back(SimpleRay(origin,
@@ -2765,5 +2763,5 @@
 	  sumContributions += c1;
 	  if (c1 > maxContribution)
-			maxContribution = c1;
+		maxContribution = c1;
 	  
 	  //$$ 20.7. changed to sqr to pronouce higher contribution so that
@@ -2806,5 +2804,5 @@
 		pow(((weightAbsContributions*sumContributions +
 			  (1.0f - weightAbsContributions)*sumRelContributions)/sumWeights), 1.0f);
-#else 1
+#else 
 	  leaf->mImportance =
 		(weightAbsContributions*maxContribution +
Index: GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp	(revision 1932)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp	(revision 1942)
@@ -3,4 +3,5 @@
 #include "Ray.h"
 #include "Preprocessor.h"
+#include "ViewCellsManager.h"
 
 
@@ -10,5 +11,5 @@
 #define DEBUG_RAYCAST 0
 
-#define EXACT_BOX_CLIPPING 1
+#define EXACT_BOX_CLIPPING 0
 
 RayCaster::RayCaster(const Preprocessor &preprocessor):
@@ -38,4 +39,35 @@
 }
 
+bool
+RayCaster::ClipToViewSpaceBox(const Vector3 &origin,
+							  const Vector3 &termination,
+							  Vector3 &clippedOrigin,
+							  Vector3 &clippedTermination)
+{
+  Ray ray(origin, termination - origin, Ray::LINE_SEGMENT);	
+  ray.Precompute();
+  
+  float tmin, tmax;
+  if ((!mPreprocessor.mViewCellsManager->
+	   GetViewSpaceBox().ComputeMinMaxT(ray, &tmin, &tmax)) ||
+	  tmin>=tmax
+	  )
+	return false;
+
+  if (tmin >= 1.0f || tmax <=0.0f)
+	return false;
+  
+  if (tmin > 0.0f)
+	clippedOrigin = ray.Extrap(tmin);
+  else
+	clippedOrigin = origin;
+  
+  if (tmax < 1.0f)
+	clippedTermination = ray.Extrap(tmax);
+  else
+	clippedTermination = termination;
+  
+  return true;
+}
 
 /** Checks if ray is valid, (e.g., not in empty view space or outside the view space)
@@ -140,12 +172,20 @@
 	// degenerate rays checked by geometrical constraint...
 	//	!pruneInvalidRays || (hitA.mObject != hitB.mObject);
+
 	
 #if DEBUG_RAYCAST
 	Debug<<"PR2"<<flush;
 #endif
-
-	if (!pruneInvalidRays || hitA.mObject) 
-	{
-		VssRay *vssRay = new VssRay(hitB.mPoint,
+	const bool validSample = true;
+	if (validSample) {
+	  Vector3 clipA, clipB;
+	  if (!ClipToViewSpaceBox(hitA.mPoint,
+							  hitB.mPoint,
+							  clipA,
+							  clipB))
+		return 0;
+	  if (!pruneInvalidRays || hitA.mObject) {
+		VssRay *vssRay = new VssRay(
+									clipB,
 									hitA.mPoint,
 									hitB.mObject,
@@ -167,14 +207,15 @@
 #endif
 
-	if (castDoubleRay && (!pruneInvalidRays || hitB.mObject))
-	{
-		VssRay *vssRay = new VssRay(hitA.mPoint,
-									hitB.mPoint,
-									hitA.mObject,
-									hitB.mObject,
-									mPreprocessor.mPass,
-									simpleRay.mPdf);
-
-		if (validB)
+	  if (castDoubleRay && (!pruneInvalidRays || hitB.mObject))
+		{
+		  VssRay *vssRay = new VssRay(
+									  clipA,
+									  hitB.mPoint,
+									  hitA.mObject,
+									  hitB.mObject,
+									  mPreprocessor.mPass,
+									  simpleRay.mPdf
+									  );
+		  if (validB)
 			vssRay->mFlags |= VssRay::Valid;
 
@@ -183,10 +224,10 @@
 		++ hits;
 		//cout << "vssray 2: " << *vssRay << endl;
-	}
-	
-#if DEBUG_RAYCAST
-	Debug<<"PR4"<<flush;
-#endif
-
+		}
+#if DEBUG_RAYCAST
+	  Debug<<"PR4"<<flush;
+#endif
+	}
+	
 	return hits;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1940)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1942)
@@ -28,5 +28,5 @@
 #include "ObjExporter.h"
 #include "SceneGraph.h"
-#include "GlobalLinesRenderer.h"
+//#include "GlobalLinesRenderer.h"
 
 #include "ViewCellsManager.h"
Index: GTP/trunk/Lib/Vis/Preprocessing/src/CombinedPreprocessor.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/CombinedPreprocessor.cpp	(revision 1931)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/CombinedPreprocessor.cpp	(revision 1942)
@@ -79,19 +79,23 @@
 	totalVssRays += (int)vssRays.size();
 
+	mMixtureDistribution->ComputeContributions(vssRays);
+
 	if (mExportRays) {
 	  Debug<<"Exporting rays..."<<endl<<flush;
 	  char filename[256];
+
+	  VssRayContainer contributingRays;
+	  vssRays.GetContributingRays(contributingRays, 0);
+	  sprintf(filename, "rss-crays-%04d.x3d", mPass);
+	  ExportRays(filename, contributingRays, mExportNumRays);
+
 	  sprintf(filename, "rss-rays-i%04d.x3d", mPass);
 	  ExportRays(filename, vssRays, mExportNumRays);
-	  
-	  //	  VssRayContainer contributingRays;
-	  //	  vssRays.GetContributingRays(contributingRays, 0);
-	  //	  sprintf(filename, "rss-crays-%04d.x3d", mPass);
-	  //	  ExportRays(filename, contributingRays, mExportNumRays);
+
 	  Debug<<"done."<<endl<<flush;
 	}
 
-	mMixtureDistribution->ComputeContributions(vssRays);
-
+	mMixtureDistribution->UpdateDistributions(vssRays);
+	
 	if (i - lastEvaluation >= mSamplesPerEvaluation) {
 	  mViewCellsManager->PrintPvsStatistics(mStats);
@@ -114,5 +118,7 @@
 	
   }
-  
+
+  EvalViewCellHistogram();
+
   return true;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VssRay.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VssRay.cpp	(revision 1932)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VssRay.cpp	(revision 1942)
@@ -357,16 +357,12 @@
 {
   VssRayContainer::const_iterator it = begin();
-
-  // ofstream s("contrib.log");
-
-  for (; it != end(); it++) 
-  {
-	  VssRay *ray = *it;
-
-	  // s<<"(pass="<<ray->mPass<<", c="<<ray->mPvsContribution<<")"<<endl;
-	  if (ray->mPass >= minPass && ray->mPvsContribution > 0)
-		  selected.push_back(ray);
-  }
-
+  //  ofstream s("contrib.log");
+  for (; it != end(); it++) {
+	VssRay *ray = *it;
+	//	cout<<"(pass="<<ray->mPass<<", c="<<ray->mPvsContribution<<")"<<endl;
+	if (ray->mPass >= minPass && ray->mPvsContribution > 0)
+	  selected.push_back(ray);
+  }
+  
   return (int)selected.size();
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/preprocessor.pro
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/preprocessor.pro	(revision 1931)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/preprocessor.pro	(revision 1942)
@@ -25,5 +25,5 @@
 unix:INCLUDEPATH += ../support/src/xerces-c-src_2_7_0/include
 
-INCLUDEPATH += ../src  $$NONGTP/Xerces/xerces/include  $$NONGTP/Zlib/include $$NONGTP/Boost $$NONGTP/Devil/include
+INCLUDEPATH += ../src ../src/QtInterface $$NONGTP/Xerces/xerces/include  $$NONGTP/Zlib/include $$NONGTP/Boost $$NONGTP/Devil/include
 
 win32:LIBPATH += GL $$NONGTP/Xerces/xerces/lib $$NONGTP/Devil/lib \
@@ -87,5 +87,5 @@
 # Input
 HEADERS += Halton.h VssRay.h VssPreprocessor.h RssTree.h GlRenderer.h \
-PreprocessorThread.h Preprocessor.h Beam.h QtGlViewer.h
+PreprocessorThread.h Preprocessor.h Beam.h 
 
 
@@ -111,11 +111,13 @@
 Trackball.cpp ObjExporter.cpp SubdivisionCandidate.cpp \
 Mailable.cpp \
-CombinedPreprocessor.cpp QtGlViewer.cpp 
+CombinedPreprocessor.cpp 
 
 SOURCES += BoostPreprocessorThread.cpp 
 
 CONFIG(qt) {
-HEADERS += QtPreprocessorThread.h QtGlRenderer.h
-SOURCES += OcclusionQuery.cpp QtPreprocessorThread.cpp QtGlRenderer.cpp
+HEADERS += QtPreprocessorThread.h QtInterface/QtGlRenderer.h \
+QtInterface/QtGlViewer.h
+SOURCES += OcclusionQuery.cpp QtPreprocessorThread.cpp \
+QtInterface/QtGlRenderer.cpp QtInterface/QtGlViewer.cpp 
 } else {
 SOURCES += BoostPreprocessorThread.cpp 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.cpp	(revision 1931)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.cpp	(revision 1942)
@@ -527,5 +527,7 @@
  
 	float contribution =
-	  mPreprocessor.mViewCellsManager->ComputeSampleContribution(*ray, true, false);
+	  mPreprocessor.mViewCellsManager->ComputeSampleContribution(*ray,
+																 true,
+																 false);
 
 	mDistributions[i]->mContribution += contribution;
@@ -536,13 +538,17 @@
   }
 
+  
+  UpdateRatios();
+}
+
+void
+MixtureDistribution::UpdateDistributions(VssRayContainer &vssRays)
+{
   // now update the distributions with all the rays
-  for (i=0; i < mDistributions.size(); i++) {
+  for (int i=0; i < mDistributions.size(); i++) {
 	mDistributions[i]->Update(vssRays);
   }
-  
-  
-  UpdateRatios();
-}
-
+}
+  
 void
 MixtureDistribution::UpdateRatios()
Index: GTP/trunk/Lib/Vis/Preprocessing/src/QtGlViewer.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/QtGlViewer.cpp	(revision 1936)
+++ 	(revision )
@@ -1,190 +1,0 @@
-// ===================================================================
-// $Id$
-#ifdef USE_QT
-
-// Qt headers
-#include <QtGui>
-#include <QtOpenGL>
-
-// C++ standard headers
-#include <cmath>
-
-// local headers
-#include "common.h"
-#include "QtGlViewer.h"
-#include "QtGlRenderer.h"
-#include "Trackball.h"
-#include "RssPreprocessor.h"
-#include "SceneGraph.h"
-
-
-namespace GtpVisibilityPreprocessor {
-
-QtGlRendererWidget *renderer;
-
-QtGlViewer::QtGlViewer(QWidget *parent,
-					   QtGlRendererWidget *renderer):
-  QGLWidget(parent), mRenderer(renderer)
-{
-	scale = 1.0f;
-	mWireframe = false;
-	trackball(manipulatorLastQuat, 0.0f, 0.0f, 0.0f, 0.0f);
-	connect(renderer, SIGNAL(PvsUpdated()), this, SLOT(updateGL()));
-}
-  
-QSize
-QtGlViewer::minimumSizeHint() const
-{
-  return QSize(100, 100);
-}
-
-QSize
-QtGlViewer::sizeHint() const {
-  return QSize(500, 500);
-}
-  
-// This method has to be rendefined by all renderer implementations
-void
-QtGlViewer::RenderScene()
-{
-	mRenderer->mFrame++;
-	
-	// render into the right side of the window buffer
-	if (mRenderer->mRenderViewCells) 
-	  mRenderer->RenderViewCells();
-	
-	mRenderer->RenderPvs();
-	
-// 	if (mRenderer->mShowRays) {
-// 	  RssPreprocessor *p = (RssPreprocessor *)
-// 			mRenderer->mViewCellsManager->GetPreprocessor();
-// 	  if (p->mRssTree) {
-// 			VssRayContainer rays;
-// 			p->mRssTree->CollectRays(rays, 10000);
-// 			mRenderer->RenderRays(rays);
-// 	  }
-// 	}
-	
-	if (mRenderer->mShowRenderCost) 
-	  mRenderer->RenderRenderCost();
-
-	glColor3f(1.0f, 1.0f, 1.0f);
-	mRenderer->RenderInfo();
-}
-
-
-void
-QtGlViewer::initializeGL()
-{  
-  const char *vendorString, *rendererString, *versionString, *extString;
-
-  // get GL info
-  vendorString = (const char *) glGetString(GL_VENDOR);
-  rendererString = (const char *) glGetString(GL_RENDERER);
-  versionString = (const char *) glGetString(GL_VERSION);
-  extString = (const char *) glGetString(GL_EXTENSIONS);
-  
-  Debug << "Info: GL Vendor = "<<vendorString<<endl
-        << "Info: GL Renderer = "<<rendererString<<endl
-        << "Info: GL Version = "<<versionString<<endl
-        << "Info: GL Extensions = "<<extString<<endl<<flush;
-
-
-  return;
-}
-
-void
-QtGlViewer::paintGL()
-{
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  glLoadIdentity();
-
-  float m[4][4];
-
-  glLoadIdentity();
-  gluLookAt(0.0, 0.0, 1.0,  /* eye is at (0,0,30) */
-						0.0, 0.0, 0.0,      /* center is at (0,0,0) */
-						0.0, 1.0, 0.);      /* up is in positive Y direction */
-  
-  build_rotmatrix(m, manipulatorLastQuat);
-  glMultMatrixf(&m[0][0]);
-
-  float s = scale*20.0f/Magnitude(mRenderer->mSceneGraph->GetBox().Diagonal());
-  glScalef(s, s, s);
-  
-  Vector3 t = -mRenderer->mSceneGraph->GetBox().Center();
-  glTranslatef(t.x, t.y, t.z);
-
-	RenderScene();
-}
-
-void
-QtGlViewer::resizeGL(int width, int height)
-{
-  glViewport(0, 0, width, height);
-  
-  glMatrixMode(GL_PROJECTION);
-  glLoadIdentity();
-  gluPerspective(70.0, 1.0, 0.1, 100.0);
-  //  glOrtho(-0.5*width/height, +0.5*width/height, 0.5, -0.5, 4.0, 15.0);
-  glMatrixMode(GL_MODELVIEW);
-}
-
-
-void
-QtGlViewer::mousePressEvent(QMouseEvent *event)
-{
-  lastPos = event->pos();
-}
-
-void
-QtGlViewer::keyPressEvent ( QKeyEvent * e )
-{
-  switch (e->key()) {
-  case Qt::Key_W:
-		mWireframe  = !mWireframe;
-		updateGL();
-  default:
-		e->ignore();
-		break;
-  }
-  updateGL();
-}
-
-void
-QtGlViewer::mouseMoveEvent(QMouseEvent *event)
-{
-  int dx = event->x() - lastPos.x();
-  int dy = event->y() - lastPos.y();  
-  
-  if (event->modifiers() & Qt::CTRL)
-		{
-			scale = scale*(1.0f - dy/(float)height());
-			if (scale < 0.01f)
-				scale = 0.01f;
-			updateGL();
-		}
-  else {
-		float W = width();
-		float H = height();
-		int x = event->x();
-		int lastX = lastPos.x();
-		int y = event->y();
-		int lastY = lastPos.y();
-	
-		float quat[4];
-		trackball(quat,
-							(2.0 * lastX - W) / W,
-							(H - 2.0 * lastY) / H,
-							(2.0 * x - W) / W,
-							(H - 2.0 * y) / H
-							);
-		add_quats(quat, manipulatorLastQuat, manipulatorLastQuat);
-  }
-  
-  lastPos = event->pos();
-updateGL();
-}
-}
-
-#endif
