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

Revision 3258, 64.4 KB checked in by mattausch, 15 years ago (diff)

worked on new method

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