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

Revision 3103, 49.2 KB checked in by mattausch, 16 years ago (diff)

still some error with ssao on edges
bilateral filter slow

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