source: GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp @ 2614

Revision 2614, 42.8 KB checked in by mattausch, 16 years ago (diff)

worked on dynamic objects

  • Property svn:executable set to *
Line 
1#include "Mesh.h"
2#include "glInterface.h"
3#include "OcclusionQuery.h"
4#include "GlRenderer.h"
5#include "ViewCellsManager.h"
6#include "SceneGraph.h"
7#include "ViewCell.h"
8#include "Beam.h"
9#include "KdTree.h"
10#include "Environment.h"
11#include "Triangle3.h"
12#include "IntersectableWrapper.h"
13#include "BvHierarchy.h"
14#include "KdTree.h"
15#include "SamplingStrategy.h"
16#include "Preprocessor.h"
17#include "SceneGraph.h"
18
19
20#ifdef USE_CG
21
22#include <Cg/cg.h>
23#include <Cg/cgGL.h>
24
25#endif
26
27// if 1 = SAFE RENDERING OF PVS primitives without VBOs for Pvs error estimation
28#define EVAL_ERROR 0
29
30namespace GtpVisibilityPreprocessor {
31
32
33static bool arbQuerySupport = false;
34static bool nvQuerySupport = false;
35
36static GLuint frontDepthMap;
37static GLuint backDepthMap;
38
39const int depthMapSize = 512;
40
41
42static void InitExtensions()
43{
44        GLenum err = glewInit();
45
46        if (GLEW_OK != err)
47        {
48                // problem: glewInit failed, something is seriously wrong
49                cerr << "Error: " << glewGetErrorString(err) << endl;
50                exit(1);
51        }
52
53        if (GLEW_ARB_occlusion_query)
54                arbQuerySupport = true;
55       
56        if (GLEW_NV_occlusion_query)
57                nvQuerySupport = true;
58
59        if  (!arbQuerySupport && !nvQuerySupport)
60        {
61                cout << "I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n";
62                exit(1);
63        }
64
65        if (!GLEW_ARB_vertex_buffer_object)
66        {
67                cout << "vbos not supported" << endl;
68        }
69        else
70        {
71                cout << "vbos supported" << endl;
72        }
73}
74
75
76GlRenderer::GlRenderer(SceneGraph *sceneGraph,
77                                           ViewCellsManager *viewCellsManager,
78                                           KdTree *tree):
79Renderer(sceneGraph, viewCellsManager),
80mKdTree(tree),
81mUseFalseColors(false),
82mVboId(-1),
83mData(NULL),
84mIndices(NULL),
85//mUseVbos(true),
86mUseVbos(false),
87mCurrentFrame(-1)
88{
89        mSceneGraph->CollectObjects(mObjects);
90
91#if 1
92        viewCellsManager->GetViewPoint(mViewPoint);
93        mViewDirection = Vector3(0,0,1);
94#else
95        mViewPoint = Vector3(1099.9,183.0,-387);
96        mViewDirection = Vector3(-0.6,0,-0.8);
97#endif
98        mFrame = 0;
99        mWireFrame = false;
100        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace",
101                                                      mDetectEmptyViewSpace);
102
103        mSnapErrorFrames = true;
104        mSnapPrefix = "snap/";
105        mUseForcedColors = false;
106        mRenderBoxes = false;
107        //mUseGlLists = true;
108        mUseGlLists = false;
109
110        if (mViewCellsManager->GetViewCellPointsList()->size())
111                mPvsStatFrames = (int)mViewCellsManager->GetViewCellPointsList()->size();
112        else
113                Environment::GetSingleton()->GetIntValue("Preprocessor.pvsRenderErrorSamples",
114                                                                                                 mPvsStatFrames);
115       
116       
117        mPvsErrorBuffer.resize(mPvsStatFrames);
118        ClearErrorBuffer();
119}
120
121
122GlRenderer::~GlRenderer()
123{
124        cerr<<"gl renderer destructor..\n";
125
126        CLEAR_CONTAINER(mOcclusionQueries);
127
128        DeleteVbos();
129
130        if (mData) delete [] mData;
131        if (mIndices) delete [] mIndices;
132
133        glDeleteBuffersARB(1, &mVboId);
134        cerr<<"done."<<endl;
135}
136
137
138void GlRenderer::RenderTriangle(TriangleIntersectable *object)
139{
140        Triangle3 *t = &(object->GetItem());
141        glBegin(GL_TRIANGLES);
142        Vector3 normal = t->GetNormal();
143        glNormal3f(normal.x, normal.y, normal.z);
144        glVertex3f(t->mVertices[0].x, t->mVertices[0].y, t->mVertices[0].z);
145        glVertex3f(t->mVertices[1].x, t->mVertices[1].y, t->mVertices[1].z);
146        glVertex3f(t->mVertices[2].x, t->mVertices[2].y, t->mVertices[2].z);
147        glEnd();
148}
149
150
151void GlRenderer::RenderIntersectable(Intersectable *object)
152{
153        if (!object || (object->mRenderedFrame == mCurrentFrame))
154                return;
155
156        object->mRenderedFrame = mCurrentFrame;
157
158        glPushAttrib(GL_CURRENT_BIT);
159
160        if (mUseFalseColors)
161                SetupFalseColor(object->mId);
162
163        switch (object->Type())
164        {
165        case Intersectable::MESH_INSTANCE:
166                RenderMeshInstance((MeshInstance *)object);
167                break;
168        case Intersectable::VIEW_CELL:
169                RenderViewCell(static_cast<ViewCell *>(object));
170                break;
171        case Intersectable::TRANSFORMED_MESH_INSTANCE:
172                RenderTransformedMeshInstance(static_cast<TransformedMeshInstance *>(object));
173                break;
174        case Intersectable::TRIANGLE_INTERSECTABLE:
175                RenderTriangle(static_cast<TriangleIntersectable *>(object));
176                break;
177        case Intersectable::BVH_INTERSECTABLE:
178                {
179                        BvhNode *node = static_cast<BvhNode *>(object);
180
181                        if (mRenderBoxes)
182                                RenderBox(node->GetBoundingBox());
183                        else
184                                RenderBvhNode(node);
185                        break;
186                }
187        case Intersectable::KD_INTERSECTABLE:
188                {
189                        KdNode *node = (static_cast<KdIntersectable *>(object))->GetItem();
190
191                        if (mRenderBoxes)
192                                RenderBox(mKdTree->GetBox(node));
193                        else
194                                RenderKdNode(node);
195                        break;
196                }
197
198        default:
199                cerr<<"Rendering this object not yet implemented\n";
200                break;
201        }
202
203        glPopAttrib();
204}
205
206
207void GlRenderer::RenderRays(const VssRayContainer &rays, int colorType, int showDistribution, int maxAge)
208{
209        float importance;
210
211        glBegin(GL_LINES);
212
213        VssRayContainer::const_iterator it = rays.begin(), it_end = rays.end();
214
215        for (; it != it_end; ++it)
216        {
217                VssRay *ray = *it;
218
219                // only show distributions that were checked
220                if (((ray->mDistribution == SamplingStrategy::DIRECTION_BASED_DISTRIBUTION) && ((showDistribution & 1) == 0)) ||
221                        ((ray->mDistribution == SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION) && ((showDistribution & 2) == 0)) ||
222                        ((ray->mDistribution == SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION) && ((showDistribution & 4) == 0)) ||
223                        ((ray->mDistribution == SamplingStrategy::MUTATION_BASED_DISTRIBUTION) && ((showDistribution & 8) == 0)) ||
224                        ((mViewCellsManager->GetPreprocessor()->mPass - ray->mPass) >= maxAge))
225                {
226                        continue;
227                }
228               
229                switch (colorType)
230                {
231                case 0:
232                        glColor3f(1.0f, 0.0f, 0.0f);
233                        break;
234
235                case 1:
236                        importance = 1.0f * ray->Length() /  Magnitude(mViewCellsManager->GetViewSpaceBox().Diagonal());
237                        glColor3f(importance, importance, importance);
238                        break;
239
240                case 2:
241                        importance = log10(1e3 * ray->mPvsContribution) / 3.0f;
242                        glColor3f(importance, importance, importance);
243                        break;
244
245                case 3:
246                        {
247                                // nested switches ok?
248                                switch (ray->mDistribution)
249                                {
250                                case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
251                                        glColor3f(1, 0, 0);
252                                        break;
253                                case SamplingStrategy::MUTATION_BASED_DISTRIBUTION:
254                                        glColor3f(0, 1, 0);
255                                        break;
256                                case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
257                                        glColor3f(0, 1, 1);
258                                        break;
259                                        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
260                                        glColor3f(1, 1, 0);
261                                        break;
262                                }
263                        }
264                }               
265
266                glVertex3fv(&ray->mOrigin.x);
267                glVertex3fv(&ray->mTermination.x);
268        }
269
270        glEnd();
271}
272
273
274void GlRenderer::RenderViewCell(ViewCell *vc)
275{
276        if (vc->GetMesh())
277        {
278                if (!mUseFalseColors)
279                {
280                        if (vc->GetValid())
281                                glColor3f(0,1,0);
282                        else
283                                glColor3f(0,0,1);
284                }
285
286                RenderMesh(vc->GetMesh());
287        }
288        else
289        {
290                // render viewcells in the subtree
291                if (!vc->IsLeaf())
292                {
293                        ViewCellInterior *vci = (ViewCellInterior *) vc;
294
295                        ViewCellContainer::iterator it = vci->mChildren.begin();
296                        for (; it != vci->mChildren.end(); ++it)
297                        {
298                                RenderViewCell(*it);
299                        }
300                }
301                else
302                {
303                        // cerr<<"Empty viewcell mesh\n";
304                }
305        }
306}
307
308
309void GlRenderer::RenderMeshInstance(MeshInstance *mi)
310{
311        RenderMesh(mi->GetMesh());
312}
313
314
315void
316GlRenderer::RenderTransformedMeshInstance(TransformedMeshInstance *mi)
317{
318        // apply world transform before rendering
319        Matrix4x4 m;
320        mi->GetWorldTransform(m);
321
322        glPushMatrix();
323        glMultMatrixf((float *)m.x);
324
325        RenderMesh(mi->GetMesh());
326       
327        glPopMatrix();
328}
329
330
331void
332GlRenderer::SetupFalseColor(const unsigned int id)
333{
334        // swap bits of the color
335        glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
336}
337
338
339unsigned int GlRenderer::GetId(const unsigned char r,
340                                                           const unsigned char g,
341                                                           const unsigned char b) const
342{
343        return r + (g << 8) + (b << 16);
344}
345
346
347void
348GlRenderer::SetupMaterial(Material *m)
349{
350  if (m)
351        glColor3fv(&(m->mDiffuseColor.r));
352}
353
354
355void GlRenderer::RenderMesh(Mesh *mesh)
356{
357        int i = 0;
358
359        if (!mUseFalseColors && !mUseForcedColors)
360                SetupMaterial(mesh->mMaterial);
361
362        for (i = 0; i < mesh->mFaces.size(); i++)
363        {
364                if (mWireFrame)
365                        glBegin(GL_LINE_LOOP);
366                else
367                        glBegin(GL_POLYGON);
368
369                Face *face = mesh->mFaces[i];
370                Vector3 normal = mesh->GetNormal(i);
371
372                glNormal3f(normal.x, normal.y, normal.z);
373                for (int j = 0; j < face->mVertexIndices.size(); j++) {
374                        glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
375                }
376                glEnd();
377        }
378}
379       
380void GlRenderer::InitGL()
381{
382        mSphere = (GLUquadric *)gluNewQuadric();
383
384        glMatrixMode(GL_PROJECTION);
385        glLoadIdentity();
386
387        glMatrixMode(GL_MODELVIEW);
388        glLoadIdentity();
389
390        glFrontFace(GL_CCW);
391        glCullFace(GL_BACK);
392
393        glShadeModel(GL_FLAT);
394        glDepthFunc(GL_LESS );
395        glEnable(GL_DEPTH_TEST);
396        glEnable(GL_CULL_FACE);
397
398        InitExtensions();
399
400        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
401
402        glEnable(GL_NORMALIZE);
403
404        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
405
406        OcclusionQuery::GenQueries(mOcclusionQueries, 10);
407
408        SceneGraphInterior *interior = mSceneGraph->GetRoot();
409
410        SceneGraphNodeContainer::iterator ni = interior->mChildren.begin();
411
412        for (; ni != interior->mChildren.end(); ni++)
413        {
414                CreateVertexArrays(static_cast<SceneGraphLeaf *>(*ni));
415        }
416}
417
418
419void
420GlRenderer::SetupProjection(const int w, const int h, const float angle)
421{
422  glViewport(0, 0, w, h);
423  glMatrixMode(GL_PROJECTION);
424  glLoadIdentity();
425  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
426  glMatrixMode(GL_MODELVIEW);
427}
428
429
430
431void
432GlRenderer::SetupCamera()
433{
434        Vector3 target = mViewPoint + mViewDirection;
435
436        Vector3 up(0,1,0);
437
438        if (fabs(DotProd(mViewDirection, up)) > 0.99f)
439          up = Vector3(1, 0, 0);
440
441        glLoadIdentity();
442        gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
443                target.x, target.y, target.z,
444                up.x, up.y, up.z);
445}
446
447void
448GlRenderer::_RenderScene()
449{
450        ObjectContainer::const_iterator oi = mObjects.begin();
451        for (; oi != mObjects.end(); oi++)
452                RenderIntersectable(*oi);
453}
454
455void GlRenderer::_RenderSceneTrianglesWithDrawArrays()
456{
457        EnableDrawArrays();
458       
459        if (mUseVbos)
460                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
461
462        int offset = (int)mObjects.size() * 3;
463        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
464       
465        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
466        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
467       
468        glDrawArrays(GL_TRIANGLES, 0, (int)mObjects.size() * 3);
469        //DisableDrawArrays();
470}
471
472
473void GlRenderer::_RenderSceneTriangles()
474{
475        glBegin(GL_TRIANGLES);
476
477        ObjectContainer::const_iterator oi = mObjects.begin();
478        for (; oi != mObjects.end(); oi++) {
479
480                if ((*oi)->Type() == Intersectable::TRIANGLE_INTERSECTABLE) {
481                        TriangleIntersectable *object = (TriangleIntersectable *)*oi;
482                        Triangle3 *t = &(object->GetItem());
483
484                        Vector3 normal = t->GetNormal();
485                        glNormal3f(normal.x, normal.y, normal.z);
486                        glVertex3f(t->mVertices[0].x, t->mVertices[0].y, t->mVertices[0].z);
487                        glVertex3f(t->mVertices[1].x, t->mVertices[1].y, t->mVertices[1].z);
488                        glVertex3f(t->mVertices[2].x, t->mVertices[2].y, t->mVertices[2].z);
489
490                }
491        }
492
493        glEnd();
494}
495
496
497bool
498GlRenderer::RenderScene()
499{
500        Intersectable::NewMail();
501
502        Preprocessor *p = mViewCellsManager->GetPreprocessor();
503        // handle dynamic objects
504        DynamicObjectsContainer::const_iterator dit, dit_end = p->mDynamicObjects.end();
505
506        for (dit = p->mDynamicObjects.begin(); dit != dit_end; ++ dit)
507        {
508                RenderIntersectable(*dit);
509        }
510
511#if 1
512        _RenderSceneTrianglesWithDrawArrays();
513
514#else
515        static int glList = -1;
516        if (mUseGlLists) {
517                if (glList == -1) {
518                        glList = glGenLists(1);
519                        glNewList(glList, GL_COMPILE);
520                        _RenderSceneTriangles();
521                        glEndList();
522                }
523
524                glCallList(glList);
525        } else
526                _RenderSceneTriangles();
527
528#endif
529        return true;
530}
531
532
533void
534GlRendererBuffer::EvalQueryWithItemBuffer()
535{
536        // read back the texture
537        glReadPixels(0, 0,
538                                GetWidth(), GetHeight(),
539                                GL_RGBA,
540                                GL_UNSIGNED_BYTE,
541                                mPixelBuffer);
542               
543                       
544        unsigned int *p = mPixelBuffer;
545                       
546        for (int y = 0; y < GetHeight(); y++)
547        {
548                for (int x = 0; x < GetWidth(); x++, p++)
549                {
550                        unsigned int id = (*p) & 0xFFFFFF;
551
552                        if (id != 0xFFFFFF)
553                        {
554                                ++ mObjects[id]->mCounter;
555                        }
556                }
557        }
558}
559
560
561
562/****************************************************************/
563/*               GlRendererBuffer implementation                */
564/****************************************************************/
565
566
567
568GlRendererBuffer::GlRendererBuffer(SceneGraph *sceneGraph,
569                                                                   ViewCellsManager *viewcells,
570                                                                   KdTree *tree):
571GlRenderer(sceneGraph, viewcells, tree) 
572{
573  mPixelBuffer = NULL;
574  // implement width and height in subclasses
575}
576
577
578void
579GlRendererBuffer::EvalQueryWithOcclusionQueries(
580                                                                           //RenderCostSample &sample
581                                                                           )
582{
583        glDepthFunc(GL_LEQUAL);
584               
585        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
586        glDepthMask(GL_FALSE);
587
588
589        // simulate detectemptyviewspace using backface culling
590        if (mDetectEmptyViewSpace)
591        {
592                glEnable(GL_CULL_FACE);
593                //cout << "culling" << endl;
594        }
595        else
596        {
597                //cout << "not culling" << endl;
598                glDisable(GL_CULL_FACE);
599        }
600
601       
602        //const int numQ = 1;
603        const int numQ = (int)mOcclusionQueries.size();
604       
605        //glFinish();
606#if 0
607        //-- now issue queries for all objects
608        for (int j = 0; j < (int)mObjects.size(); ++ j)
609        {
610                mOcclusionQueries[j]->BeginQuery();
611                RenderIntersectable(mObjects[j]);
612                mOcclusionQueries[j]->EndQuery();
613
614                unsigned int pixelCount;
615
616                pixelCount = mOcclusionQueries[j]->GetQueryResult();
617               
618                mObjects[j]->mCounter += pixelCount;
619        }
620#else
621
622        int q = 0;
623
624        //-- now issue queries for all objects
625        for (int j = 0; j < (int)mObjects.size(); j += q)
626        {       
627                for (q = 0; ((j + q) < (int)mObjects.size()) && (q < numQ); ++ q)
628                {
629                        //glFinish();
630                        mOcclusionQueries[q]->BeginQuery();
631                       
632                        RenderIntersectable(mObjects[j + q]);
633               
634                        mOcclusionQueries[q]->EndQuery();
635                        //glFinish();
636                }
637                //cout << "q: " << q << endl;
638                // collect results of the queries
639                for (int t = 0; t < q; ++ t)
640                {
641                        unsigned int pixelCount;
642               
643                        //-- reenable other state
644#if 0
645                        bool available;
646
647                        do
648                        {
649                                available = mOcclusionQueries[t]->ResultAvailable();
650                               
651                                if (!available) cout << "W";
652                        }
653                        while (!available);
654#endif
655
656                        pixelCount = mOcclusionQueries[t]->GetQueryResult();
657
658                        //if (pixelCount > 0)
659                        //      cout <<"o="<<j+q<<" q="<<mOcclusionQueries[q]->GetQueryId()<<" pc="<<pixelCount<<" ";
660                        mObjects[j + t]->mCounter += pixelCount;
661               
662                }
663
664                //j += q;
665        }
666#endif
667        //glFinish();
668        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
669        glDepthMask(GL_TRUE);
670       
671        glEnable(GL_CULL_FACE);
672}
673
674
675void
676GlRenderer::RandomViewPoint()
677{
678  // do not use this function since it could return different viewpoints for
679  // different executions of the algorithm
680
681  //  mViewCellsManager->GetViewPoint(mViewPoint);
682
683  while (1) {
684        Vector3 pVector = Vector3(halton.GetNumber(1),
685                                                          halton.GetNumber(2),
686                                                          halton.GetNumber(3));
687       
688        mViewPoint =  mViewCellsManager->GetViewSpaceBox().GetPoint(pVector);
689        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
690        if (v && v->GetValid())
691          break;
692        // generate a new vector
693        halton.GenerateNext();
694  }
695 
696  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
697                                                        M_PI*halton.GetNumber(5),
698                                                        0.0f);
699 
700  mViewDirection = Normalize(Vector3(sin(dVector.x),
701                                                                         //     cos(dVector.y),
702                                                                         0.0f,
703                                                                         cos(dVector.x)));
704  halton.GenerateNext();
705}
706
707
708void
709GlRenderer::RenderBox(const AxisAlignedBox3 &box)
710{
711
712  glBegin(GL_LINE_LOOP);
713  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
714  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
715  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
716  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
717  glEnd();
718
719  glBegin(GL_LINE_LOOP);
720  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
721  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
722  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
723  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
724  glEnd();
725
726  glBegin(GL_LINE_LOOP);
727  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
728  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
729  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
730  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
731  glEnd();
732
733  glBegin(GL_LINE_LOOP);
734  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
735  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
736  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
737  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
738  glEnd();
739
740  glBegin(GL_LINE_LOOP);
741  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
742  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
743  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
744  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
745  glEnd();
746
747  glBegin(GL_LINE_LOOP);
748  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
749  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
750  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
751  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
752
753  glEnd();
754
755}
756
757void
758GlRenderer::RenderBvhNode(BvhNode *node)
759{
760  if (node->IsLeaf()) {
761        BvhLeaf *leaf = (BvhLeaf *) node;
762
763#if 0
764        if (leaf->mGlList == 0) {
765          leaf->mGlList = glGenLists(1);
766          if (leaf->mGlList != 0)
767                glNewList(leaf->mGlList, GL_COMPILE);
768         
769          for (int i=0; i < leaf->mObjects.size(); i++)
770                RenderIntersectable(leaf->mObjects[i]);
771         
772          if (leaf->mGlList != 0)
773                glEndList();
774        }
775       
776        if (leaf->mGlList != 0)
777          glCallList(leaf->mGlList);
778#else
779        for (int i=0; i < leaf->mObjects.size(); i++)
780          RenderIntersectable(leaf->mObjects[i]);
781#endif
782  } else {
783        BvhInterior *in = (BvhInterior *)node;
784        RenderBvhNode(in->GetBack());
785        RenderBvhNode(in->GetFront());
786  }
787}
788
789void
790GlRenderer::RenderKdNode(KdNode *node)
791{
792        if (node->IsLeaf())
793        {
794#if !EVAL_ERROR
795                RenderKdLeaf(static_cast<KdLeaf *>(node));
796#else
797                KdLeaf *leaf = (KdLeaf *)node;
798                for (int i=0; i < leaf->mObjects.size(); i++)
799                {
800                        RenderIntersectable(leaf->mObjects[i]);
801                }
802#endif
803        }
804        else
805        {
806                KdInterior *in = (KdInterior *)node;
807                RenderKdNode(in->mBack);
808                RenderKdNode(in->mFront);
809        }
810}
811
812
813
814
815void
816GlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
817                                                                           const bool useOcclusionQueries,
818                                                                           const int threshold
819                                                                           )
820{
821        // choose a random view point
822        mViewCellsManager->GetViewPoint(mViewPoint);
823        sample.mPosition = mViewPoint;
824        //cout << "viewpoint: " << mViewPoint << endl;
825
826        // take a render cost sample by rendering a cube
827        Vector3 directions[6];
828
829        directions[0] = Vector3(1,0,0);
830        directions[1] = Vector3(0,1,0);
831        directions[2] = Vector3(0,0,1);
832        directions[3] = Vector3(-1,0,0);
833        directions[4] = Vector3(0,-1,0);
834        directions[5] = Vector3(0,0,-1);
835
836        sample.mVisibleObjects = 0;
837
838        // reset object counters
839        ObjectContainer::const_iterator it, it_end = mObjects.end();
840
841        for (it = mObjects.begin(); it != it_end; ++ it)
842        {
843                (*it)->mCounter = 0;
844
845        }
846
847        ++ mFrame;
848
849        //glCullFace(GL_FRONT);
850        glCullFace(GL_BACK);
851        glDisable(GL_CULL_FACE);
852
853
854        // query all 6 directions for a full point sample
855        for (int i = 0; i < 6; ++ i)
856        {
857                mViewDirection = directions[i];
858                SetupCamera();
859
860                glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
861                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
862                //glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);      glDepthMask(GL_TRUE);
863                glDepthFunc(GL_LESS);
864
865                mUseFalseColors = true;
866
867                // the actual scene rendering fills the depth (for occlusion queries)
868                // and the frame buffer (for item buffer)
869                RenderScene();
870
871
872                if (0)
873                {
874                        char filename[256];
875                        sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
876                        //                QImage im = toImage();
877                        //                im.save(filename, "PNG");
878                }
879
880                // evaluate the sample
881                if (useOcclusionQueries)
882                {
883                        EvalQueryWithOcclusionQueries();
884                }
885                else
886                {
887                        EvalQueryWithItemBuffer();
888                }
889        } 
890
891        // now evaluate the statistics over that sample
892        // currently only the number of visible objects is taken into account
893        sample.Reset();
894
895        for (it = mObjects.begin(); it != it_end; ++ it)
896        {
897                Intersectable *obj = *it;
898                if (obj->mCounter >= threshold)
899                {
900                        ++ sample.mVisibleObjects;
901                        sample.mVisiblePixels += obj->mCounter;
902                }
903        }
904
905        //cout << "RS=" << sample.mVisibleObjects << " ";
906}
907
908
909GlRendererBuffer::~GlRendererBuffer()
910{
911#if 0
912#ifdef USE_CG
913        if (sCgFragmentProgram)
914                cgDestroyProgram(sCgFragmentProgram);
915        if (sCgContext)
916                cgDestroyContext(sCgContext);
917#endif
918#endif
919
920}
921
922
923void
924GlRendererBuffer::SampleRenderCost(const int numSamples,
925                                                                   vector<RenderCostSample> &samples,
926                                                                   const bool useOcclusionQueries,
927                                                                   const int threshold
928                                                                   )
929{
930        MakeCurrent();
931
932        if (mPixelBuffer == NULL)
933                mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
934
935        // using 90 degree projection to capture 360 view with 6 samples
936        SetupProjection(GetHeight(), GetHeight(), 90.0f);
937
938        //samples.resize(numSamples);
939        halton.Reset();
940
941        // the number of queries queried in batch mode
942        const int numQ = 500;
943
944        //const int numQ = (int)mObjects.size();
945        if (useOcclusionQueries)
946        {
947                cout << "\ngenerating " << numQ << " queries ... ";
948                OcclusionQuery::GenQueries(mOcclusionQueries, numQ);
949                cout << "finished" << endl;
950        }
951
952        // sampling queries
953        for (int i = 0; i < numSamples; ++ i)
954        {
955                cout << ".";
956                EvalRenderCostSample(samples[i], useOcclusionQueries, threshold);
957        }
958
959        DoneCurrent();
960}
961
962
963
964
965
966void
967GlRenderer::ClearErrorBuffer()
968{
969  for (int i=0; i < mPvsStatFrames; i++) {
970        mPvsErrorBuffer[i].mError = 1.0f;
971  }
972  mPvsStat.maxError = 0.0f;
973}
974
975
976void
977GlRendererBuffer::EvalPvsStat()
978{
979        MakeCurrent();
980       
981        GlRenderer::EvalPvsStat();
982       
983        DoneCurrent();
984  //  mRenderingFinished.wakeAll();
985}
986
987
988void GlRendererBuffer::EvalPvsStat(const SimpleRayContainer &viewPoints)
989{
990        MakeCurrent();
991
992        GlRenderer::EvalPvsStat(viewPoints);
993 
994        DoneCurrent();
995}
996
997
998void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
999                                                                                           Beam &beam,
1000                                                                                           const int desiredSamples,
1001                                                                                           BeamSampleStatistics &stat)
1002{
1003        // TODO: should be moved out of here (not to be done every time)
1004        // only back faces are interesting for the depth pass
1005        glShadeModel(GL_FLAT);
1006        glDisable(GL_LIGHTING);
1007
1008        // needed to kill the fragments for the front buffer
1009        glEnable(GL_ALPHA_TEST);
1010        glAlphaFunc(GL_GREATER, 0);
1011
1012        // assumes that the beam is constructed and contains kd-tree nodes
1013        // and viewcells which it intersects
1014 
1015 
1016        // Get the number of viewpoints to be sampled
1017        // Now it is a sqrt but in general a wiser decision could be made.
1018        // The less viewpoints the better for rendering performance, since less passes
1019        // over the beam is needed.
1020        // The viewpoints could actually be generated outside of the bounding box which
1021        // would distribute the 'efective viewpoints' of the object surface and thus
1022        // with a few viewpoints better sample the viewpoint space....
1023
1024        //TODO: comment in
1025        //int viewPointSamples = sqrt((float)desiredSamples);
1026        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
1027       
1028        // the number of direction samples per pass is given by the number of viewpoints
1029        int directionalSamples = desiredSamples / viewPointSamples;
1030       
1031        Debug << "directional samples: " << directionalSamples << endl;
1032        for (int i = 0; i < viewPointSamples; ++ i)
1033        {
1034                Vector3 viewPoint = beam.mBox.GetRandomPoint();
1035               
1036                // perhaps the viewpoint should be shifted back a little bit so that it always lies
1037                // inside the source object
1038                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
1039        // would require more complicated sampling (perhaps hierarchical rejection sampling of
1040                // the object surface is an option here - only the mesh faces which are inside the box
1041                // are considered as candidates)
1042               
1043                SampleViewpointContributions(sourceObject,
1044                                                                         viewPoint,
1045                                                                         beam,
1046                                                                         directionalSamples,
1047                                                                         stat);
1048        }
1049
1050
1051        // note:
1052        // this routine would be called only if the number of desired samples is sufficiently
1053        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
1054        // distributing the work between cpu and gpu would also allow us to place more sophisticated
1055        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
1056        // in order that thios scheme is working well the gpu render buffer should run in a separate
1057        // thread than the cpu sampler, which would not be such a big problem....
1058
1059        // disable alpha test again
1060        glDisable(GL_ALPHA_TEST);
1061}
1062
1063
1064
1065void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
1066                                                                                                        const Vector3 viewPoint,
1067                                                                                                        Beam &beam,
1068                                                                                                        const int samples,
1069                                                    BeamSampleStatistics &stat)
1070{
1071    // 1. setup the view port to match the desired samples
1072        glViewport(0, 0, samples, samples);
1073
1074        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
1075        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
1076
1077
1078        // 3. reset z-buffer to 0 and render the source object for the beam
1079        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
1080        //    save result to the front depth map
1081        //    the front depth map holds ray origins
1082
1083
1084        // front depth buffer must be initialised to 0
1085        float clearDepth;
1086       
1087        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
1088        glClearDepth(0.0f);
1089        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1090
1091
1092        // glFrontFace(GL_CCW);
1093        glEnable(GL_CULL_FACE);
1094        glCullFace(GL_FRONT);
1095        glColorMask(0, 0, 0, 0);
1096       
1097
1098        // stencil is increased where the source object is located
1099        glEnable(GL_STENCIL_TEST);     
1100        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
1101        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1102
1103
1104#if 0
1105        static int glSourceObjList = -1;         
1106        if (glSourceObjList != -1)
1107        {
1108                glSourceObjList = glGenLists(1);
1109                glNewList(glSourceObjList, GL_COMPILE);
1110
1111                RenderIntersectable(sourceObject);
1112       
1113                glEndList();
1114        }
1115        glCallList(glSourceObjList);
1116
1117#else
1118        RenderIntersectable(sourceObject);
1119
1120#endif 
1121
1122         // copy contents of the front depth buffer into depth texture
1123        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
1124        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1125
1126        // reset clear function
1127        glClearDepth(clearDepth);
1128       
1129       
1130        // 4. set up the termination depth buffer (= standard depth buffer)
1131        //    only rays which have non-zero entry in the origin buffer are valid since
1132        //    they realy start on the object surface (this is tagged by setting a
1133        //    stencil buffer bit at step 3).
1134       
1135        glStencilFunc(GL_EQUAL, 0x1, 0x1);
1136        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1137
1138        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1139        glDepthMask(1);
1140
1141        glEnable(GL_DEPTH_TEST);
1142               
1143        glEnable(GL_CULL_FACE);
1144        glCullFace(GL_BACK);
1145
1146        // setup front depth buffer
1147        glEnable(GL_TEXTURE_2D);
1148       
1149#if 0
1150#ifdef USE_CG
1151        // bind pixel shader implementing the front depth buffer functionality
1152        cgGLBindProgram(sCgFragmentProgram);
1153        cgGLEnableProfile(sCgFragmentProfile);
1154#endif
1155#endif
1156        // 5. render all objects inside the beam
1157        //    we can use id based false color to read them back for gaining the pvs
1158
1159        glColorMask(1, 1, 1, 1);
1160
1161       
1162        // if objects not stored in beam => extract objects
1163        if (beam.mFlags & !Beam::STORE_OBJECTS)
1164        {
1165                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
1166
1167                Intersectable::NewMail();
1168                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
1169                {
1170                        mKdTree->CollectObjects(*it, beam.mObjects);
1171                }
1172        }
1173
1174
1175        //    (objects can be compiled to a gl list now so that subsequent rendering for
1176        //    this beam is fast - the same hold for step 3)
1177        //    Afterwards we have two depth buffers defining the ray origin and termination
1178       
1179
1180#if 0
1181        static int glObjList = -1;
1182        if (glObjList != -1)
1183        {
1184                glObjList = glGenLists(1);
1185                glNewList(glObjList, GL_COMPILE);
1186       
1187                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1188                for (it = beam.mObjects.begin(); it != it_end; ++ it)
1189                {
1190                        // render all objects except the source object
1191                        if (*it != sourceObject)
1192                                RenderIntersectable(*it);
1193                }
1194               
1195                glEndList();
1196        }
1197
1198        glCallList(glObjList);
1199#else
1200        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1201        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1202        {       
1203                // render all objects except the source object
1204                if (*it != sourceObject)
1205                        RenderIntersectable(*it);
1206        }
1207#endif
1208       
1209        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1210        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1211        //     between origin and termination buffer
1212
1213        // create new queries if necessary
1214        OcclusionQuery::GenQueries(mOcclusionQueries, (int)beam.mViewCells.size());
1215
1216        // check whether any backfacing polygon would pass the depth test?
1217        // matt: should check both back /front facing because of dual depth buffer
1218        // and danger of cutting the near plane with front facing polys.
1219       
1220        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1221        glDepthMask(GL_FALSE);
1222        glDisable(GL_CULL_FACE);
1223
1224 
1225        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1226
1227        int queryIdx = 0;
1228
1229        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1230        {
1231                mOcclusionQueries[queryIdx ++]->BeginQuery();
1232                RenderIntersectable(*vit);
1233                mOcclusionQueries[queryIdx]->EndQuery();
1234
1235                ++ queryIdx;
1236        }
1237
1238        // at this point, if possible, go and do some other computation
1239
1240        // 7. The number of visible pixels is the number of sample rays which see the source
1241        //    object from the corresponding viewcell -> remember these values for later update
1242        //   of the viewcell pvs - or update immediately?
1243
1244        queryIdx = 0;
1245
1246        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1247        {
1248                // fetch queries
1249                unsigned int pixelCount = mOcclusionQueries[queryIdx ++]->GetQueryResult();
1250
1251                if (pixelCount)
1252                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1253        }
1254       
1255
1256        // 8. Copmpute rendering statistics
1257        // In general it is not neccessary to remember to extract all the rays cast. I hope it
1258        // would be sufficient to gain only the intergral statistics about the new contributions
1259        // and so the rss tree would actually store no new rays (only the initial ones)
1260        // the subdivision of the tree would only be driven by the statistics (the glrender could
1261        // evaluate the contribution entropy for example)
1262        // However might be an option to extract/store only those the rays which made a contribution
1263        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
1264
1265        ObjectContainer pvsObj;
1266        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
1267       
1268        // to gain ray source and termination
1269        // copy contents of ray termination buffer into depth texture
1270        // and compare with ray source buffer
1271#if 0
1272        VssRayContainer rays;
1273
1274        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
1275        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1276
1277        ComputeRays(Intersectable *sourceObj, rays);
1278
1279#endif
1280
1281        ////////
1282        //-- cleanup
1283
1284        // reset gl state
1285        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1286        glDepthMask(GL_TRUE);
1287        glEnable(GL_CULL_FACE);
1288        glDisable(GL_STENCIL_TEST);
1289
1290#if 0
1291#ifdef USE_CG
1292        cgGLDisableProfile(sCgFragmentProfile);
1293#endif
1294#endif
1295
1296        glDisable(GL_TEXTURE_2D);
1297
1298        // remove objects from beam
1299        if (beam.mFlags & !Beam::STORE_OBJECTS)
1300                beam.mObjects.clear();
1301}
1302
1303
1304void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
1305                                                                                                   const Beam &beam,
1306                                                                                                   Intersectable *sourceObject)
1307{
1308        float left, right, bottom, top, znear, zfar;
1309
1310        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
1311                                                                   mSceneGraph->GetBox());
1312
1313        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
1314        glMatrixMode(GL_PROJECTION);
1315        glLoadIdentity();
1316        glFrustum(left, right, bottom, top, znear, zfar);
1317        //glFrustum(-1, 1, -1, 1, 1, 20000);
1318
1319    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
1320        const Vector3 up =
1321                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
1322
1323#ifdef GTP_DEBUG
1324        Debug << "view point: " << viewPoint << endl;
1325        Debug << "eye: " << center << endl;
1326        Debug << "up: " << up << endl;
1327#endif
1328
1329        glMatrixMode(GL_MODELVIEW);
1330        glLoadIdentity();
1331        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
1332                          center.x, center.y, center.z,                   
1333                          up.x, up.y, up.z);
1334}               
1335
1336 
1337void GlRendererBuffer::InitGL()
1338{
1339        MakeCurrent();
1340        GlRenderer::InitGL();
1341
1342        // initialise dual depth buffer textures
1343        glGenTextures(1, &frontDepthMap);
1344        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1345
1346        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1347                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1348
1349        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1350        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1351        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1352        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1353
1354        glGenTextures(1, &backDepthMap);
1355        glBindTexture(GL_TEXTURE_2D, backDepthMap);
1356
1357        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1358                                 depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1359        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1360        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1361        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1362        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1363
1364#if 0
1365#ifdef USE_CG
1366
1367        // cg initialization
1368        cgSetErrorCallback(handleCgError);
1369        sCgContext = cgCreateContext();
1370
1371        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1372                sCgFragmentProfile = CG_PROFILE_ARBFP1;
1373        else
1374        {
1375                // try FP30
1376                if (cgGLIsProfileSupported(CG_PROFILE_FP30))
1377                        sCgFragmentProfile = CG_PROFILE_FP30;
1378                else
1379                {
1380                        Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
1381                        exit(1);
1382                }
1383        }
1384
1385        sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
1386                                                         CG_SOURCE, "../src/dual_depth.cg",
1387                                                                                                 sCgFragmentProfile,
1388                                                                                                 NULL,
1389                                                                                                 NULL);
1390
1391        if (!cgIsProgramCompiled(sCgFragmentProgram))
1392                cgCompileProgram(sCgFragmentProgram);
1393
1394        cgGLLoadProgram(sCgFragmentProgram);
1395        cgGLBindProgram(sCgFragmentProgram);
1396
1397        Debug << "---- PROGRAM BEGIN ----\n" <<
1398                cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
1399
1400#endif
1401#endif
1402        DoneCurrent();
1403}
1404
1405
1406void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
1407{
1408        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
1409        {
1410                //todo glGetTexImage()
1411        }
1412}
1413
1414bool GlRendererBuffer::ValidViewPoint()
1415{       
1416        MakeCurrent();
1417
1418        SetupProjection(GetWidth(), GetHeight());
1419
1420        bool result = GlRenderer::ValidViewPoint();
1421       
1422        DoneCurrent();
1423       
1424        return result;
1425}
1426
1427
1428void
1429GlRenderer::EvalPvsStat()
1430{
1431  mPvsStat.Reset();
1432  halton.Reset();
1433
1434  SetupProjection(GetWidth(), GetHeight());
1435
1436  cout<<"Random Pvs STATS, mPvsStatFrames="<<mPvsStatFrames<<endl;
1437 
1438  for (int i=0; i < mPvsStatFrames; i++) {
1439        float err;
1440        // set frame id for saving the error buffer
1441        mFrame = i;
1442        //      cerr<<"RV"<<endl;
1443        RandomViewPoint();
1444        //      cerr<<"RV2"<<endl;
1445
1446        if (mPvsErrorBuffer[i].mError == 1.0f) {
1447          // check if the view point is valid
1448          if (!ValidViewPoint())
1449                mPvsErrorBuffer[i].mError = -1.0f;
1450         
1451          // manualy corrected view point
1452          if (mFrame == 5105)
1453                mPvsErrorBuffer[i].mError = -1.0f;
1454        }
1455       
1456       
1457        // atlanta problematic frames: 325 525 691 1543
1458#if 0
1459        if (mFrame != 325 &&
1460                mFrame != 525 &&
1461                mFrame != 691 &&
1462                mFrame != 1543)
1463          mPvsErrorBuffer[i] = -1;
1464        else {
1465          Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
1466        }
1467#endif
1468       
1469        if (mPvsErrorBuffer[i].mError > 0.0f) {
1470          int pvsSize;
1471
1472          float error = GetPixelError(pvsSize);
1473
1474          mPvsErrorBuffer[i].mError = error;
1475          mPvsErrorBuffer[i].mPvsSize = pvsSize;
1476
1477          //      emit UpdatePvsErrorItem(i,
1478          //                                                      mPvsErrorBuffer[i]);
1479          cout<<"("<<i<<","<<mPvsErrorBuffer[i].mError<<")";
1480          //      swapBuffers();
1481        }
1482       
1483        err = mPvsErrorBuffer[i].mError;
1484       
1485        if (err >= 0.0f) {
1486          if (err > mPvsStat.maxError)
1487                mPvsStat.maxError = err;
1488          mPvsStat.sumError += err;
1489          mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1490         
1491          if (err == 0.0f)
1492                mPvsStat.errorFreeFrames++;
1493          mPvsStat.frames++;
1494        }
1495  }
1496 
1497  glFinish();
1498  cout<<endl<<flush;
1499}
1500
1501
1502void GlRenderer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1503{
1504  mPvsStat.Reset();
1505
1506  SetupProjection(GetWidth(), GetHeight());
1507 
1508  cout << "mPvsStatFrames=" << mPvsStatFrames << endl;
1509 
1510  SimpleRayContainer::const_iterator sit, sit_end = viewPoints.end();
1511  int i = 0;
1512 
1513  for (sit = viewPoints.begin(); sit != sit_end; ++ sit, ++ i)
1514        {
1515         
1516          //cout << "view point: " << (*sit) << endl;;
1517          SimpleRay sray = *sit;
1518         
1519          float err;
1520         
1521          // set frame id for saving the error buffer
1522          mFrame = i;
1523          mViewPoint = sray.mOrigin;
1524          mViewDirection = sray.mDirection;
1525         
1526          if (mPvsErrorBuffer[i].mError > 0.0f)
1527          {
1528                  int pvsSize;
1529
1530                  // compute the pixel error
1531                  float error = GetPixelError(pvsSize);
1532
1533                  mPvsErrorBuffer[i].mError = error;
1534                  mPvsErrorBuffer[i].mPvsSize = pvsSize;
1535
1536                  cout << "(" << i << "," << mPvsErrorBuffer[i].mError <<")";
1537          }
1538
1539          err = mPvsErrorBuffer[i].mError;
1540
1541          if (err >= 0.0f)
1542          {
1543                  if (err > mPvsStat.maxError)
1544                          mPvsStat.maxError = err;
1545
1546                  mPvsStat.sumError += err;
1547                  mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1548
1549                  if (err == 0.0f)
1550                          ++ mPvsStat.errorFreeFrames;
1551
1552                  ++ mPvsStat.frames;
1553          }
1554        }
1555 
1556  glFinish();
1557  cout << endl << flush;
1558}
1559
1560
1561
1562bool
1563GlRenderer::ValidViewPoint()
1564{
1565        //cout<<"VV4 ";
1566        if (!mDetectEmptyViewSpace)
1567                return true;
1568        //cout << "vp: " << mViewPoint << " dir: " << mViewDirection << endl;
1569
1570        OcclusionQuery *query = mOcclusionQueries[0];
1571
1572        // now check whether any backfacing polygon would pass the depth test
1573        SetupCamera();
1574        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1575        glEnable( GL_CULL_FACE );
1576        glCullFace(GL_BACK);
1577
1578        //cout<<"VV1 ";
1579        RenderScene();
1580
1581        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1582        glDepthMask(GL_FALSE);
1583        glDisable( GL_CULL_FACE );
1584
1585        query->BeginQuery();
1586
1587        //  cout<<"VV2 ";
1588        RenderScene();
1589        //  cout<<"VV3 ";
1590
1591        query->EndQuery();
1592
1593        // at this point, if possible, go and do some other computation
1594        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1595        glDepthMask(GL_TRUE);
1596        glEnable( GL_CULL_FACE );
1597
1598        //      int wait = 0;
1599        //      while (!query->ResultAvailable()) {
1600        //        wait++;
1601        //      }
1602
1603        // reenable other state
1604        unsigned int pixelCount = query->GetQueryResult();
1605        //  cout<<"VV4 ";
1606
1607
1608        if (pixelCount > 0)
1609        {
1610                return false; // backfacing polygon found -> not a valid viewspace sample
1611        }
1612        return true;
1613}
1614
1615
1616float GlRenderer::GetPixelError(int &pvsSize)
1617{
1618  return -1.0f;
1619}
1620
1621
1622void GlRenderer::RenderViewPoint()
1623{
1624        mWireFrame = true;
1625        glPushMatrix();
1626        glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
1627        glScalef(5.0f, 5.0f, 5.0f);
1628        glPushAttrib(GL_CURRENT_BIT);
1629        glColor3f(1.0f, 0.0f, 0.0f);
1630        gluSphere((::GLUquadric *)mSphere,
1631                1e-3*Magnitude(mViewCellsManager->GetViewSpaceBox().Size()), 6, 6);
1632        glPopAttrib();
1633        glPopMatrix();
1634        mWireFrame = false;
1635}
1636
1637
1638void GlRenderer::EnableDrawArrays()
1639{
1640        glEnableClientState(GL_VERTEX_ARRAY);
1641        glEnableClientState(GL_NORMAL_ARRAY);
1642}
1643
1644
1645void GlRenderer::DisableDrawArrays()
1646{
1647        glDisableClientState(GL_VERTEX_ARRAY);
1648        glDisableClientState(GL_NORMAL_ARRAY);
1649}
1650
1651
1652#if 0
1653
1654void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1655{
1656        int bufferSize = 0;
1657
1658        // count #new triangles
1659        for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1660        {
1661                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1662
1663                // check if already rendered
1664                if (!obj->Mailed())
1665                        bufferSize += 3;
1666                //else cout << obj->mMailbox << " " << obj->sMailId << " ";
1667        }
1668
1669        Vector3 *vertices = new Vector3[bufferSize];
1670        Vector3 *normals = new Vector3[bufferSize];
1671
1672        int j = 0;
1673
1674        for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1675        {
1676                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1677
1678                // check if already rendered
1679                if (obj->Mailed())
1680                        continue;
1681
1682                obj->Mail();
1683
1684                Triangle3 tri = obj->GetItem();
1685
1686                vertices[j * 3 + 0] = tri.mVertices[0];
1687                vertices[j * 3 + 1] = tri.mVertices[1];
1688                vertices[j * 3 + 2] = tri.mVertices[2];
1689
1690                Vector3 n = tri.GetNormal();
1691
1692                normals[j * 3 + 0] = n;
1693                normals[j * 3 + 1] = n;
1694                normals[j * 3 + 2] = n;
1695
1696                ++ j;
1697        }
1698
1699        glVertexPointer(3, GL_FLOAT, 0, vertices);
1700        glNormalPointer(GL_FLOAT, 0, normals);
1701
1702        glDrawArrays(GL_TRIANGLES, 0, bufferSize);
1703
1704        DEL_PTR(vertices);
1705        DEL_PTR(normals);
1706}
1707
1708#else
1709
1710void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1711{
1712        if (!leaf->mIndexBufferSize)
1713                return;
1714
1715        size_t offset = mObjects.size() * 3;
1716        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
1717       
1718        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
1719        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
1720       
1721        glDrawElements(GL_TRIANGLES, leaf->mIndexBufferSize, GL_UNSIGNED_INT, mIndices + leaf->mIndexBufferStart);
1722}
1723
1724#endif
1725
1726
1727void GlRenderer::CreateVertexArrays(SceneGraphLeaf *leaf)
1728{
1729    mData = new Vector3[leaf->mGeometry.size() * 6];
1730        mIndices = new unsigned int[leaf->mGeometry.size() * 3];
1731
1732        size_t offset = leaf->mGeometry.size() * 3;
1733
1734        for (size_t i = 0; i < leaf->mGeometry.size(); ++ i)
1735        {
1736                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mGeometry[i]);
1737
1738                Triangle3 tri = obj->GetItem();
1739                const Vector3 n = tri.GetNormal();
1740
1741                mData[i * 3 + 0] = tri.mVertices[0];
1742                mData[i * 3 + 1] = tri.mVertices[1];
1743                mData[i * 3 + 2] = tri.mVertices[2];
1744
1745                mData[offset + i * 3 + 0] = n;
1746                mData[offset + i * 3 + 1] = n;
1747                mData[offset + i * 3 + 2] = n;
1748        }
1749
1750        if (mUseVbos)
1751        {
1752                EnableDrawArrays();
1753
1754                glGenBuffersARB(1, &mVboId);
1755                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
1756
1757                glVertexPointer(3, GL_FLOAT, 0, (char *)NULL);
1758                glNormalPointer(GL_FLOAT, 0, (char *)NULL + offset * sizeof(Vector3));
1759
1760                glBufferDataARB(GL_ARRAY_BUFFER_ARB, leaf->mGeometry.size() * 6 * sizeof(Vector3), mData, GL_STATIC_DRAW_ARB);
1761                glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
1762
1763                DisableDrawArrays();
1764
1765                delete [] mData;
1766        }
1767
1768        cout << "\n******** created vertex buffer objects **********" << endl; 
1769}
1770
1771
1772void GlRenderer::DeleteVbos()
1773{
1774        glDeleteBuffersARB(1, &mVboId);
1775
1776/*
1777        KdLeafContainer leaves;
1778        mKdTree->CollectLeaves(leaves);
1779
1780        KdLeafContainer::const_iterator kit, kit_end = leaves.end();
1781
1782        for (kit = leaves.begin(); kit != kit_end; ++ kit)
1783        {
1784                KdLeaf *leaf = *kit;
1785
1786                if (leaf->mVboId == -1)
1787                {
1788                        // delete old vbo
1789                        glDeleteBuffersARB(1, &leaf->mVboId);
1790                        leaf->mVboId = -1;
1791                }
1792        }
1793*/
1794}
1795
1796
1797
1798}
Note: See TracBrowser for help on using the repository browser.