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

Revision 2616, 43.7 KB checked in by bittner, 16 years ago (diff)

merge

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