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

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