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

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