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

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