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

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