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

Revision 2667, 47.5 KB checked in by bittner, 16 years ago (diff)

merge on nemo

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