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

Revision 3054, 46.1 KB checked in by mattausch, 16 years ago (diff)

worked on render queue

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