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

Revision 2613, 42.7 KB checked in by bittner, 16 years ago (diff)

evaluation of pvs error still does not work

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