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

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