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

Revision 2636, 60.4 KB checked in by bittner, 16 years ago (diff)

moving objects partially functional

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