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

Revision 2878, 40.6 KB checked in by mattausch, 16 years ago (diff)

for some reasons very slow even in small streets on my home computer!!

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