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

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