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

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