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

Revision 2723, 71.3 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 = 0;//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                        //////////////
356                        //-- output error visualization
357
358                        char filename[256];
359                        //sprintf(filename, "error-frame-%04d-%05d.bmp", pass, mFrame);
360                        //sprintf(filename, "error-frame-%05d-%0.5f.png", mFrame, pErrorPixels);
361                        sprintf_s(filename, "error-frame-%05d-%04d-%08d.png", mFrame, viewcell->GetId(), pixelCount);
362
363                        QImage im = toImage();
364                        string str = mSnapPrefix + filename;
365                        QString qstr(str.c_str());
366
367                        im.save(qstr, "PNG");
368
369                        if (0)
370                        {
371                                ///////////
372                                //-- output computed pvs
373
374                                //mUseFalseColors = false;
375                                mUseFalseColors = true;
376                                glPushAttrib(GL_CURRENT_BIT);
377                                glColor3f(0, 1, 0);
378
379                                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
380                                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
381
382                                KdNode::NewMail2();
383                                Intersectable::NewMail();
384
385                                ++ mCurrentFrame;
386
387                                // render pvs once
388                                RenderPvs(pvs);
389                                // hack for gvs vis
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        float x = 20.0f;
1355        float y = 20.0f;
1356        float z = 20.0f;
1357
1358        AxisAlignedBox3 box(Vector3(0.5f * x, 0, -0.5f * z), Vector3(-0.5f * x, y, 0.5f * z));
1359
1360//      box.Scale(Vector3(0.02f, 0.1f, 0.1f));
1361
1362        box.Translate(-box.Min());
1363
1364        SceneGraphLeaf *leaf = GetPreprocessor()->GenerateBoxGeometry(box);
1365        mPlacer->AddObject(leaf);
1366       
1367        LoadObject("../data/teapot.bn");
1368        LoadObject("../data/bunny.bn");
1369        LoadObject("../data/horse.bn");
1370}
1371
1372
1373void QtGlRendererWidget::NextObject()
1374{
1375        mPlacer->NextObject();
1376}
1377
1378
1379void QtGlRendererWidget::LoadObject(const string &filename)
1380{
1381        cout << "Loading model " << filename << endl;
1382
1383        SceneGraphLeaf *leaf =
1384                mViewCellsManager->GetPreprocessor()->LoadDynamicGeometry(filename);
1385
1386        if (leaf)
1387        {
1388                mPlacer->AddObject(leaf);
1389                cout << "Loading finished" << endl;
1390        }
1391        else
1392                cerr << "Loading failed" << endl;
1393       
1394    //updateGL();
1395}
1396
1397
1398QtGlRendererWidget::~QtGlRendererWidget()
1399{
1400        delete mPlacer;
1401}
1402
1403
1404void
1405QtGlRendererWidget::RenderRenderCost()
1406{
1407        static vector<float> costFunction;
1408        static float maxCost = -1;
1409        if (costFunction.size()==0) {
1410                ViewCellsTree *tree = mViewCellsManager->GetViewCellsTree();
1411                if (tree) {
1412                        tree->GetCostFunction(costFunction);
1413                        maxCost = -1;
1414                        for (int i=0;  i < costFunction.size(); i++) {
1415                                //                cout<<i<<":"<<costFunction[i]<<" ";
1416                                // update cost function to an absolute value based on the total geometry count
1417                                costFunction[i] *= mSceneGraph->GetSize();
1418                                if (costFunction[i] > maxCost)
1419                                        maxCost = costFunction[i];
1420                        }
1421                }
1422        }
1423
1424
1425        int currentPos = (int)mViewCellsManager->GetViewCells().size();
1426        float currentCost= -1;
1427
1428        if (currentPos < costFunction.size())
1429                currentCost = costFunction[currentPos];
1430#if 1   
1431        cout<<"costFunction.size()="<<(int)costFunction.size()<<endl;
1432        cout<<"CP="<<currentPos<<endl;
1433        cout<<"MC="<<maxCost<<endl;
1434        cout<<"CC="<<currentCost<<endl;
1435#endif
1436        if (costFunction.size()) {
1437                float scaley = 1.0f/log10(maxCost);
1438                float scalex = 1.0f/(float)costFunction.size();
1439
1440                glDisable(GL_DEPTH_TEST);
1441                // init ortographic projection
1442                glMatrixMode(GL_PROJECTION);
1443
1444                glPushMatrix();
1445
1446                glLoadIdentity();
1447                gluOrtho2D(0, 1.0f, 0, 1.0f);
1448
1449                glTranslatef(0.1f, 0.1f, 0.0f);
1450                glScalef(0.8f, 0.8f, 1.0f);
1451                glMatrixMode(GL_MODELVIEW);
1452                glLoadIdentity();
1453
1454                glColor3f(1.0f,0,0);
1455                glBegin(GL_LINE_STRIP);
1456                //        glVertex3f(0,0,0);
1457
1458                for (int i=0;  i < costFunction.size(); i++) {
1459                        float x =  i*scalex;
1460                        float y = log10(costFunction[i])*scaley;
1461                        glVertex3f(x,y,0.0f);
1462                }
1463                glEnd();
1464
1465                glColor3f(1.0f,0,0);
1466                glBegin(GL_LINES);
1467                float x =  currentPos*scalex;
1468                glVertex3f(x,0.0,0.0f);
1469                glVertex3f(x,1.0f,0.0f);
1470                glEnd();
1471
1472                glColor3f(0.0f,0,0);
1473                // show a grid
1474                glBegin(GL_LINE_LOOP);
1475                glVertex3f(0,0,0.0f);
1476                glVertex3f(1,0,0.0f);
1477                glVertex3f(1,1,0.0f);
1478                glVertex3f(0,1,0.0f);
1479                glEnd();
1480
1481                glBegin(GL_LINES);
1482                for (int i=0;  i < costFunction.size(); i += 1000) {
1483                        float x =  i*scalex;
1484                        glVertex3f(x,0.0,0.0f);
1485                        glVertex3f(x,1.0f,0.0f);
1486                }
1487
1488                for (int i=0;  pow(10.0f, i) < maxCost; i+=1) {
1489                        float y = i*scaley;
1490                        //              QString s;
1491                        //              s.sprintf("%d", (int)pow(10,i));
1492                        //              renderText(width()/2+5, y*height(), s);
1493                        glVertex3f(0.0f, y, 0.0f);
1494                        glVertex3f(1.0f, y, 0.0f);
1495                }
1496
1497                glEnd();
1498
1499
1500                // restore the projection matrix
1501                glMatrixMode(GL_PROJECTION);
1502                glPopMatrix();
1503                glMatrixMode(GL_MODELVIEW);
1504                glEnable(GL_DEPTH_TEST);
1505
1506        }
1507
1508
1509
1510}
1511
1512void
1513QtGlRendererWidget::RenderInfo()
1514{
1515
1516        QString s;
1517
1518        int vc = 0;
1519        if (mViewCellsManager)
1520                vc = (int)mViewCellsManager->GetViewCells().size();
1521
1522        int filter = 0;
1523        if (mViewCellsManager)
1524                filter = mViewCellsManager->GetMaxFilterSize();
1525
1526#if 0 //REMOVE_TEMPORARY
1527        s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f)",
1528                mFrame,
1529                mViewPoint.x,
1530                mViewPoint.y,
1531                mViewPoint.z,
1532                mViewDirection.x,
1533                mViewDirection.y,
1534                mViewDirection.z
1535                );
1536
1537        renderText(20, 20, s);
1538
1539        s.sprintf("viewcells:%04d filter:%04d pvs:%04d error:%5.5f %",
1540                vc,
1541                filter,
1542                mPvsSize,
1543                mRenderError * 100.0f);
1544
1545        renderText(20, 40, s);
1546#endif
1547
1548        glDisable(GL_LIGHTING);
1549        //qglColor(QColor(0, 255, 0));
1550        glColor3f(0, 1, 0);
1551        QFont font40; font40.setPointSize(25);
1552        //s.sprintf("PVS: %04d", mPvsSize);
1553        //renderText(20, 40, s, font40);
1554       
1555        //s.sprintf("RAW TRI: %07d", mViewCellsManager->GetPreprocessor()->mGenericStats);
1556        //renderText(290, 40, s, font40);
1557        //s.sprintf("PVS TRI: %07d", mViewCellsManager->GetPreprocessor()->mGenericStats2);
1558        //renderText(290, 70, s, font40);
1559
1560        s.sprintf("PVS TRI: %08d", (int)mCurrentPvsCost);
1561        //renderText(290, 70, s, font40);
1562        renderText(325, 40, s, font40);
1563        s.sprintf("error: %3.3f %", mRenderError * 100.0f);
1564        renderText(20, 40, s, font40);
1565
1566        //renderText(290, 70, s, font40);
1567        glEnable(GL_LIGHTING);
1568
1569}
1570
1571
1572void
1573QtGlRendererWidget::SetViewCellGranularity(int number)
1574{
1575        if (mViewCellsManager)
1576        {
1577                //      mViewCellsManager->SetMaxFilterSize(number);
1578
1579                // $$ tmp off
1580                mViewCellsManager->CollectViewCells(number);
1581
1582                // $$ does not work so far:(
1583                //      mViewCellsManager->UpdatePvsForEvaluation();
1584                //      mViewCellsManager->FinalizeViewCells(false);
1585        }
1586        updateGL();
1587}
1588
1589void
1590QtGlRendererWidget::SetVisibilityFilterSize(int number)
1591{
1592        if (mViewCellsManager)
1593                mViewCellsManager->SetMaxFilterSize(number);
1594
1595        mPvsCache.Reset();
1596        updateGL();
1597}
1598
1599void
1600QtGlRendererWidget::SetSpatialFilterSize(int number)
1601{
1602        mSpatialFilterSize = 1e-3*number;
1603        mPvsCache.Reset();
1604        updateGL();
1605}
1606
1607void
1608QtGlRendererWidget::SetSceneCut(int number)
1609{
1610        // assume the cut plane can only be aligned with xz plane
1611        // shift it along y according to number, which is percentage of the bounding
1612        // box position
1613        if (mViewCellsManager)
1614        {
1615                const float f = number / 1000.0f;
1616                AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1617                Vector3 p = (1.0f - f) * box.Min() + f * box.Max();
1618                mSceneCutPlane.mNormal = Vector3(0, -1, 0);
1619                mSceneCutPlane.mD = -DotProd(mSceneCutPlane.mNormal, p);
1620
1621                updateGL();
1622        }
1623}
1624
1625void
1626QtGlRendererWidget::SetHidingCost(int number)
1627{
1628        mHidingCost = (float)number / 1000.0f;
1629}
1630
1631
1632void
1633QtGlRendererWidget::SetTopDistance(int number)
1634{
1635        mTopDistance = number / 1000.0f;
1636        updateGL();
1637}
1638
1639void QtGlRendererWidget::SetTransparency(int number)
1640{
1641        mTransparency = number / 1000.0f;
1642        updateGL();
1643}
1644
1645
1646float QtGlRendererWidget::ComputeRenderCost(ViewCell *vc)
1647{
1648        float renderCost = 0;
1649
1650#ifdef USE_VERBOSE_PVS
1651        if (mShowDistanceWeightedPvs)
1652        {
1653                return vc->GetPvs().mStats.mDistanceWeightedPvs;
1654        }
1655        else if (mShowDistanceWeightedTriangles)
1656        {
1657                return vc->GetPvs().mStats.mDistanceWeightedTriangles;
1658        }
1659        else //if (mShowWeightedTriangles)
1660        {
1661                return vc->GetPvs().mStats.mWeightedTriangles;
1662        }
1663#else
1664        return 0.0f;
1665#endif
1666}
1667
1668
1669void QtGlRendererWidget::ComputeMaxValues(const ViewCellContainer &viewCells,
1670                                                                                  int &maxPvs,
1671                                                                                  int &maxPiercingRays,
1672                                                                                  float &maxRelativeRays,
1673                                                                                  float &maxRcCost)
1674{
1675        maxPvs = -1;
1676        maxPiercingRays = 1; // not zero for savety
1677        maxRelativeRays = Limits::Small; // not zero for savety
1678        maxRcCost = Limits::Small;
1679
1680        for (size_t i = 0; i < viewCells.size(); ++ i)
1681        {
1682                ViewCell *vc = viewCells[i];
1683
1684                if (mShowPvsSizes) // pvs size
1685                {
1686                        //const int p = vc->GetPvs().CountObjectsInPvs();
1687                        const int p = vc->GetPvs().GetSize();
1688                        if (p > maxPvs)
1689                                maxPvs = p;
1690                }
1691                else if (mShowPiercingRays) // relative number of rays
1692                {
1693                        const int piercingRays = vc->GetNumPiercingRays();
1694
1695                        if (piercingRays > maxPiercingRays)
1696                                maxPiercingRays = piercingRays;
1697                }
1698                else if (mShowWeightedRays)
1699                {
1700                        const int piercingRays = vc->GetNumPiercingRays();
1701
1702                        const float relativeArea =
1703                                vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1704
1705                        if ((float)piercingRays / relativeArea > maxRelativeRays)
1706                                maxRelativeRays = (float)piercingRays / relativeArea;
1707                }
1708                else if (mShowWeightedCost)
1709                {
1710                        const float rcCost = ComputeRenderCost(vc);
1711                        mViewCellsManager->UpdateScalarPvsCost(vc, rcCost);
1712
1713                        if (rcCost > maxRcCost)
1714                                maxRcCost = rcCost;
1715                }
1716        }
1717}
1718
1719
1720void QtGlRendererWidget::RenderViewCells()
1721{
1722        mUseFalseColors = true;
1723        //glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT);
1724
1725        glEnable(GL_CULL_FACE);
1726        glCullFace(GL_FRONT);
1727        //glDisable(GL_CULL_FACE);
1728
1729        if (mCutViewCells)
1730        {
1731                double eq[4];
1732                eq[0] = mSceneCutPlane.mNormal.x;
1733                eq[1] = mSceneCutPlane.mNormal.y;
1734                eq[2] = mSceneCutPlane.mNormal.z;
1735                eq[3] = mSceneCutPlane.mD;
1736
1737                glClipPlane(GL_CLIP_PLANE0, eq);
1738                glEnable(GL_CLIP_PLANE0);
1739        }
1740
1741        ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
1742       
1743        int maxPvs, maxPiercingRays;
1744        float maxRelativeRays, maxRcCost;
1745
1746        ComputeMaxValues(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1747        //cout << "maxRcCost: " << maxRcCost << endl;
1748
1749        // set the max render cost to fixed value
1750        //maxRcCost = 1000.0f;
1751
1752        // transparency
1753        if (!mUseTransparency)
1754        {
1755                glEnable(GL_DEPTH_TEST);
1756                glDisable(GL_BLEND);
1757        }
1758        else
1759        {
1760                glDisable(GL_DEPTH_TEST);
1761                glEnable(GL_BLEND);
1762
1763                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1764                //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1765
1766                for (int i = 0; i < viewcells.size(); ++ i)
1767                {
1768                        ViewCell *vc = viewcells[i];
1769
1770                        const float dist = SqrDistance(mDummyViewPoint, vc->GetBox().Center());
1771                        vc->SetDistance(dist);
1772                }
1773
1774                sort(viewcells.begin(), viewcells.end(), nearerThan);
1775        }
1776
1777        //mWireFrame = true;
1778               
1779        // normal rendering
1780        //if (!mShowPvsSizes && !mShowPiercingRays && !mShowWeightedRays && !mShowWeightedCost && !mShowComparison)
1781        if (mUseStandardColors)
1782        {
1783                for (int i = 0; i < viewcells.size(); ++ i)
1784                {
1785                        ViewCell *vc = viewcells[i];
1786                        RgbColor c;
1787
1788                        //if (!mShowPvsSizes && !mShowPiercingRays)
1789                        c = vc->GetColor();
1790                       
1791                        glColor3f(c.r, c.g, c.b);
1792
1793                        if (!mHideByCost || (mHidingCost < (vc->GetNumPiercingRays() / (float)maxPiercingRays)))
1794                        {
1795                RenderViewCell(vc);
1796                        }
1797                }
1798        }
1799        else // using specialised colors
1800        {
1801                if (!mShowComparison)
1802                        AssignImportanceByRelativeValue(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1803                else
1804                {
1805                        if (mCompareInfo.empty())
1806                        {
1807                                LogReader reader;
1808                                reader.SetFilename("compare.log");
1809                                int samples;
1810                                reader.Read(samples, mCompareInfo);
1811                        }
1812
1813                        AssignColorByComparison(viewcells, mCompareInfo);
1814                }
1815
1816                glEnable(GL_DEPTH_TEST);       
1817        }
1818       
1819        glEnable(GL_CULL_FACE);
1820        glDisable(GL_CULL_FACE);
1821
1822        glDisable(GL_CLIP_PLANE0);
1823
1824        mUseFalseColors = false;
1825        mWireFrame = false;
1826
1827        glPopAttrib();
1828}
1829
1830
1831void QtGlRendererWidget::AssignImportanceByRelativeValue(const ViewCellContainer &viewCells,
1832                                                                                                                 int &maxPvs,
1833                                                                                                                 int &maxPiercingRays,
1834                                                                                                                 float &maxRelativeRays,
1835                                                                                                                 float &maxRcCost)
1836{
1837        for (size_t i = 0; i < viewCells.size(); ++ i)
1838        {
1839                RgbColor c;
1840                ViewCell *vc = viewCells[i];
1841
1842                float importance;
1843
1844                if (mShowPiercingRays)
1845                {
1846                        importance = mTransferFunction *
1847                                ((float)vc->GetNumPiercingRays() / (float)maxPiercingRays);
1848                }
1849                else if (mShowWeightedRays) // relative number of rays
1850                {
1851                        float relativeArea = vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1852
1853                        if (relativeArea < Limits::Small)
1854                                relativeArea = Limits::Small;
1855
1856                        importance = mTransferFunction * ((float)vc->GetNumPiercingRays() / relativeArea) / maxRelativeRays;
1857                }
1858                else if (mShowPvsSizes) // pvs size
1859                {
1860                        importance = mTransferFunction *
1861                                ((float)vc->GetPvs().GetSize() / (float)maxPvs);
1862                } // weighted render cost
1863                else if (mShowWeightedCost)
1864                {
1865                        const float rcCost = mTransferFunction * ComputeRenderCost(vc);
1866                        importance = rcCost / maxRcCost;
1867                }
1868               
1869                if (importance > 1.0f) importance = 1.0f;
1870                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1871                c = RainbowColorMapping(importance);
1872
1873                glColor4f(c.r, c.g, c.b, 1.0f - mTransparency);
1874
1875                if (!mHideByCost || (mHidingCost < importance))
1876                {
1877                        RenderViewCell(vc);
1878                }
1879        }
1880}
1881
1882
1883void QtGlRendererWidget::AssignColorByComparison(const ViewCellContainer &viewcells,
1884                                                                                                 //const ViewCellInfoContainer &infos1,
1885                                                                                                 const ViewCellInfoContainer &compareInfo)
1886{
1887        if (viewcells.size() > compareInfo.size())
1888        {
1889                cerr << "loaded size (" << (int)compareInfo.size()
1890                         << ") does not fit to view cells size (" << (int)viewcells.size() << ")" << endl;
1891                return;
1892        }
1893
1894        //const float maxRatio = 1.0f;
1895        const float maxRatio = 2.0f;
1896        const float minRatio = 0.0f;
1897
1898        const float scale = 1.0f / (maxRatio - minRatio);
1899
1900        for (size_t i = 0; i < viewcells.size(); ++ i)
1901        {
1902                RgbColor c;
1903                ViewCell *vc = viewcells[i];
1904
1905                //ViewCellInfo vc1Info = infos1[i];
1906                ViewCellInfo vc2Info = compareInfo[i];
1907
1908                //const float vcRatio = vc->GetNumPiercingRays() / vc2Info.mPiercingRays + Limits::Small;
1909                float vcRatio = 1.0f;//maxRatio;
1910               
1911                if (vc2Info.mPvsSize > Limits::Small)
1912                        vcRatio = (float)vc->GetPvs().GetSize() / vc2Info.mPvsSize;
1913
1914                // truncate here
1915                if (vcRatio > maxRatio) vcRatio = 1.0f;
1916
1917                const float importance = (vcRatio - minRatio) * scale;
1918       
1919                if (0 && (i < 20))
1920                {
1921                        cout << "pvs1: " << vc->GetPvs().GetSize() << " pvs2: "
1922                                 << compareInfo[i].mPvsSize << " importance: " << importance << endl;
1923                }
1924
1925                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1926                c = RainbowColorMapping(importance);
1927
1928                glColor4f(c.r, c.g, c.b, 1.0f);
1929
1930                if (1)//!mHideByCost || (mHidingCost < importance))
1931                {
1932                        RenderViewCell(vc);
1933                }
1934        }
1935}
1936
1937
1938
1939/**********************************************************************/
1940/*              QtRendererControlWidget implementation                */
1941/**********************************************************************/
1942
1943
1944QGroupBox *QtRendererControlWidget::CreateVisualizationPanel(QWidget *parent)
1945{
1946        QRadioButton *rb1, *rb2, *rb3, *rb4, *rb5;
1947       
1948        rb1 = new QRadioButton("random colors", parent);
1949        rb1->setText("random");
1950        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWireFrame(bool)));
1951
1952        // Create a check box to be in the group box
1953        rb2 = new QRadioButton("piercing rays", parent);
1954        rb2->setText("piercing rays");
1955        //vl->addWidget(rb1);
1956        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowPiercingRays(bool)));
1957
1958        rb3 = new QRadioButton("pvs size", parent);
1959        rb3->setText("pvs size");
1960        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
1961       
1962        rb4 = new QRadioButton("weighted rays", parent);
1963        rb4->setText("weighted rays");
1964        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedRays(bool)));
1965       
1966        rb5 = new QRadioButton("pvs cost", parent);
1967        rb5->setText("pvs cost");
1968        connect(rb5, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedCost(bool)));
1969
1970        QGroupBox *groupBox = new QGroupBox("PVS Visualization");
1971
1972        QVBoxLayout *vbox2 = new QVBoxLayout;
1973   
1974        vbox2->addWidget(rb1);
1975        vbox2->addWidget(rb2);
1976        vbox2->addWidget(rb3);
1977        vbox2->addWidget(rb4);
1978        vbox2->addWidget(rb5);
1979       
1980        rb5->setChecked(true);
1981
1982        vbox2->addStretch(1);
1983        groupBox->setLayout(vbox2);
1984
1985        return groupBox;
1986}
1987
1988
1989QGroupBox *QtRendererControlWidget::CreateTrafoPanel(QWidget *parent)
1990{
1991        QRadioButton *rb1, *rb2, *rb3;
1992       
1993        rb1 = new QRadioButton("translation", parent);
1994        rb1->setText("translation");
1995        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetTranslation(bool)));
1996
1997        // Create a check box to be in the group box
1998        rb2 = new QRadioButton("scale", parent);
1999        rb2->setText("scale");
2000        //vl->addWidget(rb1);
2001        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetScale(bool)));
2002
2003        rb3 = new QRadioButton("rotation", parent);
2004        rb3->setText("rotation");
2005        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetRotation(bool)));
2006   
2007        QVBoxLayout *vbox2 = new QVBoxLayout;
2008        QGroupBox *groupBox = new QGroupBox("Dynamic Obojects");
2009
2010        vbox2->addWidget(rb1);
2011        vbox2->addWidget(rb2);
2012        vbox2->addWidget(rb3);
2013       
2014        rb1->setChecked(true);
2015
2016        vbox2->addStretch(1);
2017
2018
2019        QPushButton *button = new QPushButton("Update", groupBox);
2020        vbox2->addWidget(button);
2021        connect(button, SIGNAL(clicked()), SIGNAL(UpdateDynamicObjects()));
2022       
2023        button = new QPushButton("Delete", groupBox);
2024        vbox2->addWidget(button);
2025        connect(button, SIGNAL(clicked()), SIGNAL(DeleteDynamicObject()));
2026       
2027        button = new QPushButton("Next object", groupBox);
2028        vbox2->layout()->addWidget(button);
2029        connect(button, SIGNAL(clicked()), SIGNAL(NextObject()));
2030
2031        groupBox->setLayout(vbox2);
2032       
2033        return groupBox;
2034}
2035
2036
2037QGroupBox *QtRendererControlWidget::CreateRenderCostPanel(QWidget *parent)
2038{
2039        QRadioButton *rb1, *rb2, *rb3;
2040       
2041        // Create a check box to be in the group box
2042        rb1 = new QRadioButton("triangles", parent);
2043        rb1->setText("triangles");
2044        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedTriangles(bool)));
2045
2046        rb2 = new QRadioButton("distance weighted pvs", parent);
2047        rb2->setText("distance weighted");
2048        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedPvs(bool)));
2049
2050        rb3 = new QRadioButton("distance weighted triangles", parent);
2051        rb3->setText("distance weighted triangles");
2052        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedTriangles(bool)));
2053
2054        QGroupBox *groupBox = new QGroupBox("Render cost options");
2055        QVBoxLayout *vbox2 = new QVBoxLayout;
2056   
2057        vbox2->addWidget(rb1);
2058        vbox2->addWidget(rb2);
2059        vbox2->addWidget(rb3);
2060       
2061        rb1->setChecked(true);
2062
2063        vbox2->addStretch(1);
2064        groupBox->setLayout(vbox2);
2065
2066        return groupBox;
2067}
2068
2069
2070QGroupBox *QtRendererControlWidget::CreateRayVisualizationPanel(QWidget *parent)
2071{
2072        QRadioButton *rb1, *rb2, *rb3, *rb4;
2073       
2074        // Create a check box to be in the group box
2075        rb1 = new QRadioButton("const color", parent);
2076        rb1->setText("const color");
2077        //vl->addWidget(rb1);
2078        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(UseConstColorForRayViz(bool)));
2079
2080        rb2 = new QRadioButton("ray length", parent);
2081        rb2->setText("ray length");
2082        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(UseRayLengthForRayViz(bool)));
2083       
2084        rb3 = new QRadioButton("contribution", parent);
2085        rb3->setText("contribution");
2086        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowContribution(bool)));
2087       
2088        rb4 = new QRadioButton("distribution", parent);
2089        rb4->setText("distribution");
2090        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution(bool)));
2091
2092
2093        ///////////////////////////
2094
2095       
2096        QGroupBox *groupBox = new QGroupBox("Ray visualization");
2097        QVBoxLayout *vbox2 = new QVBoxLayout;
2098   
2099        vbox2->addWidget(rb1);
2100        vbox2->addWidget(rb2);
2101        vbox2->addWidget(rb3);
2102        vbox2->addWidget(rb4);
2103       
2104        rb1->setChecked(true);
2105
2106
2107        QCheckBox *cb = new QCheckBox("Distribution 1", parent);
2108        vbox2->addWidget(cb);
2109        cb->setChecked(true);
2110        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution1(bool)));
2111
2112        cb = new QCheckBox("Distribution 2", parent);
2113        vbox2->addWidget(cb);
2114        cb->setChecked(true);
2115        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution2(bool)));
2116
2117        cb = new QCheckBox("Distribution 3", parent);
2118        vbox2->addWidget(cb);
2119        cb->setChecked(true);
2120        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution3(bool)));
2121       
2122        cb = new QCheckBox("Distribution 4", parent);
2123        vbox2->addWidget(cb);
2124        cb->setChecked(true);
2125        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution4(bool)));
2126
2127
2128        vbox2->addStretch(1);
2129        groupBox->setLayout(vbox2);
2130
2131        return groupBox;
2132}
2133
2134
2135QtRendererControlWidget::QtRendererControlWidget(QWidget * parent, Qt::WFlags f):
2136QWidget(parent, f)
2137{
2138
2139        QVBoxLayout *vl = new QVBoxLayout;
2140        setLayout(vl);
2141       
2142        //QWidget *vbox;
2143
2144        //vbox = new QGroupBox("Render Controls", this);
2145        //layout()->addWidget(vbox);
2146        //vl = new QVBoxLayout;
2147        //vbox->setLayout(vl);
2148
2149        QLabel *label;
2150        QSlider *slider;
2151        QPushButton *button;
2152
2153#if 0//REMOVE_TEMPORARY
2154
2155        label = new QLabel("Granularity");
2156        //vbox->layout()->addWidget(label);
2157        vl->addWidget(label);
2158
2159        slider = new QSlider(Qt::Horizontal);
2160        vl->addWidget(slider);
2161        slider->show();
2162        slider->setRange(1, 10000);
2163        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2164        slider->setValue(200);
2165
2166        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
2167
2168        ///////////////////////////
2169
2170        label = new QLabel("Transfer function");
2171        vl->addWidget(label);
2172
2173        slider = new QSlider(Qt::Horizontal);
2174        vl->addWidget(slider);
2175        slider->show();
2176        slider->setRange(1, 10000);
2177        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2178        slider->setValue(100);
2179
2180
2181        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransferFunction(int)));
2182
2183        ////////////////////////////////////////7
2184
2185        button = new QPushButton("Update all PVSs");
2186        vl->addWidget(button);
2187        connect(button, SIGNAL(clicked()), SLOT(UpdateAllPvs()));
2188
2189        ////////////////////////////////////////77777
2190
2191        label = new QLabel("Filter size");
2192        vl->addWidget(label);
2193
2194        slider = new QSlider(Qt::Horizontal);
2195        vl->addWidget(slider);
2196        slider->show();
2197        slider->setRange(1, 100);
2198        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2199        slider->setValue(3);
2200
2201        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetVisibilityFilterSize(int)));
2202
2203#endif
2204
2205
2206       
2207        ///////////////////////////////////
2208
2209
2210        QWidget *hbox = new QWidget();
2211        vl->addWidget(hbox);
2212        QHBoxLayout *hlayout = new QHBoxLayout;
2213        hbox->setLayout(hlayout);
2214
2215        QCheckBox *cb = new QCheckBox("Show viewcells", hbox);
2216        hlayout->addWidget(cb);
2217        cb->setChecked(false);
2218        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
2219       
2220        cb = new QCheckBox("Render errors", hbox);
2221        hlayout->layout()->addWidget(cb);
2222        cb->setChecked(false);
2223        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
2224
2225#if REMOVE_TEMPORARY
2226        cb = new QCheckBox("Render cost curve", hbox);
2227        hlayout->addWidget(cb);
2228        cb->setChecked(false);
2229        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
2230#endif
2231        cb = new QCheckBox("Show rays", hbox);
2232        hlayout->addWidget(cb);
2233        cb->setChecked(false);
2234        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRays(bool)));
2235#if REMOVE_TEMPORARY   
2236        cb = new QCheckBox("Show Comparison", hbox);
2237        hlayout->addWidget(cb);
2238        cb->setChecked(false);
2239        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowComparison(bool)));
2240#endif
2241
2242        //////////////////
2243
2244        QHBoxLayout *vh = new QHBoxLayout;
2245
2246        QGroupBox *myBox = new QGroupBox("Visualization");
2247
2248        myBox->setLayout(vh);
2249        vl->addWidget(myBox, 0, 0);
2250
2251        QGroupBox *groupBox = CreateVisualizationPanel(hbox);
2252        vh->addWidget(groupBox, 0, 0);
2253
2254#if REMOVE_TEMPORARY
2255        QGroupBox *groupBox2 = CreateRenderCostPanel(hbox);
2256        vh->addWidget(groupBox2, 0, 0);
2257       
2258        QGroupBox *groupBox3 = CreateRayVisualizationPanel(hbox);
2259        vh->addWidget(groupBox3, 0, 0);
2260#endif
2261
2262#if 1
2263        QGroupBox *groupBox4 = CreateTrafoPanel(hbox);
2264        vh->addWidget(groupBox4, 0, 0);
2265#endif
2266
2267        //////////////////////////////////
2268
2269        bool tmp = false;
2270        const int range = 1000;
2271
2272        //vbox->resize(800,150);
2273        QWidget *vbox;
2274
2275        vbox = new QGroupBox("Rendering", this);
2276        layout()->addWidget(vbox);
2277
2278        vl = new QVBoxLayout;
2279        vbox->setLayout(vl);
2280
2281
2282        cb = new QCheckBox("Cut view cells", vbox);
2283        vbox->layout()->addWidget(cb);
2284        cb->setChecked(false);
2285        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
2286
2287
2288        slider = new QSlider(Qt::Horizontal, vbox);
2289        vbox->layout()->addWidget(slider);
2290        slider->show();
2291        slider->setRange(0, 1000);
2292        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2293        slider->setValue(1000);
2294
2295        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
2296
2297
2298        cb = new QCheckBox("Use spatial filter", vbox);
2299        vbox->layout()->addWidget(cb);
2300        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter", tmp);
2301        cb->setChecked(tmp);
2302        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
2303
2304
2305        label = new QLabel("Spatial Filter size");
2306        vbox->layout()->addWidget(label);
2307       
2308        slider = new QSlider(Qt::Horizontal, vbox);
2309        vbox->layout()->addWidget(slider);
2310        slider->show();
2311        slider->setRange(1, 100);
2312        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2313        slider->setValue(10);
2314
2315        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSpatialFilterSize(int)));
2316
2317        ////////////////////////////
2318
2319       
2320        cb = new QCheckBox("Hide view cells by render cost ", vbox);
2321        vbox->layout()->addWidget(cb);
2322        cb->setChecked(false);
2323        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetHideByCost(bool)));
2324
2325        label = new QLabel("Hide by cost");
2326        vbox->layout()->addWidget(label);
2327
2328        // the render cost visualization
2329        slider = new QSlider(Qt::Horizontal, vbox);
2330        vbox->layout()->addWidget(slider);
2331        slider->show();
2332        slider->setRange(0, range);
2333        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2334        slider->setValue(0);
2335        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetHidingCost(int)));
2336
2337        ///////////////////////////////////////////
2338
2339        cb = new QCheckBox("Top View", vbox);
2340        vbox->layout()->addWidget(cb);
2341        cb->setChecked(false);
2342        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
2343
2344
2345        label = new QLabel("Top distance");
2346        vbox->layout()->addWidget(label);
2347       
2348        slider = new QSlider(Qt::Horizontal, vbox);
2349        vbox->layout()->addWidget(slider);
2350        slider->show();
2351        slider->setRange(1, 1000);
2352        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2353        slider->setValue(500);
2354
2355        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTopDistance(int)));
2356       
2357
2358        ///////////////////////////////////////////
2359#if REMOVE_TEMPORARY
2360        cb = new QCheckBox("Transparency", vbox);
2361        vbox->layout()->addWidget(cb);
2362        cb->setChecked(false);
2363        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseTransparency(bool)));
2364
2365        label = new QLabel("Use transparency");
2366        vbox->layout()->addWidget(label);
2367
2368        // the render cost visualization
2369        slider = new QSlider(Qt::Horizontal, vbox);
2370        vbox->layout()->addWidget(slider);
2371        slider->show();
2372        slider->setRange(0, range);
2373        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2374        slider->setValue(0);
2375        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransparency(int)));
2376#endif
2377       
2378
2379        //////////////////////////////
2380
2381#if REMOVE_TEMPORARY
2382
2383        cb = new QCheckBox("Cut scene", vbox);
2384        vbox->layout()->addWidget(cb);
2385        cb->setChecked(false);
2386        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
2387
2388        cb = new QCheckBox("Render boxes", vbox);
2389        vbox->layout()->addWidget(cb);
2390        cb->setChecked(false);
2391        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderBoxes(bool)));
2392
2393        cb = new QCheckBox("Render visibility estimates", vbox);
2394        vbox->layout()->addWidget(cb);
2395        cb->setChecked(false);
2396        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderVisibilityEstimates(bool)));
2397#endif
2398
2399#if REMOVE_TEMPORARY
2400
2401        cb = new QCheckBox("Use filter", vbox);
2402        vbox->layout()->addWidget(cb);
2403        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp);
2404        cb->setChecked(tmp);
2405        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
2406#endif
2407
2408#if REMOVE_TEMPORARY
2409       
2410        cb = new QCheckBox("Render filter", vbox);
2411        vbox->layout()->addWidget(cb);
2412        cb->setChecked(true);
2413        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderFilter(bool)));
2414
2415        /*vbox = new QGroupBox("PVS Errors", this);
2416        layout()->addWidget(vbox);
2417
2418        vl = new QVBoxLayout;
2419        vbox->setLayout(vl);
2420
2421        button = new QPushButton("Compute Visibility", vbox);
2422        vbox->layout()->addWidget(button);
2423        connect(button, SIGNAL(clicked()), SLOT(ComputeVisibility()));
2424
2425        button = new QPushButton("Stop Computation", vbox);
2426        vbox->layout()->addWidget(button);
2427        connect(button, SIGNAL(clicked()), SLOT(StopComputation()));
2428
2429        button = new QPushButton("Set Random View Point", vbox);
2430        vbox->layout()->addWidget(button);
2431        connect(button, SIGNAL(clicked()), SLOT(SetRandomViewPoint()));*/
2432
2433        button = new QPushButton("Store statistics", vbox);
2434        vbox->layout()->addWidget(button);
2435        connect(button, SIGNAL(clicked()), SIGNAL(StoreStatistics()));
2436
2437#endif
2438
2439#if 0
2440       
2441        button = new QPushButton("Compute GVS", vbox);
2442        vbox->layout()->addWidget(button);
2443        connect(button, SIGNAL(clicked()), SIGNAL(ComputeGVS()));
2444#endif
2445       
2446        button = new QPushButton("Replay view points", vbox);
2447        vbox->layout()->addWidget(button);
2448        connect(button, SIGNAL(clicked()), SIGNAL(ReplayViewPoints()));
2449
2450
2451        /*cb = new QCheckBox("Stats", vbox);
2452        vbox->layout()->addWidget(cb);
2453        cb->setChecked(false);
2454        connect(cb, SIGNAL(toggled(bool)), SIGNAL(StoreStatistics()));*/
2455
2456        if (0)
2457        {
2458                vbox = new QGroupBox("PVS Errors", this);
2459                layout()->addWidget(vbox);
2460
2461                vl = new QVBoxLayout;
2462                vbox->setLayout(vl);
2463
2464                mPvsErrorWidget = new QListWidget(vbox);
2465                vbox->layout()->addWidget(mPvsErrorWidget);
2466
2467                connect(mPvsErrorWidget,
2468                        SIGNAL(doubleClicked(const QModelIndex &)),
2469                        this,
2470                        SLOT(PvsErrorClicked(const QModelIndex &)));
2471
2472                button = new QPushButton("Next Error Frame", vbox);
2473                vbox->layout()->addWidget(button);
2474                connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
2475        }
2476       
2477        //connect(button, SIGNAL(clicked(void)), SLOT(StoreStatistics(void)));
2478       
2479        //////////////////////////////////////////
2480
2481
2482        setWindowTitle("Preprocessor Control Widget");
2483        adjustSize();
2484}
2485
2486
2487
2488
2489void
2490QtRendererControlWidget::FocusNextPvsErrorFrame(void)
2491{}
2492
2493void
2494QtRendererControlWidget::UpdatePvsErrorItem(int row,
2495                                                                                        GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
2496{
2497
2498        QListWidgetItem *i = mPvsErrorWidget->item(row);
2499        QString s;
2500        s.sprintf("%5.5f", pvsErrorEntry.mError);
2501        if (i) {
2502                i->setText(s);
2503        } else {
2504                new QListWidgetItem(s, mPvsErrorWidget);
2505        }
2506        mPvsErrorWidget->update();
2507}
2508
2509
2510
2511
2512/*********************************************************************/
2513/*                   QtGlDebuggerWidget implementation               */
2514/*********************************************************************/
2515
2516
2517QtGlDebuggerWidget::QtGlDebuggerWidget(QtGlRendererBuffer *buf, QWidget *parent)
2518: QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
2519{
2520        // create the pbuffer
2521        //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
2522        //mUpdateTimerId = startTimer(20);
2523        setWindowTitle(("OpenGL pbuffers"));
2524}
2525
2526
2527QtGlDebuggerWidget::~QtGlDebuggerWidget()
2528{
2529        mRenderBuffer->releaseFromDynamicTexture();
2530        glDeleteTextures(1, &dynamicTexture);
2531
2532        DEL_PTR(mRenderBuffer);
2533}
2534
2535
2536void QtGlDebuggerWidget::initializeGL()
2537{
2538        glMatrixMode(GL_PROJECTION);
2539        glLoadIdentity();
2540
2541        glFrustum(-1, 1, -1, 1, 10, 100);
2542        glTranslatef(-0.5f, -0.5f, -0.5f);
2543        glTranslatef(0.0f, 0.0f, -15.0f);
2544        glMatrixMode(GL_MODELVIEW);
2545
2546        glEnable(GL_CULL_FACE);
2547        initCommon();
2548        initPbuffer();
2549
2550}
2551
2552
2553void QtGlDebuggerWidget::resizeGL(int w, int h)
2554{
2555        glViewport(0, 0, w, h);
2556}
2557
2558
2559void QtGlDebuggerWidget::paintGL()
2560{
2561        // draw a spinning cube into the pbuffer..
2562        mRenderBuffer->makeCurrent();
2563
2564        BeamSampleStatistics stats;
2565        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
2566
2567        glFlush();
2568
2569        // rendering directly to a texture is not supported on X11, unfortunately
2570        mRenderBuffer->updateDynamicTexture(dynamicTexture);
2571
2572        // and use the pbuffer contents as a texture when rendering the
2573        // background and the bouncing cubes
2574        makeCurrent();
2575        glBindTexture(GL_TEXTURE_2D, dynamicTexture);
2576        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2577
2578        // draw the background
2579        glMatrixMode(GL_MODELVIEW);
2580        glPushMatrix();
2581        glLoadIdentity();
2582        glMatrixMode(GL_PROJECTION);
2583        glPushMatrix();
2584        glLoadIdentity();
2585
2586        glPopMatrix();
2587        glMatrixMode(GL_MODELVIEW);
2588        glPopMatrix();
2589}
2590
2591
2592void QtGlDebuggerWidget::initPbuffer()
2593{
2594        // set up the pbuffer context
2595        mRenderBuffer->makeCurrent();
2596        // generate a texture that has the same size/format as the pbuffer
2597        dynamicTexture = mRenderBuffer->generateDynamicTexture();
2598        // bind the dynamic texture to the pbuffer - this is a no-op under X11
2599        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
2600        //makeCurrent();
2601}
2602
2603
2604void QtGlDebuggerWidget::initCommon()
2605{
2606        glEnable(GL_TEXTURE_2D);
2607        glEnable(GL_DEPTH_TEST);
2608
2609        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
2610}
2611
2612
2613void QtGlRendererWidget::_RenderColoredPvs()
2614{
2615        // note: could be done more efficiently using color buffers
2616        mPvsSize = mPvsCache.mPvs.GetSize();
2617
2618        ObjectPvsIterator it = mPvsCache.mPvs.GetIterator();
2619
2620        PvsData pvsData;
2621
2622        while (it.HasMoreEntries())
2623        {
2624                Intersectable *obj = it.Next(pvsData);
2625
2626                RgbColor color;
2627
2628                //cerr << "sumpdf: " << pvsData.mSumPdf << endl;
2629                if (mUseRandomColorPerPvsObject)
2630                {
2631                        if (obj->Type() == Intersectable::KD_INTERSECTABLE)
2632                        {
2633                                KdIntersectable *kdint = static_cast<KdIntersectable *>(obj);
2634
2635                                if (kdint->mGenericIdx == -1)
2636                                {
2637                                        kdint->mGenericIdx = (int)mColors.size();
2638                                        mColors.push_back(RandomColor(0, 1));
2639                                }
2640                                color = mColors[kdint->mGenericIdx];
2641                        }
2642                }
2643                else
2644                {
2645                        color = RainbowColorMapping(mTransferFunction * log10(pvsData.mSumPdf + 1));
2646                }
2647
2648                glColor3f(color.r, color.g, color.b);
2649
2650                mUseForcedColors = true;
2651                RenderIntersectable(obj);
2652                mUseForcedColors = false;
2653        }
2654}
2655
2656
2657void QtGlRendererWidget::UpdateDynamicObjects()
2658{
2659        preprocessor->ScheduleUpdateDynamicObjects(); 
2660}
2661
2662
2663void QtGlRendererWidget::ReplayViewPoints()
2664{
2665        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
2666
2667        ViewCellPointsList::const_iterator vit, vit_end = vcPoints->end();
2668
2669        sViewPointsList.clear();
2670
2671        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
2672        {
2673                ViewCellPoints *vp = *vit;
2674
2675                SimpleRayContainer::const_iterator rit, rit_end = vp->second.end();
2676       
2677                for (rit = vp->second.begin(); rit != rit_end; ++ rit)
2678                {
2679                        sViewPointsList.push_back(*rit);
2680                }
2681        }
2682
2683        if (!sViewPointsList.empty())
2684        {
2685                cout << "replaying " << (int)sViewPointsList.size() << " view points " << endl;
2686               
2687                mReplayMode = true;
2688               
2689                if (mExportFrameBuffer)
2690                        GetPreprocessor()->mSynchronize = true;
2691
2692                sCurrentSamples = GetPreprocessor()->mCurrentSamples;
2693                sViewPointsListIt = sViewPointsList.begin();
2694        }
2695}
2696
2697
2698
2699Vector3 QtGlRendererWidget::Unproject(int x, int y)
2700{
2701        // swap y coordinate
2702        y = GetHeight() - y;
2703
2704        // HACK: should come from camera!
2705        double projection[16];
2706        glGetDoublev(GL_PROJECTION_MATRIX, projection);
2707        double modelview[16];
2708        glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
2709
2710        const int viewport[4] = {0,0, GetWidth(), GetHeight()};
2711
2712        RenderScene();
2713
2714        float z;
2715        glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);
2716       
2717        GLdouble rx, ry, rz;
2718        gluUnProject(x, y, z, modelview, projection, viewport, &rx, &ry, &rz);
2719
2720        return Vector3(rx, ry, rz);
2721}
2722
2723
2724int QtGlRendererWidget::FindDynamicObject(float x, float y)
2725{
2726
2727        if (GetPreprocessor()->mDynamicObjects.empty())
2728                return -1;
2729
2730        makeCurrent();
2731       
2732        // this is the same as in every OpenGL picking example
2733        const int maxSize = 512;
2734       
2735        // see below for an explanation on the buffer content
2736        GLuint buffer[maxSize];
2737        glSelectBuffer(maxSize, buffer);
2738       
2739        // enter select mode
2740        glRenderMode(GL_SELECT);
2741        glInitNames();
2742        glPushName(0);
2743       
2744        glMatrixMode(GL_PROJECTION);
2745        glPushMatrix();
2746        glLoadIdentity();
2747
2748        glViewport(0, 0, width(), height());
2749
2750        GLint viewport[4];
2751        glGetIntegerv(GL_VIEWPORT, viewport);
2752
2753        const float w = 1.0f;
2754
2755        //gluPickMatrix(x, y, 1000.0, 1000.0, viewport);
2756        gluPickMatrix((GLdouble)x, (GLdouble)(viewport[3] - y), w, w, viewport);
2757
2758        GLfloat aspect = (GLfloat) width() / height();
2759        gluPerspective(70.0f, aspect, 0.1f, 2.0f * Magnitude(mSceneGraph->GetBox().Diagonal()));
2760       
2761        glMatrixMode(GL_MODELVIEW);
2762        glPushMatrix();
2763        glLoadIdentity();
2764        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2765       
2766       
2767        SetupCamera();
2768
2769        for (GLuint i = 0; i < GetPreprocessor()->mDynamicObjects.size(); ++ i)
2770        {
2771                glLoadName(i);
2772                _RenderDynamicObject(GetPreprocessor()->mDynamicObjects[i]);
2773        }
2774
2775        glFlush();
2776        glPopMatrix();
2777
2778        glMatrixMode(GL_PROJECTION);
2779        glPopMatrix();
2780
2781        int hits = glRenderMode(GL_RENDER);
2782
2783        // finally release the rendering context again
2784        if (!hits)
2785        {
2786                cout << "no object picked" << endl;
2787                return -1;
2788        }
2789
2790        //processHits(hits, buffer);
2791       
2792        // Each hit takes 4 items in the buffer.
2793        // The first item is the number of names on the name stack when the hit occured.
2794        // The second item is the minimum z value of all the verticies that intersected
2795        // the viewing area at the time of the hit. The third item is the maximum z value
2796        // of all the vertices that intersected the viewing area at the time of the hit
2797        // and the last item is the content of the name stack at the time of the hit
2798        // (name of the object). We are only interested in the object name
2799        // (number of the surface).
2800        // return the name of the clicked surface
2801        return buffer[3];
2802}
2803
2804
2805void QtGlRendererWidget::DeleteDynamicObject()
2806{
2807        Preprocessor *p = GetPreprocessor();
2808
2809        if ((mCurrentDynamicObjectIdx < 0) ||
2810                (mCurrentDynamicObjectIdx >= p->mDynamicObjects.size()))
2811                return;
2812
2813        cout << "deleting object" << endl;
2814
2815        SceneGraphLeaf *l = p->mDynamicObjects[mCurrentDynamicObjectIdx];
2816
2817        // tell the preprocessor that an object was deleted
2818        p->ObjectRemoved(l);
2819
2820        swap(p->mDynamicObjects[mCurrentDynamicObjectIdx], p->mDynamicObjects.back());
2821        p->mDynamicObjects.pop_back();
2822
2823        delete l;
2824
2825        mCurrentDynamicObjectIdx = -1;
2826}       
2827
2828}
Note: See TracBrowser for help on using the repository browser.