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

Revision 1112, 56.6 KB checked in by bittner, 18 years ago (diff)

Merge with Olivers code

  • 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
13
14//#define GL_GLEXT_PROTOTYPES
15
16
17#include <Cg/cg.h>
18#include <Cg/cgGL.h>
19
20
21#include <QVBoxLayout>
22
23namespace GtpVisibilityPreprocessor {
24
25static CGcontext sCgContext = NULL;
26static CGprogram sCgFragmentProgram = NULL;
27static CGprofile sCgFragmentProfile;
28
29GLuint frontDepthMap;
30GLuint backDepthMap;
31
32const int depthMapSize = 512;
33static vector<OcclusionQuery *> sQueries;
34
35GlRendererWidget *rendererWidget = NULL;
36GlDebuggerWidget *debuggerWidget = NULL;
37
38static bool arbQuerySupport = false;
39static bool nvQuerySupport = false;
40
41
42static void InitExtensions()
43{
44        GLenum err = glewInit();
45
46        if (GLEW_OK != err)
47        {
48                // problem: glewInit failed, something is seriously wrong
49                cerr << "Error: " << glewGetErrorString(err) << endl;
50                exit(1);
51        }
52
53        if (GLEW_ARB_occlusion_query)
54                arbQuerySupport = true;
55       
56        if (GLEW_NV_occlusion_query)
57                nvQuerySupport = true;
58       
59
60        if  (!arbQuerySupport && !nvQuerySupport)
61        {
62                cout << "I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n";
63                exit(1);
64        }
65}
66
67
68GlRenderer::GlRenderer(SceneGraph *sceneGraph,
69                                           ViewCellsManager *viewCellsManager,
70                                           KdTree *tree):
71  Renderer(sceneGraph, viewCellsManager),
72  mKdTree(tree)
73{
74  mSceneGraph->CollectObjects(&mObjects);
75
76  //  mViewCellsManager->GetViewPoint(mViewPoint);
77
78  mViewPoint = mSceneGraph->GetBox().Center();
79  mViewDirection = Vector3(0,0,1);
80
81  //  mViewPoint = Vector3(991.7, 187.8, -271);
82  //  mViewDirection = Vector3(0.9, 0, -0.4);
83
84  //  timerId = startTimer(10);
85  // debug coords for atlanta
86  //  mViewPoint = Vector3(3473, 6.778, -1699);
87  //  mViewDirection = Vector3(-0.2432, 0, 0.97);
88 
89  mFrame = 0;
90  mWireFrame = false;
91  Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
92  mSnapErrorFrames = true;
93  mSnapPrefix = "snap/";
94  mUseForcedColors = false;
95
96  mUseGlLists = true;
97  //mUseGlLists = false;
98}
99
100GlRenderer::~GlRenderer()
101{
102  cerr<<"gl renderer destructor..\n";
103  if (sCgFragmentProgram)
104        cgDestroyProgram(sCgFragmentProgram);
105  if (sCgContext)
106        cgDestroyContext(sCgContext);
107  cerr<<"done."<<endl;
108   
109  CLEAR_CONTAINER(sQueries);
110  CLEAR_CONTAINER(mOcclusionQueries);
111}
112
113
114static void handleCgError()
115{
116    Debug << "Cg error: " << cgGetErrorString(cgGetError()) << endl;
117    exit(1);
118}
119
120void
121GlRenderer::RenderIntersectable(Intersectable *object)
122{
123
124  glPushAttrib(GL_CURRENT_BIT);
125  if (mUseFalseColors)
126        SetupFalseColor(object->mId);
127 
128
129  switch (object->Type()) {
130  case Intersectable::MESH_INSTANCE:
131        RenderMeshInstance((MeshInstance *)object);
132        break;
133  case Intersectable::VIEW_CELL:
134          RenderViewCell(dynamic_cast<ViewCell *>(object));
135          break;
136  case Intersectable::TRANSFORMED_MESH_INSTANCE:
137          RenderTransformedMeshInstance(dynamic_cast<TransformedMeshInstance *>(object));
138          break;
139  default:
140        cerr<<"Rendering this object not yet implemented\n";
141        break;
142  }
143
144  glPopAttrib();
145}
146
147
148void
149GlRenderer::RenderViewCell(ViewCell *vc)
150{
151  if (vc->GetMesh()) {
152
153        if (!mUseFalseColors) {
154          if (vc->GetValid())
155                glColor3f(0,1,0);
156          else
157                glColor3f(0,0,1);
158        }
159       
160        RenderMesh(vc->GetMesh());
161  } else {
162        // render viewcells in the subtree
163        if (!vc->IsLeaf()) {
164          ViewCellInterior *vci = (ViewCellInterior *) vc;
165
166          ViewCellContainer::iterator it = vci->mChildren.begin();
167          for (; it != vci->mChildren.end(); ++it) {
168                RenderViewCell(*it);
169          }
170        } else {
171          //      cerr<<"Empty viewcell mesh\n";
172        }
173  }
174}
175
176
177void
178GlRenderer::RenderMeshInstance(MeshInstance *mi)
179{
180  RenderMesh(mi->GetMesh());
181}
182
183
184void
185GlRenderer::RenderTransformedMeshInstance(TransformedMeshInstance *mi)
186{
187        // apply world transform before rendering
188        Matrix4x4 m;
189        mi->GetWorldTransform(m);
190
191        glPushMatrix();
192/* cout << "\n";
193        for (int i = 0; i < 4; ++ i)
194                for (int j = 0; j < 4; ++ j)
195                        cout << m.x[i][j] << " "; cout << "\n"*/
196
197        glMultMatrixf((float *)m.x);
198
199        /*GLfloat dummy[16];
200        glGetFloatv(GL_MODELVIEW_MATRIX, dummy);
201        for (int i = 0; i < 16; ++ i)
202                cout << dummy[i] << " ";
203        cout << endl;*/
204        RenderMesh(mi->GetMesh());
205       
206        glPopMatrix();
207}
208
209
210void
211GlRenderer::SetupFalseColor(const int id)
212{
213  // swap bits of the color
214  glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
215}
216
217
218int GlRenderer::GetId(int r, int g, int b) const
219{
220        return r + (g << 8) + (b << 16);
221}
222
223void
224GlRenderer::SetupMaterial(Material *m)
225{
226  if (m)
227        glColor3fv(&(m->mDiffuseColor.r));
228}
229
230void
231GlRenderer::RenderMesh(Mesh *mesh)
232{
233  int i = 0;
234
235  if (!mUseFalseColors && !mUseForcedColors)
236        SetupMaterial(mesh->mMaterial);
237 
238  for (i=0; i < mesh->mFaces.size(); i++) {
239        if (mWireFrame)
240          glBegin(GL_LINE_LOOP);
241        else
242          glBegin(GL_POLYGON);
243
244        Face *face = mesh->mFaces[i];
245        for (int j = 0; j < face->mVertexIndices.size(); j++) {
246          glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
247        }
248        glEnd();
249  }
250}
251       
252void
253GlRenderer::InitGL()
254{
255  glMatrixMode(GL_PROJECTION);
256  glLoadIdentity();
257 
258  glMatrixMode(GL_MODELVIEW);
259  glLoadIdentity();
260
261  glEnable(GL_CULL_FACE);
262  glShadeModel(GL_FLAT);
263  glEnable(GL_DEPTH_TEST);
264  glEnable(GL_CULL_FACE);
265 
266  // HACK!! but using glew keeps crashing for some reason ...
267  InitExtensions();
268 
269#if 0
270  GLfloat mat_ambient[]   = {  0.5, 0.5, 0.5, 1.0  };
271  /*  mat_specular and mat_shininess are NOT default values     */
272  GLfloat mat_diffuse[]   = {  1.0, 1.0, 1.0, 1.0  };
273  GLfloat mat_specular[]  = {  0.3, 0.3, 0.3, 1.0  };
274  GLfloat mat_shininess[] = {  1.0  };
275 
276  GLfloat light_ambient[]  = {  0.2, 0.2, 0.2, 1.0  };
277  GLfloat light_diffuse[]  = {  0.4, 0.4, 0.4, 1.0  };
278  GLfloat light_specular[] = {  0.3, 0.3, 0.3, 1.0  };
279 
280  GLfloat lmodel_ambient[] = {  0.3, 0.3, 0.3, 1.0  };
281 
282 
283  // default Material
284  glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
285  glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
286  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
287  glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
288
289  // a light
290  glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
291  glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
292  glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
293 
294  glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
295  glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
296  glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
297 
298  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
299 
300  glEnable(GL_LIGHTING);
301  glEnable(GL_LIGHT0);
302  glEnable(GL_LIGHT1);
303 
304 
305  // set position of the light
306  GLfloat infinite_light[] = {  1.0, 0.8, 1.0, 0.0  };
307  glLightfv (GL_LIGHT0, GL_POSITION, infinite_light);
308 
309  // set position of the light2
310  GLfloat infinite_light2[] = {  -0.3, 1.5, 1.0, 0.0  };
311  glLightfv (GL_LIGHT1, GL_POSITION, infinite_light2);
312 
313  glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
314  //   glColorMaterial( GL_FRONT_AND_BACK, GL_SPECULAR);
315  glEnable(GL_COLOR_MATERIAL);
316 
317  glShadeModel( GL_FLAT );
318 
319  glDepthFunc( GL_LESS );
320  glEnable( GL_DEPTH_TEST );
321#endif
322
323  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
324
325  glEnable( GL_NORMALIZE );
326 
327  glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
328}
329
330void
331GlRendererWidget::RenderInfo()
332{
333  QString s;
334  int vc = 0;
335  if (mViewCellsManager)
336        vc = mViewCellsManager->GetViewCells().size();
337  int filter = 0;
338  if (mViewCellsManager)
339        filter = mViewCellsManager->GetMaxFilterSize();
340
341  s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f) viewcells:%04d filter:%04d pvs:%04d error:%5.5f\%",
342                        mFrame,
343                        mViewPoint.x,
344                        mViewPoint.y,
345                        mViewPoint.z,
346                        mViewDirection.x,
347                        mViewDirection.y,
348                        mViewDirection.z,
349                        vc,
350
351                        filter,
352                        mPvsSize,
353                        mRenderError*100.0f
354                        );
355 
356  glColor3f(0.0f,0.0f,0.0f);
357  renderText(0,20,s);
358 
359  if (mShowRenderCost) {
360        static vector<float> costFunction;
361        static float maxCost = -1;
362        if (costFunction.size()==0) {
363          ViewCellsTree *tree = mViewCellsManager->GetViewCellsTree();
364          if (tree) {
365                tree->GetCostFunction(costFunction);
366                maxCost = -1;
367                for (int i=0;  i < costFunction.size(); i++) {
368                  //              cout<<i<<":"<<costFunction[i]<<" ";
369                  if (costFunction[i] > maxCost)
370                        maxCost = costFunction[i];
371                }
372          }
373        }
374
375       
376        int currentPos = mViewCellsManager->GetViewCells().size();
377        float currentCost=-1;
378
379        if (currentPos < costFunction.size())
380          currentCost = costFunction[currentPos];
381#if 0   
382        cout<<"costFunction.size()="<<costFunction.size()<<endl;
383        cout<<"CP="<<currentPos<<endl;
384        cout<<"MC="<<maxCost<<endl;
385        cout<<"CC="<<currentCost<<endl;
386#endif
387        if (costFunction.size()) {
388          glDisable(GL_DEPTH_TEST);
389          // init ortographic projection
390          glMatrixMode(GL_PROJECTION);
391          glPushMatrix();
392         
393          glLoadIdentity();
394          gluOrtho2D(0, 1.0f, 0, 1.0f);
395         
396          glTranslatef(0.1f, 0.1f, 0.0f);
397          glScalef(0.8f, 0.8f, 1.0f);
398          glMatrixMode(GL_MODELVIEW);
399          glLoadIdentity();
400         
401          glColor3f(1.0f,0,0);
402          glBegin(GL_LINE_STRIP);
403          //      glVertex3f(0,0,0);
404         
405          for (int i=0;  i < costFunction.size(); i++) {
406                float x =  i/(float)costFunction.size();
407                float y = costFunction[i]/(maxCost*0.5f);
408                glVertex3f(x,y,0.0f);
409          }
410          glEnd();
411         
412          glColor3f(1.0f,0,0);
413          glBegin(GL_LINES);
414          float x =  currentPos/(float)costFunction.size();
415          glVertex3f(x,0.0,0.0f);
416          glVertex3f(x,1.0f,0.0f);
417          glEnd();
418         
419          glColor3f(0.0f,0,0);
420          // show a grid
421          glBegin(GL_LINE_LOOP);
422          glVertex3f(0,0,0.0f);
423          glVertex3f(1,0,0.0f);
424          glVertex3f(1,1,0.0f);
425          glVertex3f(0,1,0.0f);
426          glEnd();
427
428          glBegin(GL_LINES);
429          for (int i=0;  i < 50000 && i < costFunction.size(); i+=10000) {
430                float x =  i/(float)costFunction.size();
431                glVertex3f(x,0.0,0.0f);
432                glVertex3f(x,1.0f,0.0f);
433          }
434
435          for (int i=0;  i < maxCost; i+=100) {
436                float y = i/(maxCost*0.5f);
437                glVertex3f(0,y,0.0f);
438                glVertex3f(1,y,0.0f);
439          }
440
441          glEnd();
442
443         
444          // restore the projection matrix
445          glMatrixMode(GL_PROJECTION);
446          glPopMatrix();
447          glMatrixMode(GL_MODELVIEW);
448          glEnable(GL_DEPTH_TEST);
449
450        }
451  }
452}
453
454
455void
456GlRenderer::SetupProjection(const int w, const int h, const float angle)
457{
458  glViewport(0, 0, w, h);
459  glMatrixMode(GL_PROJECTION);
460  glLoadIdentity();
461  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
462  glMatrixMode(GL_MODELVIEW);
463}
464
465void
466GlRenderer::SetupCamera()
467{
468  Vector3 target = mViewPoint + mViewDirection;
469
470  Vector3 up(0,1,0);
471 
472  if (abs(DotProd(mViewDirection, up)) > 0.99f)
473        up = Vector3(1, 0, 0);
474 
475  glLoadIdentity();
476  gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
477                        target.x, target.y, target.z,
478                        up.x, up.y, up.z);
479}
480
481
482void
483GlRendererBuffer::EvalQueryWithItemBuffer(
484                                                                                  //RenderCostSample &sample
485                                                                           )
486{
487        // read back the texture
488        glReadPixels(0, 0,
489                                GetWidth(), GetHeight(),
490                                GL_RGBA,
491                                GL_UNSIGNED_BYTE,
492                                mPixelBuffer);
493               
494                       
495        unsigned int *p = mPixelBuffer;
496                       
497        for (int y = 0; y < GetHeight(); y++)
498        {
499                for (int x = 0; x < GetWidth(); x++, p++)
500                {
501                        unsigned int id = (*p) & 0xFFFFFF;
502
503                        if (id != 0xFFFFFF)
504                                ++ mObjects[id]->mCounter;
505                }
506        }
507}
508
509//std::ofstream outfile("try_arb.txt");
510void
511GlRendererBuffer::EvalQueryWithOcclusionQueries(
512                                                                           //RenderCostSample &sample
513                                                                           )
514{
515        glDepthFunc(GL_LEQUAL);
516               
517        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
518        glDepthMask(GL_FALSE);
519
520
521        // simulate detectemptyviewspace using backface culling
522        if (mDetectEmptyViewSpace)
523        {
524                glEnable(GL_CULL_FACE);
525                //cout << "culling" << endl;
526        }
527        else
528        {
529                //cout << "not culling" << endl;
530                glDisable(GL_CULL_FACE);
531        }
532
533       
534        //const int numQ = 1;
535        const int numQ = (int)mOcclusionQueries.size();
536       
537        //glFinish();
538#if 0
539        //-- now issue queries for all objects
540        for (int j = 0; j < (int)mObjects.size(); ++ j)
541        {
542                mOcclusionQueries[j]->BeginQuery();
543                RenderIntersectable(mObjects[j]);
544                mOcclusionQueries[j]->EndQuery();
545
546                unsigned int pixelCount;
547
548                pixelCount = mOcclusionQueries[j]->GetQueryResult();
549                mObjects[j]->mCounter += pixelCount;
550        }
551#else
552
553        int q = 0;
554
555        //-- now issue queries for all objects
556        for (int j = 0; j < (int)mObjects.size(); j += q)
557        {       
558                for (q = 0; ((j + q) < (int)mObjects.size()) && (q < numQ); ++ q)
559                {
560                        //glFinish();
561                        mOcclusionQueries[q]->BeginQuery();
562                       
563                        RenderIntersectable(mObjects[j + q]);
564               
565                        mOcclusionQueries[q]->EndQuery();
566                        //glFinish();
567                }
568                //cout << "q: " << q << endl;
569                // collect results of the queries
570                for (int t = 0; t < q; ++ t)
571                {
572                        unsigned int pixelCount;
573               
574                        //-- reenable other state
575#if 0
576                        bool available;
577
578                        do
579                        {
580                                available = mOcclusionQueries[t]->ResultAvailable();
581                               
582                                if (!available) cout << "W";
583                        }
584                        while (!available);
585#endif
586
587                        pixelCount = mOcclusionQueries[t]->GetQueryResult();
588
589                        //if (pixelCount > 0)
590                        //      cout <<"o="<<j+q<<" q="<<mOcclusionQueries[q]->GetQueryId()<<" pc="<<pixelCount<<" ";
591                        mObjects[j + t]->mCounter += pixelCount;
592                }
593
594                //j += q;
595        }
596#endif
597        //glFinish();
598        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
599        glDepthMask(GL_TRUE);
600       
601        glEnable(GL_CULL_FACE);
602}
603
604
605void
606GlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
607                                                                           const bool useOcclusionQueries,
608                                                                           const int threshold
609                                                                           )
610{
611        // choose a random view point
612        mViewCellsManager->GetViewPoint(mViewPoint);
613        sample.mPosition = mViewPoint;
614        //cout << "viewpoint: " << mViewPoint << endl;
615
616        // take a render cost sample by rendering a cube
617        Vector3 directions[6];
618
619        directions[0] = Vector3(1,0,0);
620        directions[1] = Vector3(0,1,0);
621        directions[2] = Vector3(0,0,1);
622        directions[3] = Vector3(-1,0,0);
623        directions[4] = Vector3(0,-1,0);
624        directions[5] = Vector3(0,0,-1);
625
626        sample.mVisibleObjects = 0;
627
628        // reset object counters
629        ObjectContainer::const_iterator it, it_end = mObjects.end();
630
631        for (it = mObjects.begin(); it != it_end; ++ it)
632        {
633                (*it)->mCounter = 0;
634        }
635
636        ++ mFrame;
637
638        //glCullFace(GL_FRONT);
639        glCullFace(GL_BACK);
640        glDisable(GL_CULL_FACE);
641       
642
643        // query all 6 directions for a full point sample
644        for (int i = 0; i < 6; ++ i)
645        {
646                mViewDirection = directions[i];
647                SetupCamera();
648
649                glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
650                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
651                //glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);      glDepthMask(GL_TRUE);
652                glDepthFunc(GL_LESS);
653
654                mUseFalseColors = true;
655
656                // the actual scene rendering fills the depth (for occlusion queries)
657                // and the frame buffer (for item buffer)
658                RenderScene();
659
660
661                if (0)
662                {
663                        char filename[256];
664                        sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
665                        QImage im = toImage();
666                        im.save(filename, "PNG");
667                }
668         
669                // evaluate the sample
670                if (useOcclusionQueries)
671                {
672                        EvalQueryWithOcclusionQueries();
673                }
674                else
675                {
676                        EvalQueryWithItemBuffer();
677                }
678        } 
679
680        // now evaluate the statistics over that sample
681        // currently only the number of visible objects is taken into account
682        sample.Reset();
683
684        for (it = mObjects.begin(); it != it_end; ++ it)
685        {
686                Intersectable *obj = *it;
687                if (obj->mCounter >= threshold)
688                {
689                        ++ sample.mVisibleObjects;
690                        sample.mVisiblePixels += obj->mCounter;
691                }
692        }
693
694        //cout << "RS=" << sample.mVisibleObjects << " ";
695}
696
697
698void
699GlRendererBuffer::SampleRenderCost(const int numSamples,
700                                                                   vector<RenderCostSample> &samples,
701                                                                   const bool useOcclusionQueries,
702                                                                   const int threshold
703                                                                   )
704{
705  makeCurrent();
706
707  if (mPixelBuffer == NULL)
708          mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
709 
710  // using 90 degree projection to capture 360 view with 6 samples
711  SetupProjection(GetHeight(), GetHeight(), 90.0f);
712
713  //samples.resize(numSamples);
714  halton.Reset();
715 
716  // the number of queries queried in batch mode
717  const int numQ = 500;
718
719  //const int numQ = (int)mObjects.size();
720  if (useOcclusionQueries)
721  {
722          cout << "\ngenerating " << numQ << " queries ... ";
723          OcclusionQuery::GenQueries(mOcclusionQueries, numQ);
724          cout << "finished" << endl;
725  }
726
727  // sampling queries
728  for (int i = 0; i < numSamples; ++ i)
729  {
730          cout << ".";
731          EvalRenderCostSample(samples[i], useOcclusionQueries, threshold);
732  }
733
734  doneCurrent();
735
736}
737 
738
739void
740GlRendererBuffer::RandomViewPoint()
741{
742  // do not use this function since it could return different viewpoints for
743  // different executions of the algorithm
744
745  //  mViewCellsManager->GetViewPoint(mViewPoint);
746
747  while (1) {
748        Vector3 pVector = Vector3(halton.GetNumber(1),
749                                                          halton.GetNumber(2),
750                                                          halton.GetNumber(3));
751       
752        mViewPoint =  mViewCellsManager->GetViewSpaceBox().GetPoint(pVector);
753        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
754        if (v && v->GetValid())
755          break;
756        // generate a new vector
757        halton.GenerateNext();
758  }
759 
760  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
761                                                        M_PI*halton.GetNumber(5),
762                                                        0.0f);
763 
764  mViewDirection = Normalize(Vector3(sin(dVector.x),
765                                                                         //                                                                      cos(dVector.y),
766                                                                         0.0f,
767                                                                         cos(dVector.x)));
768  halton.GenerateNext();
769}
770
771
772GlRendererBuffer::GlRendererBuffer(const int w,
773                                                                   const int h,
774                                                                   SceneGraph *sceneGraph,
775                                                                   ViewCellsManager *viewcells,
776                                                                   KdTree *tree):
777QGLPixelBuffer(QSize(w, h)), GlRenderer(sceneGraph, viewcells, tree) {
778 
779  Environment::GetSingleton()->GetIntValue("Preprocessor.pvsRenderErrorSamples", mPvsStatFrames);
780  mPvsErrorBuffer.resize(mPvsStatFrames);
781  ClearErrorBuffer();
782
783  mPixelBuffer = NULL;
784 
785  makeCurrent();
786  InitGL();
787  doneCurrent();
788 
789}
790
791float
792GlRendererBuffer::GetPixelError(int &pvsSize)
793{
794  float pErrorPixels = -1.0f;
795 
796  glReadBuffer(GL_BACK);
797 
798  //  mUseFalseColors = true;
799 
800  mUseFalseColors = false;
801  unsigned int pixelCount;
802
803  //static int query = -1;
804  //if (query == -1)
805//        glGenOcclusionQueriesNV(1, (unsigned int *)&query);
806
807  OcclusionQuery query;
808
809  if (mDetectEmptyViewSpace) {
810        // now check whether any backfacing polygon would pass the depth test
811        SetupCamera();
812        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
813        glEnable( GL_CULL_FACE );
814       
815        RenderScene();
816       
817        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
818        glDepthMask(GL_FALSE);
819        glDisable( GL_CULL_FACE );
820
821       
822        query.BeginQuery();
823       
824        RenderScene();
825       
826        query.EndQuery();
827       
828        // at this point, if possible, go and do some other computation
829        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
830        glDepthMask(GL_TRUE);
831        glEnable( GL_CULL_FACE );
832       
833        // reenable other state
834        pixelCount = query.GetQueryResult();
835       
836        if (pixelCount > 0)
837          return -1.0f; // backfacing polygon found -> not a valid viewspace sample
838  } else
839        glDisable( GL_CULL_FACE );
840       
841
842  ViewCell *viewcell = NULL;
843 
844  PrVs prvs;
845 
846  mViewCellsManager->SetMaxFilterSize(0);
847  mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
848  viewcell = prvs.mViewCell;
849 
850  //  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
851  pvsSize = 0;
852  if (viewcell) {
853        SetupCamera();
854        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
855
856        glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
857       
858        // Render PVS
859        std::map<Intersectable *,
860          PvsData<Intersectable *>,
861          LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
862
863        pvsSize = viewcell->GetPvs().mEntries.size();
864       
865        for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
866          Intersectable *object = (*it).first;
867          RenderIntersectable(object);
868        }
869
870        //      glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
871        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
872        mUseFalseColors = true;
873
874        query.BeginQuery();
875
876        SetupCamera();
877
878        RenderScene();
879       
880        query.EndQuery();
881       
882
883        unsigned int pixelCount;
884        // reenable other state
885        pixelCount = query.GetQueryResult();
886       
887       
888        pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
889        if (mSnapErrorFrames && pErrorPixels > 0.01) {
890         
891          char filename[256];
892          sprintf(filename, "error-frame-%04d-%0.5f.png", mFrame, pErrorPixels);
893          QImage im = toImage();
894          im.save(mSnapPrefix + filename, "PNG");
895          if (1) { //0 && mFrame == 1543) {
896                int x,y;
897                int lastIndex = -1;
898                for (y=0; y < im.height(); y++)
899                  for (x=0; x < im.width(); x++) {
900                        QRgb p = im.pixel(x,y);
901                        int index = qRed(p) + (qGreen(p)<<8) + (qBlue(p)<<16);
902                        if (qGreen(p) != 255 && index!=0) {
903                          if (index != lastIndex) {
904                                //                              Debug<<"ei="<<index<<" ";
905                                lastIndex = index;
906                          }
907                        }
908                  }
909          }
910
911
912          mUseFalseColors = false;
913          glPushAttrib(GL_CURRENT_BIT);
914          glColor3f(0,1,0);
915          glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
916          SetupCamera();
917          glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
918         
919          // Render PVS
920          std::map<Intersectable *,
921                PvsData<Intersectable *>,
922                LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
923         
924          for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
925                Intersectable *object = (*it).first;
926                RenderIntersectable(object);
927          }
928
929          im = toImage();
930          sprintf(filename, "error-frame-%04d-%0.5f-pvs.png", mFrame, pErrorPixels);
931          im.save(mSnapPrefix + filename, "PNG");
932          glPopAttrib();
933        }
934        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
935  }
936
937  if (viewcell && mViewCellsManager->GetMaxFilterSize() > 0)
938        mViewCellsManager->DeleteLocalMergeTree(viewcell);
939 
940  return pErrorPixels;
941}
942
943
944void
945GlRendererWidget::SetupProjection(const int w, const int h, const float angle)
946{
947  if (!mTopView)
948        GlRenderer::SetupProjection(w, h, angle);
949  else {
950        glViewport(0, 0, w, h);
951        glMatrixMode(GL_PROJECTION);
952        glLoadIdentity();
953        gluPerspective(50.0, 1.0, 0.1, 20.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
954        glMatrixMode(GL_MODELVIEW);
955  }
956}
957
958void
959GlRendererWidget::RenderPvs()
960{
961  SetupCamera();
962  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
963 
964  ViewCell *viewcell = NULL;
965
966  PrVs prvs;
967 
968  if (!mUseFilter) {
969        viewcell = mViewCellsManager->GetViewCell(mViewPoint, true);
970  } else {
971        //  mViewCellsManager->SetMaxFilterSize(1);
972        mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
973        viewcell = prvs.mViewCell;
974  }
975 
976  if (viewcell) {
977        // copy the pvs so that it can be filtered...
978        ObjectPvs pvs = viewcell->GetPvs();
979
980        if (mUseSpatialFilter) {
981          mViewCellsManager->ApplySpatialFilter(mKdTree,
982                                                                                        mSpatialFilterSize*
983                                                                                        Magnitude(mViewCellsManager->GetViewSpaceBox().Size()),
984                                                                                        pvs);
985        }
986       
987       
988        // read back the texture
989        std::map<Intersectable *,
990          PvsData<Intersectable *>,
991          LtSample<Intersectable *> >::const_iterator it = pvs.mEntries.begin();
992
993        mPvsSize = pvs.mEntries.size();
994         
995        for (; it != pvs.mEntries.end(); ++ it) {
996          Intersectable *object = (*it).first;
997          float visibility = log10((*it).second.mSumPdf + 1)/5.0f;
998          glColor3f(visibility, 0.0f, 0.0f);
999          mUseForcedColors = true;
1000          RenderIntersectable(object);
1001          mUseForcedColors = false;
1002        }
1003
1004        if (mRenderFilter) {
1005          mWireFrame = true;
1006          RenderIntersectable(viewcell);
1007          mWireFrame = false;
1008        }
1009       
1010        if (mUseFilter)
1011          mViewCellsManager->DeleteLocalMergeTree(viewcell);
1012  } else {
1013        ObjectContainer::const_iterator oi = mObjects.begin();
1014        for (; oi != mObjects.end(); oi++)
1015          RenderIntersectable(*oi);
1016  }
1017}
1018
1019float
1020GlRendererWidget::RenderErrors()
1021{
1022  float pErrorPixels = -1.0f;
1023
1024  glReadBuffer(GL_BACK);
1025 
1026  mUseFalseColors = true;
1027
1028  SetupCamera();
1029  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1030 
1031  double eq[4];
1032  eq[0] = mSceneCutPlane.mNormal.x;
1033  eq[1] = mSceneCutPlane.mNormal.y;
1034  eq[2] = mSceneCutPlane.mNormal.z;
1035  eq[3] = mSceneCutPlane.mD;
1036 
1037  if (mCutScene) {
1038        glClipPlane(GL_CLIP_PLANE0, eq);
1039    glEnable(GL_CLIP_PLANE0);
1040  }
1041 
1042  if (mDetectEmptyViewSpace)
1043        glEnable( GL_CULL_FACE );
1044  else
1045        glDisable( GL_CULL_FACE );
1046
1047  ObjectContainer::const_iterator oi = mObjects.begin();
1048  for (; oi != mObjects.end(); oi++)
1049        RenderIntersectable(*oi);
1050
1051  ViewCell *viewcell = NULL;
1052
1053  QImage im1, im2;
1054  QImage diff;
1055 
1056  if (viewcell) {
1057        // read back the texture
1058        im1 = grabFrameBuffer(true);
1059       
1060        RenderPvs();
1061
1062        // read back the texture
1063        im2 = grabFrameBuffer(true);
1064       
1065        diff = im1;
1066        int x, y;
1067        int errorPixels = 0;
1068       
1069        for (y = 0; y < im1.height(); y++)
1070          for (x = 0; x < im1.width(); x++)
1071                if (im1.pixel(x, y) == im2.pixel(x, y))
1072                  diff.setPixel(x, y, qRgba(0,0,0,0));
1073                else {
1074                  diff.setPixel(x, y, qRgba(255,128,128,255));
1075                  errorPixels++;
1076                }
1077        pErrorPixels = ((float)errorPixels)/(im1.height()*im1.width());
1078  }
1079
1080  // now render the pvs again
1081  SetupCamera();
1082  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1083  mUseFalseColors = false;
1084 
1085  oi = mObjects.begin();
1086  for (; oi != mObjects.end(); oi++)
1087        RenderIntersectable(*oi);
1088
1089  // now render im1
1090  if (viewcell) {
1091        if (0 && mTopView) {
1092          mWireFrame = true;
1093          RenderIntersectable(viewcell);
1094          mWireFrame = false;
1095        }
1096       
1097        // init ortographic projection
1098        glMatrixMode(GL_PROJECTION);
1099        glPushMatrix();
1100       
1101        glLoadIdentity();
1102        gluOrtho2D(0, 1.0f, 0, 1.0f);
1103       
1104        glMatrixMode(GL_MODELVIEW);
1105        glLoadIdentity();
1106       
1107        bindTexture(diff);
1108       
1109        glPushAttrib(GL_ENABLE_BIT);
1110        glEnable( GL_ALPHA_TEST );
1111        glDisable( GL_CULL_FACE );
1112        glAlphaFunc( GL_GREATER, 0.5 );
1113       
1114        glEnable( GL_TEXTURE_2D );
1115        glBegin(GL_QUADS);
1116       
1117        glTexCoord2f(0,0);
1118        glVertex3f(0,0,0);
1119       
1120        glTexCoord2f(1,0);
1121        glVertex3f( 1, 0, 0);
1122       
1123        glTexCoord2f(1,1);
1124        glVertex3f( 1, 1, 0);
1125       
1126        glTexCoord2f(0,1);
1127        glVertex3f(0, 1, 0);
1128        glEnd();
1129       
1130        glPopAttrib();
1131       
1132        // restore the projection matrix
1133        glMatrixMode(GL_PROJECTION);
1134        glPopMatrix();
1135        glMatrixMode(GL_MODELVIEW);
1136  }
1137
1138  glDisable(GL_CLIP_PLANE0);
1139 
1140  mRenderError = pErrorPixels;
1141  return pErrorPixels;
1142}
1143
1144void
1145GlRenderer::_RenderScene()
1146{
1147  ObjectContainer::const_iterator oi = mObjects.begin();
1148
1149  for (; oi != mObjects.end(); oi++)
1150        RenderIntersectable(*oi);
1151}
1152
1153bool
1154GlRenderer::RenderScene()
1155{
1156  static int glList = -1;
1157  if (mUseGlLists) {
1158        if (glList == -1) {
1159          glList = glGenLists(1);
1160          glNewList(glList, GL_COMPILE);
1161          _RenderScene();
1162          glEndList();
1163        }
1164        glCallList(glList);
1165  } else
1166        _RenderScene();
1167       
1168 
1169  return true;
1170}
1171
1172
1173void
1174GlRendererBuffer::ClearErrorBuffer()
1175{
1176  for (int i=0; i < mPvsStatFrames; i++) {
1177        mPvsErrorBuffer[i].mError = 1.0f;
1178  }
1179}
1180
1181
1182void
1183GlRendererBuffer::EvalPvsStat()
1184{
1185  mPvsStat.Reset();
1186  halton.Reset();
1187
1188  makeCurrent();
1189
1190
1191  SetupProjection(GetWidth(), GetHeight());
1192
1193 
1194  for (int i=0; i < mPvsStatFrames; i++) {
1195        float err;
1196        // set frame id for saving the error buffer
1197        mFrame = i;
1198        RandomViewPoint();
1199
1200        // atlanta problematic frames: 325 525 691 1543
1201#if 0
1202        if (mFrame != 325 &&
1203                mFrame != 525 &&
1204                mFrame != 691 &&
1205                mFrame != 1543)
1206          mPvsErrorBuffer[i] = -1;
1207        else {
1208          Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
1209        }
1210#endif
1211        if (mPvsErrorBuffer[i].mError > 0.0f) {
1212          int pvsSize;
1213
1214
1215          float error = GetPixelError(pvsSize);
1216          mPvsErrorBuffer[i].mError = error;
1217          mPvsErrorBuffer[i].mPvsSize = pvsSize;
1218
1219          emit UpdatePvsErrorItem(i,
1220                                                          mPvsErrorBuffer[i]);
1221         
1222          cout<<"("<<i<<","<<mPvsErrorBuffer[i].mError<<")";
1223          //      swapBuffers();
1224        }
1225       
1226        err = mPvsErrorBuffer[i].mError;
1227       
1228        if (err >= 0.0f) {
1229          if (err > mPvsStat.maxError)
1230                mPvsStat.maxError = err;
1231          mPvsStat.sumError += err;
1232          mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1233         
1234          if (err == 0.0f)
1235                mPvsStat.errorFreeFrames++;
1236          mPvsStat.frames++;
1237        }
1238  }
1239
1240  glFinish();
1241  doneCurrent();
1242
1243  cout<<endl<<flush;
1244  //  mRenderingFinished.wakeAll();
1245}
1246
1247
1248
1249
1250
1251void
1252GlRendererWidget::mousePressEvent(QMouseEvent *e)
1253{
1254  int x = e->pos().x();
1255  int y = e->pos().y();
1256
1257  mousePoint.x = x;
1258  mousePoint.y = y;
1259 
1260}
1261
1262void
1263GlRendererWidget::mouseMoveEvent(QMouseEvent *e)
1264{
1265  float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
1266  float TURN_SENSITIVITY=0.1f;
1267  float TILT_SENSITIVITY=32.0 ;
1268  float TURN_ANGLE= M_PI/36.0 ;
1269
1270  int x = e->pos().x();
1271  int y = e->pos().y();
1272 
1273  if (e->modifiers() & Qt::ControlModifier) {
1274        mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY/2.0;
1275        mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY/2.0;
1276  } else {
1277        mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
1278        float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
1279        float angle = atan2(mViewDirection.x, mViewDirection.z);
1280        mViewDirection.x = sin(angle+adiff);
1281        mViewDirection.z = cos(angle+adiff);
1282  }
1283 
1284  mousePoint.x = x;
1285  mousePoint.y = y;
1286 
1287  updateGL();
1288}
1289
1290void
1291GlRendererWidget::mouseReleaseEvent(QMouseEvent *)
1292{
1293
1294
1295}
1296
1297void
1298GlRendererWidget::resizeGL(int w, int h)
1299{
1300  SetupProjection(w, h);
1301  updateGL();
1302}
1303
1304void
1305GlRendererWidget::paintGL()
1306{
1307  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1308
1309 
1310  if (!mRenderViewCells) {
1311        if (mRenderErrors)
1312          RenderErrors();
1313        else
1314          RenderPvs();
1315        RenderInfo();
1316  } else {
1317        RenderViewCells();
1318       
1319        mWireFrame = true;
1320        RenderScene();
1321        mWireFrame = false;
1322       
1323        RenderInfo();
1324  }
1325
1326  mFrame++;
1327}
1328
1329
1330void
1331GlRendererWidget::SetupCamera()
1332{
1333  if (!mTopView)
1334        GlRenderer::SetupCamera();
1335  else {
1336        if (0) {
1337          float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
1338          Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
1339                                                                                          -1,
1340                                                                                          mViewDirection.y);
1341         
1342          Vector3 target = mViewPoint + dist*mViewDirection;
1343          Vector3 up(0,1,0);
1344         
1345          glLoadIdentity();
1346          gluLookAt(pos.x, pos.y, pos.z,
1347                                target.x, target.y, target.z,
1348                                up.x, up.y, up.z);
1349        } else {
1350          float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*mTopDistance;
1351          Vector3 pos = mViewPoint  + dist*Vector3(0,
1352                                                                                           1,
1353                                                                                           0);
1354         
1355          Vector3 target = mViewPoint;
1356          Vector3 up(mViewDirection.x, 0, mViewDirection.z);
1357         
1358          glLoadIdentity();
1359          gluLookAt(pos.x, pos.y, pos.z,
1360                                target.x, target.y, target.z,
1361                                up.x, up.y, up.z);
1362         
1363        }
1364  }
1365
1366}
1367
1368void
1369GlRendererWidget::keyPressEvent ( QKeyEvent * e )
1370{
1371  switch (e->key()) {
1372  case Qt::Key_T:
1373        mTopView = !mTopView;
1374        SetupProjection(width(), height());
1375        updateGL();
1376        break;
1377  case Qt::Key_V:
1378        mRenderViewCells = !mRenderViewCells;
1379        updateGL();
1380        break;
1381  case Qt::Key_P:
1382        // set random viewpoint
1383        mViewCellsManager->GetViewPoint(mViewPoint);
1384        updateGL();
1385        break;
1386
1387  default:
1388        e->ignore();
1389        break;
1390  }
1391}
1392
1393 
1394RendererControlWidget::RendererControlWidget(QWidget * parent, Qt::WFlags f):
1395  QWidget(parent, f)
1396{
1397
1398  QVBoxLayout *vl = new QVBoxLayout;
1399  setLayout(vl);
1400 
1401  QWidget *vbox = new QGroupBox("ViewCells", this);
1402  layout()->addWidget(vbox);
1403 
1404  vl = new QVBoxLayout;
1405  vbox->setLayout(vl);
1406
1407  QLabel *label = new QLabel("Granularity");
1408  vbox->layout()->addWidget(label);
1409
1410  QSlider *slider = new QSlider(Qt::Horizontal, vbox);
1411  vl->addWidget(slider);
1412  slider->show();
1413  slider->setRange(1, 10000);
1414  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1415  slider->setValue(200);
1416
1417  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
1418
1419  label = new QLabel("Filter size");
1420  vbox->layout()->addWidget(label);
1421 
1422  slider = new QSlider(Qt::Horizontal, vbox);
1423  vbox->layout()->addWidget(slider);
1424  slider->show();
1425  slider->setRange(1, 100);
1426  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1427  slider->setValue(3);
1428 
1429  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetVisibilityFilterSize(int)));
1430
1431
1432  label = new QLabel("Spatial Filter size");
1433  vbox->layout()->addWidget(label);
1434 
1435  slider = new QSlider(Qt::Horizontal, vbox);
1436  vbox->layout()->addWidget(slider);
1437  slider->show();
1438  slider->setRange(1, 100);
1439  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1440  slider->setValue(10);
1441 
1442  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSpatialFilterSize(int)));
1443
1444
1445
1446  QWidget *hbox = new QWidget(vbox);
1447  vl->addWidget(hbox);
1448  QHBoxLayout *hlayout = new QHBoxLayout;
1449  hbox->setLayout(hlayout);
1450 
1451  QCheckBox *cb = new QCheckBox("Show viewcells", hbox);
1452  hlayout->addWidget(cb);
1453  cb->setChecked(false);
1454  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
1455
1456  cb = new QCheckBox("Show render cost", hbox);
1457  hlayout->addWidget(cb);
1458  cb->setChecked(false);
1459  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
1460
1461  cb = new QCheckBox("Show pvs sizes", hbox);
1462  hlayout->addWidget(cb);
1463  cb->setChecked(false);
1464  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
1465
1466  vbox->resize(800,100);
1467
1468 
1469  vbox = new QGroupBox("Rendering", this);
1470  layout()->addWidget(vbox);
1471 
1472  vl = new QVBoxLayout;
1473  vbox->setLayout(vl);
1474
1475
1476
1477  slider = new QSlider(Qt::Horizontal, vbox);
1478  vbox->layout()->addWidget(slider);
1479  slider->show();
1480  slider->setRange(0, 1000);
1481  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1482  slider->setValue(1000);
1483
1484  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
1485
1486  cb = new QCheckBox("Render errors", vbox);
1487  vbox->layout()->addWidget(cb);
1488  cb->setChecked(false);
1489  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
1490
1491  cb = new QCheckBox("Use filter", vbox);
1492  vbox->layout()->addWidget(cb);
1493  cb->setChecked(true);
1494  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
1495
1496  cb = new QCheckBox("Use spatial filter", vbox);
1497  vbox->layout()->addWidget(cb);
1498  cb->setChecked(true);
1499  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
1500
1501  cb = new QCheckBox("Render filter", vbox);
1502  vbox->layout()->addWidget(cb);
1503  cb->setChecked(true);
1504  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderFilter(bool)));
1505
1506
1507  cb = new QCheckBox("Cut view cells", vbox);
1508  vbox->layout()->addWidget(cb);
1509  cb->setChecked(false);
1510  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
1511
1512  cb = new QCheckBox("Cut scene", vbox);
1513  vbox->layout()->addWidget(cb);
1514  cb->setChecked(false);
1515  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
1516
1517 
1518  slider = new QSlider(Qt::Horizontal, vbox);
1519  vbox->layout()->addWidget(slider);
1520  slider->show();
1521  slider->setRange(1, 1000);
1522  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1523  slider->setValue(500);
1524 
1525  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTopDistance(int)));
1526 
1527  cb = new QCheckBox("Top View", vbox);
1528  vbox->layout()->addWidget(cb);
1529  cb->setChecked(false);
1530  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
1531
1532  vbox = new QGroupBox("PVS Errors", this);
1533  layout()->addWidget(vbox);
1534
1535  vl = new QVBoxLayout;
1536  vbox->setLayout(vl);
1537
1538  mPvsErrorWidget = new QListWidget(vbox);
1539  vbox->layout()->addWidget(mPvsErrorWidget);
1540 
1541  connect(mPvsErrorWidget,
1542                  SIGNAL(doubleClicked(const QModelIndex &)),
1543                  this,
1544                  SLOT(PvsErrorClicked(const QModelIndex &)));
1545 
1546  QPushButton *button = new QPushButton("Next Error Frame", vbox);
1547  vbox->layout()->addWidget(button);
1548  connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
1549
1550  setWindowTitle("Preprocessor Control Widget");
1551  adjustSize();
1552}
1553
1554
1555
1556void
1557RendererControlWidget::FocusNextPvsErrorFrame(void)
1558{
1559 
1560 
1561}
1562
1563void
1564RendererControlWidget::UpdatePvsErrorItem(int row,
1565                                                                                  GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
1566{
1567
1568  QListWidgetItem *i = mPvsErrorWidget->item(row);
1569  QString s;
1570  s.sprintf("%5.5f", pvsErrorEntry.mError);
1571  if (i) {
1572        i->setText(s);
1573  } else {
1574        new QListWidgetItem(s, mPvsErrorWidget);
1575  }
1576  mPvsErrorWidget->update();
1577}
1578
1579GlRendererWidget::GlRendererWidget(SceneGraph *sceneGraph,
1580                                                                   ViewCellsManager *viewcells,
1581                                                                   KdTree *tree,
1582                                                                   QWidget * parent,
1583                                                                   const QGLWidget * shareWidget,
1584                                                                   Qt::WFlags f
1585                                                                   )
1586  :
1587  GlRenderer(sceneGraph, viewcells, tree), QGLWidget(parent, shareWidget, f)
1588{
1589  mTopView = false;
1590  mRenderViewCells = false;
1591  mTopDistance = 1.0f;
1592  mCutViewCells = false;
1593  mCutScene = false;
1594  mRenderErrors = false;
1595  mRenderFilter = true;
1596
1597  bool tmp;
1598
1599  Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp );
1600  mUseFilter = tmp;
1601 
1602  Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
1603                                                        tmp );
1604
1605  mUseSpatialFilter = tmp;
1606
1607  mShowRenderCost = false;
1608  mShowPvsSizes = false;
1609  mSpatialFilterSize = 0.01;
1610  mPvsSize = 0;
1611  mRenderError = 0.0f;
1612  mControlWidget = new RendererControlWidget(NULL);
1613 
1614  connect(mControlWidget, SIGNAL(SetViewCellGranularity(int)), this, SLOT(SetViewCellGranularity(int)));
1615  connect(mControlWidget, SIGNAL(SetSceneCut(int)), this, SLOT(SetSceneCut(int)));
1616  connect(mControlWidget, SIGNAL(SetTopDistance(int)), this, SLOT(SetTopDistance(int)));
1617
1618  connect(mControlWidget, SIGNAL(SetVisibilityFilterSize(int)), this, SLOT(SetVisibilityFilterSize(int)));
1619  connect(mControlWidget, SIGNAL(SetSpatialFilterSize(int)), this, SLOT(SetSpatialFilterSize(int)));
1620
1621  connect(mControlWidget, SIGNAL(SetShowViewCells(bool)), this, SLOT(SetShowViewCells(bool)));
1622  connect(mControlWidget, SIGNAL(SetShowRenderCost(bool)), this, SLOT(SetShowRenderCost(bool)));
1623  connect(mControlWidget, SIGNAL(SetShowPvsSizes(bool)), this, SLOT(SetShowPvsSizes(bool)));
1624  connect(mControlWidget, SIGNAL(SetTopView(bool)), this, SLOT(SetTopView(bool)));
1625  connect(mControlWidget, SIGNAL(SetCutViewCells(bool)), this, SLOT(SetCutViewCells(bool)));
1626  connect(mControlWidget, SIGNAL(SetCutScene(bool)), this, SLOT(SetCutScene(bool)));
1627  connect(mControlWidget, SIGNAL(SetRenderErrors(bool)), this, SLOT(SetRenderErrors(bool)));
1628  connect(mControlWidget, SIGNAL(SetRenderFilter(bool)), this, SLOT(SetRenderFilter(bool)));
1629  connect(mControlWidget, SIGNAL(SetUseFilter(bool)), this, SLOT(SetUseFilter(bool)));
1630  connect(mControlWidget, SIGNAL(SetUseSpatialFilter(bool)),
1631                  this, SLOT(SetUseSpatialFilter(bool)));
1632
1633 
1634  mControlWidget->show();
1635}
1636
1637void
1638GlRendererWidget::SetViewCellGranularity(int number)
1639{
1640  if (mViewCellsManager)
1641        //      mViewCellsManager->SetMaxFilterSize(number);
1642    mViewCellsManager->CollectViewCells(number);
1643
1644  updateGL();
1645}
1646
1647void
1648GlRendererWidget::SetVisibilityFilterSize(int number)
1649{
1650  if (mViewCellsManager)
1651        mViewCellsManager->SetMaxFilterSize(number);
1652  updateGL();
1653}
1654
1655void
1656GlRendererWidget::SetSpatialFilterSize(int number)
1657{
1658  mSpatialFilterSize = 1e-3*number;
1659  updateGL();
1660}
1661
1662void
1663GlRendererWidget::SetSceneCut(int number)
1664{
1665  // assume the cut plane can only be aligned with xz plane
1666  // shift it along y according to number, which is percentage of the bounding
1667  // box position
1668  if (mViewCellsManager) {
1669        AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1670        Vector3 p = box.Min() + (number/1000.0f)*box.Max();
1671        mSceneCutPlane.mNormal = Vector3(0,-1,0);
1672        mSceneCutPlane.mD = -DotProd(mSceneCutPlane.mNormal, p);
1673        updateGL();
1674  }
1675}
1676
1677void
1678GlRendererWidget::SetTopDistance(int number)
1679{
1680  mTopDistance = number/1000.0f;
1681  updateGL();
1682}
1683
1684void
1685GlRendererWidget::RenderViewCells()
1686{
1687  mUseFalseColors = true;
1688
1689  SetupCamera();
1690  glEnable(GL_CULL_FACE);
1691  //glDisable(GL_CULL_FACE);
1692  glCullFace(GL_FRONT);
1693  double eq[4];
1694  eq[0] = mSceneCutPlane.mNormal.x;
1695  eq[1] = mSceneCutPlane.mNormal.y;
1696  eq[2] = mSceneCutPlane.mNormal.z;
1697  eq[3] = mSceneCutPlane.mD;
1698
1699  if (mCutViewCells) {
1700        glClipPlane(GL_CLIP_PLANE0, eq);
1701        glEnable(GL_CLIP_PLANE0);
1702  }
1703 
1704  int i;
1705  ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
1706  int maxPvs = -1;
1707  for (i=0; i < viewcells.size(); i++) {
1708        ViewCell *vc = viewcells[i];
1709        int p = vc->GetPvs().GetSize();
1710        if (p > maxPvs)
1711          maxPvs = p;
1712  }
1713
1714
1715  for (i=0; i < viewcells.size(); i++) {
1716        ViewCell *vc = viewcells[i];
1717        //      Mesh *m = vc->GetMesh();
1718
1719
1720        RgbColor c;
1721
1722        if (!mShowPvsSizes)
1723          c = vc->GetColor();
1724        else {
1725          float importance = (float)vc->GetPvs().GetSize() / (float)maxPvs;
1726          c = RgbColor(importance, 1.0f - importance, 0.0f);
1727        }
1728        glColor3f(c.r, c.g, c.b);
1729       
1730        RenderViewCell(vc);
1731  }
1732
1733  glDisable(GL_CLIP_PLANE0);
1734
1735}
1736
1737void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
1738                                                                                           Beam &beam,
1739                                                                                           const int desiredSamples,
1740                                                                                           BeamSampleStatistics &stat)
1741{
1742        // TODO: should be moved out of here (not to be done every time)
1743        // only back faces are interesting for the depth pass
1744        glShadeModel(GL_FLAT);
1745        glDisable(GL_LIGHTING);
1746
1747        // needed to kill the fragments for the front buffer
1748        glEnable(GL_ALPHA_TEST);
1749        glAlphaFunc(GL_GREATER, 0);
1750
1751        // assumes that the beam is constructed and contains kd-tree nodes
1752        // and viewcells which it intersects
1753 
1754 
1755        // Get the number of viewpoints to be sampled
1756        // Now it is a sqrt but in general a wiser decision could be made.
1757        // The less viewpoints the better for rendering performance, since less passes
1758        // over the beam is needed.
1759        // The viewpoints could actually be generated outside of the bounding box which
1760        // would distribute the 'efective viewpoints' of the object surface and thus
1761        // with a few viewpoints better sample the viewpoint space....
1762
1763        //TODO: comment in
1764        //int viewPointSamples = sqrt((float)desiredSamples);
1765        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
1766       
1767        // the number of direction samples per pass is given by the number of viewpoints
1768        int directionalSamples = desiredSamples / viewPointSamples;
1769       
1770        Debug << "directional samples: " << directionalSamples << endl;
1771        for (int i = 0; i < viewPointSamples; ++ i)
1772        {
1773                Vector3 viewPoint = beam.mBox.GetRandomPoint();
1774               
1775                // perhaps the viewpoint should be shifted back a little bit so that it always lies
1776                // inside the source object
1777                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
1778        // would require more complicated sampling (perhaps hierarchical rejection sampling of
1779                // the object surface is an option here - only the mesh faces which are inside the box
1780                // are considered as candidates)
1781               
1782                SampleViewpointContributions(sourceObject,
1783                                                                         viewPoint,
1784                                                                         beam,
1785                                                                         directionalSamples,
1786                                                                         stat);
1787        }
1788
1789
1790        // note:
1791        // this routine would be called only if the number of desired samples is sufficiently
1792        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
1793        // distributing the work between cpu and gpu would also allow us to place more sophisticated
1794        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
1795        // in order that thios scheme is working well the gpu render buffer should run in a separate
1796        // thread than the cpu sampler, which would not be such a big problem....
1797
1798        // disable alpha test again
1799        glDisable(GL_ALPHA_TEST);
1800}
1801
1802
1803void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
1804                                                                                                        const Vector3 viewPoint,
1805                                                                                                        Beam &beam,
1806                                                                                                        const int samples,
1807                                                    BeamSampleStatistics &stat)
1808{
1809    // 1. setup the view port to match the desired samples
1810        glViewport(0, 0, samples, samples);
1811
1812        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
1813        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
1814
1815
1816        // 3. reset z-buffer to 0 and render the source object for the beam
1817        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
1818        //    save result to the front depth map
1819        //    the front depth map holds ray origins
1820
1821
1822        // front depth buffer must be initialised to 0
1823        float clearDepth;
1824       
1825        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
1826        glClearDepth(0.0f);
1827        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1828
1829
1830        //glFrontFace(GL_CW);
1831        glEnable(GL_CULL_FACE);
1832        glCullFace(GL_FRONT);
1833        glColorMask(0, 0, 0, 0);
1834       
1835
1836        // stencil is increased where the source object is located
1837        glEnable(GL_STENCIL_TEST);     
1838        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
1839        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1840
1841
1842#if 0
1843        static int glSourceObjList = -1;         
1844        if (glSourceObjList != -1)
1845        {
1846                glSourceObjList = glGenLists(1);
1847                glNewList(glSourceObjList, GL_COMPILE);
1848
1849                RenderIntersectable(sourceObject);
1850       
1851                glEndList();
1852        }
1853        glCallList(glSourceObjList);
1854
1855#else
1856        RenderIntersectable(sourceObject);
1857
1858#endif 
1859
1860         // copy contents of the front depth buffer into depth texture
1861        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
1862        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1863
1864
1865        // reset clear function
1866        glClearDepth(clearDepth);
1867
1868       
1869       
1870        // 4. set up the termination depth buffer (= standard depth buffer)
1871        //    only rays which have non-zero entry in the origin buffer are valid since
1872        //    they realy start on the object surface (this is tagged by setting a
1873        //    stencil buffer bit at step 3).
1874       
1875        glStencilFunc(GL_EQUAL, 0x1, 0x1);
1876        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1877
1878        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1879        glDepthMask(1);
1880
1881        glEnable(GL_DEPTH_TEST);
1882               
1883        glEnable(GL_CULL_FACE);
1884        glCullFace(GL_BACK);
1885
1886        // setup front depth buffer
1887        glEnable(GL_TEXTURE_2D);
1888       
1889        // bind pixel shader implementing the front depth buffer functionality
1890        cgGLBindProgram(sCgFragmentProgram);
1891        cgGLEnableProfile(sCgFragmentProfile);
1892
1893
1894        // 5. render all objects inside the beam
1895        //    we can use id based false color to read them back for gaining the pvs
1896
1897        glColorMask(1, 1, 1, 1);
1898
1899       
1900        // if objects not stored in beam => extract objects
1901        if (beam.mFlags & !Beam::STORE_OBJECTS)
1902        {
1903                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
1904
1905                Intersectable::NewMail();
1906                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
1907                {
1908                        mKdTree->CollectObjects(*it, beam.mObjects);
1909                }
1910        }
1911
1912
1913        //    (objects can be compiled to a gl list now so that subsequent rendering for
1914        //    this beam is fast - the same hold for step 3)
1915        //    Afterwards we have two depth buffers defining the ray origin and termination
1916       
1917
1918#if 0
1919        static int glObjList = -1;
1920        if (glObjList != -1)
1921        {
1922                glObjList = glGenLists(1);
1923                glNewList(glObjList, GL_COMPILE);
1924       
1925                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1926                for (it = beam.mObjects.begin(); it != it_end; ++ it)
1927                {
1928                        // render all objects except the source object
1929                        if (*it != sourceObject)
1930                                RenderIntersectable(*it);
1931                }
1932               
1933                glEndList();
1934        }
1935
1936        glCallList(glObjList);
1937#else
1938        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1939        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1940        {       
1941                // render all objects except the source object
1942                if (*it != sourceObject)
1943                        RenderIntersectable(*it);
1944        }
1945#endif
1946       
1947   
1948
1949        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1950        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1951        //     between origin and termination buffer
1952
1953        // create new queries if necessary
1954        OcclusionQuery::GenQueries(sQueries, (int)beam.mViewCells.size());
1955
1956        // check whether any backfacing polygon would pass the depth test?
1957        // matt: should check both back /front facing because of dual depth buffer
1958        // and danger of cutting the near plane with front facing polys.
1959       
1960        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1961        glDepthMask(GL_FALSE);
1962        glDisable(GL_CULL_FACE);
1963
1964 
1965        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1966
1967        int queryIdx = 0;
1968
1969        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1970        {
1971                sQueries[queryIdx ++]->BeginQuery();
1972
1973                RenderIntersectable(*vit);
1974               
1975                sQueries[queryIdx]->EndQuery();
1976
1977                ++ queryIdx;
1978        }
1979
1980
1981
1982        // at this point, if possible, go and do some other computation
1983
1984
1985       
1986        // 7. The number of visible pixels is the number of sample rays which see the source
1987        //    object from the corresponding viewcell -> remember these values for later update
1988        //   of the viewcell pvs - or update immediately?
1989
1990        queryIdx = 0;
1991
1992        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1993        {
1994                // fetch queries
1995                unsigned int pixelCount = sQueries[queryIdx ++]->GetQueryResult();
1996
1997                if (pixelCount)
1998                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1999        }
2000       
2001
2002        // 8. Copmpute rendering statistics
2003        // In general it is not neccessary to remember to extract all the rays cast. I hope it
2004        // would be sufficient to gain only the intergral statistics about the new contributions
2005        // and so the rss tree would actually store no new rays (only the initial ones)
2006        // the subdivision of the tree would only be driven by the statistics (the glrender could
2007        // evaluate the contribution entropy for example)
2008        // However might be an option to extract/store only those the rays which made a contribution
2009        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
2010
2011        ObjectContainer pvsObj;
2012        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
2013       
2014        // to gain ray source and termination
2015        // copy contents of ray termination buffer into depth texture
2016        // and compare with ray source buffer
2017#if 0
2018        VssRayContainer rays;
2019
2020        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
2021        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
2022
2023        ComputeRays(Intersectable *sourceObj, rays);
2024
2025#endif
2026
2027
2028
2029        //-- cleanup
2030
2031
2032        // reset gl state
2033        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2034        glDepthMask(GL_TRUE);
2035        glEnable(GL_CULL_FACE);
2036        glDisable(GL_STENCIL_TEST);
2037        cgGLDisableProfile(sCgFragmentProfile);
2038        glDisable(GL_TEXTURE_2D);
2039
2040        // remove objects from beam
2041        if (beam.mFlags & !Beam::STORE_OBJECTS)
2042                beam.mObjects.clear();
2043}
2044
2045
2046void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
2047                                                                                                   const Beam &beam,
2048                                                                                                   Intersectable *sourceObject)
2049{
2050        float left, right, bottom, top, znear, zfar;
2051
2052        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
2053                                                                   mSceneGraph->GetBox());
2054
2055        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
2056        glMatrixMode(GL_PROJECTION);
2057        glLoadIdentity();
2058        glFrustum(left, right, bottom, top, znear, zfar);
2059        //glFrustum(-1, 1, -1, 1, 1, 20000);
2060
2061    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
2062        const Vector3 up =
2063                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
2064
2065#ifdef _DEBUG
2066        Debug << "view point: " << viewPoint << endl;
2067        Debug << "eye: " << center << endl;
2068        Debug << "up: " << up << endl;
2069#endif
2070
2071        glMatrixMode(GL_MODELVIEW);
2072        glLoadIdentity();
2073        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
2074                          center.x, center.y, center.z,                   
2075                          up.x, up.y, up.z);
2076}               
2077
2078 
2079void GlRendererBuffer::InitGL()
2080{
2081 makeCurrent();
2082 GlRenderer::InitGL();
2083
2084#if 1
2085        // initialise dual depth buffer textures
2086        glGenTextures(1, &frontDepthMap);
2087        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
2088       
2089        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
2090                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
2091        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2092        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2093        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2094        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2095
2096        glGenTextures(1, &backDepthMap);
2097        glBindTexture(GL_TEXTURE_2D, backDepthMap);
2098       
2099        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
2100                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
2101        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2102        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2103        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2104        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2105
2106        // cg initialization
2107        cgSetErrorCallback(handleCgError);
2108        sCgContext = cgCreateContext();
2109       
2110        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
2111                sCgFragmentProfile = CG_PROFILE_ARBFP1;
2112        else
2113        {
2114          // try FP30
2115          if (cgGLIsProfileSupported(CG_PROFILE_FP30))
2116            sCgFragmentProfile = CG_PROFILE_FP30;
2117          else
2118          {
2119                  Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
2120                  exit(1);
2121          }
2122  }
2123
2124
2125 sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
2126                                                                                           CG_SOURCE, "../src/dual_depth.cg",
2127                                                                                           sCgFragmentProfile,
2128                                                                                           NULL,
2129                                                                                           NULL);
2130
2131  if (!cgIsProgramCompiled(sCgFragmentProgram))
2132          cgCompileProgram(sCgFragmentProgram);
2133
2134  cgGLLoadProgram(sCgFragmentProgram);
2135  cgGLBindProgram(sCgFragmentProgram);
2136
2137  Debug << "---- PROGRAM BEGIN ----\n" <<
2138          cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
2139
2140#endif
2141  doneCurrent();
2142}
2143
2144
2145void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
2146{
2147        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
2148        {
2149                //todo glGetTexImage()
2150        }
2151}
2152
2153
2154
2155inline bool ilt(Intersectable *obj1, Intersectable *obj2)
2156{
2157        return obj1->mId < obj2->mId;
2158}
2159
2160
2161int GlRendererBuffer::ComputePvs(ObjectContainer &objects,
2162                                                                 ObjectContainer &pvs) const
2163{
2164        int pvsSize = 0;
2165        QImage image = toImage();
2166        Intersectable::NewMail();
2167
2168        std::stable_sort(objects.begin(), objects.end(), ilt);
2169
2170        MeshInstance dummy(NULL);
2171
2172        Intersectable *obj = NULL;
2173                       
2174        for (int x = 0; x < image.width(); ++ x)
2175        {
2176                for (int y = 0; y < image.height(); ++ y)
2177                {
2178                        QRgb pix = image.pixel(x, y);
2179                        const int id = GetId(qRed(pix), qGreen(pix), qBlue(pix));
2180
2181                        dummy.SetId(id);
2182
2183                        ObjectContainer::iterator oit =
2184                                lower_bound(objects.begin(), objects.end(), &dummy, ilt);
2185                       
2186                       
2187                        if (//(oit != oit.end()) &&
2188                                ((*oit)->GetId() == id) &&
2189                                !obj->Mailed())
2190                        {
2191                                obj = *oit;
2192                                obj->Mail();
2193                                ++ pvsSize;
2194                                pvs.push_back(obj);
2195                        }
2196                }
2197        }
2198
2199        return pvsSize;
2200}
2201
2202/***********************************************************************/
2203/*                     GlDebuggerWidget implementation                             */
2204/***********************************************************************/
2205
2206
2207GlDebuggerWidget::GlDebuggerWidget(GlRendererBuffer *buf, QWidget *parent)
2208      : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
2209{
2210        // create the pbuffer
2211    //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
2212    timerId = startTimer(20);
2213    setWindowTitle(("OpenGL pbuffers"));
2214}
2215
2216
2217GlDebuggerWidget::~GlDebuggerWidget()
2218{
2219 mRenderBuffer->releaseFromDynamicTexture();
2220   glDeleteTextures(1, &dynamicTexture);
2221         
2222         DEL_PTR(mRenderBuffer);
2223}
2224
2225
2226void GlDebuggerWidget::initializeGL()
2227{
2228        glMatrixMode(GL_PROJECTION);
2229        glLoadIdentity();
2230
2231        glFrustum(-1, 1, -1, 1, 10, 100);
2232        glTranslatef(-0.5f, -0.5f, -0.5f);
2233        glTranslatef(0.0f, 0.0f, -15.0f);
2234        glMatrixMode(GL_MODELVIEW);
2235
2236        glEnable(GL_CULL_FACE);
2237        initCommon();
2238        initPbuffer();
2239
2240}
2241
2242
2243void GlDebuggerWidget::resizeGL(int w, int h)
2244{
2245        glViewport(0, 0, w, h);
2246}
2247
2248
2249void GlDebuggerWidget::paintGL()
2250{
2251        // draw a spinning cube into the pbuffer..
2252        mRenderBuffer->makeCurrent();
2253       
2254        BeamSampleStatistics stats;
2255        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
2256
2257        glFlush();
2258
2259        // rendering directly to a texture is not supported on X11, unfortunately
2260    mRenderBuffer->updateDynamicTexture(dynamicTexture);
2261   
2262    // and use the pbuffer contents as a texture when rendering the
2263    // background and the bouncing cubes
2264    makeCurrent();
2265    glBindTexture(GL_TEXTURE_2D, dynamicTexture);
2266    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2267
2268    // draw the background
2269    glMatrixMode(GL_MODELVIEW);
2270    glPushMatrix();
2271    glLoadIdentity();
2272    glMatrixMode(GL_PROJECTION);
2273    glPushMatrix();
2274    glLoadIdentity();
2275
2276        glPopMatrix();
2277        glMatrixMode(GL_MODELVIEW);
2278        glPopMatrix();
2279}
2280
2281
2282void GlDebuggerWidget::initPbuffer()
2283{
2284        // set up the pbuffer context
2285    mRenderBuffer->makeCurrent();
2286        /*mRenderBuffer->InitGL();
2287
2288        glViewport(0, 0, mRenderBuffer->size().width(), mRenderBuffer->size().height());
2289        glMatrixMode(GL_PROJECTION);
2290        glLoadIdentity();
2291        glOrtho(-1, 1, -1, 1, -99, 99);
2292        glTranslatef(-0.5f, -0.5f, 0.0f);
2293        glMatrixMode(GL_MODELVIEW);
2294        glLoadIdentity();
2295
2296        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);*/
2297       
2298        // generate a texture that has the same size/format as the pbuffer
2299    dynamicTexture = mRenderBuffer->generateDynamicTexture();
2300
2301        // bind the dynamic texture to the pbuffer - this is a no-op under X11
2302        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
2303        makeCurrent();
2304}
2305
2306void GlDebuggerWidget::initCommon()
2307{
2308        glEnable(GL_TEXTURE_2D);
2309        glEnable(GL_DEPTH_TEST);
2310
2311        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
2312}
2313
2314}
Note: See TracBrowser for help on using the repository browser.