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

Revision 2587, 41.3 KB checked in by mattausch, 16 years ago (diff)

worked on ray viz

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