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

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