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

Revision 3314, 69.5 KB checked in by mattausch, 15 years ago (diff)

reverted to old sampling scheme

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