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

Revision 2678, 46.7 KB checked in by mattausch, 16 years ago (diff)

started working on dynamic objects

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