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

Revision 1942, 37.8 KB checked in by bittner, 17 years ago (diff)

tmp commit

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