source: GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp @ 2116

Revision 2116, 37.0 KB checked in by mattausch, 17 years ago (diff)

implemented hashpvs

  • Property svn:executable set to *
Line 
1#include "Mesh.h"
2#include "glInterface.h"
3#include "OcclusionQuery.h"
4#include "GlRenderer.h"
5#include "ViewCellsManager.h"
6#include "SceneGraph.h"
7//#include "ObjectPvs.h"
8#include "Viewcell.h"
9#include "Beam.h"
10#include "KdTree.h"
11#include "Environment.h"
12#include "Triangle3.h"
13#include "IntersectableWrapper.h"
14#include "BvHierarchy.h"
15#include "KdTree.h"
16
17#ifdef USE_CG
18
19#include <Cg/cg.h>
20#include <Cg/cgGL.h>
21
22#endif
23
24namespace GtpVisibilityPreprocessor {
25
26
27static bool arbQuerySupport = false;
28static bool nvQuerySupport = false;
29
30static GLuint frontDepthMap;
31static GLuint backDepthMap;
32
33const int depthMapSize = 512;
34
35static void InitExtensions()
36{
37        GLenum err = glewInit();
38
39        if (GLEW_OK != err)
40        {
41                // problem: glewInit failed, something is seriously wrong
42                cerr << "Error: " << glewGetErrorString(err) << endl;
43                exit(1);
44        }
45
46        if (GLEW_ARB_occlusion_query)
47                arbQuerySupport = true;
48       
49        if (GLEW_NV_occlusion_query)
50                nvQuerySupport = true;
51       
52
53        if  (!arbQuerySupport && !nvQuerySupport)
54        {
55                cout << "I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n";
56                exit(1);
57        }
58}
59
60
61GlRenderer::GlRenderer(SceneGraph *sceneGraph,
62                                           ViewCellsManager *viewCellsManager,
63                                           KdTree *tree):
64  Renderer(sceneGraph, viewCellsManager),
65  mKdTree(tree)
66{
67  mSceneGraph->CollectObjects(&mObjects);
68
69  //  mViewCellsManager->GetViewPoint(mViewPoint);
70
71  viewCellsManager->GetViewPoint(mViewPoint);
72        //mSceneGraph->GetBox().Center();
73  mViewDirection = Vector3(0,0,1);
74
75  //  mViewPoint = Vector3(991.7, 187.8, -271);
76  //  mViewDirection = Vector3(0.9, 0, -0.4);
77
78  //  timerId = startTimer(10);
79  // debug coords for atlanta
80  //  mViewPoint = Vector3(3473, 6.778, -1699);
81  //  mViewDirection = Vector3(-0.2432, 0, 0.97);
82 
83  mFrame = 0;
84  mWireFrame = false;
85  Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace",
86                                                                                        mDetectEmptyViewSpace);
87  mSnapErrorFrames = true;
88  mSnapPrefix = "snap/";
89  mUseForcedColors = false;
90  mRenderBoxes = false;
91 // mUseGlLists = true;
92  mUseGlLists = false;
93
94  if (mViewCellsManager->GetViewCellPoints()->size())
95        mPvsStatFrames = (int)mViewCellsManager->GetViewCellPoints()->size();
96  else
97        Environment::GetSingleton()->GetIntValue("Preprocessor.pvsRenderErrorSamples", mPvsStatFrames);
98
99
100  mPvsErrorBuffer.resize(mPvsStatFrames);
101  ClearErrorBuffer();
102}
103
104GlRenderer::~GlRenderer()
105{
106  cerr<<"gl renderer destructor..\n";
107 
108  //CLEAR_CONTAINER(sQueries);
109  CLEAR_CONTAINER(mOcclusionQueries);
110
111  cerr<<"done."<<endl;
112}
113
114
115void
116GlRenderer::RenderTriangle(TriangleIntersectable *object)
117{
118  Triangle3 &t = object->GetItem();
119
120  glBegin(GL_TRIANGLES);
121  Vector3 normal = t.GetNormal();
122  glNormal3f(normal.x, normal.y, normal.z);
123  glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
124  glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
125  glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
126  glEnd();
127}
128
129void
130GlRenderer::RenderIntersectable(Intersectable *object)
131{
132  if (!object)
133        return;
134 
135  if (object->Mailed())
136        return;
137
138  object->Mail();
139 
140  glPushAttrib(GL_CURRENT_BIT);
141  if (mUseFalseColors)
142        SetupFalseColor(object->mId);
143 
144  switch (object->Type()) {
145  case Intersectable::MESH_INSTANCE:
146        RenderMeshInstance((MeshInstance *)object);
147        break;
148  case Intersectable::VIEW_CELL:
149        RenderViewCell(static_cast<ViewCell *>(object));
150        break;
151  case Intersectable::TRANSFORMED_MESH_INSTANCE:
152        RenderTransformedMeshInstance(static_cast<TransformedMeshInstance *>(object));
153        break;
154  case Intersectable::TRIANGLE_INTERSECTABLE:
155        RenderTriangle(static_cast<TriangleIntersectable *>(object));
156        break;
157  case Intersectable::BVH_INTERSECTABLE: {
158
159        BvhNode *node = static_cast<BvhNode *>(object);
160       
161        if (mRenderBoxes)
162          RenderBox(node->GetBoundingBox());
163        else
164          RenderBvhNode(node);
165        break;
166  }
167  case Intersectable::KD_INTERSECTABLE: {
168        KdNode *node = (static_cast<KdIntersectable *>(object))->GetItem();
169       
170        if (mRenderBoxes)
171          RenderBox(mKdTree->GetBox(node));
172        else
173          RenderKdNode(node);
174        break;
175  }
176       
177  default:
178        cerr<<"Rendering this object not yet implemented\n";
179        break;
180  }
181
182  glPopAttrib();
183}
184
185void
186GlRenderer::RenderRays(const VssRayContainer &rays)
187{
188  VssRayContainer::const_iterator it = rays.begin(), it_end = rays.end();
189
190  glBegin(GL_LINES);
191  for (; it != it_end; ++it) {
192        VssRay *ray = *it;
193        float importance = log10(1e3*ray->mWeightedPvsContribution)/3.0f;
194        //      cout<<"w="<<ray->mWeightedPvsContribution<<" r="<<ray->mWeightedPvsContribution;
195        glColor3f(importance, importance, importance);
196        glVertex3fv(&ray->mOrigin.x);
197        glVertex3fv(&ray->mTermination.x);
198  }
199  glEnd();
200}
201
202
203
204void
205GlRenderer::RenderViewCell(ViewCell *vc)
206{
207  if (vc->GetMesh()) {
208
209        if (!mUseFalseColors) {
210          if (vc->GetValid())
211                glColor3f(0,1,0);
212          else
213                glColor3f(0,0,1);
214        }
215       
216        RenderMesh(vc->GetMesh());
217  } else {
218        // render viewcells in the subtree
219        if (!vc->IsLeaf()) {
220          ViewCellInterior *vci = (ViewCellInterior *) vc;
221
222          ViewCellContainer::iterator it = vci->mChildren.begin();
223          for (; it != vci->mChildren.end(); ++it) {
224                RenderViewCell(*it);
225          }
226        } else {
227          //      cerr<<"Empty viewcell mesh\n";
228        }
229  }
230}
231
232
233void
234GlRenderer::RenderMeshInstance(MeshInstance *mi)
235{
236  RenderMesh(mi->GetMesh());
237}
238
239
240void
241GlRenderer::RenderTransformedMeshInstance(TransformedMeshInstance *mi)
242{
243        // apply world transform before rendering
244        Matrix4x4 m;
245        mi->GetWorldTransform(m);
246
247        glPushMatrix();
248/* cout << "\n";
249        for (int i = 0; i < 4; ++ i)
250                for (int j = 0; j < 4; ++ j)
251                        cout << m.x[i][j] << " "; cout << "\n"*/
252
253        glMultMatrixf((float *)m.x);
254
255        /*GLfloat dummy[16];
256        glGetFloatv(GL_MODELVIEW_MATRIX, dummy);
257        for (int i = 0; i < 16; ++ i)
258                cout << dummy[i] << " ";
259        cout << endl;*/
260        RenderMesh(mi->GetMesh());
261       
262        glPopMatrix();
263}
264
265
266void
267GlRenderer::SetupFalseColor(const unsigned int id)
268{
269        // swap bits of the color
270        glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
271}
272
273
274unsigned int GlRenderer::GetId(const unsigned char r,
275                                                           const unsigned char g,
276                                                           const unsigned char b) const
277{
278        return r + (g << 8) + (b << 16);
279}
280
281
282void
283GlRenderer::SetupMaterial(Material *m)
284{
285  if (m)
286        glColor3fv(&(m->mDiffuseColor.r));
287}
288
289
290void
291GlRenderer::RenderMesh(Mesh *mesh)
292{
293  int i = 0;
294
295  if (!mUseFalseColors && !mUseForcedColors)
296          SetupMaterial(mesh->mMaterial);
297 
298  for (i=0; i < mesh->mFaces.size(); i++) {
299        if (mWireFrame)
300          glBegin(GL_LINE_LOOP);
301        else
302          glBegin(GL_POLYGON);
303
304        Face *face = mesh->mFaces[i];
305        for (int j = 0; j < face->mVertexIndices.size(); j++) {
306          glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
307        }
308        glEnd();
309  }
310}
311       
312void
313GlRenderer::InitGL()
314{
315  mSphere = (GLUquadric *)gluNewQuadric();
316 
317  glMatrixMode(GL_PROJECTION);
318  glLoadIdentity();
319 
320  glMatrixMode(GL_MODELVIEW);
321  glLoadIdentity();
322
323  glFrontFace(GL_CCW);
324  glCullFace(GL_BACK);
325  glEnable(GL_CULL_FACE);
326  glShadeModel(GL_FLAT);
327  glDepthFunc( GL_LESS );
328  glEnable(GL_DEPTH_TEST);
329  glEnable(GL_CULL_FACE);
330 
331  InitExtensions();
332
333  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
334
335  glEnable( GL_NORMALIZE );
336 
337  glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
338 
339  OcclusionQuery::GenQueries(mOcclusionQueries, 10);
340}
341
342
343void
344GlRenderer::SetupProjection(const int w, const int h, const float angle)
345{
346  glViewport(0, 0, w, h);
347  glMatrixMode(GL_PROJECTION);
348  glLoadIdentity();
349  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
350  glMatrixMode(GL_MODELVIEW);
351}
352
353
354
355void
356GlRenderer::SetupCamera()
357{
358  Vector3 target = mViewPoint + mViewDirection;
359  //cout << "vp: " << mViewPoint << " dr: " << mViewDirection << endl;
360  //cout<<"box: " << mKdTree->GetBox()<<endl;
361  Vector3 up(0,1,0);
362 
363  if (abs(DotProd(mViewDirection, up)) > 0.99f)
364        up = Vector3(1, 0, 0);
365 
366  glLoadIdentity();
367  gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
368                        target.x, target.y, target.z,
369                        up.x, up.y, up.z);
370}
371
372void
373GlRenderer::_RenderScene()
374{
375  ObjectContainer::const_iterator oi = mObjects.begin();
376  for (; oi != mObjects.end(); oi++)
377        RenderIntersectable(*oi);
378}
379
380void
381GlRenderer::_RenderSceneTriangles()
382{
383  glBegin(GL_TRIANGLES);
384
385  ObjectContainer::const_iterator oi = mObjects.begin();
386  for (; oi != mObjects.end(); oi++) {
387       
388        if ((*oi)->Type() == Intersectable::TRIANGLE_INTERSECTABLE) {
389          TriangleIntersectable *object = (TriangleIntersectable *)*oi;
390          Triangle3 &t = object->GetItem();
391         
392          Vector3 normal = t.GetNormal();
393          glNormal3f(normal.x, normal.y, normal.z);
394          glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
395          glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
396          glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
397         
398        }
399  }
400
401  glEnd();
402 
403}
404
405bool
406GlRenderer::RenderScene()
407{
408  Intersectable::NewMail();
409  static int glList = -1;
410  if (mUseGlLists) {
411        if (glList == -1) {
412          glList = glGenLists(1);
413          glNewList(glList, GL_COMPILE);
414          _RenderSceneTriangles();
415          glEndList();
416        }
417       
418        glCallList(glList);
419  } else
420        _RenderSceneTriangles();
421       
422 
423  return true;
424}
425
426
427void
428GlRendererBuffer::EvalQueryWithItemBuffer(
429                                                                                  //RenderCostSample &sample
430                                                                           )
431{
432        // read back the texture
433        glReadPixels(0, 0,
434                                GetWidth(), GetHeight(),
435                                GL_RGBA,
436                                GL_UNSIGNED_BYTE,
437                                mPixelBuffer);
438               
439                       
440        unsigned int *p = mPixelBuffer;
441                       
442        for (int y = 0; y < GetHeight(); y++)
443        {
444                for (int x = 0; x < GetWidth(); x++, p++)
445                {
446                        unsigned int id = (*p) & 0xFFFFFF;
447
448                        if (id != 0xFFFFFF)
449                        {
450                                ++ mObjects[id]->mCounter;
451                        }
452                }
453        }
454}
455
456
457
458/****************************************************************/
459/*               GlRendererBuffer implementation                */
460/****************************************************************/
461
462
463
464GlRendererBuffer::GlRendererBuffer(SceneGraph *sceneGraph,
465                                                                   ViewCellsManager *viewcells,
466                                                                   KdTree *tree):
467GlRenderer(sceneGraph, viewcells, tree) 
468{
469 
470  mPixelBuffer = NULL;
471 
472  // implement width and height in subclasses
473}
474
475
476void
477GlRendererBuffer::EvalQueryWithOcclusionQueries(
478                                                                           //RenderCostSample &sample
479                                                                           )
480{
481        glDepthFunc(GL_LEQUAL);
482               
483        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
484        glDepthMask(GL_FALSE);
485
486
487        // simulate detectemptyviewspace using backface culling
488        if (mDetectEmptyViewSpace)
489        {
490                glEnable(GL_CULL_FACE);
491                //cout << "culling" << endl;
492        }
493        else
494        {
495                //cout << "not culling" << endl;
496                glDisable(GL_CULL_FACE);
497        }
498
499       
500        //const int numQ = 1;
501        const int numQ = (int)mOcclusionQueries.size();
502       
503        //glFinish();
504#if 0
505        //-- now issue queries for all objects
506        for (int j = 0; j < (int)mObjects.size(); ++ j)
507        {
508                mOcclusionQueries[j]->BeginQuery();
509                RenderIntersectable(mObjects[j]);
510                mOcclusionQueries[j]->EndQuery();
511
512                unsigned int pixelCount;
513
514                pixelCount = mOcclusionQueries[j]->GetQueryResult();
515               
516                mObjects[j]->mCounter += pixelCount;
517        }
518#else
519
520        int q = 0;
521
522        //-- now issue queries for all objects
523        for (int j = 0; j < (int)mObjects.size(); j += q)
524        {       
525                for (q = 0; ((j + q) < (int)mObjects.size()) && (q < numQ); ++ q)
526                {
527                        //glFinish();
528                        mOcclusionQueries[q]->BeginQuery();
529                       
530                        RenderIntersectable(mObjects[j + q]);
531               
532                        mOcclusionQueries[q]->EndQuery();
533                        //glFinish();
534                }
535                //cout << "q: " << q << endl;
536                // collect results of the queries
537                for (int t = 0; t < q; ++ t)
538                {
539                        unsigned int pixelCount;
540               
541                        //-- reenable other state
542#if 0
543                        bool available;
544
545                        do
546                        {
547                                available = mOcclusionQueries[t]->ResultAvailable();
548                               
549                                if (!available) cout << "W";
550                        }
551                        while (!available);
552#endif
553
554                        pixelCount = mOcclusionQueries[t]->GetQueryResult();
555
556                        //if (pixelCount > 0)
557                        //      cout <<"o="<<j+q<<" q="<<mOcclusionQueries[q]->GetQueryId()<<" pc="<<pixelCount<<" ";
558                        mObjects[j + t]->mCounter += pixelCount;
559               
560                }
561
562                //j += q;
563        }
564#endif
565        //glFinish();
566        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
567        glDepthMask(GL_TRUE);
568       
569        glEnable(GL_CULL_FACE);
570}
571
572
573void
574GlRenderer::RandomViewPoint()
575{
576  // do not use this function since it could return different viewpoints for
577  // different executions of the algorithm
578
579  //  mViewCellsManager->GetViewPoint(mViewPoint);
580
581  while (1) {
582        Vector3 pVector = Vector3(halton.GetNumber(1),
583                                                          halton.GetNumber(2),
584                                                          halton.GetNumber(3));
585       
586        mViewPoint =  mViewCellsManager->GetViewSpaceBox().GetPoint(pVector);
587        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
588        if (v && v->GetValid())
589          break;
590        // generate a new vector
591        halton.GenerateNext();
592  }
593 
594  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
595                                                        M_PI*halton.GetNumber(5),
596                                                        0.0f);
597 
598  mViewDirection = Normalize(Vector3(sin(dVector.x),
599                                                                         //                                                                      cos(dVector.y),
600                                                                         0.0f,
601                                                                         cos(dVector.x)));
602  halton.GenerateNext();
603}
604
605
606void
607GlRenderer::RenderBox(const AxisAlignedBox3 &box)
608{
609
610  glBegin(GL_LINE_LOOP);
611  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
612  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
613  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
614  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
615  glEnd();
616
617  glBegin(GL_LINE_LOOP);
618  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
619  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
620  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
621  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
622  glEnd();
623
624  glBegin(GL_LINE_LOOP);
625  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
626  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
627  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
628  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
629  glEnd();
630
631  glBegin(GL_LINE_LOOP);
632  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
633  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
634  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
635  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
636  glEnd();
637
638  glBegin(GL_LINE_LOOP);
639  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
640  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
641  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
642  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
643  glEnd();
644
645  glBegin(GL_LINE_LOOP);
646  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
647  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
648  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
649  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
650
651  glEnd();
652
653}
654
655void
656GlRenderer::RenderBvhNode(BvhNode *node)
657{
658  if (node->IsLeaf()) {
659        BvhLeaf *leaf = (BvhLeaf *) node;
660
661#if 0
662        if (leaf->mGlList == 0) {
663          leaf->mGlList = glGenLists(1);
664          if (leaf->mGlList != 0)
665                glNewList(leaf->mGlList, GL_COMPILE);
666         
667          for (int i=0; i < leaf->mObjects.size(); i++)
668                RenderIntersectable(leaf->mObjects[i]);
669         
670          if (leaf->mGlList != 0)
671                glEndList();
672        }
673       
674        if (leaf->mGlList != 0)
675          glCallList(leaf->mGlList);
676#else
677        for (int i=0; i < leaf->mObjects.size(); i++)
678          RenderIntersectable(leaf->mObjects[i]);
679#endif
680  } else {
681        BvhInterior *in = (BvhInterior *)node;
682        RenderBvhNode(in->GetBack());
683        RenderBvhNode(in->GetFront());
684  }
685
686  //cout << "leaf obj " << i << endl;
687
688}
689
690void
691GlRenderer::RenderKdNode(KdNode *node)
692{
693  if (node->IsLeaf()) {
694        KdLeaf *leaf = (KdLeaf *) node;
695        for (int i=0; i < leaf->mObjects.size(); i++) {
696          RenderIntersectable(leaf->mObjects[i]);
697        }
698  } else {
699        KdInterior *in = (KdInterior *)node;
700        RenderKdNode(in->mBack);
701        RenderKdNode(in->mFront);
702  }
703 
704}
705
706
707
708
709
710
711
712void
713GlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
714                                                                           const bool useOcclusionQueries,
715                                                                           const int threshold
716                                                                           )
717{
718  // choose a random view point
719  mViewCellsManager->GetViewPoint(mViewPoint);
720  sample.mPosition = mViewPoint;
721  //cout << "viewpoint: " << mViewPoint << endl;
722 
723  // take a render cost sample by rendering a cube
724  Vector3 directions[6];
725 
726  directions[0] = Vector3(1,0,0);
727  directions[1] = Vector3(0,1,0);
728  directions[2] = Vector3(0,0,1);
729  directions[3] = Vector3(-1,0,0);
730  directions[4] = Vector3(0,-1,0);
731  directions[5] = Vector3(0,0,-1);
732 
733  sample.mVisibleObjects = 0;
734 
735  // reset object counters
736  ObjectContainer::const_iterator it, it_end = mObjects.end();
737 
738  for (it = mObjects.begin(); it != it_end; ++ it)
739        {
740          (*it)->mCounter = 0;
741         
742        }
743
744  ++ mFrame;
745 
746  //glCullFace(GL_FRONT);
747  glCullFace(GL_BACK);
748  glDisable(GL_CULL_FACE);
749 
750 
751        // query all 6 directions for a full point sample
752  for (int i = 0; i < 6; ++ i)
753        {
754          mViewDirection = directions[i];
755          SetupCamera();
756         
757          glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
758          glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
759          //glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);    glDepthMask(GL_TRUE);
760          glDepthFunc(GL_LESS);
761         
762          mUseFalseColors = true;
763         
764          // the actual scene rendering fills the depth (for occlusion queries)
765          // and the frame buffer (for item buffer)
766          RenderScene();
767         
768         
769          if (0)
770                {
771                  char filename[256];
772                  sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
773                  //              QImage im = toImage();
774                  //              im.save(filename, "PNG");
775                }
776         
777          // evaluate the sample
778          if (useOcclusionQueries)
779                {
780                  EvalQueryWithOcclusionQueries();
781                }
782          else
783                {
784                  EvalQueryWithItemBuffer();
785                }
786        } 
787 
788  // now evaluate the statistics over that sample
789  // currently only the number of visible objects is taken into account
790  sample.Reset();
791 
792  for (it = mObjects.begin(); it != it_end; ++ it)
793        {
794          Intersectable *obj = *it;
795          if (obj->mCounter >= threshold)
796                {
797                  ++ sample.mVisibleObjects;
798                  sample.mVisiblePixels += obj->mCounter;
799                }
800        }
801 
802  //cout << "RS=" << sample.mVisibleObjects << " ";
803}
804
805
806GlRendererBuffer::~GlRendererBuffer()
807{
808#if 0
809#ifdef USE_CG
810        if (sCgFragmentProgram)
811                cgDestroyProgram(sCgFragmentProgram);
812        if (sCgContext)
813                cgDestroyContext(sCgContext);
814#endif
815#endif
816}
817
818
819void
820GlRendererBuffer::SampleRenderCost(const int numSamples,
821                                                                   vector<RenderCostSample> &samples,
822                                                                   const bool useOcclusionQueries,
823                                                                   const int threshold
824                                                                   )
825{
826  MakeCurrent();
827
828  if (mPixelBuffer == NULL)
829          mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
830 
831  // using 90 degree projection to capture 360 view with 6 samples
832  SetupProjection(GetHeight(), GetHeight(), 90.0f);
833
834  //samples.resize(numSamples);
835  halton.Reset();
836 
837  // the number of queries queried in batch mode
838  const int numQ = 500;
839
840  //const int numQ = (int)mObjects.size();
841  if (useOcclusionQueries)
842  {
843          cout << "\ngenerating " << numQ << " queries ... ";
844          OcclusionQuery::GenQueries(mOcclusionQueries, numQ);
845          cout << "finished" << endl;
846  }
847
848  // sampling queries
849  for (int i = 0; i < numSamples; ++ i)
850  {
851          cout << ".";
852          EvalRenderCostSample(samples[i], useOcclusionQueries, threshold);
853  }
854
855  DoneCurrent();
856}
857 
858
859
860
861
862void
863GlRenderer::ClearErrorBuffer()
864{
865  for (int i=0; i < mPvsStatFrames; i++) {
866        mPvsErrorBuffer[i].mError = 1.0f;
867  }
868  mPvsStat.maxError = 0.0f;
869}
870
871
872void
873GlRendererBuffer::EvalPvsStat()
874{
875        MakeCurrent();
876       
877        GlRenderer::EvalPvsStat();
878       
879        DoneCurrent();
880  //  mRenderingFinished.wakeAll();
881}
882
883
884void GlRendererBuffer::EvalPvsStat(const SimpleRayContainer &viewPoints)
885{
886        MakeCurrent();
887
888        GlRenderer::EvalPvsStat(viewPoints);
889 
890        DoneCurrent();
891}
892
893
894void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
895                                                                                           Beam &beam,
896                                                                                           const int desiredSamples,
897                                                                                           BeamSampleStatistics &stat)
898{
899        // TODO: should be moved out of here (not to be done every time)
900        // only back faces are interesting for the depth pass
901        glShadeModel(GL_FLAT);
902        glDisable(GL_LIGHTING);
903
904        // needed to kill the fragments for the front buffer
905        glEnable(GL_ALPHA_TEST);
906        glAlphaFunc(GL_GREATER, 0);
907
908        // assumes that the beam is constructed and contains kd-tree nodes
909        // and viewcells which it intersects
910 
911 
912        // Get the number of viewpoints to be sampled
913        // Now it is a sqrt but in general a wiser decision could be made.
914        // The less viewpoints the better for rendering performance, since less passes
915        // over the beam is needed.
916        // The viewpoints could actually be generated outside of the bounding box which
917        // would distribute the 'efective viewpoints' of the object surface and thus
918        // with a few viewpoints better sample the viewpoint space....
919
920        //TODO: comment in
921        //int viewPointSamples = sqrt((float)desiredSamples);
922        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
923       
924        // the number of direction samples per pass is given by the number of viewpoints
925        int directionalSamples = desiredSamples / viewPointSamples;
926       
927        Debug << "directional samples: " << directionalSamples << endl;
928        for (int i = 0; i < viewPointSamples; ++ i)
929        {
930                Vector3 viewPoint = beam.mBox.GetRandomPoint();
931               
932                // perhaps the viewpoint should be shifted back a little bit so that it always lies
933                // inside the source object
934                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
935        // would require more complicated sampling (perhaps hierarchical rejection sampling of
936                // the object surface is an option here - only the mesh faces which are inside the box
937                // are considered as candidates)
938               
939                SampleViewpointContributions(sourceObject,
940                                                                         viewPoint,
941                                                                         beam,
942                                                                         directionalSamples,
943                                                                         stat);
944        }
945
946
947        // note:
948        // this routine would be called only if the number of desired samples is sufficiently
949        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
950        // distributing the work between cpu and gpu would also allow us to place more sophisticated
951        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
952        // in order that thios scheme is working well the gpu render buffer should run in a separate
953        // thread than the cpu sampler, which would not be such a big problem....
954
955        // disable alpha test again
956        glDisable(GL_ALPHA_TEST);
957}
958
959
960
961void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
962                                                                                                        const Vector3 viewPoint,
963                                                                                                        Beam &beam,
964                                                                                                        const int samples,
965                                                    BeamSampleStatistics &stat)
966{
967    // 1. setup the view port to match the desired samples
968        glViewport(0, 0, samples, samples);
969
970        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
971        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
972
973
974        // 3. reset z-buffer to 0 and render the source object for the beam
975        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
976        //    save result to the front depth map
977        //    the front depth map holds ray origins
978
979
980        // front depth buffer must be initialised to 0
981        float clearDepth;
982       
983        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
984        glClearDepth(0.0f);
985        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
986
987
988        // glFrontFace(GL_CCW);
989        glEnable(GL_CULL_FACE);
990        glCullFace(GL_FRONT);
991        glColorMask(0, 0, 0, 0);
992       
993
994        // stencil is increased where the source object is located
995        glEnable(GL_STENCIL_TEST);     
996        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
997        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
998
999
1000#if 0
1001        static int glSourceObjList = -1;         
1002        if (glSourceObjList != -1)
1003        {
1004                glSourceObjList = glGenLists(1);
1005                glNewList(glSourceObjList, GL_COMPILE);
1006
1007                RenderIntersectable(sourceObject);
1008       
1009                glEndList();
1010        }
1011        glCallList(glSourceObjList);
1012
1013#else
1014        RenderIntersectable(sourceObject);
1015
1016#endif 
1017
1018         // copy contents of the front depth buffer into depth texture
1019        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
1020        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1021
1022        // reset clear function
1023        glClearDepth(clearDepth);
1024       
1025       
1026        // 4. set up the termination depth buffer (= standard depth buffer)
1027        //    only rays which have non-zero entry in the origin buffer are valid since
1028        //    they realy start on the object surface (this is tagged by setting a
1029        //    stencil buffer bit at step 3).
1030       
1031        glStencilFunc(GL_EQUAL, 0x1, 0x1);
1032        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1033
1034        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1035        glDepthMask(1);
1036
1037        glEnable(GL_DEPTH_TEST);
1038               
1039        glEnable(GL_CULL_FACE);
1040        glCullFace(GL_BACK);
1041
1042        // setup front depth buffer
1043        glEnable(GL_TEXTURE_2D);
1044       
1045#if 0
1046#ifdef USE_CG
1047        // bind pixel shader implementing the front depth buffer functionality
1048        cgGLBindProgram(sCgFragmentProgram);
1049        cgGLEnableProfile(sCgFragmentProfile);
1050#endif
1051#endif
1052        // 5. render all objects inside the beam
1053        //    we can use id based false color to read them back for gaining the pvs
1054
1055        glColorMask(1, 1, 1, 1);
1056
1057       
1058        // if objects not stored in beam => extract objects
1059        if (beam.mFlags & !Beam::STORE_OBJECTS)
1060        {
1061                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
1062
1063                Intersectable::NewMail();
1064                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
1065                {
1066                        mKdTree->CollectObjects(*it, beam.mObjects);
1067                }
1068        }
1069
1070
1071        //    (objects can be compiled to a gl list now so that subsequent rendering for
1072        //    this beam is fast - the same hold for step 3)
1073        //    Afterwards we have two depth buffers defining the ray origin and termination
1074       
1075
1076#if 0
1077        static int glObjList = -1;
1078        if (glObjList != -1)
1079        {
1080                glObjList = glGenLists(1);
1081                glNewList(glObjList, GL_COMPILE);
1082       
1083                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1084                for (it = beam.mObjects.begin(); it != it_end; ++ it)
1085                {
1086                        // render all objects except the source object
1087                        if (*it != sourceObject)
1088                                RenderIntersectable(*it);
1089                }
1090               
1091                glEndList();
1092        }
1093
1094        glCallList(glObjList);
1095#else
1096        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1097        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1098        {       
1099                // render all objects except the source object
1100                if (*it != sourceObject)
1101                        RenderIntersectable(*it);
1102        }
1103#endif
1104       
1105        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1106        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1107        //     between origin and termination buffer
1108
1109        // create new queries if necessary
1110        OcclusionQuery::GenQueries(mOcclusionQueries, (int)beam.mViewCells.size());
1111
1112        // check whether any backfacing polygon would pass the depth test?
1113        // matt: should check both back /front facing because of dual depth buffer
1114        // and danger of cutting the near plane with front facing polys.
1115       
1116        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1117        glDepthMask(GL_FALSE);
1118        glDisable(GL_CULL_FACE);
1119
1120 
1121        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1122
1123        int queryIdx = 0;
1124
1125        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1126        {
1127                mOcclusionQueries[queryIdx ++]->BeginQuery();
1128
1129                RenderIntersectable(*vit);
1130               
1131                mOcclusionQueries[queryIdx]->EndQuery();
1132
1133                ++ queryIdx;
1134        }
1135
1136        // at this point, if possible, go and do some other computation
1137
1138        // 7. The number of visible pixels is the number of sample rays which see the source
1139        //    object from the corresponding viewcell -> remember these values for later update
1140        //   of the viewcell pvs - or update immediately?
1141
1142        queryIdx = 0;
1143
1144        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1145        {
1146                // fetch queries
1147                unsigned int pixelCount = mOcclusionQueries[queryIdx ++]->GetQueryResult();
1148
1149                if (pixelCount)
1150                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1151        }
1152       
1153
1154        // 8. Copmpute rendering statistics
1155        // In general it is not neccessary to remember to extract all the rays cast. I hope it
1156        // would be sufficient to gain only the intergral statistics about the new contributions
1157        // and so the rss tree would actually store no new rays (only the initial ones)
1158        // the subdivision of the tree would only be driven by the statistics (the glrender could
1159        // evaluate the contribution entropy for example)
1160        // However might be an option to extract/store only those the rays which made a contribution
1161        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
1162
1163        ObjectContainer pvsObj;
1164        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
1165       
1166        // to gain ray source and termination
1167        // copy contents of ray termination buffer into depth texture
1168        // and compare with ray source buffer
1169#if 0
1170        VssRayContainer rays;
1171
1172        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
1173        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1174
1175        ComputeRays(Intersectable *sourceObj, rays);
1176
1177#endif
1178
1179        ////////
1180        //-- cleanup
1181
1182        // reset gl state
1183        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1184        glDepthMask(GL_TRUE);
1185        glEnable(GL_CULL_FACE);
1186        glDisable(GL_STENCIL_TEST);
1187
1188#if 0
1189#ifdef USE_CG
1190        cgGLDisableProfile(sCgFragmentProfile);
1191#endif
1192#endif
1193
1194        glDisable(GL_TEXTURE_2D);
1195
1196        // remove objects from beam
1197        if (beam.mFlags & !Beam::STORE_OBJECTS)
1198                beam.mObjects.clear();
1199}
1200
1201
1202void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
1203                                                                                                   const Beam &beam,
1204                                                                                                   Intersectable *sourceObject)
1205{
1206        float left, right, bottom, top, znear, zfar;
1207
1208        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
1209                                                                   mSceneGraph->GetBox());
1210
1211        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
1212        glMatrixMode(GL_PROJECTION);
1213        glLoadIdentity();
1214        glFrustum(left, right, bottom, top, znear, zfar);
1215        //glFrustum(-1, 1, -1, 1, 1, 20000);
1216
1217    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
1218        const Vector3 up =
1219                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
1220
1221#ifdef GTP_DEBUG
1222        Debug << "view point: " << viewPoint << endl;
1223        Debug << "eye: " << center << endl;
1224        Debug << "up: " << up << endl;
1225#endif
1226
1227        glMatrixMode(GL_MODELVIEW);
1228        glLoadIdentity();
1229        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
1230                          center.x, center.y, center.z,                   
1231                          up.x, up.y, up.z);
1232}               
1233
1234 
1235void GlRendererBuffer::InitGL()
1236{
1237        MakeCurrent();
1238        GlRenderer::InitGL();
1239
1240        // initialise dual depth buffer textures
1241        glGenTextures(1, &frontDepthMap);
1242        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1243       
1244        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1245                                 depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1246
1247        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1248        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1249        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1250        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1251
1252        glGenTextures(1, &backDepthMap);
1253        glBindTexture(GL_TEXTURE_2D, backDepthMap);
1254       
1255        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1256                                 depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1257        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1258        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1259        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1260        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1261
1262#if 0
1263#ifdef USE_CG
1264
1265        // cg initialization
1266        cgSetErrorCallback(handleCgError);
1267        sCgContext = cgCreateContext();
1268       
1269        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1270                sCgFragmentProfile = CG_PROFILE_ARBFP1;
1271        else
1272        {
1273          // try FP30
1274          if (cgGLIsProfileSupported(CG_PROFILE_FP30))
1275            sCgFragmentProfile = CG_PROFILE_FP30;
1276          else
1277          {
1278                  Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
1279                  exit(1);
1280          }
1281  }
1282
1283 sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
1284                                                                                           CG_SOURCE, "../src/dual_depth.cg",
1285                                                                                           sCgFragmentProfile,
1286                                                                                           NULL,
1287                                                                                           NULL);
1288
1289  if (!cgIsProgramCompiled(sCgFragmentProgram))
1290          cgCompileProgram(sCgFragmentProgram);
1291
1292  cgGLLoadProgram(sCgFragmentProgram);
1293  cgGLBindProgram(sCgFragmentProgram);
1294
1295  Debug << "---- PROGRAM BEGIN ----\n" <<
1296          cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
1297
1298#endif
1299
1300#endif
1301  DoneCurrent();
1302}
1303
1304
1305void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
1306{
1307        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
1308        {
1309                //todo glGetTexImage()
1310        }
1311}
1312
1313bool GlRendererBuffer::ValidViewPoint()
1314{       
1315        MakeCurrent();
1316
1317        SetupProjection(GetWidth(), GetHeight());
1318
1319        bool result = GlRenderer::ValidViewPoint();
1320
1321        DoneCurrent();
1322       
1323        return result;
1324}
1325
1326
1327void
1328GlRenderer::EvalPvsStat()
1329{
1330  mPvsStat.Reset();
1331  halton.Reset();
1332
1333  SetupProjection(GetWidth(), GetHeight());
1334
1335  cout<<"mPvsStatFrames="<<mPvsStatFrames<<endl;
1336 
1337  for (int i=0; i < mPvsStatFrames; i++) {
1338        float err;
1339        // set frame id for saving the error buffer
1340        mFrame = i;
1341        RandomViewPoint();
1342
1343        if (mPvsErrorBuffer[i].mError == 1.0f) {
1344          // check if the view point is valid
1345          if (!ValidViewPoint())
1346                mPvsErrorBuffer[i].mError = -1.0f;
1347
1348          // manualy corrected view point
1349          if (mFrame == 5105)
1350                mPvsErrorBuffer[i].mError = -1.0f;
1351        }
1352       
1353       
1354        // atlanta problematic frames: 325 525 691 1543
1355#if 0
1356        if (mFrame != 325 &&
1357                mFrame != 525 &&
1358                mFrame != 691 &&
1359                mFrame != 1543)
1360          mPvsErrorBuffer[i] = -1;
1361        else {
1362          Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
1363        }
1364#endif
1365       
1366        if (mPvsErrorBuffer[i].mError > 0.0f) {
1367          int pvsSize;
1368         
1369          float error = GetPixelError(pvsSize);
1370          mPvsErrorBuffer[i].mError = error;
1371          mPvsErrorBuffer[i].mPvsSize = pvsSize;
1372
1373          //      emit UpdatePvsErrorItem(i,
1374          //                                                      mPvsErrorBuffer[i]);
1375          cout<<"("<<i<<","<<mPvsErrorBuffer[i].mError<<")";
1376          //      swapBuffers();
1377        }
1378       
1379        err = mPvsErrorBuffer[i].mError;
1380       
1381        if (err >= 0.0f) {
1382          if (err > mPvsStat.maxError)
1383                mPvsStat.maxError = err;
1384          mPvsStat.sumError += err;
1385          mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1386         
1387          if (err == 0.0f)
1388                mPvsStat.errorFreeFrames++;
1389          mPvsStat.frames++;
1390        }
1391  }
1392 
1393  glFinish();
1394  cout<<endl<<flush;
1395}
1396
1397
1398void GlRenderer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1399{
1400  mPvsStat.Reset();
1401
1402  SetupProjection(GetWidth(), GetHeight());
1403 
1404  cout << "mPvsStatFrames=" << mPvsStatFrames << endl;
1405 
1406  SimpleRayContainer::const_iterator sit, sit_end = viewPoints.end();
1407  int i = 0;
1408 
1409  for (sit = viewPoints.begin(); sit != sit_end; ++ sit, ++ i)
1410        {
1411         
1412          //cout << "view point: " << (*sit) << endl;;
1413          SimpleRay sray = *sit;
1414         
1415          float err;
1416         
1417          // set frame id for saving the error buffer
1418          mFrame = i;
1419          mViewPoint = sray.mOrigin;
1420          mViewDirection = sray.mDirection;
1421         
1422          if (mPvsErrorBuffer[i].mError > 0.0f)
1423                {
1424                  int pvsSize;
1425                 
1426                  // compute the pixel error
1427                  float error = GetPixelError(pvsSize);
1428                 
1429                  mPvsErrorBuffer[i].mError = error;
1430                  mPvsErrorBuffer[i].mPvsSize = pvsSize;
1431                 
1432                  cout << "(" << i << "," << mPvsErrorBuffer[i].mError <<")";
1433                }
1434         
1435          err = mPvsErrorBuffer[i].mError;
1436         
1437          if (err >= 0.0f)
1438                {
1439                  if (err > mPvsStat.maxError)
1440                        mPvsStat.maxError = err;
1441                 
1442                  mPvsStat.sumError += err;
1443                        mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1444                       
1445                        if (err == 0.0f)
1446                          ++ mPvsStat.errorFreeFrames;
1447                       
1448                        ++ mPvsStat.frames;
1449                }
1450        }
1451 
1452  glFinish();
1453  cout << endl << flush;
1454}
1455
1456
1457
1458bool
1459GlRenderer::ValidViewPoint()
1460{
1461   //cout<<"VV4 ";
1462        if (!mDetectEmptyViewSpace)
1463                return true;
1464        //cout << "vp: " << mViewPoint << " dir: " << mViewDirection << endl;
1465
1466  OcclusionQuery *query = mOcclusionQueries[0];
1467
1468  // now check whether any backfacing polygon would pass the depth test
1469  SetupCamera();
1470  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1471  glEnable( GL_CULL_FACE );
1472  glCullFace(GL_BACK);
1473 
1474  //cout<<"VV1 ";
1475  RenderScene();
1476 
1477  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1478  glDepthMask(GL_FALSE);
1479  glDisable( GL_CULL_FACE );
1480 
1481  query->BeginQuery();
1482 
1483  //  cout<<"VV2 ";
1484  RenderScene();
1485  //  cout<<"VV3 ";
1486 
1487  query->EndQuery();
1488 
1489  // at this point, if possible, go and do some other computation
1490  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1491  glDepthMask(GL_TRUE);
1492  glEnable( GL_CULL_FACE );
1493
1494  //  int wait = 0;
1495  //  while (!query.ResultAvailable()) {
1496  //    wait++;
1497  //  }
1498 
1499  // reenable other state
1500  unsigned int pixelCount = query->GetQueryResult();
1501  //  cout<<"VV4 ";
1502 
1503          //cout<<"count: " << pixelCount<<endl;
1504 
1505  if (pixelCount > 0)
1506  {
1507        return false; // backfacing polygon found -> not a valid viewspace sample
1508  }
1509  return true;
1510}
1511
1512float
1513GlRenderer::GetPixelError(int &pvsSize)
1514{
1515  return -1.0f;
1516}
1517
1518void
1519GlRenderer::RenderViewPoint()
1520{
1521  mWireFrame = true;
1522  glPushMatrix();
1523  glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
1524  glScalef(5.0f,5.0f,5.0f);
1525  glPushAttrib(GL_CURRENT_BIT);
1526  glColor3f(1.0f, 0.0f, 0.0f);
1527  gluSphere((::GLUquadric *)mSphere,
1528                        1e-3*Magnitude(mViewCellsManager->GetViewSpaceBox().Size()), 6, 6);
1529  glPopAttrib();
1530  glPopMatrix();
1531  mWireFrame = false;
1532}
1533
1534
1535
1536
1537
1538}
Note: See TracBrowser for help on using the repository browser.