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

Revision 3203, 52.7 KB checked in by mattausch, 16 years ago (diff)

only adapting filter size left ...

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