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

Revision 2663, 47.5 KB checked in by mattausch, 16 years ago (diff)

debugging vp evaluation

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