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

Revision 2887, 42.0 KB checked in by mattausch, 16 years ago (diff)

made changes to view transformation but still not working

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