source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/chcdemo.cpp @ 2881

Revision 2881, 41.1 KB checked in by mattausch, 16 years ago (diff)

working quite well

Line 
1// occquery.cpp : Defines the entry point for the console application.
2//
3#include "glInterface.h"
4#include <math.h>
5#include <time.h>
6#include "common.h"
7#include "RenderTraverser.h"
8#include "SceneEntity.h"
9#include "Vector3.h"
10#include "Matrix4x4.h"
11#include "ResourceManager.h"
12#include "Bvh.h"
13#include "Camera.h"
14#include "Geometry.h"
15#include "BvhLoader.h"
16#include "FrustumCullingTraverser.h"
17#include "StopAndWaitTraverser.h"
18#include "CHCTraverser.h"
19#include "CHCPlusPlusTraverser.h"
20#include "Visualization.h"
21#include "RenderState.h"
22#include "Timer/PerfTimer.h"
23#include "SceneQuery.h"
24#include "RenderQueue.h"
25#include "Material.h"
26#include <Cg/cg.h>
27#include <Cg/cgGL.h>
28#include "glfont2.h"
29#include "PerformanceGraph.h"
30#include "Environment.h"
31#include "Halton.h"
32#include "Transform3.h"
33#include "SampleGenerator.h"
34#include "FrameBufferObject.h"
35#include "SsaoShader.h"
36#include "DeferredShader.h"
37
38
39using namespace std;
40using namespace CHCDemoEngine;
41
42
43static Environment env;
44
45
46/////////////
47//-- fbos
48
49FrameBufferObject *fbo = NULL;
50
51bool isFirstTexture = true;
52
53GLuint fontTex;
54
55/// the renderable scene geometry
56SceneEntityContainer sceneEntities;
57// traverses and renders the hierarchy
58RenderTraverser *traverser = NULL;
59/// the hierarchy
60Bvh *bvh = NULL;
61/// handles scene loading
62ResourceManager *loader = NULL;
63/// the scene camera
64Camera *camera = NULL;
65/// the scene camera
66Camera *visCamera = NULL;
67/// the visualization
68Visualization *visualization = NULL;
69/// the current render state
70RenderState state;
71/// the rendering algorithm
72int renderMode = RenderTraverser::CHCPLUSPLUS;
73// eye near plane distance
74float nearDist = 0.2f;
75/// the field of view
76float fov = 50.0f;
77/// the pixel threshold where a node is still considered invisible
78int threshold;
79
80int assumedVisibleFrames = 10;
81int maxBatchSize = 50;
82
83int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
84
85SceneQuery *sceneQuery = NULL;
86RenderQueue *renderQueue = NULL;
87
88/// these values get scaled with the frame rate
89static float keyForwardMotion = 30.0f;
90static float keyRotation = 1.5f;
91
92/// elapsed time in milliseconds
93double elapsedTime = 1000.0f;
94double algTime = 1000.0f;
95
96static int winWidth = 1024;
97static int winHeight = 768;
98static float winAspectRatio = 1.0f;
99
100double accumulatedTime = 1000;
101float fps = 1e3f;
102
103float myfar = 0;
104
105glfont::GLFont myfont;
106
107// rendertexture
108static int texWidth = 1024;
109static int texHeight = 768;
110
111//static int texWidth = 512;
112//static int texHeight = 384;
113
114//static int texWidth = 2048;
115//static int texHeight = 2048;
116
117int renderedObjects = 0;
118int renderedNodes = 0;
119int renderedTriangles = 0;
120
121int issuedQueries = 0;
122int traversedNodes = 0;
123int frustumCulledNodes = 0;
124int queryCulledNodes = 0;
125int stateChanges = 0;
126int numBatches = 0;
127
128bool showHelp = false;
129bool showStatistics = false;
130bool showOptions = true;
131bool showBoundingVolumes = false;
132bool visMode = false;
133
134// mouse navigation state
135int xEyeBegin = 0;
136int yEyeBegin = 0;
137int yMotionBegin = 0;
138int verticalMotionBegin = 0;
139int horizontalMotionBegin = 0;
140
141bool useOptimization = false;
142bool useTightBounds = true;
143bool useRenderQueue = true;
144bool useMultiQueries = true;
145bool flyMode = true;
146
147SceneEntityContainer skyGeometry;
148
149bool leftKeyPressed = false;
150bool rightKeyPressed = false;
151bool upKeyPressed = false;
152bool downKeyPressed = false;
153bool descendKeyPressed = false;
154bool ascendKeyPressed = false;
155
156bool useGlobIllum = false;
157bool useSsao = false;
158bool useTemporalCoherence = true;
159
160static float ssaoExpFactor = 0.1f;
161
162bool showAlgorithmTime = false;
163
164GLubyte *randomNormals = NULL;
165
166PerfTimer frameTimer, algTimer;
167
168int renderType = RenderState::FIXED;
169
170PerformanceGraph *perfGraph = NULL;
171
172bool useFullScreen = false;
173
174bool useLODs = true;
175
176
177static Matrix4x4 matProjectionView = IdentityMatrix();
178
179
180
181// function forward declarations
182void InitExtensions();
183void DisplayVisualization();
184void InitGLstate();
185void InitRenderTexture();
186void InitCg();
187void CleanUp();
188void SetupEyeView();
189void UpdateEyeMtx();
190void SetupLighting();
191void DisplayStats();
192void Output(int x, int y, const char *string);
193void DrawHelpMessage();
194void RenderSky();
195void RenderVisibleObjects();
196
197void Begin2D();
198void End2D();
199void KeyBoard(unsigned char c, int x, int y);
200void DrawStatistics();
201void Display();
202void Special(int c, int x, int y);
203void KeyUp(unsigned char c, int x, int y);
204void SpecialKeyUp(int c, int x, int y);
205void Reshape(int w, int h);
206void Mouse(int button, int state, int x, int y);
207void LeftMotion(int x, int y);
208void RightMotion(int x, int y);
209void MiddleMotion(int x, int y);
210void CalcDecimalPoint(string &str, int d);
211void ResetTraverser();
212
213void KeyHorizontalMotion(float shift);
214void KeyVerticalMotion(float shift);
215
216void PlaceViewer(const Vector3 &oldPos);
217
218
219inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
220inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
221
222void InitFBO();
223
224SsaoShader *ssaoShader = NULL;
225DeferredShader *deferredShader = NULL;
226
227static GLenum mrt[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
228
229
230/////////
231//-- cg stuff
232
233static CGcontext sCgContext = NULL;
234static CGprogram sCgMrtVertexProgram = NULL;
235
236static CGparameter sModelViewProjMatrixParam;
237static CGparameter sMaxDepthParam;
238static CGparameter sMaxDepthParamTex;
239
240static Matrix4x4 oldViewProjMatrix;
241
242
243static void cgErrorCallback()
244{
245        CGerror lastError = cgGetError();
246
247        if(lastError)
248        {
249                printf("%s\n\n", cgGetErrorString(lastError));
250                printf("%s\n", cgGetLastListing(sCgContext));
251               
252                printf("Cg error, exiting...\n");
253
254                exit(0);
255        }
256}
257
258
259static void PrintGLerror(char *msg)
260{
261        GLenum errCode;
262        const GLubyte *errStr;
263       
264        if ((errCode = glGetError()) != GL_NO_ERROR)
265        {
266                errStr = gluErrorString(errCode);
267                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
268        }
269}
270
271
272int main(int argc, char* argv[])
273{
274        int returnCode = 0;
275
276        Vector3 camPos(.0f, .0f, .0f);
277        Vector3 camDir(.0f, 1.0f, .0f);
278
279        cout << "=== reading environment file ===" << endl << endl;
280
281        string envFileName = "default.env";
282        if (!env.Read(envFileName))
283        {
284                cerr << "loading environment " << envFileName << " failed!" << endl;
285        }
286        else
287        {
288                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
289                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
290                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
291
292                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
293                env.GetFloatParam(string("keyRotation"), keyRotation);
294
295                env.GetIntParam(string("winWidth"), winWidth);
296                env.GetIntParam(string("winHeight"), winHeight);
297
298                env.GetBoolParam(string("useFullScreen"), useFullScreen);
299                env.GetFloatParam(string("expFactor"), ssaoExpFactor);
300                env.GetVectorParam(string("camPosition"), camPos);
301                env.GetVectorParam(string("camDirection"), camDir);
302
303                env.GetBoolParam(string("useLODs"), useLODs);
304
305                //env.GetStringParam(string("modelPath"), model_path);
306                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
307
308
309                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
310                cout << "maxBatchSize: " << maxBatchSize << endl;
311                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
312
313                cout << "keyForwardMotion: " << keyForwardMotion << endl;
314                cout << "keyRotation: " << keyRotation << endl;
315                cout << "winWidth: " << winWidth << endl;
316                cout << "winHeight: " << winHeight << endl;
317                cout << "useFullScreen: " << useFullScreen << endl;
318                cout << "useLODs: " << useLODs << endl;
319                cout << "camPosition: " << camPos << endl;
320                cout << "expFactor: " << ssaoExpFactor << endl;
321
322                //cout << "model path: " << model_path << endl;
323
324                cout << "**** end parameters ****" << endl << endl;
325        }
326
327        ///////////////////////////
328
329        camera = new Camera(winWidth, winHeight, fov);
330        camera->SetNear(nearDist);
331       
332        camera->SetDirection(camDir);
333        camera->SetPosition(camPos);
334
335        visCamera = new Camera(winWidth, winHeight, fov);
336
337        visCamera->SetNear(0.0f);
338        visCamera->Yaw(.5 * M_PI);
339
340        renderQueue = new RenderQueue(&state, camera);
341
342        glutInitWindowSize(winWidth, winHeight);
343        glutInit(&argc, argv);
344        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
345        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
346        //glutInitDisplayString("samples=2");
347
348        SceneEntity::SetUseLODs(useLODs);
349
350
351        if (!useFullScreen)
352        {
353                glutCreateWindow("FriendlyCulling");
354        }
355        else
356        {
357                glutGameModeString( "1024x768:32@75" );
358                glutEnterGameMode();
359        }
360
361        glutDisplayFunc(Display);
362        glutKeyboardFunc(KeyBoard);
363        glutSpecialFunc(Special);
364        glutReshapeFunc(Reshape);
365        glutMouseFunc(Mouse);
366        glutIdleFunc(Display);
367        glutKeyboardUpFunc(KeyUp);
368        glutSpecialUpFunc(SpecialKeyUp);
369        glutIgnoreKeyRepeat(true);
370
371        // initialise gl graphics
372        InitExtensions();
373        InitGLstate();
374
375        glEnable(GL_MULTISAMPLE_ARB);
376        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
377
378        LeftMotion(0, 0);
379        MiddleMotion(0, 0);
380
381        perfGraph = new PerformanceGraph(1000);
382
383        loader = new ResourceManager();
384
385        //const string filename("data/city/model/city.dem");
386        const string filename = string(model_path + "city.dem");
387
388        if (loader->Load(filename, sceneEntities))
389                cout << "scene " << filename << " loaded" << endl;
390        else
391        {
392                cerr << "loading scene " << filename << " failed" << endl;
393                CleanUp();
394                exit(0);
395        }
396
397        SceneEntityContainer dummy;
398
399        const string envname = string(model_path + "env.dem");
400
401        if (loader->Load(envname, skyGeometry))
402                cout << "sky box " << filename << " loaded" << endl;
403        else
404        {
405                cerr << "loading sky box " << filename << " failed" << endl;
406                CleanUp();
407                exit(0);
408        }
409
410        const string bvh_filename = string(model_path + "city.bvh");
411        BvhLoader bvhLoader;
412        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
413
414        if (!bvh)
415        {
416                cerr << "loading bvh " << bvh_filename << " failed" << endl;
417                CleanUp();
418                exit(0);
419        }
420
421        // set far plane based on scene extent
422        myfar = 10.0f * Magnitude(bvh->GetBox().Diagonal());
423        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
424
425        bvh->SetCamera(camera);
426       
427        InitCg();
428
429        DeferredShader::Init(sCgContext);
430        SsaoShader::Init(sCgContext);
431
432        //deferredShader = new DeferredShader(texWidth, texHeight);
433        //ssaoShader = new SsaoShader(texWidth, texHeight, camera, myfar / 10.0f);
434
435        // initialize the render traverser
436        ResetTraverser();
437
438        visualization = new Visualization(bvh, camera, NULL, &state);
439
440        sceneQuery = new SceneQuery(bvh->GetBox(), traverser);
441
442        // frame time is restarted every frame
443        frameTimer.Start();
444
445        // the rendering loop
446        glutMainLoop();
447
448        // clean up
449        CleanUp();
450
451        return 0;
452}
453
454
455void InitCg(void)
456{
457        // Setup Cg
458        cgSetErrorCallback(cgErrorCallback);
459
460        // Create cgContext.
461        sCgContext = cgCreateContext();
462
463        // get the best profile for this hardware
464        RenderState::sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
465        cgGLSetOptimalOptions(RenderState::sCgFragmentProfile);
466
467        RenderState::sCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
468        cgGLSetOptimalOptions(RenderState::sCgVertexProfile);
469
470        sCgMrtVertexProgram =
471                cgCreateProgramFromFile(sCgContext,
472                                                                CG_SOURCE,
473                                                                "src/shaders/mrt.cg",
474                                                                RenderState::sCgVertexProfile,
475                                                                "vtx",
476                                                                NULL);
477
478        if (sCgMrtVertexProgram != NULL)
479        {
480                cgGLLoadProgram(sCgMrtVertexProgram);
481
482                Transform3::sModelMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelMatrix");
483                sModelViewProjMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelViewProj");
484        }
485
486        RenderState::sCgMrtFragmentTexProgram =
487                cgCreateProgramFromFile(sCgContext,
488                                                                CG_SOURCE,
489                                                                "src/shaders/mrt.cg",
490                                                                RenderState::sCgFragmentProfile,
491                                                                "fragtex",
492                                                                NULL);
493
494        if (RenderState::sCgMrtFragmentTexProgram != NULL)
495        {
496                cgGLLoadProgram(RenderState::sCgMrtFragmentTexProgram);
497
498                sMaxDepthParamTex = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "maxDepth");
499                Material::sDiffuseTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "diffuse");
500                Material::sAmbientTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "ambient");
501
502                cgGLSetParameter1f(sMaxDepthParamTex, 10.0f / myfar);
503                Debug << "maxdepth: " << 10.0f / myfar << endl;
504        }
505        else
506                cerr << "fragment tex program failed to load" << endl;
507
508        RenderState::sCgMrtFragmentProgram =
509                cgCreateProgramFromFile(sCgContext,
510                                                                CG_SOURCE,
511                                                                "src/shaders/mrt.cg",
512                                                                RenderState::sCgFragmentProfile,
513                                                                "frag",
514                                                                NULL);
515
516        if (RenderState::sCgMrtFragmentProgram != NULL)
517        {
518                cgGLLoadProgram(RenderState::sCgMrtFragmentProgram);
519
520                sMaxDepthParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "maxDepth");
521                Material::sDiffuseParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "diffuse");
522                Material::sAmbientParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "ambient");
523
524                cgGLSetParameter1f(sMaxDepthParam, 10.0f / myfar);
525        }
526        else
527                cerr << "fragment program failed to load" << endl;
528
529        PrintGLerror("init");
530
531        cout << "cg initialization successful" << endl;
532}
533
534
535void InitFBO()
536{
537        // this fbo basicly stores the scene information we get from standard rendering of a frame
538        // we store colors, normals, positions (for the ssao)
539        fbo = new FrameBufferObject(texWidth, texHeight, FrameBufferObject::DEPTH_24);
540
541        // the diffuse color buffer
542        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
543        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
544
545        // the positions buffer
546        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
547        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
548       
549        // the normals buffer
550        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
551        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
552
553        // another color buffer
554        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
555
556        PrintGLerror("fbo");
557}
558
559
560bool InitFont(void)
561{
562        glEnable(GL_TEXTURE_2D);
563
564        glGenTextures(1, &fontTex);
565        glBindTexture(GL_TEXTURE_2D, fontTex);
566        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
567                return false;
568
569        glDisable(GL_TEXTURE_2D);
570       
571        return true;
572}
573
574
575void InitGLstate()
576{
577        glClearColor(0.0f, 0.0, 0.2f, 0.0f);
578       
579        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
580        glPixelStorei(GL_PACK_ALIGNMENT,1);
581       
582        glDepthFunc(GL_LESS);
583        glEnable(GL_DEPTH_TEST);
584
585        SetupLighting();
586
587        glColor3f(1.0f, 1.0f, 1.0f);
588        glShadeModel(GL_SMOOTH);
589       
590        glMaterialf(GL_FRONT, GL_SHININESS, 64);
591        glEnable(GL_NORMALIZE);
592               
593        //glEnable(GL_ALPHA_TEST);
594        glDisable(GL_ALPHA_TEST);
595        glAlphaFunc(GL_GEQUAL, 0.8f);
596
597        glFrontFace(GL_CCW);
598        glCullFace(GL_BACK);
599        glEnable(GL_CULL_FACE);
600
601        //glDisable(GL_CULL_FACE);
602        glDisable(GL_TEXTURE_2D);
603
604        GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
605        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
606        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
607
608        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
609        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
610        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
611
612        glDepthFunc(GL_LESS);
613
614        if (!InitFont())
615                cerr << "font creation failed" << endl;
616        else
617                cout << "successfully created font" << endl;
618}
619
620
621void DrawHelpMessage()
622{
623        const char *message[] =
624        {
625                "Help information",
626                "",
627                "'F1'           - shows/dismisses this message",
628                "'F2'           - shows/hides bird eye view",
629                "'F3'           - shows/hides bounds (boxes or tight bounds)",
630                "'F4',          - shows/hides parameters",
631                "'F5'           - shows/hides statistics",
632                "'F6',          - toggles between fly/walkmode",
633                "'F7',          - cycles throw render modes",
634                "'F8',          - enables/disables ambient occlusion (only deferred)",
635                "'F9',          - shows pure algorithm render time (using glFinish)",
636                "'SPACE'        - cycles through occlusion culling algorithms",
637                "",
638                "'MOUSE LEFT'        - turn left/right, move forward/backward",
639                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
640                "'MOUSE MIDDLE'      - move up/down, left/right",
641                "'CURSOR UP/DOWN'    - move forward/backward",
642                "'CURSOR LEFT/RIGHT' - turn left/right",
643                "",
644                "'-'/'+'        - decreases/increases max batch size",
645                "'1'/'2'        - downward/upward motion",
646                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
647                "'5'/'6'        - decreases/increases assumed visible frames",
648                "",
649                "'R'            - use render queue",
650                "'B'            - use tight bounds",
651                "'M'            - use multiqueries",
652                "'O'            - use CHC optimization (geometry queries for leaves)",
653                0,
654        };
655       
656       
657        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
658
659        glRecti(30, 30, winWidth - 30, winHeight - 30);
660
661        glEnd();
662
663        glColor3f(1.0f, 1.0f, 1.0f);
664       
665        glEnable(GL_TEXTURE_2D);
666        myfont.Begin();
667
668        int x = 40, y = 30;
669
670        for(int i = 0; message[i] != 0; ++ i)
671        {
672                if(message[i][0] == '\0')
673                {
674                        y += 15;
675                }
676                else
677                {
678                        myfont.DrawString(message[i], x, winHeight - y);
679                        y += 25;
680                }
681        }
682        glDisable(GL_TEXTURE_2D);
683}
684
685
686void ResetTraverser()
687{
688        DEL_PTR(traverser);
689
690        bvh->ResetNodeClassifications();
691
692        switch (renderMode)
693        {
694        case RenderTraverser::CULL_FRUSTUM:
695                traverser = new FrustumCullingTraverser();
696                break;
697        case RenderTraverser::STOP_AND_WAIT:
698                traverser = new StopAndWaitTraverser();
699                break;
700        case RenderTraverser::CHC:
701                traverser = new CHCTraverser();
702                break;
703        case RenderTraverser::CHCPLUSPLUS:
704                traverser = new CHCPlusPlusTraverser();
705                break;
706       
707        default:
708                traverser = new FrustumCullingTraverser();
709        }
710
711        traverser->SetCamera(camera);
712        traverser->SetHierarchy(bvh);
713        traverser->SetRenderQueue(renderQueue);
714        traverser->SetRenderState(&state);
715        traverser->SetUseOptimization(useOptimization);
716        traverser->SetUseRenderQueue(useRenderQueue);
717        traverser->SetVisibilityThreshold(threshold);
718        traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
719        traverser->SetMaxBatchSize(maxBatchSize);
720        traverser->SetUseMultiQueries(useMultiQueries);
721        traverser->SetUseTightBounds(useTightBounds);
722        traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
723        traverser->SetRenderQueue(renderQueue);
724}
725
726
727void SetupLighting()
728{
729        glEnable(GL_LIGHTING);
730        glEnable(GL_LIGHT0);
731        glEnable(GL_LIGHT1);
732       
733        GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0};
734        GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
735        GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
736           
737        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
738
739        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
740        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
741        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
742
743
744        ////////////
745        //-- second light
746
747        GLfloat ambient1[] = {0.2, 0.2, 0.2, 1.0};
748        GLfloat diffuse1[] = {1.0, 1.0, 1.0, 1.0};
749        //GLfloat diffuse1[] = {0.5, 0.5, 0.5, 1.0};
750        GLfloat specular1[] = {0.0, 0.0, 0.0, 1.0};
751
752        glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
753        glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
754        glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
755
756       
757        //////////////////////////////
758
759        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
760        glLightfv(GL_LIGHT0, GL_POSITION, position);
761
762        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
763        glLightfv(GL_LIGHT1, GL_POSITION, position1);
764
765        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
766        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
767        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
768}
769
770
771void SetupEyeView()
772{
773        // store matrix of last frame
774        oldViewProjMatrix = matProjectionView;
775
776        glMatrixMode(GL_PROJECTION);
777        glLoadIdentity();
778
779        gluPerspective(fov, winAspectRatio, nearDist, myfar);
780
781        glMatrixMode(GL_MODELVIEW);
782        glLoadIdentity();
783
784        // set up the camera view
785        camera->SetupCameraView();
786
787        // set lights
788        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
789        glLightfv(GL_LIGHT0, GL_POSITION, position);
790
791        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
792        glLightfv(GL_LIGHT1, GL_POSITION, position1);
793
794       
795        /////////////////
796
797        Matrix4x4 matViewing, matProjection;
798
799        camera->GetModelViewMatrix(matViewing);
800        camera->GetProjectionMatrix(matProjection);
801
802        // store matrix for later use
803        matProjectionView = matViewing * matProjection;
804       
805        if (renderType == RenderState::DEFERRED)
806        {
807                // set modelview matrix for shaders
808                cgGLSetStateMatrixParameter(sModelViewProjMatrixParam,
809                                                                        CG_GL_MODELVIEW_PROJECTION_MATRIX,
810                                                                        CG_GL_MATRIX_IDENTITY);
811
812                static Matrix4x4 identity = IdentityMatrix();
813                cgGLSetMatrixParameterfc(Transform3::sModelMatrixParam, (const float *)identity.x);
814        }               
815}
816
817
818void KeyHorizontalMotion(float shift)
819{
820        Vector3 hvec = camera->GetDirection();
821        hvec.z = 0;
822
823        Vector3 pos = camera->GetPosition();
824        pos += hvec * shift;
825       
826        camera->SetPosition(pos);
827}
828
829
830void KeyVerticalMotion(float shift)
831{
832        Vector3 uvec = Vector3(0, 0, shift);
833
834        Vector3 pos = camera->GetPosition();
835        pos += uvec;
836       
837        camera->SetPosition(pos);
838}
839
840
841// the main rendering loop
842void Display()
843{       
844        Vector3 oldPos = camera->GetPosition();
845
846        if (leftKeyPressed)
847                camera->Pitch(KeyRotationAngle());
848        if (rightKeyPressed)
849                camera->Pitch(-KeyRotationAngle());
850        if (upKeyPressed)
851                KeyHorizontalMotion(KeyShift());
852        if (downKeyPressed)
853                KeyHorizontalMotion(-KeyShift());
854        if (ascendKeyPressed)
855                KeyVerticalMotion(KeyShift());
856        if (descendKeyPressed)
857                KeyVerticalMotion(-KeyShift());
858
859        // place view on ground
860        if (!flyMode) PlaceViewer(oldPos);
861
862        if (showAlgorithmTime)
863        {
864                glFinish();
865                algTimer.Start();
866        }
867       
868        // render without shading
869        switch (renderType)
870        {
871        case RenderState::FIXED:
872       
873                glEnable(GL_MULTISAMPLE_ARB);
874               
875                state.SetRenderType(RenderState::FIXED);
876                glEnable(GL_LIGHTING);
877
878                cgGLDisableProfile(RenderState::sCgFragmentProfile);
879                cgGLDisableProfile(RenderState::sCgVertexProfile);
880
881                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
882
883                break;
884
885        case RenderState::DEPTH_PASS:
886
887                glEnable(GL_MULTISAMPLE_ARB);
888               
889                cgGLDisableProfile(RenderState::sCgFragmentProfile);
890                cgGLDisableProfile(RenderState::sCgVertexProfile);
891
892                state.SetRenderType(RenderState::DEPTH_PASS);
893
894                // the scene is rendered withouth any shading   
895                glDisable(GL_LIGHTING);
896       
897                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
898
899                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
900
901                break;
902       
903        case RenderState::DEFERRED:
904
905                if (!fbo) InitFBO();
906
907                // multisampling does not work with deferred shading
908                glDisable(GL_MULTISAMPLE_ARB);
909
910                state.SetRenderType(RenderState::DEFERRED);
911
912                fbo->Bind();
913       
914                glPushAttrib(GL_VIEWPORT_BIT);
915                glViewport(0, 0, texWidth, texHeight);
916
917                cgGLEnableProfile(RenderState::sCgFragmentProfile);
918                cgGLBindProgram(RenderState::sCgMrtFragmentProgram);
919
920                cgGLEnableProfile(RenderState::sCgVertexProfile);
921                cgGLBindProgram(sCgMrtVertexProgram);
922
923                /// draw to 3 color buffers
924                glDrawBuffers(3, mrt);
925
926                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
927
928                break;
929        }
930
931
932        glDepthFunc(GL_LESS);
933
934        glDisable(GL_TEXTURE_2D);
935        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
936               
937
938        // reset lod levels for current frame
939        LODLevel::InitFrame(camera->GetPosition());
940
941
942        // bring eye modelview matrix up-to-date
943        SetupEyeView();
944
945        // actually render the scene geometry using one of the specified algorithms
946        traverser->RenderScene();
947
948
949
950        /////////
951        //-- do the rest of the rendering
952
953        glEnableClientState(GL_VERTEX_ARRAY);
954        glEnableClientState(GL_NORMAL_ARRAY);
955
956
957        // reset depth pass and render visible objects
958        if (renderType == RenderState::DEPTH_PASS)
959        {
960                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
961                RenderVisibleObjects();
962        }
963       
964
965        ///////////////
966        //-- render sky
967
968        RenderSky();
969
970        state.Reset();
971
972        glDisableClientState(GL_VERTEX_ARRAY);
973        glDisableClientState(GL_NORMAL_ARRAY);
974
975
976        if (renderType == RenderState::DEFERRED)
977        {
978                FrameBufferObject::Release();
979
980                cgGLDisableProfile(RenderState::sCgVertexProfile);
981                cgGLDisableProfile(RenderState::sCgFragmentProfile);
982
983                if (useSsao)
984                {
985                        if (!ssaoShader) ssaoShader = new SsaoShader(texWidth, texHeight, camera, myfar / 10.0f);
986                        //DEL_PTR(deferredShader);
987                        ssaoShader->Render(fbo, oldViewProjMatrix, ssaoExpFactor);
988
989                }
990                else
991                {
992                        if (!deferredShader) deferredShader = new DeferredShader(texWidth, texHeight);
993                        //DEL_PTR(ssaoShader);
994                        deferredShader->Render(fbo);
995                }
996        }
997        else
998        {
999                /*DEL_PTR(fbo);
1000                DEL_PTR(ssaoShader);
1001                DEL_PTR(deferredShader);
1002                */
1003        }
1004       
1005        ///////////
1006
1007        state.SetRenderType(RenderState::FIXED);
1008
1009        if (showAlgorithmTime)
1010        {
1011                glFinish();
1012
1013                algTime = algTimer.Elapsedms();
1014                perfGraph->AddData(algTime);
1015
1016                perfGraph->Draw();
1017        }
1018        else
1019        {
1020                if (visMode) DisplayVisualization();
1021        }
1022
1023        //glFlush();
1024
1025        const bool restart = true;
1026        elapsedTime = frameTimer.Elapsedms(restart);
1027
1028        DisplayStats();
1029
1030        // flip textures for temporal smoothing
1031        isFirstTexture = !isFirstTexture;
1032
1033        glutSwapBuffers();
1034}
1035
1036
1037#pragma warning( disable : 4100 )
1038void KeyBoard(unsigned char c, int x, int y)
1039{
1040        switch(c)
1041        {
1042        case 27:
1043                CleanUp();
1044                exit(0);
1045                break;
1046        case 32: //space
1047                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
1048                ResetTraverser();
1049                break;
1050        case 'h':
1051        case 'H':
1052                showHelp = !showHelp;
1053                break;
1054        case '+':
1055                if (maxBatchSize < 10)
1056                        maxBatchSize = 10;
1057                else
1058                        maxBatchSize += 10;
1059
1060                traverser->SetMaxBatchSize(maxBatchSize);
1061                break;
1062        case '-':
1063                maxBatchSize -= 10;
1064                if (maxBatchSize < 0) maxBatchSize = 1;
1065                traverser->SetMaxBatchSize(maxBatchSize);               
1066                break;
1067        case 'M':
1068        case 'm':
1069                useMultiQueries = !useMultiQueries;
1070                traverser->SetUseMultiQueries(useMultiQueries);
1071                break;
1072        case '1':
1073                descendKeyPressed = true;
1074                break;
1075        case '2':
1076                ascendKeyPressed = true;
1077                break;
1078        case '3':
1079                if (trianglesPerVirtualLeaf >= 100)
1080                        trianglesPerVirtualLeaf -= 100;
1081                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1082                break;
1083        case '4':
1084                trianglesPerVirtualLeaf += 100;
1085                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1086                break;
1087        case '5':
1088                assumedVisibleFrames -= 1;
1089                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1090                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1091                break;
1092        case '6':
1093                assumedVisibleFrames += 1;
1094                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1095                break;
1096        case '7':
1097                ssaoExpFactor *= 0.5f;
1098                break;
1099        case '8':
1100                ssaoExpFactor *= 2.0f;
1101                if (ssaoExpFactor > 1.0f) ssaoExpFactor = 1.0f;
1102                break;
1103        case '9':
1104                useLODs = !useLODs;
1105                SceneEntity::SetUseLODs(useLODs);
1106                break;
1107        case 'g':
1108        case 'G':
1109                useGlobIllum = !useGlobIllum;
1110                ssaoShader->SetUseGlobIllum(useGlobIllum);
1111                break;
1112        case 't':
1113        case 'T':
1114                useTemporalCoherence = !useTemporalCoherence;
1115                ssaoShader->SetUseTemporalCoherence(useTemporalCoherence);
1116                break;
1117        case 'o':
1118        case 'O':
1119                useOptimization = !useOptimization;
1120                traverser->SetUseOptimization(useOptimization);
1121                break;
1122        case 'a':
1123        case 'A':
1124                        leftKeyPressed = true;
1125                break;
1126        case 'd':
1127        case 'D':
1128                        rightKeyPressed = true;
1129                break;
1130        case 'w':
1131        case 'W':
1132                        upKeyPressed = true;
1133                break;
1134        case 's':
1135        case 'S':
1136                        downKeyPressed = true;
1137                break;
1138        case 'r':
1139        case 'R':
1140                {
1141                        useRenderQueue = !useRenderQueue;
1142                        traverser->SetUseRenderQueue(useRenderQueue);
1143                }
1144                break;
1145        case 'b':
1146        case 'B':
1147                {
1148                        useTightBounds = !useTightBounds;
1149                        traverser->SetUseTightBounds(useTightBounds);
1150                }
1151                break;
1152        default:
1153                return;
1154        }
1155
1156        glutPostRedisplay();
1157}
1158
1159
1160void SpecialKeyUp(int c, int x, int y)
1161{
1162        switch (c)
1163        {
1164        case GLUT_KEY_LEFT:
1165                leftKeyPressed = false;
1166                break;
1167        case GLUT_KEY_RIGHT:
1168                rightKeyPressed = false;
1169                break;
1170        case GLUT_KEY_UP:
1171                upKeyPressed = false;
1172                break;
1173        case GLUT_KEY_DOWN:
1174                downKeyPressed = false;
1175                break;
1176        default:
1177                return;
1178        }
1179        //glutPostRedisplay();
1180}
1181
1182
1183void KeyUp(unsigned char c, int x, int y)
1184{
1185        switch (c)
1186        {
1187
1188        case 'A':
1189        case 'a':
1190                leftKeyPressed = false;
1191                break;
1192        case 'D':
1193        case 'd':
1194                rightKeyPressed = false;
1195                break;
1196        case 'W':
1197        case 'w':
1198                upKeyPressed = false;
1199                break;
1200        case 'S':
1201        case 's':
1202                downKeyPressed = false;
1203                break;
1204        case '1':
1205                descendKeyPressed = false;
1206                break;
1207        case '2':
1208                ascendKeyPressed = false;
1209                break;
1210       
1211        default:
1212                return;
1213        }
1214        //glutPostRedisplay();
1215}
1216
1217
1218void Special(int c, int x, int y)
1219{
1220        switch(c)
1221        {
1222        case GLUT_KEY_F1:
1223                showHelp = !showHelp;
1224                break;
1225        case GLUT_KEY_F2:
1226                visMode = !visMode;
1227                break;
1228        case GLUT_KEY_F3:
1229                showBoundingVolumes = !showBoundingVolumes;
1230                traverser->SetShowBounds(showBoundingVolumes);
1231                break;
1232        case GLUT_KEY_F4:
1233                showOptions = !showOptions;
1234                break;
1235        case GLUT_KEY_F5:
1236                showStatistics = !showStatistics;
1237                break;
1238        case GLUT_KEY_F6:
1239                flyMode = !flyMode;
1240                break;
1241        case GLUT_KEY_F7:
1242
1243                renderType = (renderType + 1) % 3;
1244                traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
1245               
1246                break;
1247        case GLUT_KEY_F8:
1248                useSsao = !useSsao;
1249                break;
1250        case GLUT_KEY_F9:
1251                showAlgorithmTime = !showAlgorithmTime;
1252                break;
1253
1254        case GLUT_KEY_LEFT:
1255                {
1256                        leftKeyPressed = true;
1257                        camera->Pitch(KeyRotationAngle());
1258                }
1259                break;
1260        case GLUT_KEY_RIGHT:
1261                {
1262                        rightKeyPressed = true;
1263                        camera->Pitch(-KeyRotationAngle());
1264                }
1265                break;
1266        case GLUT_KEY_UP:
1267                {
1268                        upKeyPressed = true;
1269                        KeyHorizontalMotion(KeyShift());
1270                }
1271                break;
1272        case GLUT_KEY_DOWN:
1273                {
1274                        downKeyPressed = true;
1275                        KeyHorizontalMotion(-KeyShift());
1276                }
1277                break;
1278        default:
1279                return;
1280
1281        }
1282
1283        glutPostRedisplay();
1284}
1285
1286#pragma warning( default : 4100 )
1287
1288
1289void Reshape(int w, int h)
1290{
1291        winAspectRatio = 1.0f;
1292
1293        glViewport(0, 0, w, h);
1294       
1295        winWidth = w;
1296        winHeight = h;
1297
1298        if (w) winAspectRatio = (float) w / (float) h;
1299
1300        glMatrixMode(GL_PROJECTION);
1301        glLoadIdentity();
1302
1303        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1304
1305        glMatrixMode(GL_MODELVIEW);
1306
1307        glutPostRedisplay();
1308}
1309
1310
1311void Mouse(int button, int state, int x, int y)
1312{
1313        if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
1314        {
1315                xEyeBegin = x;
1316                yMotionBegin = y;
1317
1318                glutMotionFunc(LeftMotion);
1319        }
1320        else if ((button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN))
1321        {
1322                xEyeBegin = x;
1323                yEyeBegin = y;
1324                yMotionBegin = y;
1325
1326                glutMotionFunc(RightMotion);
1327        }
1328        else if ((button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN))
1329        {
1330                horizontalMotionBegin = x;
1331                verticalMotionBegin = y;
1332                glutMotionFunc(MiddleMotion);
1333        }
1334
1335        glutPostRedisplay();
1336}
1337
1338
1339/**     rotation for left/right mouse drag
1340        motion for up/down mouse drag
1341*/
1342void LeftMotion(int x, int y)
1343{
1344        Vector3 viewDir = camera->GetDirection();
1345        Vector3 pos = camera->GetPosition();
1346
1347        // don't move in the vertical direction
1348        Vector3 horView(viewDir[0], viewDir[1], 0);
1349       
1350        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1351
1352        camera->Pitch(eyeXAngle);
1353
1354        pos += horView * (yMotionBegin - y) * 0.2f;
1355       
1356        camera->SetPosition(pos);
1357       
1358        xEyeBegin = x;
1359        yMotionBegin = y;
1360
1361        glutPostRedisplay();
1362}
1363
1364
1365/**     rotation for left / right mouse drag
1366        motion for up / down mouse drag
1367*/
1368void RightMotion(int x, int y)
1369{
1370        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1371        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1372
1373        camera->Yaw(eyeYAngle);
1374        camera->Pitch(eyeXAngle);
1375
1376        xEyeBegin = x;
1377        yEyeBegin = y;
1378
1379        glutPostRedisplay();
1380}
1381
1382
1383// strafe
1384void MiddleMotion(int x, int y)
1385{
1386        Vector3 viewDir = camera->GetDirection();
1387        Vector3 pos = camera->GetPosition();
1388
1389        // the 90 degree rotated view vector
1390        // y zero so we don't move in the vertical
1391        Vector3 rVec(viewDir[0], viewDir[1], 0);
1392       
1393        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1394        rVec = rot * rVec;
1395       
1396        pos -= rVec * (x - horizontalMotionBegin) * 0.1f;
1397        pos[2] += (verticalMotionBegin - y) * 0.1f;
1398
1399        camera->SetPosition(pos);
1400
1401        horizontalMotionBegin = x;
1402        verticalMotionBegin = y;
1403
1404        glutPostRedisplay();
1405}
1406
1407
1408void InitExtensions(void)
1409{
1410        GLenum err = glewInit();
1411
1412        if (GLEW_OK != err)
1413        {
1414                // problem: glewInit failed, something is seriously wrong
1415                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
1416                exit(1);
1417        }
1418        if  (!GLEW_ARB_occlusion_query)
1419        {
1420                printf("I require the GL_ARB_occlusion_query to work.\n");
1421                exit(1);
1422        }
1423}
1424
1425
1426void Begin2D()
1427{
1428        glDisable(GL_LIGHTING);
1429        glDisable(GL_DEPTH_TEST);
1430
1431        glMatrixMode(GL_PROJECTION);
1432        glPushMatrix();
1433        glLoadIdentity();
1434
1435        gluOrtho2D(0, winWidth, 0, winHeight);
1436
1437        glMatrixMode(GL_MODELVIEW);
1438        glPushMatrix();
1439        glLoadIdentity();
1440}
1441
1442
1443void End2D()
1444{
1445        glMatrixMode(GL_PROJECTION);
1446        glPopMatrix();
1447
1448        glMatrixMode(GL_MODELVIEW);
1449        glPopMatrix();
1450
1451        glEnable(GL_LIGHTING);
1452        glEnable(GL_DEPTH_TEST);
1453}
1454
1455
1456// displays the visualisation of culling algorithm
1457void DisplayVisualization()
1458{
1459        visualization->SetFrameId(traverser->GetCurrentFrameId());
1460       
1461        Begin2D();
1462        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1463        glEnable(GL_BLEND);
1464        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
1465
1466        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
1467        glDisable(GL_BLEND);
1468        End2D();
1469       
1470       
1471        AxisAlignedBox3 box = bvh->GetBox();
1472
1473        // hack: set far plane for viz
1474        camera->SetFar(0.35f * Magnitude(box.Diagonal()));
1475
1476        const float offs = box.Size().x * 0.3f;
1477       
1478        //Vector3 vizpos = Vector3(box.Min().x, box.Min().y + box.Size().y * 0.5f, box.Min().z + box.Size().z * 50);
1479        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
1480       
1481        visCamera->SetPosition(vizpos);
1482        visCamera->ResetPitchAndYaw();
1483        //visCamera->Pitch(M_PI);
1484
1485        glPushAttrib(GL_VIEWPORT_BIT);
1486        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
1487
1488        glMatrixMode(GL_PROJECTION);
1489        glPushMatrix();
1490
1491        glLoadIdentity();
1492       
1493        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
1494
1495        glMatrixMode(GL_MODELVIEW);
1496        glPushMatrix();
1497
1498        visCamera->SetupCameraView();
1499
1500        //Matrix4x4 rotX = RotationXMatrix(camera->GetYaw());
1501        //glMultMatrixf((float *)rotX.x);
1502        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
1503        glMultMatrixf((float *)rotZ.x);
1504
1505        Vector3 pos = camera->GetPosition();
1506        glTranslatef(-pos.x, -pos.y, -pos.z);
1507
1508
1509        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
1510        glLightfv(GL_LIGHT0, GL_POSITION, position);
1511
1512        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
1513        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1514
1515        glClear(GL_DEPTH_BUFFER_BIT);
1516
1517
1518        ////////////
1519        //-- visualization of the occlusion culling
1520
1521        visualization->Render();
1522       
1523       
1524        // reset previous settings
1525        glPopAttrib();
1526
1527        glMatrixMode(GL_PROJECTION);
1528        glPopMatrix();
1529        glMatrixMode(GL_MODELVIEW);
1530        glPopMatrix();
1531}
1532
1533
1534// cleanup routine after the main loop
1535void CleanUp()
1536{
1537        DEL_PTR(traverser);
1538        DEL_PTR(sceneQuery);
1539        DEL_PTR(bvh);
1540        DEL_PTR(visualization);
1541        DEL_PTR(camera);
1542        DEL_PTR(loader);
1543        DEL_PTR(renderQueue);
1544        DEL_PTR(perfGraph);
1545
1546        DEL_PTR(fbo);
1547        DEL_PTR(ssaoShader);
1548        DEL_PTR(deferredShader);
1549
1550        if (sCgMrtVertexProgram)
1551                cgDestroyProgram(sCgMrtVertexProgram);
1552        if (RenderState::sCgMrtFragmentProgram)
1553                cgDestroyProgram(RenderState::sCgMrtFragmentProgram);
1554        if (RenderState::sCgMrtFragmentTexProgram)
1555                cgDestroyProgram(RenderState::sCgMrtFragmentTexProgram);
1556       
1557        if (sCgContext)
1558                cgDestroyContext(sCgContext);
1559}
1560
1561
1562// this function inserts a dezimal point after each 1000
1563void CalcDecimalPoint(string &str, int d, int len)
1564{
1565        static vector<int> numbers;
1566        numbers.clear();
1567
1568        static string shortStr;
1569        shortStr.clear();
1570
1571        static char hstr[100];
1572
1573        while (d != 0)
1574        {
1575                numbers.push_back(d % 1000);
1576                d /= 1000;
1577        }
1578
1579        // first element without leading zeros
1580        if (numbers.size() > 0)
1581        {
1582                sprintf(hstr, "%d", numbers.back());
1583                shortStr.append(hstr);
1584        }
1585       
1586        for (int i = (int)numbers.size() - 2; i >= 0; i--)
1587        {
1588                sprintf(hstr, ",%03d", numbers[i]);
1589                shortStr.append(hstr);
1590        }
1591
1592        int dif = len - (int)shortStr.size();
1593
1594        for (int i = 0; i < dif; ++ i)
1595        {
1596                str += " ";
1597        }
1598
1599        str.append(shortStr);
1600}
1601
1602
1603void DisplayStats()
1604{
1605        static char msg[9][300];
1606
1607        static double frameTime = elapsedTime;
1608        static double renderTime = algTime;
1609
1610        const float expFactor = 0.1f;
1611
1612        // if some strange render time spike happened in this frame => don't count
1613        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1614       
1615        static float rTime = 1000.0f;
1616
1617        if (showAlgorithmTime)
1618        {
1619                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1620        }
1621
1622        accumulatedTime += elapsedTime;
1623
1624        if (accumulatedTime > 500) // update every fraction of a second
1625        {       
1626                accumulatedTime = 0;
1627
1628                if (frameTime) fps = 1e3f / (float)frameTime;
1629
1630                rTime = renderTime;
1631                renderedObjects = traverser->GetStats().mNumRenderedGeometry;
1632                renderedNodes = traverser->GetStats().mNumRenderedNodes;
1633                renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1634
1635                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1636                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1637                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1638                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1639                stateChanges = traverser->GetStats().mNumStateChanges;
1640                numBatches = traverser->GetStats().mNumBatches;
1641        }
1642
1643
1644        Begin2D();
1645
1646        glEnable(GL_BLEND);
1647        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1648
1649        if (showHelp)
1650        {       
1651                DrawHelpMessage();
1652        }
1653        else
1654        {
1655                if (showOptions)
1656                {
1657                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1658                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1659                }
1660
1661                if (showStatistics)
1662                {
1663                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1664                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1665                }
1666
1667                glEnable(GL_TEXTURE_2D);
1668
1669                myfont.Begin();
1670
1671                if (showOptions)
1672                {
1673                        glColor3f(0.0f, 1.0f, 0.0f);
1674
1675                        int i = 0;
1676
1677                        static char *renderTypeStr[] = {"fixed function", "fixed function + depth pass", "deferred shading"};
1678       
1679                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1680                                                        useMultiQueries, useTightBounds, useRenderQueue);
1681
1682                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderTypeStr[renderType], useSsao);
1683
1684                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
1685
1686                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1687                                assumedVisibleFrames, maxBatchSize);
1688
1689                        for (int j = 0; j < 4; ++ j)
1690                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
1691                }
1692
1693                if (showStatistics)
1694                {
1695                        glColor3f(1.0f, 1.0f, 0.0f);
1696
1697                        string str;
1698                        string str2;
1699
1700                        int len = 10;
1701                        CalcDecimalPoint(str, renderedTriangles, len);
1702                        CalcDecimalPoint(str2, bvh->GetBvhStats().mTriangles, len);
1703
1704                        int i = 4;
1705
1706                        sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
1707                                renderedNodes, bvh->GetNumVirtualNodes(), str.c_str(), str2.c_str());
1708
1709                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1710                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1711
1712                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1713                                issuedQueries, stateChanges, numBatches);
1714
1715                        for (int j = 4; j < 7; ++ j)
1716                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
1717                }
1718
1719                glColor3f(1.0f, 1.0f, 1.0f);
1720                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
1721               
1722                if (!showAlgorithmTime)
1723                {
1724                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1725                }
1726                else
1727                {
1728                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1729                }
1730
1731                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
1732               
1733                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1734                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
1735        }
1736
1737        glDisable(GL_BLEND);
1738        glDisable(GL_TEXTURE_2D);
1739
1740        End2D();
1741}       
1742
1743
1744void RenderSky()
1745{
1746        SceneEntityContainer::const_iterator sit, sit_end = skyGeometry.end();
1747
1748        for (sit = skyGeometry.begin(); sit != sit_end; ++ sit)
1749                (*sit)->Render(&state);
1750}
1751
1752
1753void RenderVisibleObjects()
1754{
1755        state.SetRenderType(RenderState::FIXED);
1756        state.Reset();
1757
1758        glEnable(GL_LIGHTING);
1759        glDepthFunc(GL_LEQUAL);
1760
1761        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
1762
1763        SceneEntityContainer::const_iterator sit,
1764                sit_end = traverser->GetVisibleObjects().end();
1765
1766        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
1767                renderQueue->Enqueue(*sit);
1768               
1769        renderQueue->Apply();
1770
1771        glDepthFunc(GL_LESS);
1772}
1773
1774
1775void PlaceViewer(const Vector3 &oldPos)
1776{
1777        Vector3 playerPos = camera->GetPosition();
1778
1779        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
1780
1781        if (validIntersect)
1782                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
1783        {
1784                camera->SetPosition(playerPos);
1785        }
1786}
Note: See TracBrowser for help on using the repository browser.