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

Revision 3225, 60.2 KB checked in by mattausch, 16 years ago (diff)

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