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

Revision 2702, 47.4 KB checked in by mattausch, 16 years ago (diff)

implemented dynamic object placement / removal

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