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

Revision 3214, 54.7 KB checked in by mattausch, 16 years ago (diff)

worked on lense flare

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