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

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