source: GTP/trunk/Lib/Vis/Preprocessing/src/QtGlRenderer.cpp @ 1585

Revision 1585, 49.7 KB checked in by bittner, 18 years ago (diff)

renderer changes

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