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

Revision 2695, 47.1 KB checked in by mattausch, 16 years ago (diff)

debug version: problematic view points for vienna detected

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