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

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