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

Revision 1613, 52.5 KB checked in by bittner, 18 years ago (diff)

kd-tree hack active

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