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

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