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

Revision 3226, 60.3 KB checked in by mattausch, 16 years ago (diff)

worked on submission

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