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

Revision 2617, 59.6 KB checked in by bittner, 16 years ago (diff)

change to USE_BIT_PVS for timing tests: Warning visualization will probably not work correctly

Line 
1#include "glInterface.h"
2#include "QtGlRenderer.h"
3#include "Mesh.h"
4#include "OcclusionQuery.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#include "Material.h"
17#include "IntersectableWrapper.h"
18#include "LogWriter.h"
19
20
21#define USE_CG 1
22
23
24#if USE_CG
25#include <Cg/cg.h>
26#include <Cg/cgGL.h>
27#endif
28
29#include <QVBoxLayout>
30
31namespace GtpVisibilityPreprocessor {
32
33
34 
35class ViewCellsManager;
36
37static CGcontext sCgContext = NULL;
38static CGprogram sCgFragmentProgram = NULL;
39static CGprofile sCgFragmentProfile;
40
41
42//static vector<OcclusionQuery *> sQueries;
43
44QtGlRendererWidget *rendererWidget = NULL;
45QtGlDebuggerWidget *debuggerWidget = NULL;
46
47const static int SAMPLES_INCR = 2000000;
48
49
50
51static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
52{
53        return obj1->mId < obj2->mId;
54}
55
56
57inline static bool nearerThan(ViewCell *vc1, ViewCell *vc2)
58{
59        return vc1->GetDistance() > vc2->GetDistance();
60}
61
62
63#if USE_CG
64static void handleCgError()
65{
66    Debug << "Cg error: " << cgGetErrorString(cgGetError()) << endl;
67    exit(1);
68}
69#endif
70
71void
72QtGlRendererBuffer::MakeCurrent()
73{
74  makeCurrent();
75}
76
77void
78QtGlRendererBuffer::DoneCurrent()
79{
80  doneCurrent();
81}
82 
83
84QtGlRendererBuffer::QtGlRendererBuffer(const int w,
85                                                                           const int h,
86                                                                           SceneGraph *sceneGraph,
87                                                                           ViewCellsManager *viewcells,
88                                                                           KdTree *tree):
89  QGLPixelBuffer(QSize(w, h)),
90  GlRendererBuffer(sceneGraph, viewcells, tree)
91{
92  MakeCurrent();
93  InitGL();
94  DoneCurrent();
95}
96
97
98// reimplemented here so that we can snap the error windows
99float
100QtGlRendererBuffer::GetPixelError(int &pvsSize)
101{
102
103  MakeCurrent();
104
105  float pErrorPixels = -1.0f;
106
107
108        mUseFalseColors = false;
109        unsigned int pixelCount;
110
111
112        ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
113        if (viewcell == NULL)
114                return 0.0f;
115
116        ObjectPvs pvs;
117       
118        if (1)
119                pvs = viewcell->GetPvs();
120        else
121                mViewCellsManager->ApplyFilter2(viewcell, false, 1.0f, pvs);
122
123        mUseForcedColors = true;
124
125        SetupCamera();
126        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
127        glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
128        glColor3f(0,1,0);
129
130
131        glStencilFunc(GL_EQUAL, 0x0, 0x1);
132        glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
133
134        // Render PVS
135        ObjectPvsIterator it = pvs.GetIterator();
136
137        pvsSize = pvs.GetSize();
138        cout<<pvsSize<<endl;
139
140        Intersectable::NewMail();
141        while (it.HasMoreEntries())
142          {
143                RenderIntersectable(it.Next());
144          }
145
146        //glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
147        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
148        glEnable(GL_STENCIL_TEST);
149        glColor3f(1,0,0);
150
151       
152        OcclusionQuery *query = mOcclusionQueries[0];
153
154        //      SetupCamera();
155
156        Intersectable::NewMail();
157
158        query->BeginQuery();
159
160        RenderScene();
161       
162        query->EndQuery();
163        glDisable(GL_STENCIL_TEST);
164
165        // reenable other state
166        //  int wait=0;
167        //  while (!query.ResultAvailable()) {
168        //      wait++;
169        //  }
170       
171
172        pixelCount = query->GetQueryResult();
173        //      cout<<"pc="<<pixelCount<<endl;
174       
175        pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
176
177
178        if (mSnapErrorFrames && (0 && pErrorPixels >= 0.01f)) {
179          glReadBuffer(GL_BACK);
180          //glReadBuffer(GL_FRONT);
181         
182          char filename[256];
183          sprintf(filename, "error-frame-%04d-%0.5f.png", mFrame, pErrorPixels);
184          QImage im = toImage();
185          string str = mSnapPrefix + filename;
186          QString qstr(str.c_str());
187         
188          im.save(qstr, "PNG");
189          if (0) { //0 && mFrame == 1543) {
190                int x,y;
191                int lastIndex = -1;
192                for (y=0; y < im.height(); y++)
193                  for (x=0; x < im.width(); x++) {
194                        QRgb p = im.pixel(x,y);
195                        int index = qRed(p) + (qGreen(p)<<8) + (qBlue(p)<<16);
196                        if (qGreen(p) != 255 && index!=0) {
197                          if (index != lastIndex) {
198                                //                              Debug<<"ei="<<index<<" ";
199                                lastIndex = index;
200                          }
201                        }
202                  }
203          }
204         
205          mUseFalseColors = false;
206          glPushAttrib(GL_CURRENT_BIT);
207          glColor3f(0,1,0);
208          glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
209          glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
210         
211          // Render PVS
212          Intersectable::NewMail();
213         
214         
215          ObjectPvsIterator it = pvs.GetIterator();
216          for (; it.HasMoreEntries(); )
217                {
218                  RenderIntersectable(it.Next());
219                }
220
221          mUseForcedColors = false;
222         
223          im = toImage();
224          sprintf(filename, "error-frame-%04d-%0.5f-pvs.png", mFrame, pErrorPixels);
225          str = mSnapPrefix + filename;
226          qstr = str.c_str();
227          im.save(qstr, "PNG");
228          glPopAttrib();
229        }
230       
231        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
232
233        DoneCurrent();
234
235        return pErrorPixels;
236}
237
238int
239QtGlRendererBuffer::ComputePvs(ObjectContainer &objects,
240                                                           ObjectContainer &pvs) const
241{
242        int pvsSize = 0;
243        QImage image = toImage();
244        Intersectable::NewMail();
245
246        std::stable_sort(objects.begin(), objects.end(), ilt);
247
248        MeshInstance dummy(NULL);
249
250        Intersectable *obj = NULL;
251
252        for (int x = 0; x < image.width(); ++ x)
253        {
254                for (int y = 0; y < image.height(); ++ y)
255                {
256                        QRgb pix = image.pixel(x, y);
257                        const int id = GetId(qRed(pix), qGreen(pix), qBlue(pix));
258
259                        dummy.SetId(id);
260
261                        ObjectContainer::iterator oit =
262                                lower_bound(objects.begin(), objects.end(), &dummy, ilt);
263
264
265                        if (//(oit != oit.end()) &&
266                                ((*oit)->GetId() == id) &&
267                                !obj->Mailed())
268                        {
269                                obj = *oit;
270                                obj->Mail();
271                                ++ pvsSize;
272                                pvs.push_back(obj);
273                        }
274                }
275        }
276
277        return pvsSize;
278}
279
280
281void QtGlRendererWidget::InitGL()
282{
283        GlRenderer::InitGL();
284
285        GLfloat mat_ambient[] = {0.5f, 0.5f, 0.5f, 1.0f};
286       
287        // mat_specular and mat_shininess are NOT default values
288        GLfloat mat_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
289        GLfloat mat_specular[] = {0.3f, 0.3f, 0.3f, 1.0f};
290        GLfloat mat_shininess[] = {1.0f};
291
292        GLfloat light_ambient[] = {0.2f, 0.2f, 0.2f, 1.0f};
293        GLfloat light_diffuse[] = {0.4f, 0.4f, 0.4f, 1.0f};
294        GLfloat light_specular[] = {0.3f, 0.3f, 0.3f, 1.0f};
295
296        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
297
298
299        // default Material
300        glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
301        glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
302        glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
303        glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
304
305        // a light
306        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
307        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
308        glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
309
310        glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
311        glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
312        glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
313
314        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
315
316        glEnable(GL_LIGHTING);
317        glEnable(GL_LIGHT0);
318        glEnable(GL_LIGHT1);
319
320        // set position of the light
321        GLfloat infinite_light[] = {  1.0, 0.8, 1.0, 0.0  };
322        glLightfv (GL_LIGHT0, GL_POSITION, infinite_light);
323
324        // set position of the light2
325        GLfloat infinite_light2[] = {  -0.3, 1.5, 1.0, 0.0  };
326        glLightfv (GL_LIGHT1, GL_POSITION, infinite_light2);
327
328        glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
329        // glColorMaterial( GL_FRONT_AND_BACK, GL_SPECULAR);
330        glEnable(GL_COLOR_MATERIAL);
331
332        glShadeModel(GL_FLAT);
333}
334
335
336void
337QtGlRendererWidget::SetupCameraProjection(const int w, const int h, const float angle)
338{
339        if (!mTopView) {
340                int ww = w;
341                int hh = h;
342                glViewport(0, 0, ww, hh);
343                glMatrixMode(GL_PROJECTION);
344                glLoadIdentity();
345                gluPerspective(angle, ww/(float)hh, 0.1, 2.0 * Magnitude(mSceneGraph->GetBox().Diagonal()));
346                glMatrixMode(GL_MODELVIEW);
347        } else {
348                int ww = w;
349                int hh = h;
350                glViewport(0, 0, ww, hh);
351                glMatrixMode(GL_PROJECTION);
352                glLoadIdentity();
353                gluPerspective(50.0, ww / (float)hh, 0.1, 20.0 * Magnitude(mSceneGraph->GetBox().Diagonal()));
354                glMatrixMode(GL_MODELVIEW);
355        }
356}
357
358
359bool QtGlRendererWidget::PvsChanged(ViewCell *viewCell) const
360{
361        if (viewCell != mPvsCache.mViewCell)
362                return true;
363
364        if (viewCell->GetPvs().GetSize() != mPvsCache.mUnfilteredPvsSize)
365                return true;
366
367        return false;
368}
369
370
371void QtGlRendererWidget::_RenderPvs()
372{
373        mUseFalseColors = false;
374
375        int offset = (int)mObjects.size() * 3;
376        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
377
378        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
379        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
380        glDrawElements(GL_TRIANGLES, mIndexBufferSize, GL_UNSIGNED_INT, mIndices);
381#if DYNAMIC_OBJECTS_HACK
382        // handle dynamic objects
383        DynamicObjectsContainer::const_iterator dit, dit_end = mDynamicObjects.end();
384
385
386        for (dit = mDynamicObjects.begin(); dit != dit_end; ++ dit)
387        {
388#if USE_TRANSFORMED_MESH_INSTANCE_HACK
389                //cerr << "here45\n****"<<endl;
390                RenderIntersectable(*dit);
391#else
392                RenderDynamicObject(*dit);
393#endif
394        }
395#endif
396}
397
398
399void QtGlRendererWidget::PreparePvs()
400{
401        int indexBufferSize = 0;
402       
403        KdNode::NewMail();
404        //Intersectable::NewMail();
405
406        mPvsSize = mPvsCache.mPvs.GetSize();
407#if DYNAMIC_OBJECTS_HACK
408        mDynamicObjects.clear();
409#endif
410        ObjectPvsIterator it = mPvsCache.mPvs.GetIterator();
411
412        while (it.HasMoreEntries())
413        {
414                Intersectable *obj = it.Next();
415                switch (obj->Type())
416                {
417                case Intersectable::KD_INTERSECTABLE:
418                        {
419                                KdNode *node = static_cast<KdIntersectable *>(obj)->GetItem();
420                                _UpdatePvsIndices(node, indexBufferSize);
421                        }
422                        break;
423#if DYNAMIC_OBJECTS_HACK
424#if USE_TRANSFORMED_MESH_INSTANCE_HACK
425
426                case Intersectable::TRANSFORMED_MESH_INSTANCE:
427                        mDynamicObjects.push_back(static_cast<TransformedMeshInstance *>(obj));
428                        break;
429
430#else
431                case Intersectable::SCENEGRAPHLEAF_INTERSECTABLE:
432                        mDynamicObjects.push_back(static_cast<SceneGraphLeafIntersectable *>(obj)->GetItem());
433                        break;
434#endif
435#endif
436                default:
437                        cerr << "PreparePvs: type " << Intersectable::GetTypeName(obj) << " not handled yet" << endl;
438                }
439        }
440
441        mIndexBufferSize = indexBufferSize;
442}
443
444
445void QtGlRendererWidget::_UpdatePvsIndices(KdNode *node, int &indexBufferSize)
446{
447        if (node->Mailed())
448                return;
449
450        node->Mail();
451
452        // if (mObjects.size() * 3 < indexBufferSize) cerr << "problem: " << mObjects.size() * 3 << " < " << indexBufferSize << endl;
453        if (!node->IsLeaf())
454        {
455                KdInterior *kdInterior = static_cast<KdInterior *>(node);
456
457                _UpdatePvsIndices(kdInterior->mBack, indexBufferSize);
458                _UpdatePvsIndices(kdInterior->mFront, indexBufferSize);
459        }
460        else
461        {
462                KdLeaf *leaf = static_cast<KdLeaf *>(node);
463
464                leaf->mIndexBufferStart = indexBufferSize;
465
466                for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
467                {
468                        TriangleIntersectable *obj =
469                                static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
470
471                        if (obj->mRenderedFrame != mCurrentFrame)
472                        {
473                                obj->mRenderedFrame = mCurrentFrame;
474
475                                mIndices[indexBufferSize + 0] = (obj->GetId() - 1) * 3 + 0;
476                                mIndices[indexBufferSize + 1] = (obj->GetId() - 1) * 3 + 1;
477                                mIndices[indexBufferSize + 2] = (obj->GetId() - 1) * 3 + 2;
478
479                                indexBufferSize += 3;
480                        }
481                }
482
483                leaf->mIndexBufferSize = indexBufferSize - leaf->mIndexBufferStart;
484        }
485
486        //cout << "id: " << indexBufferSize << endl;
487}
488
489
490void QtGlRendererWidget::RenderPvs()
491{
492        if (mUseVbos)
493                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
494
495        ++ mCurrentFrame;
496
497        EnableDrawArrays();
498
499        //Intersectable::NewMail();
500       
501        if (mDetectEmptyViewSpace)
502                glEnable(GL_CULL_FACE);
503        else
504                glDisable(GL_CULL_FACE);
505
506        ViewCell *viewcell = NULL;
507        viewcell = mViewCellsManager->GetViewCell(mViewPoint, true);
508
509        if (viewcell)
510        {
511                // copy the pvs so that it can be filtered ...
512                if (PvsChanged(viewcell))
513                {
514                        mPvsCache.Reset();
515                        mPvsCache.mViewCell = viewcell;
516                        mPvsCache.mUnfilteredPvsSize = viewcell->GetPvs().GetSize();
517
518                        if (mUseSpatialFilter)
519                        {
520                                //mMutex.lock();
521                                // mSpatialFilter size is in range 0.001 - 0.1
522                                mViewCellsManager->ApplyFilter2(viewcell,
523                                                                    mUseFilter,
524                                                                    100.0f * mSpatialFilterSize,
525                                                                    //pvs,
526                                                                                                mPvsCache.mPvs,         
527                                                                    &mPvsCache.filteredBoxes);
528                                //mPvsCache.mPvs = pvs;
529                                //mMutex.unlock();
530                                cout << "pvs size: " << mPvsCache.mPvs.GetSize() << endl;
531                        }
532                        else
533                        {
534                                mPvsCache.mPvs = viewcell->GetPvs();
535                        }
536
537                        /// update the indices for rendering
538                        PreparePvs();
539
540                        emit PvsUpdated();
541                }
542
543
544                // Render PVS
545                if (mUseSpatialFilter && mRenderBoxes)
546                {
547                        for (int i=0; i < mPvsCache.filteredBoxes.size(); ++ i)
548                        {
549                                RenderBox(mPvsCache.filteredBoxes[i]);
550                        }
551                }
552                else
553                {
554                        if (!mRenderVisibilityEstimates && !mUseRandomColorPerPvsObject)
555                                _RenderPvs();
556                        else
557                                _RenderColoredPvs();
558                }
559
560                if (mRenderFilter)
561                {
562                        mWireFrame = true;
563                        RenderIntersectable(viewcell);
564                       
565                        /*glPushMatrix();
566                        glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
567                        glScalef(5.0f,5.0f,5.0f);
568                        glPushAttrib(GL_CURRENT_BIT);
569                        glColor3f(1.0f, 0.0f, 0.0f);
570                        //        gluSphere((::GLUquadric *)mSphere,
571                        //                              1e-3*Magnitude(mViewCellsManager->GetViewSpaceBox().Size()), 6, 6);
572                        glPopAttrib();
573                        glPopMatrix();
574                        */
575                        mWireFrame = false;
576                }
577        }
578        else
579        {
580                //ObjectContainer::const_iterator oi = mObjects.begin();
581                //for (; oi != mObjects.end(); oi++)
582                //      RenderIntersectable(*oi);
583                RenderScene();
584        }
585}
586
587float
588QtGlRendererWidget::RenderErrors()
589{
590        float pErrorPixels = -1.0f;
591
592        SetupCamera();
593        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
594
595        glPushAttrib(GL_ENABLE_BIT);
596
597        glStencilFunc(GL_EQUAL, 0x0, 0x1);
598        glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
599
600        mUseForcedColors = true;
601
602        glColor3f(0.0f, 0.8f, 0.2f);
603
604        // Render PVS
605        RenderPvs();
606
607        glEnable(GL_STENCIL_TEST);
608
609        //mUseFalseColors = true;
610
611        glDisable(GL_LIGHTING);
612
613        OcclusionQuery *query = mOcclusionQueries[0];
614        query->BeginQuery();
615
616        SetupCamera();
617
618        glColor3f(1.0f, 0.0f, 0.0f);
619
620        RenderScene();
621
622        mUseForcedColors = false;
623
624        query->EndQuery();
625
626        glDisable(GL_STENCIL_TEST);
627        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
628
629        glPopAttrib();
630
631        // reenable other state
632        //  int wait=0;
633        //  while (!query.ResultAvailable()) {
634        //      wait++;
635        //  }
636
637        int pixelCount = query->GetQueryResult();
638        pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
639        if (0) cout<<"error pixels="<<pixelCount<<endl;
640
641        mRenderError = pErrorPixels;
642
643        return pErrorPixels;
644}
645
646
647void QtGlRendererWidget::timerEvent(QTimerEvent *event)
648{
649        //std::cout << "Timer ID:" << event->timerId();
650        update();
651}
652
653
654void QtGlRendererWidget::mousePressEvent(QMouseEvent *e)
655{
656        int x = e->pos().x();
657        int y = e->pos().y();
658
659        mousePoint.x = x;
660        mousePoint.y = y;
661
662}
663
664void
665QtGlRendererWidget::mouseMoveEvent(QMouseEvent *e)
666{
667        float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
668        float TURN_SENSITIVITY = 0.1f;
669        float TILT_SENSITIVITY = 32.0 ;
670        float TURN_ANGLE= M_PI  /36.0 ;
671
672        int x = e->pos().x();
673        int y = e->pos().y();
674
675        int diffx = -(mousePoint.x - x);
676        int diffy = -(mousePoint.y - y);
677
678        const float t = 1.0f;
679
680        if (e->modifiers() & Qt::ControlModifier)
681        {
682                mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY / 2.0;
683                mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY / 2.0;
684        }
685#if DYNAMIC_OBJECTS_HACK
686        else if (e->modifiers() & Qt::AltModifier)
687        {
688                if (mCurrentDynamicObjectIdx >= 0)
689                {
690                        Matrix4x4 tm;
691                        TransformedMeshInstance *tmi;
692#if USE_TRANSFORMED_MESH_INSTANCE_HACK
693
694                        switch (mTrafoType)
695                        {
696                        case 0:
697                                {
698                                        const Vector3 transl(diffx, 0, diffy);
699                                        tmi = mViewCellsManager->GetPreprocessor()->mDynamicObjects[mCurrentDynamicObjectIdx];
700                                        tm = TranslationMatrix(transl);
701                                }
702                                break;
703                        case 1:
704                                {
705                                        float scalef = 1.0f + 0.01f * (diffx + diffy);
706                                        if (scalef < 0.9) scalef = 0.9f;
707                                        else if (scalef > 1.1f) scalef = 1.1f;
708                                        tmi = mViewCellsManager->GetPreprocessor()->mDynamicObjects[mCurrentDynamicObjectIdx];
709                                        tm = ScaleMatrix(scalef, scalef, scalef);
710                                }
711                                break;
712                        case 2:
713                                {
714                                        tmi = mViewCellsManager->GetPreprocessor()->mDynamicObjects[mCurrentDynamicObjectIdx];
715                                        tm = RotationXMatrix(diffx) * RotationYMatrix(diffy);
716                                }
717                                break;
718                        default:
719                                cerr << "not implemented" << endl;
720                        }
721
722                        tmi->ApplyWorldTransform(tm);
723#endif
724                        updateGL();
725                }
726        }
727#endif
728        else
729        {
730                mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
731                float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
732                float angle = atan2(mViewDirection.x, mViewDirection.z);
733                mViewDirection.x = sin(angle + adiff);
734                mViewDirection.z = cos(angle + adiff);
735        }
736
737        mousePoint.x = x;
738        mousePoint.y = y;
739
740        updateGL();
741}
742
743void
744QtGlRendererWidget::mouseReleaseEvent(QMouseEvent *)
745{
746}
747
748void
749QtGlRendererWidget::resizeGL(int w, int h)
750{
751        SetupCameraProjection(w, h);
752        updateGL();
753}
754
755void
756QtGlRendererWidget::paintGL()
757{
758        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
759
760        if (1)
761        {
762                SetupCameraProjection(width(), height());
763                SetupCamera();
764
765                if (mRenderErrors)
766                {
767                        RenderErrors();
768                }
769                else
770                {
771                        glColor3f(0.6f, 0.6f, 0.6f);
772                        RenderPvs();
773                }
774
775                if (1 && mShowRays)
776                {
777                        RenderRays(mViewCellsManager->mVizBuffer.GetRays(), mRayVisualizationMethod, mShowDistribution, 1);
778                }
779        }
780
781        RenderInfo();
782        mFrame ++;
783}
784
785
786void
787QtGlRendererWidget::SetupCamera()
788{
789        if (!mTopView)
790                GlRenderer::SetupCamera();
791        else
792        {
793                if (0)
794                {
795                        float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
796                        Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
797                                -1,
798                                mViewDirection.y);
799
800                        Vector3 target = mViewPoint + dist*mViewDirection;
801                        Vector3 up(0,1,0);
802
803                        glLoadIdentity();
804                        gluLookAt(pos.x, pos.y, pos.z,
805                                target.x, target.y, target.z,
806                                up.x, up.y, up.z);
807                }
808                else
809                {
810                        float dist = Magnitude(mSceneGraph->GetBox().Diagonal()) * mTopDistance;
811                        Vector3 pos = mViewPoint  + dist*Vector3(0,
812                                1,
813                                0);
814
815                        Vector3 target = mViewPoint;
816                        Vector3 up(mViewDirection.x, 0, mViewDirection.z);
817
818                        glLoadIdentity();
819                        gluLookAt(pos.x, pos.y, pos.z,
820                                target.x, target.y, target.z,
821                                up.x, up.y, up.z);
822
823                }
824        }
825
826}
827
828
829void
830QtGlRendererWidget::keyPressEvent ( QKeyEvent * e )
831{
832        switch (e->key())
833        {
834case Qt::Key_E:
835        mRenderErrors = !mRenderErrors;
836        updateGL();
837        break;
838case Qt::Key_R:
839        mUseRandomColorPerPvsObject = !mUseRandomColorPerPvsObject;;
840        updateGL();
841        break;
842case Qt::Key_T:
843        mTopView = !mTopView;
844        SetupCameraProjection(width(), height());
845        updateGL();
846        break;
847case Qt::Key_V:
848        mRenderViewCells = !mRenderViewCells;
849        updateGL();
850        break;
851case Qt::Key_P:
852        // set random viewpoint
853        mViewCellsManager->GetViewPoint(mViewPoint);
854        updateGL();
855        break;
856case Qt::Key_S: {
857        // set view poitn and direction
858        QString text;
859        bool ok;
860        text.sprintf("%f %f %f", mViewPoint.x, mViewPoint.y, mViewPoint.z);
861        text = QInputDialog::getText(this,
862                "Enter a view point",
863                "",
864                QLineEdit::Normal,
865                text,
866                &ok);
867        if (!ok)
868                break;
869
870        if (sscanf(text.toAscii(), "%f %f %f", &mViewPoint.x, &mViewPoint.y, &mViewPoint.z) == 3) {
871                text.sprintf("%f %f %f", mViewDirection.x, mViewDirection.y, mViewDirection.z);
872                text = QInputDialog::getText(this,
873                        "Enter a direction",
874                        "",
875                        QLineEdit::Normal,
876                        text,
877                        &ok);
878                if (!ok)
879                        break;
880                if (sscanf(text.toAscii(), "%f %f %f", &mViewDirection.x,
881                        &mViewDirection.y, &mViewDirection.z) == 3) {
882                                updateGL();
883                        }
884                        break;
885        }
886                                }
887default:
888        cerr << "unknown key" << endl;
889        e->ignore();
890        break;
891        }
892}
893
894
895
896QtGlRendererWidget::QtGlRendererWidget(
897                                                                           SceneGraph *sceneGraph,
898                                                                           ViewCellsManager *viewcells,
899                                                                           KdTree *tree,
900                                                                           QWidget * parent,
901                                                                           const QGLWidget * shareWidget,
902                                                                           Qt::WFlags f
903                                                                           )
904                                                                           :
905GlRendererWidget(sceneGraph, viewcells, tree), QGLWidget(parent, shareWidget, f)
906{
907        mPreprocessorThread = NULL;
908        mTopView = false;
909        mRenderViewCells = false;
910        mTopDistance = 1.0f;
911        mCutViewCells = false;
912        mCutScene = false;
913        mRenderErrors = false;
914        mRenderBoxes = false;
915        mRenderFilter = true;
916        mRenderVisibilityEstimates = false;
917
918        mUseRandomColorPerPvsObject = false;
919
920        mHideByCost = false;
921        mUseTransparency = false;
922
923        mTransferFunction = 1.0f;
924        mIndexBufferSize = 0;
925
926        //mCurrentFrame = 0;
927
928        const int delay = 250; // in milliseconds
929        timerId = startTimer(delay);
930
931        bool tmp;
932
933        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp );
934        mUseFilter = tmp;
935
936        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter", tmp );
937        mUseSpatialFilter = tmp;
938
939        //mLogWriter = new LogWriter("myfile.out");
940
941        mShowRenderCost = false;
942        mShowPvsSizes = false;
943        mShowComparison = false;
944        mShowPiercingRays = false;
945        mShowWeightedRays = false;
946        mUseStandardColors = false;
947        mShowWeightedCost = true;
948
949        mShowDistanceWeightedPvs = true;
950        mShowDistanceWeightedTriangles = false;
951        mShowWeightedTriangles = false;
952        mShowDistribution = 15;
953        mCurrentDynamicObjectIdx = -1;
954
955        mSpatialFilterSize = 0.01;
956        mPvsSize = 0;
957        mRayVisualizationMethod = 0;
958        mTrafoType = 0;
959
960        mRenderError = 0.0f;
961        mShowRays = false;
962
963        mControlWidget = new QtRendererControlWidget(NULL);
964
965        connect(mControlWidget, SIGNAL(SetViewCellGranularity(int)), this, SLOT(SetViewCellGranularity(int)));
966        connect(mControlWidget, SIGNAL(SetTransferFunction(int)), this, SLOT(SetTransferFunction(int)));
967
968        connect(mControlWidget, SIGNAL(UpdateAllPvs()), this, SLOT(UpdateAllPvs()));
969        connect(mControlWidget, SIGNAL(ComputeVisibility()), this, SLOT(ComputeVisibility()));
970        connect(mControlWidget, SIGNAL(StopComputation()), this, SLOT(StopComputation()));
971        connect(mControlWidget, SIGNAL(SetRandomViewPoint()), this,     SLOT(SetRandomViewPoint()));
972        connect(mControlWidget, SIGNAL(StoreStatistics(void)), this, SLOT(StoreStatistics(void)));
973        connect(mControlWidget, SIGNAL(LoadObject(void)), this, SLOT(LoadObject(void)));
974
975        connect(mControlWidget, SIGNAL(SetSceneCut(int)), this, SLOT(SetSceneCut(int)));
976        connect(mControlWidget, SIGNAL(SetTopDistance(int)), this, SLOT(SetTopDistance(int)));
977        connect(mControlWidget, SIGNAL(SetTransparency(int)), this, SLOT(SetTransparency(int)));
978
979        connect(mControlWidget, SIGNAL(SetVisibilityFilterSize(int)), this, SLOT(SetVisibilityFilterSize(int)));
980        connect(mControlWidget, SIGNAL(SetSpatialFilterSize(int)), this, SLOT(SetSpatialFilterSize(int)));
981        connect(mControlWidget, SIGNAL(SetHidingCost(int)), this, SLOT(SetHidingCost(int)));
982
983        connect(mControlWidget, SIGNAL(SetShowViewCells(bool)), this, SLOT(SetShowViewCells(bool)));
984        connect(mControlWidget, SIGNAL(SetShowRenderCost(bool)), this, SLOT(SetShowRenderCost(bool)));
985        connect(mControlWidget, SIGNAL(SetUseTransparency(bool)), this, SLOT(SetUseTransparency(bool)));
986        connect(mControlWidget, SIGNAL(SetShowPvsSizes(bool)), this, SLOT(SetShowPvsSizes(bool)));
987        connect(mControlWidget, SIGNAL(SetShowComparison(bool)), this, SLOT(SetShowComparison(bool)));
988        connect(mControlWidget, SIGNAL(SetTopView(bool)), this, SLOT(SetTopView(bool)));
989        connect(mControlWidget, SIGNAL(SetCutViewCells(bool)), this, SLOT(SetCutViewCells(bool)));
990        connect(mControlWidget, SIGNAL(SetHideByCost(bool)), this, SLOT(SetHideByCost(bool)));
991        connect(mControlWidget, SIGNAL(SetCutScene(bool)), this, SLOT(SetCutScene(bool)));
992        connect(mControlWidget, SIGNAL(SetRenderErrors(bool)), this, SLOT(SetRenderErrors(bool)));
993        connect(mControlWidget, SIGNAL(SetRenderBoxes(bool)), this, SLOT(SetRenderBoxes(bool)));
994        connect(mControlWidget, SIGNAL(SetRenderFilter(bool)), this, SLOT(SetRenderFilter(bool)));
995        connect(mControlWidget, SIGNAL(SetRenderVisibilityEstimates(bool)), this, SLOT(SetRenderVisibilityEstimates(bool)));
996        connect(mControlWidget, SIGNAL(SetUseFilter(bool)), this, SLOT(SetUseFilter(bool)));
997        connect(mControlWidget, SIGNAL(SetUseSpatialFilter(bool)), this, SLOT(SetUseSpatialFilter(bool)));
998        connect(mControlWidget, SIGNAL(SetShowPiercingRays(bool)), this, SLOT(SetShowPiercingRays(bool)));
999        connect(mControlWidget, SIGNAL(SetShowWireFrame(bool)), this, SLOT(SetShowWireFrame(bool)));
1000        connect(mControlWidget, SIGNAL(SetShowWeightedRays(bool)), this, SLOT(SetShowWeightedRays(bool)));
1001        connect(mControlWidget, SIGNAL(SetShowWeightedCost(bool)), this, SLOT(SetShowWeightedCost(bool)));
1002
1003        connect(mControlWidget, SIGNAL(SetShowDistanceWeightedTriangles(bool)), this, SLOT(SetShowDistanceWeightedTriangles(bool)));
1004        connect(mControlWidget, SIGNAL(SetShowDistanceWeightedPvs(bool)), this, SLOT(SetShowDistanceWeightedPvs(bool)));
1005        connect(mControlWidget, SIGNAL(SetShowWeightedTriangles(bool)), this, SLOT(SetShowWeightedTriangles(bool)));
1006
1007        connect(mControlWidget, SIGNAL(UseConstColorForRayViz(bool)), this, SLOT(UseConstColorForRayViz(bool)));
1008        connect(mControlWidget, SIGNAL(UseRayLengthForRayViz(bool)), this, SLOT(UseRayLengthForRayViz(bool)));
1009        connect(mControlWidget, SIGNAL(SetShowContribution(bool)), this, SLOT(SetShowContribution(bool)));
1010        connect(mControlWidget, SIGNAL(SetShowDistribution(bool)), this, SLOT(SetShowDistribution(bool)));
1011
1012        connect(mControlWidget, SIGNAL(SetShowDistribution1(bool)), this, SLOT(SetShowDistribution1(bool)));
1013        connect(mControlWidget, SIGNAL(SetShowDistribution2(bool)), this, SLOT(SetShowDistribution2(bool)));
1014        connect(mControlWidget, SIGNAL(SetShowDistribution3(bool)), this, SLOT(SetShowDistribution3(bool)));
1015        connect(mControlWidget, SIGNAL(SetShowDistribution4(bool)), this, SLOT(SetShowDistribution4(bool)));
1016
1017        connect(mControlWidget, SIGNAL(SetShowRays(bool)), this, SLOT(SetShowRays(bool)));
1018
1019        connect(mControlWidget, SIGNAL(SetTranslation(bool)), this, SLOT(SetTranslation(bool)));
1020        connect(mControlWidget, SIGNAL(SetRotation(bool)), this, SLOT(SetRotation(bool)));
1021        connect(mControlWidget, SIGNAL(SetScale(bool)), this, SLOT(SetScale(bool)));
1022       
1023        setWindowTitle("PVS Visualization");
1024
1025        // setting the main window size here
1026        //resize(800, 600);
1027        //resize(640, 480);
1028        //resize(512, 384);
1029        //resize(512, 320);
1030        resize(640, 400);
1031       
1032        mControlWidget->show();
1033}
1034
1035void
1036QtGlRendererWidget::UpdateAllPvs()
1037{
1038        // $$ does not work so far:(
1039        mViewCellsManager->UpdatePvsForEvaluation();
1040        //      mViewCellsManager->FinalizeViewCells(false);
1041}
1042
1043void
1044QtGlRendererWidget::ComputeVisibility()
1045{
1046        cerr<<"Compute Visibility called!\n"<<endl;
1047        if (!mPreprocessorThread->isRunning())
1048                mPreprocessorThread->RunThread();
1049}
1050
1051void
1052QtGlRendererWidget::StopComputation()
1053{
1054        cerr<<"stop computation called!\n"<<endl;
1055        mViewCellsManager->GetPreprocessor()->mStopComputation = true;
1056}
1057
1058void
1059QtGlRendererWidget::SetRandomViewPoint()
1060{
1061        cerr<<"setting random view point!\n"<<endl;
1062        mViewCellsManager->GetViewPoint(mViewPoint);
1063        updateGL();
1064}
1065
1066
1067void QtGlRendererWidget::StoreStatistics()
1068{
1069        cerr<<"storing statistics!\n"<<endl;
1070        const int currentSamples = mViewCellsManager->GetPreprocessor()->mCurrentSamples;
1071
1072        cout<<"**********************************************" << endl;
1073        cout << "reached " << currentSamples << " samples " << " => writing file" << endl;
1074               
1075        LogWriter writer;
1076        writer.SetFilename("compare.log");
1077        writer.Write(currentSamples, mViewCellsManager->GetViewCells());
1078        cout << "finished writing file" << endl;
1079        mCompareInfo.clear();
1080        updateGL();
1081}
1082
1083
1084void QtGlRendererWidget::LoadObject()
1085{
1086        string filename("../data/teapot.bn");
1087       
1088        cout << "Loading model << " << filename << endl;
1089
1090        ++ mCurrentDynamicObjectIdx;
1091
1092        if (mViewCellsManager->GetPreprocessor()->LoadDynamicGeometry(filename))
1093                cout << "Loading finished" << endl;
1094        else
1095                cerr << "Loading failed" << endl;
1096
1097    updateGL();
1098}
1099
1100void
1101QtGlRendererWidget::RenderRenderCost()
1102{
1103        static vector<float> costFunction;
1104        static float maxCost = -1;
1105        if (costFunction.size()==0) {
1106                ViewCellsTree *tree = mViewCellsManager->GetViewCellsTree();
1107                if (tree) {
1108                        tree->GetCostFunction(costFunction);
1109                        maxCost = -1;
1110                        for (int i=0;  i < costFunction.size(); i++) {
1111                                //                cout<<i<<":"<<costFunction[i]<<" ";
1112                                // update cost function to an absolute value based on the total geometry count
1113                                costFunction[i] *= mSceneGraph->GetSize();
1114                                if (costFunction[i] > maxCost)
1115                                        maxCost = costFunction[i];
1116                        }
1117                }
1118        }
1119
1120
1121        int currentPos = (int)mViewCellsManager->GetViewCells().size();
1122        float currentCost= -1;
1123
1124        if (currentPos < costFunction.size())
1125                currentCost = costFunction[currentPos];
1126#if 1   
1127        cout<<"costFunction.size()="<<(int)costFunction.size()<<endl;
1128        cout<<"CP="<<currentPos<<endl;
1129        cout<<"MC="<<maxCost<<endl;
1130        cout<<"CC="<<currentCost<<endl;
1131#endif
1132        if (costFunction.size()) {
1133                float scaley = 1.0f/log10(maxCost);
1134                float scalex = 1.0f/(float)costFunction.size();
1135
1136                glDisable(GL_DEPTH_TEST);
1137                // init ortographic projection
1138                glMatrixMode(GL_PROJECTION);
1139
1140                glPushMatrix();
1141
1142                glLoadIdentity();
1143                gluOrtho2D(0, 1.0f, 0, 1.0f);
1144
1145                glTranslatef(0.1f, 0.1f, 0.0f);
1146                glScalef(0.8f, 0.8f, 1.0f);
1147                glMatrixMode(GL_MODELVIEW);
1148                glLoadIdentity();
1149
1150                glColor3f(1.0f,0,0);
1151                glBegin(GL_LINE_STRIP);
1152                //        glVertex3f(0,0,0);
1153
1154                for (int i=0;  i < costFunction.size(); i++) {
1155                        float x =  i*scalex;
1156                        float y = log10(costFunction[i])*scaley;
1157                        glVertex3f(x,y,0.0f);
1158                }
1159                glEnd();
1160
1161                glColor3f(1.0f,0,0);
1162                glBegin(GL_LINES);
1163                float x =  currentPos*scalex;
1164                glVertex3f(x,0.0,0.0f);
1165                glVertex3f(x,1.0f,0.0f);
1166                glEnd();
1167
1168                glColor3f(0.0f,0,0);
1169                // show a grid
1170                glBegin(GL_LINE_LOOP);
1171                glVertex3f(0,0,0.0f);
1172                glVertex3f(1,0,0.0f);
1173                glVertex3f(1,1,0.0f);
1174                glVertex3f(0,1,0.0f);
1175                glEnd();
1176
1177                glBegin(GL_LINES);
1178                for (int i=0;  i < costFunction.size(); i += 1000) {
1179                        float x =  i*scalex;
1180                        glVertex3f(x,0.0,0.0f);
1181                        glVertex3f(x,1.0f,0.0f);
1182                }
1183
1184                for (int i=0;  pow(10.0f, i) < maxCost; i+=1) {
1185                        float y = i*scaley;
1186                        //              QString s;
1187                        //              s.sprintf("%d", (int)pow(10,i));
1188                        //              renderText(width()/2+5, y*height(), s);
1189                        glVertex3f(0.0f, y, 0.0f);
1190                        glVertex3f(1.0f, y, 0.0f);
1191                }
1192
1193                glEnd();
1194
1195
1196                // restore the projection matrix
1197                glMatrixMode(GL_PROJECTION);
1198                glPopMatrix();
1199                glMatrixMode(GL_MODELVIEW);
1200                glEnable(GL_DEPTH_TEST);
1201
1202        }
1203
1204
1205
1206}
1207
1208void
1209QtGlRendererWidget::RenderInfo()
1210{
1211
1212        QString s;
1213
1214        int vc = 0;
1215        if (mViewCellsManager)
1216                vc = (int)mViewCellsManager->GetViewCells().size();
1217
1218        int filter = 0;
1219        if (mViewCellsManager)
1220                filter = mViewCellsManager->GetMaxFilterSize();
1221
1222        glColor3f(0.0f, 0.0f, 1.0f);
1223
1224#if REMOVE_TEMPORARY
1225        s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f)",
1226                mFrame,
1227                mViewPoint.x,
1228                mViewPoint.y,
1229                mViewPoint.z,
1230                mViewDirection.x,
1231                mViewDirection.y,
1232                mViewDirection.z
1233                );
1234
1235        renderText(20, 20, s);
1236
1237        s.sprintf("viewcells:%04d filter:%04d pvs:%04d error:%5.5f %",
1238                vc,
1239                filter,
1240                mPvsSize,
1241                mRenderError*100.0f);
1242
1243        renderText(20, 40, s);
1244#endif
1245       
1246        QFont font40; font40.setPointSize(30);
1247        s.sprintf("PVS: %04d", mPvsSize);
1248        renderText(20, 40, s, font40);
1249}
1250
1251
1252void
1253QtGlRendererWidget::SetViewCellGranularity(int number)
1254{
1255        if (mViewCellsManager) {
1256                //      mViewCellsManager->SetMaxFilterSize(number);
1257
1258                // $$ tmp off
1259                mViewCellsManager->CollectViewCells(number);
1260
1261                // $$ does not work so far:(
1262                //      mViewCellsManager->UpdatePvsForEvaluation();
1263                //      mViewCellsManager->FinalizeViewCells(false);
1264        }
1265        updateGL();
1266}
1267
1268void
1269QtGlRendererWidget::SetVisibilityFilterSize(int number)
1270{
1271        if (mViewCellsManager)
1272                mViewCellsManager->SetMaxFilterSize(number);
1273        mPvsCache.Reset();
1274        updateGL();
1275}
1276
1277void
1278QtGlRendererWidget::SetSpatialFilterSize(int number)
1279{
1280        mSpatialFilterSize = 1e-3*number;
1281        mPvsCache.Reset();
1282        updateGL();
1283}
1284
1285void
1286QtGlRendererWidget::SetSceneCut(int number)
1287{
1288        // assume the cut plane can only be aligned with xz plane
1289        // shift it along y according to number, which is percentage of the bounding
1290        // box position
1291        if (mViewCellsManager)
1292        {
1293                const float f = number / 1000.0f;
1294                AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1295                Vector3 p = (1.0f - f) * box.Min() + f * box.Max();
1296                mSceneCutPlane.mNormal = Vector3(0,-1,0);
1297                mSceneCutPlane.mD = -DotProd(mSceneCutPlane.mNormal, p);
1298
1299                updateGL();
1300        }
1301}
1302
1303void
1304QtGlRendererWidget::SetHidingCost(int number)
1305{
1306        mHidingCost = (float)number / 1000.0f;
1307}
1308
1309
1310void
1311QtGlRendererWidget::SetTopDistance(int number)
1312{
1313        mTopDistance = number / 1000.0f;
1314        updateGL();
1315}
1316
1317void QtGlRendererWidget::SetTransparency(int number)
1318{
1319        mTransparency = number / 1000.0f;
1320        updateGL();
1321}
1322
1323#if 0
1324float QtGlRendererWidget::ComputeRenderCost(ViewCell *vc)
1325{
1326        ObjectPvs basePvs;
1327       
1328        basePvs = vc->CopyPvs();
1329        ObjectPvsIterator pit = basePvs.GetIterator();
1330
1331        float renderCost = 0;
1332
1333        //cout << "cost vis: " << mShowDistanceWeightedPvs << " " << " " << mShowDistanceWeightedTriangles << " " << mShowWeightedTriangles << endl;
1334       
1335        // first mark all objects from this pvs
1336        while (pit.HasMoreEntries())   
1337        {
1338                KdIntersectable *kdObj = static_cast<KdIntersectable *>(pit.Next());
1339
1340                if (mShowDistanceWeightedPvs)
1341                {
1342                        const AxisAlignedBox3 box = kdObj->GetBox();
1343
1344                        const float dist = SqrDistance(vc->GetBox().Center(), box.Center());
1345                        renderCost += 1.0f / dist;
1346                }
1347                else if (mShowDistanceWeightedTriangles)
1348                {
1349                        const AxisAlignedBox3 box = kdObj->GetBox();
1350
1351                        const float dist = SqrDistance(vc->GetBox().Center(), box.Center());
1352                        renderCost += kdObj->ComputeNumTriangles() / dist;
1353                }
1354                else //if (mShowWeightedTriangles)
1355                {
1356                        renderCost += kdObj->ComputeNumTriangles();
1357                }
1358                //if (pit.Next()->Mail();
1359        }
1360
1361        return renderCost;
1362}
1363#else
1364
1365float QtGlRendererWidget::ComputeRenderCost(ViewCell *vc)
1366{
1367        float renderCost = 0;
1368
1369#ifndef USE_BIT_PVS
1370        if (mShowDistanceWeightedPvs)
1371        {
1372                return vc->GetPvs().mStats.mDistanceWeightedPvs;
1373        }
1374        else if (mShowDistanceWeightedTriangles)
1375        {
1376                return vc->GetPvs().mStats.mDistanceWeightedTriangles;
1377        }
1378        else //if (mShowWeightedTriangles)
1379        {
1380                return vc->GetPvs().mStats.mWeightedTriangles;
1381        }
1382#else
1383        return 0.0f;
1384#endif
1385}
1386#endif
1387
1388
1389
1390void QtGlRendererWidget::ComputeMaxValues(const ViewCellContainer &viewCells,
1391                                                                                  int &maxPvs,
1392                                                                                  int &maxPiercingRays,
1393                                                                                  float &maxRelativeRays,
1394                                                                                  float &maxRcCost)
1395{
1396        maxPvs = -1;
1397        maxPiercingRays = 1; // not zero for savety
1398        maxRelativeRays = Limits::Small; // not zero for savety
1399        maxRcCost = Limits::Small;
1400
1401        for (size_t i = 0; i < viewCells.size(); ++ i)
1402        {
1403                ViewCell *vc = viewCells[i];
1404
1405                if (mShowPvsSizes) // pvs size
1406                {
1407                        //const int p = vc->GetPvs().CountObjectsInPvs();
1408                        const int p = vc->GetPvs().GetSize();
1409                        if (p > maxPvs)
1410                                maxPvs = p;
1411                }
1412                else if (mShowPiercingRays) // relative number of rays
1413                {
1414                        const int piercingRays = vc->GetNumPiercingRays();
1415
1416                        if (piercingRays > maxPiercingRays)
1417                                maxPiercingRays = piercingRays;
1418                }
1419                else if (mShowWeightedRays)
1420                {
1421                        const int piercingRays = vc->GetNumPiercingRays();
1422
1423                        const float relativeArea =
1424                                vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1425
1426                        if ((float)piercingRays / relativeArea > maxRelativeRays)
1427                                maxRelativeRays = (float)piercingRays / relativeArea;
1428                }
1429                else if (mShowWeightedCost)
1430                {
1431                        const float rcCost = ComputeRenderCost(vc);
1432                        mViewCellsManager->UpdateScalarPvsCost(vc, rcCost);
1433
1434                        if (rcCost > maxRcCost)
1435                                maxRcCost = rcCost;
1436                }
1437        }
1438}
1439
1440
1441void QtGlRendererWidget::RenderViewCells()
1442{
1443        mUseFalseColors = true;
1444        //glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT);
1445
1446        glEnable(GL_CULL_FACE);
1447        glCullFace(GL_FRONT);
1448        //glDisable(GL_CULL_FACE);
1449
1450        if (mCutViewCells)
1451        {
1452                double eq[4];
1453                eq[0] = mSceneCutPlane.mNormal.x;
1454                eq[1] = mSceneCutPlane.mNormal.y;
1455                eq[2] = mSceneCutPlane.mNormal.z;
1456                eq[3] = mSceneCutPlane.mD;
1457
1458                glClipPlane(GL_CLIP_PLANE0, eq);
1459                glEnable(GL_CLIP_PLANE0);
1460        }
1461
1462        ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
1463       
1464        int maxPvs, maxPiercingRays;
1465        float maxRelativeRays, maxRcCost;
1466
1467        ComputeMaxValues(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1468        // matt: temp hack
1469        //maxRcCost = 200.0f;
1470        //cout << "maxRcCost: " << maxRcCost << endl;
1471        int i;
1472
1473        // transparency
1474        if (!mUseTransparency)
1475        {
1476                glEnable(GL_DEPTH_TEST);
1477                glDisable(GL_BLEND);
1478        }
1479        else
1480        {
1481                glDisable(GL_DEPTH_TEST);
1482                glEnable(GL_BLEND);
1483
1484                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1485                //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1486
1487                for (i = 0; i < viewcells.size(); ++ i)
1488                {
1489                        ViewCell *vc = viewcells[i];
1490
1491                        const float dist = SqrDistance(mDummyViewPoint, vc->GetBox().Center());
1492                        vc->SetDistance(dist);
1493                }
1494
1495                sort(viewcells.begin(), viewcells.end(), nearerThan);
1496        }
1497
1498        //mWireFrame = true;
1499               
1500        // normal rendering
1501        //if (!mShowPvsSizes && !mShowPiercingRays && !mShowWeightedRays && !mShowWeightedCost && !mShowComparison)
1502        if (mUseStandardColors)
1503        {
1504                for (i = 0; i < viewcells.size(); ++ i)
1505                {
1506                        ViewCell *vc = viewcells[i];
1507                        RgbColor c;
1508
1509                        //if (!mShowPvsSizes && !mShowPiercingRays)
1510                        c = vc->GetColor();
1511                       
1512                        glColor3f(c.r, c.g, c.b);
1513
1514                        if (!mHideByCost || (mHidingCost < (vc->GetNumPiercingRays() / (float)maxPiercingRays)))
1515                        {
1516                RenderViewCell(vc);
1517                        }
1518                }
1519        }
1520        else // using specialised colors
1521        {
1522                if (!mShowComparison)
1523                        AssignImportanceByRelativeValue(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1524                else
1525                {
1526                        if (mCompareInfo.empty())
1527                        {
1528                                LogReader reader;
1529                                reader.SetFilename("compare.log");
1530                                int samples;
1531                                reader.Read(samples, mCompareInfo);
1532                        }
1533
1534                        AssignColorByComparison(viewcells, mCompareInfo);
1535                }
1536
1537                glEnable(GL_DEPTH_TEST);       
1538        }
1539       
1540        glEnable(GL_CULL_FACE);
1541        glDisable(GL_CULL_FACE);
1542
1543        glDisable(GL_CLIP_PLANE0);
1544
1545        mUseFalseColors = false;
1546        mWireFrame = false;
1547
1548        glPopAttrib();
1549}
1550
1551
1552void QtGlRendererWidget::AssignImportanceByRelativeValue(const ViewCellContainer &viewCells,
1553                                                                                                                 int &maxPvs,
1554                                                                                                                 int &maxPiercingRays,
1555                                                                                                                 float &maxRelativeRays,
1556                                                                                                                 float &maxRcCost)
1557{
1558        for (size_t i = 0; i < viewCells.size(); ++ i)
1559        {
1560                RgbColor c;
1561                ViewCell *vc = viewCells[i];
1562
1563                float importance;
1564
1565                if (mShowPiercingRays)
1566                {
1567                        importance = mTransferFunction *
1568                                ((float)vc->GetNumPiercingRays() / (float)maxPiercingRays);
1569                }
1570                else if (mShowWeightedRays) // relative number of rays
1571                {
1572                        float relativeArea = vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1573
1574                        if (relativeArea < Limits::Small)
1575                                relativeArea = Limits::Small;
1576
1577                        importance = mTransferFunction * ((float)vc->GetNumPiercingRays() / relativeArea) / maxRelativeRays;
1578                }
1579                else if (mShowPvsSizes) // pvs size
1580                {
1581                        importance = mTransferFunction *
1582                                ((float)vc->GetPvs().GetSize() / (float)maxPvs);
1583                } // weighted render cost
1584                else if (mShowWeightedCost)
1585                {
1586                        const float rcCost = mTransferFunction * ComputeRenderCost(vc);
1587                        importance = rcCost / maxRcCost;
1588                }
1589if (importance > 1.0f) importance = 1.0f;
1590                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1591                c = RainbowColorMapping(importance);
1592
1593                glColor4f(c.r, c.g, c.b, 1.0f - mTransparency);
1594
1595                if (!mHideByCost || (mHidingCost < importance))
1596                {
1597                        RenderViewCell(vc);
1598                }
1599        }
1600}
1601
1602
1603void QtGlRendererWidget::AssignColorByComparison(const ViewCellContainer &viewcells,
1604                                                                                                 //const ViewCellInfoContainer &infos1,
1605                                                                                                 const ViewCellInfoContainer &compareInfo)
1606{
1607        //cout << "comparing " << viewcells.size() << " view cells to " << compareInfo.size() << " values" << endl;
1608
1609        if (viewcells.size() > compareInfo.size())
1610        {
1611                cerr << "loaded size (" << (int)compareInfo.size() << ") does not fit to view cells size (" << (int)viewcells.size() << ")" << endl;
1612                return;
1613        }
1614
1615        //const float maxRatio = 1.0f;
1616        const float maxRatio = 2.0f;
1617        const float minRatio = 0.0f;
1618
1619        const float scale = 1.0f / (maxRatio - minRatio);
1620
1621        for (size_t i = 0; i < viewcells.size(); ++ i)
1622        {
1623                RgbColor c;
1624                ViewCell *vc = viewcells[i];
1625
1626                //ViewCellInfo vc1Info = infos1[i];
1627                ViewCellInfo vc2Info = compareInfo[i];
1628
1629                //const float vcRatio = vc->GetNumPiercingRays() / vc2Info.mPiercingRays + Limits::Small;
1630                float vcRatio = 1.0f;//maxRatio;
1631               
1632                if (vc2Info.mPvsSize > Limits::Small)
1633                        vcRatio = (float)vc->GetPvs().GetSize() / vc2Info.mPvsSize;
1634
1635                // truncate here
1636                if (vcRatio > maxRatio) vcRatio = 1.0f;
1637
1638                const float importance = (vcRatio - minRatio) * scale;
1639       
1640                if (0 && (i < 20))
1641                {
1642                        cout << "pvs1: " << vc->GetPvs().GetSize() << " pvs2: " << compareInfo[i].mPvsSize << " importance: " << importance << endl;
1643                }
1644
1645                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1646                c = RainbowColorMapping(importance);
1647
1648                glColor4f(c.r, c.g, c.b, 1.0f);
1649
1650                if (1)//!mHideByCost || (mHidingCost < importance))
1651                {
1652                        RenderViewCell(vc);
1653                }
1654        }
1655}
1656
1657
1658
1659/**********************************************************************/
1660/*              QtRendererControlWidget implementation                */
1661/**********************************************************************/
1662
1663
1664QGroupBox *QtRendererControlWidget::CreateVisualizationPanel(QWidget *parent)
1665{
1666        QRadioButton *rb1, *rb2, *rb3, *rb4, *rb5;
1667       
1668        rb1 = new QRadioButton("random colors", parent);
1669        rb1->setText("random");
1670        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWireFrame(bool)));
1671
1672        // Create a check box to be in the group box
1673        rb2 = new QRadioButton("piercing rays", parent);
1674        rb2->setText("piercing rays");
1675        //vl->addWidget(rb1);
1676        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowPiercingRays(bool)));
1677
1678        rb3 = new QRadioButton("pvs size", parent);
1679        rb3->setText("pvs size");
1680        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
1681       
1682        rb4 = new QRadioButton("weighted rays", parent);
1683        rb4->setText("weighted rays");
1684        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedRays(bool)));
1685       
1686        rb5 = new QRadioButton("pvs cost", parent);
1687        rb5->setText("pvs cost");
1688        connect(rb5, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedCost(bool)));
1689
1690        QGroupBox *groupBox = new QGroupBox("PVS Visualization");
1691
1692        QVBoxLayout *vbox2 = new QVBoxLayout;
1693   
1694        vbox2->addWidget(rb1);
1695        vbox2->addWidget(rb2);
1696        vbox2->addWidget(rb3);
1697        vbox2->addWidget(rb4);
1698        vbox2->addWidget(rb5);
1699       
1700        rb5->setChecked(true);
1701
1702        vbox2->addStretch(1);
1703        groupBox->setLayout(vbox2);
1704
1705        return groupBox;
1706}
1707
1708
1709QGroupBox *QtRendererControlWidget::CreateTrafoPanel(QWidget *parent)
1710{
1711        QRadioButton *rb1, *rb2, *rb3;
1712       
1713        rb1 = new QRadioButton("translation", parent);
1714        rb1->setText("translation");
1715        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetTranslation(bool)));
1716
1717        // Create a check box to be in the group box
1718        rb2 = new QRadioButton("scale", parent);
1719        rb2->setText("scale");
1720        //vl->addWidget(rb1);
1721        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetScale(bool)));
1722
1723        rb3 = new QRadioButton("rotation", parent);
1724        rb3->setText("rotation");
1725        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetRotation(bool)));
1726   
1727        QVBoxLayout *vbox2 = new QVBoxLayout;
1728        QGroupBox *groupBox = new QGroupBox("Trafo types");
1729
1730        vbox2->addWidget(rb1);
1731        vbox2->addWidget(rb2);
1732        vbox2->addWidget(rb3);
1733       
1734        rb1->setChecked(true);
1735
1736        vbox2->addStretch(1);
1737        groupBox->setLayout(vbox2);
1738
1739        return groupBox;
1740}
1741
1742
1743
1744QGroupBox *QtRendererControlWidget::CreateRenderCostPanel(QWidget *parent)
1745{
1746        QRadioButton *rb1, *rb2, *rb3;
1747       
1748        // Create a check box to be in the group box
1749        rb1 = new QRadioButton("triangles", parent);
1750        rb1->setText("triangles");
1751        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedTriangles(bool)));
1752
1753        rb2 = new QRadioButton("distance weighted pvs", parent);
1754        rb2->setText("distance weighted");
1755        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedPvs(bool)));
1756
1757        rb3 = new QRadioButton("distance weighted triangles", parent);
1758        rb3->setText("distance weighted triangles");
1759        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedTriangles(bool)));
1760
1761        QGroupBox *groupBox = new QGroupBox("Render cost options");
1762        QVBoxLayout *vbox2 = new QVBoxLayout;
1763   
1764        vbox2->addWidget(rb1);
1765        vbox2->addWidget(rb2);
1766        vbox2->addWidget(rb3);
1767       
1768        rb1->setChecked(true);
1769
1770        vbox2->addStretch(1);
1771        groupBox->setLayout(vbox2);
1772
1773        return groupBox;
1774}
1775
1776
1777QGroupBox *QtRendererControlWidget::CreateRayVisualizationPanel(QWidget *parent)
1778{
1779        QRadioButton *rb1, *rb2, *rb3, *rb4;
1780       
1781        // Create a check box to be in the group box
1782        rb1 = new QRadioButton("const color", parent);
1783        rb1->setText("const color");
1784        //vl->addWidget(rb1);
1785        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(UseConstColorForRayViz(bool)));
1786
1787        rb2 = new QRadioButton("ray length", parent);
1788        rb2->setText("ray length");
1789        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(UseRayLengthForRayViz(bool)));
1790       
1791        rb3 = new QRadioButton("contribution", parent);
1792        rb3->setText("contribution");
1793        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowContribution(bool)));
1794       
1795        rb4 = new QRadioButton("distribution", parent);
1796        rb4->setText("distribution");
1797        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution(bool)));
1798
1799
1800        ///////////////////////////
1801
1802       
1803        QGroupBox *groupBox = new QGroupBox("Ray visualization");
1804        QVBoxLayout *vbox2 = new QVBoxLayout;
1805   
1806        vbox2->addWidget(rb1);
1807        vbox2->addWidget(rb2);
1808        vbox2->addWidget(rb3);
1809        vbox2->addWidget(rb4);
1810       
1811        rb1->setChecked(true);
1812
1813
1814        QCheckBox *cb = new QCheckBox("Distribution 1", parent);
1815        vbox2->addWidget(cb);
1816        cb->setChecked(true);
1817        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution1(bool)));
1818
1819        cb = new QCheckBox("Distribution 2", parent);
1820        vbox2->addWidget(cb);
1821        cb->setChecked(true);
1822        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution2(bool)));
1823
1824        cb = new QCheckBox("Distribution 3", parent);
1825        vbox2->addWidget(cb);
1826        cb->setChecked(true);
1827        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution3(bool)));
1828       
1829        cb = new QCheckBox("Distribution 4", parent);
1830        vbox2->addWidget(cb);
1831        cb->setChecked(true);
1832        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution4(bool)));
1833
1834
1835        vbox2->addStretch(1);
1836        groupBox->setLayout(vbox2);
1837
1838        return groupBox;
1839}
1840
1841
1842QtRendererControlWidget::QtRendererControlWidget(QWidget * parent, Qt::WFlags f):
1843QWidget(parent, f)
1844{
1845
1846        QVBoxLayout *vl = new QVBoxLayout;
1847        setLayout(vl);
1848       
1849        //QWidget *vbox;
1850
1851        //vbox = new QGroupBox("Render Controls", this);
1852        //layout()->addWidget(vbox);
1853        //vl = new QVBoxLayout;
1854        //vbox->setLayout(vl);
1855
1856        QLabel *label;
1857        QSlider *slider;
1858        QPushButton *button;
1859
1860#if REMOVE_TEMPORARY
1861
1862        label = new QLabel("Granularity");
1863        //vbox->layout()->addWidget(label);
1864        vl->addWidget(label);
1865
1866        slider = new QSlider(Qt::Horizontal, vbox);
1867        vl->addWidget(slider);
1868        slider->show();
1869        slider->setRange(1, 10000);
1870        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1871        slider->setValue(200);
1872
1873        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
1874
1875        ///////////////////////////
1876
1877        label = new QLabel("Transfer function");
1878        vl->addWidget(label);
1879
1880        slider = new QSlider(Qt::Horizontal, vbox);
1881        vl->addWidget(slider);
1882        slider->show();
1883        slider->setRange(1, 10000);
1884        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1885        slider->setValue(100);
1886
1887
1888        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransferFunction(int)));
1889
1890        ////////////////////////////////////////7
1891
1892        button = new QPushButton("Update all PVSs", vbox);
1893        vl->addWidget(button);
1894        connect(button, SIGNAL(clicked()), SLOT(UpdateAllPvs()));
1895
1896        ////////////////////////////////////////77777
1897
1898        label = new QLabel("Filter size");
1899        vl->addWidget(label);
1900
1901        slider = new QSlider(Qt::Horizontal, vbox);
1902        vl->addWidget(slider);
1903        slider->show();
1904        slider->setRange(1, 100);
1905        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1906        slider->setValue(3);
1907
1908        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetVisibilityFilterSize(int)));
1909
1910#endif
1911
1912
1913       
1914        ///////////////////////////////////
1915
1916
1917        QWidget *hbox = new QWidget();//vbox);
1918        vl->addWidget(hbox);
1919        QHBoxLayout *hlayout = new QHBoxLayout;
1920        hbox->setLayout(hlayout);
1921
1922        QCheckBox *cb = new QCheckBox("Show viewcells", hbox);
1923        hlayout->addWidget(cb);
1924        cb->setChecked(false);
1925        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
1926       
1927        cb = new QCheckBox("Render errors", hbox);
1928        hlayout->layout()->addWidget(cb);
1929        cb->setChecked(false);
1930        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
1931
1932#if REMOVE_TEMPORARY
1933        cb = new QCheckBox("Render cost curve", hbox);
1934        hlayout->addWidget(cb);
1935        cb->setChecked(false);
1936        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
1937#endif
1938        cb = new QCheckBox("Show rays", hbox);
1939        hlayout->addWidget(cb);
1940        cb->setChecked(false);
1941        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRays(bool)));
1942#if REMOVE_TEMPORARY   
1943        cb = new QCheckBox("Show Comparison", hbox);
1944        hlayout->addWidget(cb);
1945        cb->setChecked(false);
1946        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowComparison(bool)));
1947#endif
1948
1949        //////////////////
1950
1951        QHBoxLayout *vh = new QHBoxLayout;
1952
1953        QGroupBox *myBox = new QGroupBox("Visualization");
1954
1955        myBox->setLayout(vh);
1956        vl->addWidget(myBox, 0, 0);
1957
1958        QGroupBox *groupBox = CreateVisualizationPanel(hbox);
1959        vh->addWidget(groupBox, 0, 0);
1960#if REMOVE_TEMPORARY
1961        QGroupBox *groupBox2 = CreateRenderCostPanel(hbox);
1962        vh->addWidget(groupBox2, 0, 0);
1963#endif
1964        QGroupBox *groupBox3 = CreateRayVisualizationPanel(hbox);
1965        vh->addWidget(groupBox3, 0, 0);
1966
1967        QGroupBox *groupBox4 = CreateTrafoPanel(hbox);
1968        vh->addWidget(groupBox4, 0, 0);
1969
1970        //////////////////////////////////
1971
1972
1973        /*cb = new QRadiobox("Top View", vbox);
1974        vl->addWidget(cb);
1975        cb->setChecked(false);
1976        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
1977*/
1978
1979        //vbox->resize(800,150);
1980        QWidget *vbox;
1981
1982        vbox = new QGroupBox("Rendering", this);
1983        layout()->addWidget(vbox);
1984
1985        vl = new QVBoxLayout;
1986        vbox->setLayout(vl);
1987
1988
1989
1990        cb = new QCheckBox("Cut view cells", vbox);
1991        vbox->layout()->addWidget(cb);
1992        cb->setChecked(false);
1993        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
1994
1995
1996        slider = new QSlider(Qt::Horizontal, vbox);
1997        vbox->layout()->addWidget(slider);
1998        slider->show();
1999        slider->setRange(0, 1000);
2000        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2001        slider->setValue(1000);
2002
2003        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
2004
2005       
2006        cb = new QCheckBox("Hide view cells by render cost ", vbox);
2007        vbox->layout()->addWidget(cb);
2008        cb->setChecked(false);
2009        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetHideByCost(bool)));
2010
2011        ////////////////////////////
2012
2013        const int range = 1000;
2014
2015        label = new QLabel("Hide by cost");
2016        vbox->layout()->addWidget(label);
2017
2018        // the render cost visualization
2019        slider = new QSlider(Qt::Horizontal, vbox);
2020        vbox->layout()->addWidget(slider);
2021        slider->show();
2022        slider->setRange(0, range);
2023        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2024        slider->setValue(0);
2025        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetHidingCost(int)));
2026
2027        ///////////////////////////////////////////
2028
2029        cb = new QCheckBox("Top View", vbox);
2030        vbox->layout()->addWidget(cb);
2031        cb->setChecked(false);
2032        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
2033
2034
2035        label = new QLabel("Top distance");
2036        vbox->layout()->addWidget(label);
2037       
2038        slider = new QSlider(Qt::Horizontal, vbox);
2039        vbox->layout()->addWidget(slider);
2040        slider->show();
2041        slider->setRange(1, 1000);
2042        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2043        slider->setValue(500);
2044
2045        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTopDistance(int)));
2046       
2047
2048        ///////////////////////////////////////////
2049#if REMOVE_TEMPORARY
2050        cb = new QCheckBox("Transparency", vbox);
2051        vbox->layout()->addWidget(cb);
2052        cb->setChecked(false);
2053        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseTransparency(bool)));
2054
2055        label = new QLabel("Use transparency");
2056        vbox->layout()->addWidget(label);
2057
2058        // the render cost visualization
2059        slider = new QSlider(Qt::Horizontal, vbox);
2060        vbox->layout()->addWidget(slider);
2061        slider->show();
2062        slider->setRange(0, range);
2063        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2064        slider->setValue(0);
2065#endif
2066        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransparency(int)));
2067
2068        //////////////////////////////
2069
2070#if REMOVE_TEMPORARY
2071        cb = new QCheckBox("Cut scene", vbox);
2072        vbox->layout()->addWidget(cb);
2073        cb->setChecked(false);
2074        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
2075
2076        cb = new QCheckBox("Render boxes", vbox);
2077        vbox->layout()->addWidget(cb);
2078        cb->setChecked(false);
2079        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderBoxes(bool)));
2080
2081        cb = new QCheckBox("Render visibility estimates", vbox);
2082        vbox->layout()->addWidget(cb);
2083        cb->setChecked(false);
2084        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderVisibilityEstimates(bool)));
2085#endif
2086
2087        bool tmp;
2088#if REMOVE_TEMPORARY
2089
2090        cb = new QCheckBox("Use filter", vbox);
2091        vbox->layout()->addWidget(cb);
2092        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp );
2093        cb->setChecked(tmp);
2094        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
2095#endif
2096
2097        cb = new QCheckBox("Use spatial filter", vbox);
2098        vbox->layout()->addWidget(cb);
2099        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
2100                tmp );
2101        cb->setChecked(tmp);
2102        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
2103#if REMOVE_TEMPORARY
2104        cb = new QCheckBox("Render filter", vbox);
2105        vbox->layout()->addWidget(cb);
2106        cb->setChecked(true);
2107        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderFilter(bool)));
2108
2109
2110        /*vbox = new QGroupBox("PVS Errors", this);
2111        layout()->addWidget(vbox);
2112
2113        vl = new QVBoxLayout;
2114        vbox->setLayout(vl);
2115
2116        button = new QPushButton("Compute Visibility", vbox);
2117        vbox->layout()->addWidget(button);
2118        connect(button, SIGNAL(clicked()), SLOT(ComputeVisibility()));
2119
2120        button = new QPushButton("Stop Computation", vbox);
2121        vbox->layout()->addWidget(button);
2122        connect(button, SIGNAL(clicked()), SLOT(StopComputation()));
2123
2124        button = new QPushButton("Set Random View Point", vbox);
2125        vbox->layout()->addWidget(button);
2126        connect(button, SIGNAL(clicked()), SLOT(SetRandomViewPoint()));*/
2127
2128        button = new QPushButton("Store statistics", vbox);
2129        vbox->layout()->addWidget(button);
2130        connect(button, SIGNAL(clicked()), SIGNAL(StoreStatistics()));
2131
2132        button = new QPushButton("Load object", vbox);
2133        vbox->layout()->addWidget(button);
2134        connect(button, SIGNAL(clicked()), SIGNAL(LoadObject()));
2135#endif
2136        /*cb = new QCheckBox("Stats", vbox);
2137        vbox->layout()->addWidget(cb);
2138        cb->setChecked(false);
2139        connect(cb, SIGNAL(toggled(bool)), SIGNAL(StoreStatistics()));*/
2140
2141        if (0)
2142        {
2143                vbox = new QGroupBox("PVS Errors", this);
2144                layout()->addWidget(vbox);
2145
2146                vl = new QVBoxLayout;
2147                vbox->setLayout(vl);
2148
2149                mPvsErrorWidget = new QListWidget(vbox);
2150                vbox->layout()->addWidget(mPvsErrorWidget);
2151
2152                connect(mPvsErrorWidget,
2153                        SIGNAL(doubleClicked(const QModelIndex &)),
2154                        this,
2155                        SLOT(PvsErrorClicked(const QModelIndex &)));
2156
2157                button = new QPushButton("Next Error Frame", vbox);
2158                vbox->layout()->addWidget(button);
2159                connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
2160        }
2161       
2162        //connect(button, SIGNAL(clicked(void)), SLOT(StoreStatistics(void)));
2163        //mHidingCost = 0.1f;
2164//////////////////////////////////////////
2165
2166        label = new QLabel("Spatial Filter size");
2167        vbox->layout()->addWidget(label);
2168
2169        slider = new QSlider(Qt::Horizontal, vbox);
2170        vbox->layout()->addWidget(slider);
2171        slider->show();
2172        slider->setRange(1, 100);
2173        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2174        slider->setValue(10);
2175
2176        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSpatialFilterSize(int)));
2177
2178
2179        setWindowTitle("Preprocessor Control Widget");
2180        adjustSize();
2181}
2182
2183
2184
2185
2186void
2187QtRendererControlWidget::FocusNextPvsErrorFrame(void)
2188{}
2189
2190void
2191QtRendererControlWidget::UpdatePvsErrorItem(int row,
2192                                                                                        GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
2193{
2194
2195        QListWidgetItem *i = mPvsErrorWidget->item(row);
2196        QString s;
2197        s.sprintf("%5.5f", pvsErrorEntry.mError);
2198        if (i) {
2199                i->setText(s);
2200        } else {
2201                new QListWidgetItem(s, mPvsErrorWidget);
2202        }
2203        mPvsErrorWidget->update();
2204}
2205
2206
2207
2208
2209/*********************************************************************/
2210/*                   QtGlDebuggerWidget implementation               */
2211/*********************************************************************/
2212
2213
2214QtGlDebuggerWidget::QtGlDebuggerWidget(QtGlRendererBuffer *buf, QWidget *parent)
2215: QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
2216{
2217        // create the pbuffer
2218        //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
2219        timerId = startTimer(20);
2220        setWindowTitle(("OpenGL pbuffers"));
2221}
2222
2223
2224QtGlDebuggerWidget::~QtGlDebuggerWidget()
2225{
2226        mRenderBuffer->releaseFromDynamicTexture();
2227        glDeleteTextures(1, &dynamicTexture);
2228
2229        DEL_PTR(mRenderBuffer);
2230}
2231
2232
2233void QtGlDebuggerWidget::initializeGL()
2234{
2235        glMatrixMode(GL_PROJECTION);
2236        glLoadIdentity();
2237
2238        glFrustum(-1, 1, -1, 1, 10, 100);
2239        glTranslatef(-0.5f, -0.5f, -0.5f);
2240        glTranslatef(0.0f, 0.0f, -15.0f);
2241        glMatrixMode(GL_MODELVIEW);
2242
2243        glEnable(GL_CULL_FACE);
2244        initCommon();
2245        initPbuffer();
2246
2247}
2248
2249
2250void QtGlDebuggerWidget::resizeGL(int w, int h)
2251{
2252        glViewport(0, 0, w, h);
2253}
2254
2255
2256void QtGlDebuggerWidget::paintGL()
2257{
2258        // draw a spinning cube into the pbuffer..
2259        mRenderBuffer->makeCurrent();
2260
2261        BeamSampleStatistics stats;
2262        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
2263
2264        glFlush();
2265
2266        // rendering directly to a texture is not supported on X11, unfortunately
2267        mRenderBuffer->updateDynamicTexture(dynamicTexture);
2268
2269        // and use the pbuffer contents as a texture when rendering the
2270        // background and the bouncing cubes
2271        makeCurrent();
2272        glBindTexture(GL_TEXTURE_2D, dynamicTexture);
2273        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2274
2275        // draw the background
2276        glMatrixMode(GL_MODELVIEW);
2277        glPushMatrix();
2278        glLoadIdentity();
2279        glMatrixMode(GL_PROJECTION);
2280        glPushMatrix();
2281        glLoadIdentity();
2282
2283        glPopMatrix();
2284        glMatrixMode(GL_MODELVIEW);
2285        glPopMatrix();
2286}
2287
2288
2289void QtGlDebuggerWidget::initPbuffer()
2290{
2291        // set up the pbuffer context
2292        mRenderBuffer->makeCurrent();
2293        /*mRenderBuffer->InitGL();
2294
2295        glViewport(0, 0, mRenderBuffer->size().width(), mRenderBuffer->size().height());
2296        glMatrixMode(GL_PROJECTION);
2297        glLoadIdentity();
2298        glOrtho(-1, 1, -1, 1, -99, 99);
2299        glTranslatef(-0.5f, -0.5f, 0.0f);
2300        glMatrixMode(GL_MODELVIEW);
2301        glLoadIdentity();
2302
2303        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);*/
2304
2305        // generate a texture that has the same size/format as the pbuffer
2306        dynamicTexture = mRenderBuffer->generateDynamicTexture();
2307
2308        // bind the dynamic texture to the pbuffer - this is a no-op under X11
2309        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
2310        makeCurrent();
2311}
2312
2313
2314void QtGlDebuggerWidget::initCommon()
2315{
2316        glEnable(GL_TEXTURE_2D);
2317        glEnable(GL_DEPTH_TEST);
2318
2319        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
2320}
2321
2322
2323void QtGlRendererWidget::_RenderColoredPvs()
2324{
2325        // note: could be done more efficiently using color buffers
2326        mPvsSize = mPvsCache.mPvs.GetSize();
2327
2328        ObjectPvsIterator it = mPvsCache.mPvs.GetIterator();
2329
2330        PvsData pvsData;
2331
2332        while (it.HasMoreEntries())
2333        {
2334                Intersectable *object = it.Next(pvsData);
2335
2336                RgbColor color;
2337
2338                //float visibility = mTransferFunction*log10(entry.mData.mSumPdf + 1); // /5.0f
2339                // glColor3f(visibility, 0.0f, 0.0f);
2340                //cerr << "sumpdf: " << pvsData.mSumPdf << endl;
2341                if (mUseRandomColorPerPvsObject)
2342                {
2343                        KdIntersectable *kdint = static_cast<KdIntersectable *>(object);
2344
2345                        if (kdint->mGenericIdx == -1)
2346                        {
2347                                kdint->mGenericIdx = (int)mColors.size();
2348                                mColors.push_back(RandomColor());
2349                        }
2350                        color = mColors[kdint->mGenericIdx];
2351                }
2352                else
2353                {
2354                        color = RainbowColorMapping(mTransferFunction * log10(pvsData.mSumPdf + 1));
2355                }
2356
2357                glColor3f(color.r, color.g, color.b);
2358
2359                mUseForcedColors = true;
2360                RenderIntersectable(object);
2361                mUseForcedColors = false;
2362        }
2363}
2364
2365}
Note: See TracBrowser for help on using the repository browser.