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

Revision 2893, 41.4 KB checked in by mattausch, 16 years ago (diff)

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