source: trunk/VUT/GtpVisibilityPreprocessor/src/GlRenderer.cpp @ 544

Revision 544, 27.6 KB checked in by mattausch, 18 years ago (diff)
  • Property svn:executable set to *
Line 
1#include "Mesh.h"
2#include "GlRenderer.h"
3#include "ViewCellsManager.h"
4#include "SceneGraph.h"
5#include "Pvs.h"
6#include "Viewcell.h"
7#include "Beam.h"
8#include "KdTree.h"
9
10#include <GL/glext.h>
11#include <Cg/cg.h>
12#include <Cg/cgGL.h>
13
14static CGcontext sCgContext = NULL;
15static CGprogram sCgFragmentProgram = NULL;
16static CGprofile sCgFragmentProfile;
17
18GLuint frontDepthMap;
19GLuint backDepthMap;
20
21const int depthMapSize = 512;
22static vector<int> sQueries;
23
24GlRendererWidget *rendererWidget = NULL;
25GlDebuggerWidget *debuggerWidget = NULL;
26
27
28#ifdef _WIN32
29PFNGLGENOCCLUSIONQUERIESNVPROC glGenOcclusionQueriesNV;
30PFNGLBEGINOCCLUSIONQUERYNVPROC glBeginOcclusionQueryNV;
31PFNGLENDOCCLUSIONQUERYNVPROC glEndOcclusionQueryNV;
32PFNGLGETOCCLUSIONQUERYUIVNVPROC glGetOcclusionQueryuivNV;
33#endif
34
35GlRenderer::GlRenderer(SceneGraph *sceneGraph,
36                                           ViewCellsManager *viewCellsManager,
37                                           KdTree *tree):
38  Renderer(sceneGraph, viewCellsManager),
39  mKdTree(tree)
40{
41  mSceneGraph->CollectObjects(&mObjects);
42  mViewPoint = mSceneGraph->GetBox().Center();
43  mViewDirection = Vector3(0,0,1);
44  //  timerId = startTimer(10);
45  mFrame = 0;
46  mWireFrame = false;
47}
48
49GlRenderer::~GlRenderer()
50{
51        cgDestroyProgram(sCgFragmentProgram);
52        cgDestroyContext(sCgContext);
53}
54
55
56static void handleCgError()
57{
58    Debug << "Cg error: " << cgGetErrorString(cgGetError()) << endl;
59    exit(1);
60}
61
62void
63GlRenderer::RenderIntersectable(Intersectable *object)
64{
65
66  SetupFalseColor(object->mId);
67
68  switch (object->Type()) {
69  case Intersectable::MESH_INSTANCE:
70        RenderMeshInstance((MeshInstance *)object);
71        break;
72  case Intersectable::VIEW_CELL:
73          RenderViewCell(dynamic_cast<ViewCell *>(object));
74          break;
75  default:
76        cerr<<"Rendering this object not yet implemented\n";
77        break;
78  }
79}
80
81
82void
83GlRenderer::RenderViewCell(ViewCell *vc)
84{
85        if (vc->GetMesh())
86                RenderMesh(vc->GetMesh());
87}
88
89void
90GlRenderer::RenderMeshInstance(MeshInstance *mi)
91{
92  RenderMesh(mi->GetMesh());
93}
94
95void
96GlRenderer::SetupFalseColor(const int id)
97{
98  // swap bits of the color
99 
100  glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
101}
102
103
104int GlRenderer::GetId(int r, int g, int b) const
105{
106        return r + (g << 8) + (b << 16);
107}
108
109void
110GlRenderer::SetupMaterial(Material *m)
111{
112  if (m)
113        glColor3fv(&(m->mDiffuseColor.r));
114  else
115        glColor3f(1.0f, 1.0f, 1.0f);
116}
117
118void
119GlRenderer::RenderMesh(Mesh *mesh)
120{
121  int i = 0;
122
123  if (!mUseFalseColors)
124        SetupMaterial(mesh->mMaterial);
125 
126  for (i=0; i < mesh->mFaces.size(); i++) {
127        if (mWireFrame)
128          glBegin(GL_LINE_LOOP);
129        else
130          glBegin(GL_POLYGON);
131
132        Face *face = mesh->mFaces[i];
133        for (int j = 0; j < face->mVertexIndices.size(); j++) {
134          glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
135        }
136        glEnd();
137  }
138}
139       
140void
141GlRenderer::InitGL()
142{
143  glMatrixMode(GL_PROJECTION);
144  glLoadIdentity();
145 
146  glMatrixMode(GL_MODELVIEW);
147  glLoadIdentity();
148
149  glEnable(GL_CULL_FACE);
150  glShadeModel(GL_FLAT);
151  glEnable(GL_DEPTH_TEST);
152  glEnable(GL_CULL_FACE);
153 
154  glGenOcclusionQueriesNV = (PFNGLGENOCCLUSIONQUERIESNVPROC)
155        wglGetProcAddress("glGenOcclusionQueriesNV");
156  glBeginOcclusionQueryNV = (PFNGLBEGINOCCLUSIONQUERYNVPROC)
157        wglGetProcAddress("glBeginOcclusionQueryNV");
158  glEndOcclusionQueryNV = (PFNGLENDOCCLUSIONQUERYNVPROC)
159        wglGetProcAddress("glEndOcclusionQueryNV");
160  glGetOcclusionQueryuivNV = (PFNGLGETOCCLUSIONQUERYUIVNVPROC)
161        wglGetProcAddress("glGetOcclusionQueryuivNV");
162}
163
164
165
166void
167GlRenderer::SetupProjection(const int w, const int h)
168{
169  glViewport(0, 0, w, h);
170  glMatrixMode(GL_PROJECTION);
171  glLoadIdentity();
172  gluPerspective(70.0, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
173  glMatrixMode(GL_MODELVIEW);
174}
175
176void
177GlRenderer::SetupCamera()
178{
179  Vector3 target = mViewPoint + mViewDirection;
180  Vector3 up(0,1,0);
181 
182  glLoadIdentity();
183  gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
184                        target.x, target.y, target.z,
185                        up.x, up.y, up.z);
186}
187
188void
189GlRenderer::RandomViewPoint()
190{
191  Vector3 pVector = Vector3(halton.GetNumber(1),
192                                                        halton.GetNumber(2),
193                                                        halton.GetNumber(3));
194 
195  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
196                                                        M_PI*halton.GetNumber(5),
197                                                        0.0f);
198 
199  mViewPoint = mSceneGraph->GetBox().GetPoint(pVector);
200 
201  mViewDirection = Normalize(Vector3(sin(dVector.x),
202                                                                         //                                                                      cos(dVector.y),
203                                                                         0.0f,
204                                                                         cos(dVector.x)));
205
206  halton.GenerateNext();
207}
208
209
210float
211GlRenderer::GetPixelError()
212{
213  float pErrorPixels = -1.0f;
214
215  glReadBuffer(GL_BACK);
216 
217  mUseFalseColors = true;
218
219  SetupCamera();
220  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
221  glEnable( GL_CULL_FACE );
222 
223  RenderScene();
224
225  // now check whether any backfacing polygon would pass the depth test
226  static int query = -1;
227  if (query == -1)
228        glGenOcclusionQueriesNV(1, (unsigned int *)&query);
229 
230  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
231  glDepthMask(GL_FALSE);
232  glDisable( GL_CULL_FACE );
233 
234  glBeginOcclusionQueryNV(query);
235 
236  RenderScene();
237 
238  glEndOcclusionQueryNV();
239
240  // at this point, if possible, go and do some other computation
241  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
242  glDepthMask(GL_TRUE);
243  glEnable( GL_CULL_FACE );
244 
245  unsigned int pixelCount;
246  // reenable other state
247  glGetOcclusionQueryuivNV(query,
248                                                   GL_PIXEL_COUNT_NV,
249                                                   &pixelCount);
250
251  if (pixelCount > 0)
252        return -1.0f; // backfacing polygon found -> not a valid viewspace sample
253
254  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
255 
256  if (viewcell) {
257        SetupCamera();
258        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
259
260        // Render PVS
261        std::map<Intersectable *,
262          PvsData<Intersectable *>,
263          LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
264       
265        for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
266          Intersectable *object = (*it).first;
267          RenderIntersectable(object);
268        }
269
270        glBeginOcclusionQueryNV(query);
271
272        SetupCamera();
273
274        RenderScene();
275       
276        glEndOcclusionQueryNV();
277       
278
279        unsigned int pixelCount;
280        // reenable other state
281        glGetOcclusionQueryuivNV(query,
282                                                         GL_PIXEL_COUNT_NV,
283                                                         &pixelCount);
284       
285        pErrorPixels = (100.f*pixelCount)/(GetWidth()*GetHeight());
286  }
287 
288  return pErrorPixels;
289}
290
291
292float
293GlRendererWidget::RenderErrors()
294{
295  float pErrorPixels = -1.0f;
296
297  glReadBuffer(GL_BACK);
298 
299  mUseFalseColors = true;
300
301  SetupCamera();
302  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
303  glEnable( GL_CULL_FACE );
304 
305  ObjectContainer::const_iterator oi = mObjects.begin();
306  for (; oi != mObjects.end(); oi++)
307        RenderIntersectable(*oi);
308
309  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
310 
311  QImage im1, im2;
312  QImage diff;
313 
314  if (viewcell) {
315        // read back the texture
316        im1 = grabFrameBuffer(true);
317       
318        SetupCamera();
319        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
320       
321        std::map<Intersectable *,
322          PvsData<Intersectable *>,
323          LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
324       
325        for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
326          Intersectable *object = (*it).first;
327          RenderIntersectable(object);
328        }
329
330        // read back the texture
331        im2 = grabFrameBuffer(true);
332       
333        diff = im1;
334        int x, y;
335        int errorPixels = 0;
336       
337        for (y = 0; y < im1.height(); y++)
338          for (x = 0; x < im1.width(); x++)
339                if (im1.pixel(x, y) == im2.pixel(x, y))
340                  diff.setPixel(x, y, qRgba(0,0,0,0));
341                else {
342                  diff.setPixel(x, y, qRgba(255,128,128,255));
343                  errorPixels++;
344                }
345        pErrorPixels = (100.f*errorPixels)/(im1.height()*im1.width());
346  }
347
348  // now render the pvs again
349  SetupCamera();
350  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
351  mUseFalseColors = false;
352       
353  oi = mObjects.begin();
354  for (; oi != mObjects.end(); oi++)
355        RenderIntersectable(*oi);
356
357  // now render im1
358  if (viewcell) {
359        if (mTopView) {
360          mWireFrame = true;
361          RenderMeshInstance(viewcell);
362          mWireFrame = false;
363        }
364       
365        // init ortographic projection
366        glMatrixMode(GL_PROJECTION);
367        glPushMatrix();
368       
369        glLoadIdentity();
370        gluOrtho2D(0, 1.0f, 0, 1.0f);
371       
372        glMatrixMode(GL_MODELVIEW);
373        glLoadIdentity();
374       
375        bindTexture(diff);
376       
377        glPushAttrib(GL_ENABLE_BIT);
378        glEnable( GL_ALPHA_TEST );
379        glDisable( GL_CULL_FACE );
380        glAlphaFunc( GL_GREATER, 0.5 );
381       
382        glEnable( GL_TEXTURE_2D );
383        glBegin(GL_QUADS);
384       
385        glTexCoord2f(0,0);
386        glVertex3f(0,0,0);
387       
388        glTexCoord2f(1,0);
389        glVertex3f( 1, 0, 0);
390       
391        glTexCoord2f(1,1);
392        glVertex3f( 1, 1, 0);
393       
394        glTexCoord2f(0,1);
395        glVertex3f(0, 1, 0);
396        glEnd();
397       
398        glPopAttrib();
399       
400        // restore the projection matrix
401        glMatrixMode(GL_PROJECTION);
402        glPopMatrix();
403        glMatrixMode(GL_MODELVIEW);
404  }
405
406  return pErrorPixels;
407}
408
409
410bool
411GlRenderer::RenderScene()
412{
413  static int glList = -1;
414  if (glList == -1)
415  {
416        glList = glGenLists(1);
417        glNewList(glList, GL_COMPILE);
418        ObjectContainer::const_iterator oi = mObjects.begin();
419        for (; oi != mObjects.end(); oi++)
420          RenderIntersectable(*oi);
421        glEndList();
422  }
423 
424  glCallList(glList);
425 
426  return true;
427}
428
429
430void
431GlRendererBuffer::ClearErrorBuffer()
432{
433  for (int i=0; i < mPvsStatFrames; i++) {
434        mPvsErrorBuffer[i] = 1.0f;
435  }
436}
437
438
439void
440GlRendererBuffer::EvalPvsStat()
441{
442  mPvsStat.Reset();
443  halton.Reset();
444
445  makeCurrent();
446  SetupProjection(GetWidth(), GetHeight());
447 
448  for (int i=0; i < mPvsStatFrames; i++) {
449        float err;
450        RandomViewPoint();
451        if (mPvsErrorBuffer[i] > 0.0f) {
452          mPvsErrorBuffer[i] = GetPixelError();
453          cout<<"("<<i<<","<<mPvsErrorBuffer[i]<<")";
454          //      swapBuffers();
455        }
456       
457        err = mPvsErrorBuffer[i];
458       
459        if (err >= 0.0f) {
460          if (err > mPvsStat.maxError)
461                mPvsStat.maxError = err;
462          mPvsStat.sumError += err;
463          if (err == 0.0f)
464                mPvsStat.errorFreeFrames++;
465          mPvsStat.frames++;
466        }
467  }
468 
469  doneCurrent();
470
471  cout<<endl<<flush;
472  mRenderingFinished.wakeAll();
473}
474
475
476
477
478
479void
480GlRendererWidget::mousePressEvent(QMouseEvent *e)
481{
482  int x = e->pos().x();
483  int y = e->pos().y();
484
485  mousePoint.x = x;
486  mousePoint.y = y;
487 
488}
489
490void
491GlRendererWidget::mouseMoveEvent(QMouseEvent *e)
492{
493  float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
494  float TURN_SENSITIVITY=0.1f;
495  float TILT_SENSITIVITY=32.0 ;
496  float TURN_ANGLE= M_PI/36.0 ;
497
498  int x = e->pos().x();
499  int y = e->pos().y();
500 
501  if (e->modifiers() & Qt::ControlModifier) {
502        mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY/2.0;
503        mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY/2.0;
504  } else {
505        mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
506        float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
507        float angle = atan2(mViewDirection.x, mViewDirection.z);
508        mViewDirection.x = sin(angle+adiff);
509        mViewDirection.z = cos(angle+adiff);
510  }
511 
512  mousePoint.x = x;
513  mousePoint.y = y;
514 
515  updateGL();
516}
517
518void
519GlRendererWidget::mouseReleaseEvent(QMouseEvent *)
520{
521
522
523}
524
525void
526GlRendererWidget::resizeGL(int w, int h)
527{
528  SetupProjection(w, h);
529  updateGL();
530}
531
532void
533GlRendererWidget::paintGL()
534{
535        RenderErrors();
536       
537        mFrame++;
538}
539
540
541void
542GlRendererWidget::SetupCamera()
543{
544  if (!mTopView)
545        GlRenderer::SetupCamera();
546  else {
547        float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
548        Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
549                                                                                        -1,
550                                                                                        mViewDirection.y);
551       
552        Vector3 target = mViewPoint + dist*mViewDirection;
553        Vector3 up(0,1,0);
554       
555        glLoadIdentity();
556        gluLookAt(pos.x, pos.y, pos.z,
557                          target.x, target.y, target.z,
558                          up.x, up.y, up.z);
559  }
560
561}
562
563void
564GlRendererWidget::keyPressEvent ( QKeyEvent * e )
565{
566  switch (e->key()) {
567  case Qt::Key_T:
568        mTopView = !mTopView;
569        updateGL();
570        break;
571  default:
572        e->ignore();
573        break;
574  }
575 
576}
577
578
579void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
580                                                                                           Beam &beam,
581                                                                                           const int desiredSamples,
582                                                                                           BeamSampleStatistics &stat)
583{
584        // TODO: should be moved out of here (not to be done every time)
585        // only back faces are interesting for the depth pass
586        glShadeModel(GL_FLAT);
587        glDisable(GL_LIGHTING);
588
589        // needed to kill the fragments for the front buffer
590        glEnable(GL_ALPHA_TEST);
591        glAlphaFunc(GL_GREATER, 0);
592
593        // assumes that the beam is constructed and contains kd-tree nodes
594        // and viewcells which it intersects
595 
596 
597        // Get the number of viewpoints to be sampled
598        // Now it is a sqrt but in general a wiser decision could be made.
599        // The less viewpoints the better for rendering performance, since less passes
600        // over the beam is needed.
601        // The viewpoints could actually be generated outside of the bounding box which
602        // would distribute the 'efective viewpoints' of the object surface and thus
603        // with a few viewpoints better sample the viewpoint space....
604
605        //TODO: comment in
606        //int viewPointSamples = sqrt((float)desiredSamples);
607        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
608       
609        // the number of direction samples per pass is given by the number of viewpoints
610        int directionalSamples = desiredSamples / viewPointSamples;
611       
612        Debug << "directional samples: " << directionalSamples << endl;
613        for (int i = 0; i < viewPointSamples; ++ i)
614        {
615                Vector3 viewPoint = beam.mBox.GetRandomPoint();
616               
617                // perhaps the viewpoint should be shifted back a little bit so that it always lies
618                // inside the source object
619                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
620        // would require more complicated sampling (perhaps hierarchical rejection sampling of
621                // the object surface is an option here - only the mesh faces which are inside the box
622                // are considered as candidates)
623               
624                SampleViewpointContributions(sourceObject,
625                                                                         viewPoint,
626                                                                         beam,
627                                                                         directionalSamples,
628                                                                         stat);
629        }
630
631
632        // note:
633        // this routine would be called only if the number of desired samples is sufficiently
634        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
635        // distributing the work between cpu and gpu would also allow us to place more sophisticated
636        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
637        // in order that thios scheme is working well the gpu render buffer should run in a separate
638        // thread than the cpu sampler, which would not be such a big problem....
639
640        // disable alpha test again
641        glDisable(GL_ALPHA_TEST);
642}
643
644
645void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
646                                                                                                        const Vector3 viewPoint,
647                                                                                                        Beam &beam,
648                                                                                                        const int samples,
649                                                    BeamSampleStatistics &stat)
650{
651    // 1. setup the view port to match the desired samples
652        glViewport(0, 0, samples, samples);
653
654        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
655        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
656
657
658        // 3. reset z-buffer to 0 and render the source object for the beam
659        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
660        //    save result to the front depth map
661        //    the front depth map holds ray origins
662
663
664        // front depth buffer must be initialised to 0
665        float clearDepth;
666       
667        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
668        glClearDepth(0.0f);
669        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
670
671
672        //glFrontFace(GL_CW);
673        glEnable(GL_CULL_FACE);
674        glCullFace(GL_FRONT);
675        glColorMask(0, 0, 0, 0);
676       
677
678        // stencil is increased where the source object is located
679        glEnable(GL_STENCIL_TEST);     
680        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
681        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
682
683
684#if 0
685        static int glSourceObjList = -1;         
686        if (glSourceObjList != -1)
687        {
688                glSourceObjList = glGenLists(1);
689                glNewList(glSourceObjList, GL_COMPILE);
690
691                RenderIntersectable(sourceObject);
692       
693                glEndList();
694        }
695        glCallList(glSourceObjList);
696
697#else
698        RenderIntersectable(sourceObject);
699
700#endif 
701
702         // copy contents of the front depth buffer into depth texture
703        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
704        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
705
706
707        // reset clear function
708        glClearDepth(clearDepth);
709
710       
711       
712        // 4. set up the termination depth buffer (= standard depth buffer)
713        //    only rays which have non-zero entry in the origin buffer are valid since
714        //    they realy start on the object surface (this is tagged by setting a
715        //    stencil buffer bit at step 3).
716       
717        glStencilFunc(GL_EQUAL, 0x1, 0x1);
718        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
719
720        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
721        glDepthMask(1);
722
723        glEnable(GL_DEPTH_TEST);
724               
725        glEnable(GL_CULL_FACE);
726        glCullFace(GL_BACK);
727
728        // setup front depth buffer
729        glEnable(GL_TEXTURE_2D);
730       
731        // bind pixel shader implementing the front depth buffer functionality
732        cgGLBindProgram(sCgFragmentProgram);
733        cgGLEnableProfile(sCgFragmentProfile);
734
735
736        // 5. render all objects inside the beam
737        //    we can use id based false color to read them back for gaining the pvs
738
739        glColorMask(1, 1, 1, 1);
740
741       
742        // if objects not stored in beam => extract objects
743        if (beam.mFlags & !Beam::STORE_OBJECTS)
744        {
745                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
746
747                Intersectable::NewMail();
748                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
749                {
750                        mKdTree->CollectObjects(*it, beam.mObjects);
751                }
752        }
753
754
755        //    (objects can be compiled to a gl list now so that subsequent rendering for
756        //    this beam is fast - the same hold for step 3)
757        //    Afterwards we have two depth buffers defining the ray origin and termination
758       
759
760#if 0
761        static int glObjList = -1;
762        if (glObjList != -1)
763        {
764                glObjList = glGenLists(1);
765                glNewList(glObjList, GL_COMPILE);
766       
767                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
768                for (it = beam.mObjects.begin(); it != it_end; ++ it)
769                {
770                        // render all objects except the source object
771                        if (*it != sourceObject)
772                                RenderIntersectable(*it);
773                }
774               
775                glEndList();
776        }
777
778        glCallList(glObjList);
779#else
780        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
781        for (it = beam.mObjects.begin(); it != it_end; ++ it)
782        {       
783                // render all objects except the source object
784                if (*it != sourceObject)
785                        RenderIntersectable(*it);
786        }
787#endif
788       
789   
790
791        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
792        //     a fragment passes if the corresponding stencil fragment is set and its depth is
793        //     between origin and termination buffer
794
795        // create new queries if necessary
796        GenQueries((int)beam.mViewCells.size());
797
798        // check whether any backfacing polygon would pass the depth test?
799        // matt: should check both back /front facing because of dual depth buffer
800        // and danger of cutting the near plane with front facing polys.
801       
802        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
803        glDepthMask(GL_FALSE);
804        glDisable(GL_CULL_FACE);
805
806 
807        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
808
809        int queryIdx = 0;
810
811        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
812        {
813                glBeginOcclusionQueryNV(sQueries[queryIdx ++]);
814
815                RenderIntersectable(*vit);
816               
817                glEndOcclusionQueryNV();
818        }
819
820
821
822        // at this point, if possible, go and do some other computation
823
824
825       
826        // 7. The number of visible pixels is the number of sample rays which see the source
827        //    object from the corresponding viewcell -> remember these values for later update
828        //   of the viewcell pvs - or update immediately?
829
830        queryIdx = 0;
831        unsigned int pixelCount;
832
833        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
834        {
835                // fetch queries
836                glGetOcclusionQueryuivNV(sQueries[queryIdx ++],
837                                                                 GL_PIXEL_COUNT_NV,
838                                                                 &pixelCount);
839                if (pixelCount)
840                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
841        }
842       
843
844        // 8. Copmpute rendering statistics
845        // In general it is not neccessary to remember to extract all the rays cast. I hope it
846        // would be sufficient to gain only the intergral statistics about the new contributions
847        // and so the rss tree would actually store no new rays (only the initial ones)
848        // the subdivision of the tree would only be driven by the statistics (the glrender could
849        // evaluate the contribution entropy for example)
850        // However might be an option to extract/store only those the rays which made a contribution
851        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
852
853        ObjectContainer pvsObj;
854        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
855       
856        // to gain ray source and termination
857        // copy contents of ray termination buffer into depth texture
858        // and compare with ray source buffer
859#if 0
860        VssRayContainer rays;
861
862        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
863        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
864
865        ComputeRays(Intersectable *sourceObj, rays);
866
867#endif
868
869
870
871        //-- cleanup
872
873
874        // reset gl state
875        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
876        glDepthMask(GL_TRUE);
877        glEnable(GL_CULL_FACE);
878        glDisable(GL_STENCIL_TEST);
879        cgGLDisableProfile(sCgFragmentProfile);
880        glDisable(GL_TEXTURE_2D);
881
882        // remove objects from beam
883        if (beam.mFlags & !Beam::STORE_OBJECTS)
884                beam.mObjects.clear();
885}
886
887
888void GlRendererBuffer::GenQueries(const int numQueries)
889{
890        if ((int)sQueries.size() < numQueries)
891        {
892                const int n = numQueries - (int)sQueries.size();
893                unsigned int *newQueries = new unsigned int[n];
894
895                glGenOcclusionQueriesNV(n, (unsigned int *)newQueries);
896
897                for (int i = 0; i < n; ++ i)
898                {
899                        sQueries.push_back(newQueries[i]);
900                }
901
902                delete [] newQueries;
903        }
904}
905
906
907void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
908                                                                                                   const Beam &beam,
909                                                                                                   Intersectable *sourceObject)
910{
911        float left, right, bottom, top, znear, zfar;
912
913        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
914                                                                   mSceneGraph->GetBox());
915
916        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
917        glMatrixMode(GL_PROJECTION);
918        glLoadIdentity();
919        glFrustum(left, right, bottom, top, znear, zfar);
920        //glFrustum(-1, 1, -1, 1, 1, 20000);
921
922    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3;
923        const Vector3 up =
924                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
925
926#ifdef _DEBUG
927        Debug << "view point: " << viewPoint << endl;
928        Debug << "eye: " << center << endl;
929        Debug << "up: " << up << endl;
930#endif
931
932        glMatrixMode(GL_MODELVIEW);
933        glLoadIdentity();
934        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
935                          center.x, center.y, center.z,                   
936                          up.x, up.y, up.z);
937}               
938
939 
940void GlRendererBuffer::InitGL()
941{
942        GlRenderer::InitGL();
943        // initialise dual depth buffer textures
944        glGenTextures(1, &frontDepthMap);
945        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
946       
947        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
948                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
949        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
950        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
951        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
952        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
953
954        glGenTextures(1, &backDepthMap);
955        glBindTexture(GL_TEXTURE_2D, backDepthMap);
956       
957        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
958                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
959        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
960        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
961        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
962        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
963
964        // cg initialization
965        cgSetErrorCallback(handleCgError);
966        sCgContext = cgCreateContext();
967       
968        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
969                sCgFragmentProfile = CG_PROFILE_ARBFP1;
970        else
971        {
972          // try FP30
973          if (cgGLIsProfileSupported(CG_PROFILE_FP30))
974            sCgFragmentProfile = CG_PROFILE_FP30;
975          else
976          {
977                  Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
978                  exit(1);
979          }
980  }
981
982  sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,             
983                                                                                           CG_SOURCE, "../src/dual_depth.cg",
984                                                                                           sCgFragmentProfile,
985                                                                                           NULL,
986                                                                                           NULL);
987
988  if (!cgIsProgramCompiled(sCgFragmentProgram))
989          cgCompileProgram(sCgFragmentProgram);
990
991  cgGLLoadProgram(sCgFragmentProgram);
992  cgGLBindProgram(sCgFragmentProgram);
993 
994  Debug << "---- PROGRAM BEGIN ----\n" <<
995          cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
996}
997
998
999void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
1000{
1001        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
1002        {
1003                //todo glGetTexImage()
1004        }
1005}
1006
1007
1008
1009inline bool ilt(Intersectable *obj1, Intersectable *obj2)
1010{
1011        return obj1->mId < obj2->mId;
1012}
1013
1014
1015int GlRendererBuffer::ComputePvs(ObjectContainer &objects,
1016                                                                 ObjectContainer &pvs) const
1017{
1018        int pvsSize = 0;
1019        QImage image = toImage();
1020        Intersectable::NewMail();
1021
1022        std::stable_sort(objects.begin(), objects.end(), ilt);
1023
1024        MeshInstance dummy(NULL);
1025
1026        Intersectable *obj = NULL;
1027                       
1028        for (int x = 0; x < image.width(); ++ x)
1029        {
1030                for (int y = 0; y < image.height(); ++ y)
1031                {
1032                        QRgb pix = image.pixel(x, y);
1033                        const int id = GetId(qRed(pix), qGreen(pix), qBlue(pix));
1034
1035                        dummy.SetId(id);
1036
1037                        ObjectContainer::iterator oit =
1038                                lower_bound(objects.begin(), objects.end(), &dummy, ilt);
1039                       
1040                       
1041                        if (//(oit != oit.end()) &&
1042                                ((*oit)->GetId() == id) &&
1043                                !obj->Mailed())
1044                        {
1045                                obj = *oit;
1046                                obj->Mail();
1047                                ++ pvsSize;
1048                                pvs.push_back(obj);
1049                        }
1050                }
1051        }
1052
1053        return pvsSize;
1054}
1055
1056/***********************************************************************/
1057/*                     GlDebuggerWidget implementation                             */
1058/***********************************************************************/
1059
1060
1061GlDebuggerWidget::GlDebuggerWidget(GlRendererBuffer *buf, QWidget *parent)
1062      : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
1063{
1064        // create the pbuffer
1065    //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
1066    timerId = startTimer(20);
1067    setWindowTitle(("OpenGL pbuffers"));
1068}
1069
1070
1071GlDebuggerWidget::~GlDebuggerWidget()
1072{
1073        mRenderBuffer->releaseFromDynamicTexture();
1074        glDeleteTextures(1, &dynamicTexture);
1075       
1076        DEL_PTR(mRenderBuffer);
1077}
1078
1079
1080void GlDebuggerWidget::initializeGL()
1081{
1082        glMatrixMode(GL_PROJECTION);
1083        glLoadIdentity();
1084
1085        glFrustum(-1, 1, -1, 1, 10, 100);
1086        glTranslatef(-0.5f, -0.5f, -0.5f);
1087        glTranslatef(0.0f, 0.0f, -15.0f);
1088        glMatrixMode(GL_MODELVIEW);
1089
1090        glEnable(GL_CULL_FACE);
1091        initCommon();
1092        initPbuffer();
1093
1094}
1095
1096
1097void GlDebuggerWidget::resizeGL(int w, int h)
1098{
1099        glViewport(0, 0, w, h);
1100}
1101
1102
1103void GlDebuggerWidget::paintGL()
1104{
1105        // draw a spinning cube into the pbuffer..
1106        mRenderBuffer->makeCurrent();
1107       
1108        BeamSampleStatistics stats;
1109        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
1110
1111        glFlush();
1112
1113        // rendering directly to a texture is not supported on X11, unfortunately
1114    mRenderBuffer->updateDynamicTexture(dynamicTexture);
1115   
1116    // and use the pbuffer contents as a texture when rendering the
1117    // background and the bouncing cubes
1118    makeCurrent();
1119    glBindTexture(GL_TEXTURE_2D, dynamicTexture);
1120    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1121
1122    // draw the background
1123    glMatrixMode(GL_MODELVIEW);
1124    glPushMatrix();
1125    glLoadIdentity();
1126    glMatrixMode(GL_PROJECTION);
1127    glPushMatrix();
1128    glLoadIdentity();
1129
1130        glPopMatrix();
1131        glMatrixMode(GL_MODELVIEW);
1132        glPopMatrix();
1133}
1134
1135
1136void GlDebuggerWidget::initPbuffer()
1137{
1138        // set up the pbuffer context
1139    mRenderBuffer->makeCurrent();
1140        /*mRenderBuffer->InitGL();
1141
1142        glViewport(0, 0, mRenderBuffer->size().width(), mRenderBuffer->size().height());
1143        glMatrixMode(GL_PROJECTION);
1144        glLoadIdentity();
1145        glOrtho(-1, 1, -1, 1, -99, 99);
1146        glTranslatef(-0.5f, -0.5f, 0.0f);
1147        glMatrixMode(GL_MODELVIEW);
1148        glLoadIdentity();
1149
1150        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);*/
1151       
1152        // generate a texture that has the same size/format as the pbuffer
1153    dynamicTexture = mRenderBuffer->generateDynamicTexture();
1154
1155        // bind the dynamic texture to the pbuffer - this is a no-op under X11
1156        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
1157        makeCurrent();
1158}
1159
1160void GlDebuggerWidget::initCommon()
1161{
1162        glEnable(GL_TEXTURE_2D);
1163        glEnable(GL_DEPTH_TEST);
1164
1165        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
1166}
Note: See TracBrowser for help on using the repository browser.