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

Revision 2611, 42.6 KB checked in by bittner, 16 years ago (diff)

pvs error debug

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