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

Revision 2663, 60.8 KB checked in by mattausch, 16 years ago (diff)

debugging vp evaluation

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