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

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