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

Revision 2932, 43.4 KB checked in by mattausch, 16 years ago (diff)
RevLine 
[2642]1// occquery.cpp : Defines the entry point for the console application.
2//
[2818]3#include "glInterface.h"
[2746]4#include <math.h>
5#include <time.h>
[2756]6#include "common.h"
[2642]7#include "RenderTraverser.h"
[2756]8#include "SceneEntity.h"
9#include "Vector3.h"
10#include "Matrix4x4.h"
[2795]11#include "ResourceManager.h"
[2756]12#include "Bvh.h"
13#include "Camera.h"
14#include "Geometry.h"
[2760]15#include "BvhLoader.h"
16#include "FrustumCullingTraverser.h"
[2763]17#include "StopAndWaitTraverser.h"
[2764]18#include "CHCTraverser.h"
[2767]19#include "CHCPlusPlusTraverser.h"
20#include "Visualization.h"
[2769]21#include "RenderState.h"
[2795]22#include "Timer/PerfTimer.h"
[2796]23#include "SceneQuery.h"
[2801]24#include "RenderQueue.h"
[2819]25#include "Material.h"
[2808]26#include <Cg/cg.h>
27#include <Cg/cgGL.h>
[2826]28#include "glfont2.h"
[2827]29#include "PerformanceGraph.h"
[2828]30#include "Environment.h"
[2837]31#include "Halton.h"
[2840]32#include "Transform3.h"
[2853]33#include "SampleGenerator.h"
[2857]34#include "FrameBufferObject.h"
[2896]35#include "DeferredRenderer.h"
[2887]36#include "ShadowMapping.h"
37#include "Light.h"
[2642]38
39
[2756]40using namespace std;
[2776]41using namespace CHCDemoEngine;
[2642]42
43
[2828]44static Environment env;
45
[2911]46#define MAX_DEPTH_CONST 10.0f
[2828]47
[2884]48// fbo
[2879]49FrameBufferObject *fbo = NULL;
[2756]50
[2826]51GLuint fontTex;
[2810]52
[2756]53/// the renderable scene geometry
54SceneEntityContainer sceneEntities;
55// traverses and renders the hierarchy
[2767]56RenderTraverser *traverser = NULL;
[2756]57/// the hierarchy
[2767]58Bvh *bvh = NULL;
[2793]59/// handles scene loading
[2795]60ResourceManager *loader = NULL;
[2756]61/// the scene camera
[2767]62Camera *camera = NULL;
[2795]63/// the scene camera
64Camera *visCamera = NULL;
[2767]65/// the visualization
66Visualization *visualization = NULL;
[2760]67/// the current render state
68RenderState state;
[2764]69/// the rendering algorithm
[2795]70int renderMode = RenderTraverser::CHCPLUSPLUS;
[2756]71// eye near plane distance
[2927]72float nearDist = 0.1f;
73float farDist = 1e6f;
[2856]74/// the field of view
75float fov = 50.0f;
[2771]76/// the pixel threshold where a node is still considered invisible
77int threshold;
[2764]78
[2776]79int assumedVisibleFrames = 10;
80int maxBatchSize = 50;
[2771]81
[2800]82int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
[2767]83
[2796]84SceneQuery *sceneQuery = NULL;
[2801]85RenderQueue *renderQueue = NULL;
[2796]86
[2897]87// traverses and renders the hierarchy
88RenderTraverser *shadowTraverser = NULL;
89
90
[2809]91/// these values get scaled with the frame rate
[2828]92static float keyForwardMotion = 30.0f;
93static float keyRotation = 1.5f;
[2801]94
[2826]95/// elapsed time in milliseconds
96double elapsedTime = 1000.0f;
97double algTime = 1000.0f;
[2795]98
[2809]99static int winWidth = 1024;
[2813]100static int winHeight = 768;
[2892]101
[2931]102const float shadowSize = 4096;
[2892]103
[2809]104static float winAspectRatio = 1.0f;
[2642]105
[2776]106double accumulatedTime = 1000;
[2770]107float fps = 1e3f;
108
[2826]109glfont::GLFont myfont;
110
[2809]111// rendertexture
[2828]112static int texWidth = 1024;
113static int texHeight = 768;
[2866]114
115
[2770]116int renderedObjects = 0;
[2773]117int renderedNodes = 0;
118int renderedTriangles = 0;
119
[2770]120int issuedQueries = 0;
121int traversedNodes = 0;
122int frustumCulledNodes = 0;
123int queryCulledNodes = 0;
124int stateChanges = 0;
[2800]125int numBatches = 0;
[2770]126
[2642]127bool showHelp = false;
[2826]128bool showStatistics = false;
[2865]129bool showOptions = true;
[2642]130bool showBoundingVolumes = false;
131bool visMode = false;
132
[2792]133// mouse navigation state
[2809]134int xEyeBegin = 0;
135int yEyeBegin = 0;
136int yMotionBegin = 0;
137int verticalMotionBegin = 0;
138int horizontalMotionBegin = 0;
[2642]139
[2770]140bool useOptimization = false;
[2786]141bool useTightBounds = true;
[2795]142bool useRenderQueue = true;
[2786]143bool useMultiQueries = true;
[2800]144bool flyMode = true;
145
[2795]146SceneEntityContainer skyGeometry;
147
[2792]148bool leftKeyPressed = false;
149bool rightKeyPressed = false;
150bool upKeyPressed = false;
151bool downKeyPressed = false;
[2837]152bool descendKeyPressed = false;
153bool ascendKeyPressed = false;
[2787]154
[2875]155bool useGlobIllum = false;
156bool useTemporalCoherence = true;
157
[2901]158static float ssaoTempCohFactor = 255.0;
[2821]159
[2826]160bool showAlgorithmTime = false;
161
[2820]162GLubyte *randomNormals = NULL;
[2809]163
[2819]164PerfTimer frameTimer, algTimer;
165
[2825]166int renderType = RenderState::FIXED;
[2820]167
[2827]168PerformanceGraph *perfGraph = NULL;
[2825]169
[2828]170bool useFullScreen = false;
[2827]171
[2865]172bool useLODs = true;
173
[2930]174DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_POISSON;
[2865]175
[2903]176bool useAdvancedShading = false;
177
[2895]178bool showShadowMap = false;
179bool shadowChanged = true;
180
[2834]181static Matrix4x4 matProjectionView = IdentityMatrix();
[2820]182
[2931]183bool renderLightView = false;
[2894]184
[2931]185
186
[2894]187ShadowMap *shadowMap = NULL;
[2887]188Light *light = NULL;
[2834]189
[2895]190
[2809]191// function forward declarations
[2759]192void InitExtensions();
[2756]193void DisplayVisualization();
[2759]194void InitGLstate();
[2809]195void InitRenderTexture();
196void InitCg();
[2759]197void CleanUp();
198void SetupEyeView();
199void UpdateEyeMtx();
200void SetupLighting();
[2764]201void DisplayStats();
[2769]202void Output(int x, int y, const char *string);
[2786]203void DrawHelpMessage();
[2796]204void RenderSky();
[2801]205void RenderVisibleObjects();
[2756]206
[2792]207void Begin2D();
208void End2D();
209void KeyBoard(unsigned char c, int x, int y);
210void DrawStatistics();
211void Display();
212void Special(int c, int x, int y);
213void KeyUp(unsigned char c, int x, int y);
214void SpecialKeyUp(int c, int x, int y);
215void Reshape(int w, int h);
216void Mouse(int button, int state, int x, int y);
217void LeftMotion(int x, int y);
218void RightMotion(int x, int y);
219void MiddleMotion(int x, int y);
220void CalcDecimalPoint(string &str, int d);
[2642]221
[2897]222RenderTraverser *CreateTraverser(Camera *cam);
223
[2792]224void KeyHorizontalMotion(float shift);
[2794]225void KeyVerticalMotion(float shift);
[2642]226
[2801]227void PlaceViewer(const Vector3 &oldPos);
[2642]228
[2801]229
[2887]230
[2826]231inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
232inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
[2792]233
[2809]234void InitFBO();
[2795]235
[2896]236DeferredRenderer *ssaoShader = NULL;
[2810]237
[2809]238
239
[2810]240/////////
241//-- cg stuff
242
[2808]243static CGcontext sCgContext = NULL;
[2810]244static CGprogram sCgMrtVertexProgram = NULL;
[2795]245
[2818]246static CGparameter sModelViewProjMatrixParam;
[2809]247static CGparameter sMaxDepthParam;
[2819]248static CGparameter sMaxDepthParamTex;
[2808]249
[2861]250static Matrix4x4 oldViewProjMatrix;
[2820]251
[2837]252
[2809]253static void cgErrorCallback()
254{
255        CGerror lastError = cgGetError();
256
257        if(lastError)
258        {
259                printf("%s\n\n", cgGetErrorString(lastError));
260                printf("%s\n", cgGetLastListing(sCgContext));
[2861]261               
[2809]262                printf("Cg error, exiting...\n");
263
264                exit(0);
265        }
266}
267
268
269static void PrintGLerror(char *msg)
270{
271        GLenum errCode;
272        const GLubyte *errStr;
273       
274        if ((errCode = glGetError()) != GL_NO_ERROR)
275        {
276                errStr = gluErrorString(errCode);
277                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
278        }
279}
280
281
[2642]282int main(int argc, char* argv[])
283{
[2781]284        int returnCode = 0;
285
[2837]286        Vector3 camPos(.0f, .0f, .0f);
[2838]287        Vector3 camDir(.0f, 1.0f, .0f);
[2837]288
[2873]289        cout << "=== reading environment file ===" << endl << endl;
[2830]290
[2837]291        string envFileName = "default.env";
292        if (!env.Read(envFileName))
293        {
294                cerr << "loading environment " << envFileName << " failed!" << endl;
295        }
296        else
297        {
298                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
299                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
300                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
[2828]301
[2837]302                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
303                env.GetFloatParam(string("keyRotation"), keyRotation);
[2828]304
[2837]305                env.GetIntParam(string("winWidth"), winWidth);
306                env.GetIntParam(string("winHeight"), winHeight);
[2828]307
[2837]308                env.GetBoolParam(string("useFullScreen"), useFullScreen);
[2901]309                env.GetFloatParam(string("tempCohFactor"), ssaoTempCohFactor);
[2837]310                env.GetVectorParam(string("camPosition"), camPos);
[2838]311                env.GetVectorParam(string("camDirection"), camDir);
[2828]312
[2865]313                env.GetBoolParam(string("useLODs"), useLODs);
314
[2846]315                //env.GetStringParam(string("modelPath"), model_path);
[2838]316                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
317
[2867]318
[2837]319                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
320                cout << "maxBatchSize: " << maxBatchSize << endl;
321                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
[2828]322
[2837]323                cout << "keyForwardMotion: " << keyForwardMotion << endl;
324                cout << "keyRotation: " << keyRotation << endl;
325                cout << "winWidth: " << winWidth << endl;
326                cout << "winHeight: " << winHeight << endl;
327                cout << "useFullScreen: " << useFullScreen << endl;
[2865]328                cout << "useLODs: " << useLODs << endl;
[2837]329                cout << "camPosition: " << camPos << endl;
[2901]330                cout << "temporal coherence: " << ssaoTempCohFactor << endl;
[2873]331
[2846]332                //cout << "model path: " << model_path << endl;
[2873]333
[2881]334                cout << "**** end parameters ****" << endl << endl;
[2837]335        }
[2829]336
[2828]337        ///////////////////////////
338
[2914]339        camera = new Camera(winWidth, winHeight, fov);
[2795]340        camera->SetNear(nearDist);
[2913]341        camera->SetFar(1000);
[2888]342
[2838]343        camera->SetDirection(camDir);
[2829]344        camera->SetPosition(camPos);
345
[2806]346        visCamera = new Camera(winWidth, winHeight, fov);
[2781]347
[2796]348        visCamera->SetNear(0.0f);
349        visCamera->Yaw(.5 * M_PI);
[2781]350
[2802]351        renderQueue = new RenderQueue(&state, camera);
[2801]352
[2760]353        glutInitWindowSize(winWidth, winHeight);
[2756]354        glutInit(&argc, argv);
[2853]355        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
356        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
[2850]357        //glutInitDisplayString("samples=2");
358
[2867]359        SceneEntity::SetUseLODs(useLODs);
360
361
[2828]362        if (!useFullScreen)
[2856]363        {
[2828]364                glutCreateWindow("FriendlyCulling");
[2856]365        }
[2828]366        else
367        {
368                glutGameModeString( "1024x768:32@75" );
369                glutEnterGameMode();
370        }
371
[2792]372        glutDisplayFunc(Display);
373        glutKeyboardFunc(KeyBoard);
374        glutSpecialFunc(Special);
375        glutReshapeFunc(Reshape);
376        glutMouseFunc(Mouse);
377        glutIdleFunc(Display);
378        glutKeyboardUpFunc(KeyUp);
379        glutSpecialUpFunc(SpecialKeyUp);
380        glutIgnoreKeyRepeat(true);
381
[2829]382        // initialise gl graphics
[2756]383        InitExtensions();
384        InitGLstate();
[2850]385
[2854]386        glEnable(GL_MULTISAMPLE_ARB);
387        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
[2850]388
[2792]389        LeftMotion(0, 0);
390        MiddleMotion(0, 0);
[2756]391
[2829]392        perfGraph = new PerformanceGraph(1000);
[2756]393
[2795]394        loader = new ResourceManager();
[2793]395
[2784]396        //const string filename("data/city/model/city.dem");
397        const string filename = string(model_path + "city.dem");
[2756]398
[2793]399        if (loader->Load(filename, sceneEntities))
[2756]400                cout << "scene " << filename << " loaded" << endl;
401        else
[2784]402        {
[2756]403                cerr << "loading scene " << filename << " failed" << endl;
[2792]404                CleanUp();
[2784]405                exit(0);
406        }
[2756]407
[2795]408        SceneEntityContainer dummy;
409
410        const string envname = string(model_path + "env.dem");
411
412        if (loader->Load(envname, skyGeometry))
413                cout << "sky box " << filename << " loaded" << endl;
414        else
415        {
416                cerr << "loading sky box " << filename << " failed" << endl;
417                CleanUp();
418                exit(0);
419        }
420
[2784]421        const string bvh_filename = string(model_path + "city.bvh");
[2760]422        BvhLoader bvhLoader;
[2784]423        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
[2762]424
[2784]425        if (!bvh)
426        {
427                cerr << "loading bvh " << bvh_filename << " failed" << endl;
[2792]428                CleanUp();
[2784]429                exit(0);
430        }
431
[2829]432        // set far plane based on scene extent
[2927]433        farDist = 10.0f * Magnitude(bvh->GetBox().Diagonal());
[2829]434        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
435
[2913]436        camera->SetFar(Magnitude(bvh->GetBox().Diagonal()));
[2829]437       
[2809]438        InitCg();
[2806]439
[2896]440        DeferredRenderer::Init(sCgContext);
[2847]441
[2861]442
[2857]443        // initialize the render traverser
[2897]444        traverser = CreateTraverser(camera);
[2756]445
[2787]446        visualization = new Visualization(bvh, camera, NULL, &state);
[2897]447       
448        state.SetRenderType(RenderState::FIXED);
[2843]449        sceneQuery = new SceneQuery(bvh->GetBox(), traverser);
[2796]450
[2895]451        //Vector3 lightDir = Normalize(Vector3(0, 1, -1));
452        Vector3 lightDir = Normalize(-Vector3(0.8f, -1.0f, 0.7f));
453       
[2893]454        light = new Light(lightDir, RgbaColor(1, 1, 1, 1));
[2887]455
[2895]456
[2847]457        // frame time is restarted every frame
458        frameTimer.Start();
[2800]459
[2857]460        // the rendering loop
[2642]461        glutMainLoop();
462
463        // clean up
[2756]464        CleanUp();
465
[2642]466        return 0;
467}
468
[2756]469
[2809]470void InitCg(void)
471{
472        // Setup Cg
473        cgSetErrorCallback(cgErrorCallback);
474
475        // Create cgContext.
476        sCgContext = cgCreateContext();
477
478        // get the best profile for this hardware
[2818]479        RenderState::sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
480        cgGLSetOptimalOptions(RenderState::sCgFragmentProfile);
[2809]481
[2818]482        RenderState::sCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
483        cgGLSetOptimalOptions(RenderState::sCgVertexProfile);
[2809]484
[2810]485        sCgMrtVertexProgram =
[2809]486                cgCreateProgramFromFile(sCgContext,
487                                                                CG_SOURCE,
[2810]488                                                                "src/shaders/mrt.cg",
[2818]489                                                                RenderState::sCgVertexProfile,
[2810]490                                                                "vtx",
[2809]491                                                                NULL);
492
[2821]493        if (sCgMrtVertexProgram != NULL)
[2809]494        {
[2810]495                cgGLLoadProgram(sCgMrtVertexProgram);
[2818]496
[2840]497                Transform3::sModelMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelMatrix");
[2818]498                sModelViewProjMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelViewProj");
[2809]499        }
500
[2819]501        RenderState::sCgMrtFragmentTexProgram =
[2809]502                cgCreateProgramFromFile(sCgContext,
503                                                                CG_SOURCE,
[2810]504                                                                "src/shaders/mrt.cg",
[2818]505                                                                RenderState::sCgFragmentProfile,
[2819]506                                                                "fragtex",
507                                                                NULL);
508
509        if (RenderState::sCgMrtFragmentTexProgram != NULL)
510        {
511                cgGLLoadProgram(RenderState::sCgMrtFragmentTexProgram);
512
513                sMaxDepthParamTex = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "maxDepth");
514                Material::sDiffuseTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "diffuse");
[2822]515                Material::sAmbientTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "ambient");
[2819]516
[2927]517                cgGLSetParameter1f(sMaxDepthParamTex, MAX_DEPTH_CONST / farDist);
[2905]518                //Debug << "maxdepth: " << MAX_DEPTH_CONST / myfar << endl;
[2819]519        }
520        else
521                cerr << "fragment tex program failed to load" << endl;
522
523        RenderState::sCgMrtFragmentProgram =
524                cgCreateProgramFromFile(sCgContext,
525                                                                CG_SOURCE,
526                                                                "src/shaders/mrt.cg",
527                                                                RenderState::sCgFragmentProfile,
[2810]528                                                                "frag",
[2809]529                                                                NULL);
530
[2819]531        if (RenderState::sCgMrtFragmentProgram != NULL)
[2809]532        {
[2819]533                cgGLLoadProgram(RenderState::sCgMrtFragmentProgram);
[2809]534
[2819]535                sMaxDepthParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "maxDepth");
536                Material::sDiffuseParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "diffuse");
[2822]537                Material::sAmbientParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "ambient");
[2818]538
[2927]539                cgGLSetParameter1f(sMaxDepthParam, MAX_DEPTH_CONST / farDist);
[2809]540        }
541        else
[2819]542                cerr << "fragment program failed to load" << endl;
[2809]543
544        PrintGLerror("init");
[2818]545
[2834]546        cout << "cg initialization successful" << endl;
[2809]547}
548
549
550void InitFBO()
[2810]551{
[2857]552        // this fbo basicly stores the scene information we get from standard rendering of a frame
553        // we store colors, normals, positions (for the ssao)
[2884]554        fbo = new FrameBufferObject(texWidth, texHeight, FrameBufferObject::DEPTH_32);
[2857]555
[2859]556        // the diffuse color buffer
[2891]557        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
558        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
[2868]559
[2859]560        // the positions buffer
[2867]561        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
[2873]562        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
[2868]563       
[2859]564        // the normals buffer
[2867]565        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
566        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
[2857]567
[2879]568        // another color buffer
[2884]569        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
[2879]570
[2810]571        PrintGLerror("fbo");
[2809]572}
573
574
[2827]575bool InitFont(void)
[2642]576{
[2826]577        glEnable(GL_TEXTURE_2D);
578
579        glGenTextures(1, &fontTex);
580        glBindTexture(GL_TEXTURE_2D, fontTex);
[2829]581        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
[2826]582                return false;
583
584        glDisable(GL_TEXTURE_2D);
[2827]585       
[2826]586        return true;
587}
588
589
590void InitGLstate()
591{
[2879]592        glClearColor(0.0f, 0.0, 0.2f, 0.0f);
[2642]593       
594        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
595        glPixelStorei(GL_PACK_ALIGNMENT,1);
596       
597        glDepthFunc(GL_LESS);
[2762]598        glEnable(GL_DEPTH_TEST);
[2642]599
[2759]600        SetupLighting();
[2642]601
[2760]602        glColor3f(1.0f, 1.0f, 1.0f);
[2642]603        glShadeModel(GL_SMOOTH);
604       
605        glMaterialf(GL_FRONT, GL_SHININESS, 64);
606        glEnable(GL_NORMALIZE);
[2767]607               
608        //glEnable(GL_ALPHA_TEST);
609        glDisable(GL_ALPHA_TEST);
[2844]610        glAlphaFunc(GL_GEQUAL, 0.8f);
[2767]611
[2642]612        glFrontFace(GL_CCW);
613        glCullFace(GL_BACK);
[2851]614        glEnable(GL_CULL_FACE);
615
616        //glDisable(GL_CULL_FACE);
[2800]617        glDisable(GL_TEXTURE_2D);
[2762]618
[2756]619        GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
620        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
[2759]621        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
[2642]622
[2756]623        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
624        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
625        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
[2801]626
627        glDepthFunc(GL_LESS);
[2826]628
[2827]629        if (!InitFont())
[2826]630                cerr << "font creation failed" << endl;
631        else
632                cout << "successfully created font" << endl;
[2642]633}
634
635
[2827]636void DrawHelpMessage()
[2826]637{
[2642]638        const char *message[] =
639        {
640                "Help information",
641                "",
642                "'F1'           - shows/dismisses this message",
[2795]643                "'F2'           - shows/hides bird eye view",
[2790]644                "'F3'           - shows/hides bounds (boxes or tight bounds)",
[2827]645                "'F4',          - shows/hides parameters",
646                "'F5'           - shows/hides statistics",
647                "'F6',          - toggles between fly/walkmode",
[2826]648                "'F7',          - cycles throw render modes",
649                "'F8',          - enables/disables ambient occlusion (only deferred)",
650                "'F9',          - shows pure algorithm render time (using glFinish)",
[2790]651                "'SPACE'        - cycles through occlusion culling algorithms",
[2642]652                "",
[2827]653                "'MOUSE LEFT'        - turn left/right, move forward/backward",
654                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
655                "'MOUSE MIDDLE'      - move up/down, left/right",
656                "'CURSOR UP/DOWN'    - move forward/backward",
657                "'CURSOR LEFT/RIGHT' - turn left/right",
[2642]658                "",
[2827]659                "'-'/'+'        - decreases/increases max batch size",
[2837]660                "'1'/'2'        - downward/upward motion",
661                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
662                "'5'/'6'        - decreases/increases assumed visible frames",
[2776]663                "",
[2786]664                "'R'            - use render queue",
[2790]665                "'B'            - use tight bounds",
666                "'M'            - use multiqueries",
[2792]667                "'O'            - use CHC optimization (geometry queries for leaves)",
[2642]668                0,
669        };
670       
[2756]671       
[2827]672        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
[2756]673
[2827]674        glRecti(30, 30, winWidth - 30, winHeight - 30);
[2642]675
[2827]676        glEnd();
677
[2756]678        glColor3f(1.0f, 1.0f, 1.0f);
679       
[2829]680        glEnable(GL_TEXTURE_2D);
[2827]681        myfont.Begin();
682
683        int x = 40, y = 30;
684
685        for(int i = 0; message[i] != 0; ++ i)
[2756]686        {
687                if(message[i][0] == '\0')
688                {
[2786]689                        y += 15;
[2756]690                }
691                else
692                {
[2827]693                        myfont.DrawString(message[i], x, winHeight - y);
694                        y += 25;
[2642]695                }
696        }
[2829]697        glDisable(GL_TEXTURE_2D);
[2642]698}
699
700
[2897]701RenderTraverser *CreateTraverser(Camera *cam)
[2764]702{
[2897]703        RenderTraverser *tr;
704       
[2771]705        bvh->ResetNodeClassifications();
706
[2764]707        switch (renderMode)
708        {
709        case RenderTraverser::CULL_FRUSTUM:
[2897]710                tr = new FrustumCullingTraverser();
[2764]711                break;
712        case RenderTraverser::STOP_AND_WAIT:
[2897]713                tr = new StopAndWaitTraverser();
[2764]714                break;
715        case RenderTraverser::CHC:
[2897]716                tr = new CHCTraverser();
[2764]717                break;
[2767]718        case RenderTraverser::CHCPLUSPLUS:
[2897]719                tr = new CHCPlusPlusTraverser();
[2767]720                break;
721       
[2764]722        default:
[2897]723                tr = new FrustumCullingTraverser();
[2764]724        }
725
[2897]726        tr->SetCamera(cam);
727        tr->SetHierarchy(bvh);
728        tr->SetRenderQueue(renderQueue);
729        tr->SetRenderState(&state);
730        tr->SetUseOptimization(useOptimization);
731        tr->SetUseRenderQueue(useRenderQueue);
732        tr->SetVisibilityThreshold(threshold);
733        tr->SetAssumedVisibleFrames(assumedVisibleFrames);
734        tr->SetMaxBatchSize(maxBatchSize);
735        tr->SetUseMultiQueries(useMultiQueries);
736        tr->SetUseTightBounds(useTightBounds);
737        tr->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
738        tr->SetRenderQueue(renderQueue);
739
740        return tr;
[2764]741}
742
743
[2759]744void SetupLighting()
[2642]745{
[2759]746        glEnable(GL_LIGHTING);
747        glEnable(GL_LIGHT0);
[2825]748        glEnable(GL_LIGHT1);
749       
[2759]750        GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0};
751        GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
752        GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
753           
[2825]754        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
[2759]755
756        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
757        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
758        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
759
760
761        ////////////
762        //-- second light
763
[2825]764        GLfloat ambient1[] = {0.2, 0.2, 0.2, 1.0};
765        GLfloat diffuse1[] = {1.0, 1.0, 1.0, 1.0};
766        //GLfloat diffuse1[] = {0.5, 0.5, 0.5, 1.0};
767        GLfloat specular1[] = {0.0, 0.0, 0.0, 1.0};
[2759]768
769        glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
770        glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
771        glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
[2825]772
[2759]773       
[2825]774        //////////////////////////////
775
776        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
777        glLightfv(GL_LIGHT0, GL_POSITION, position);
778
779        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
[2759]780        glLightfv(GL_LIGHT1, GL_POSITION, position1);
781
782        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
[2801]783        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
[2759]784        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
[2642]785}
786
[2800]787
[2795]788void SetupEyeView()
[2642]789{
[2861]790        // store matrix of last frame
791        oldViewProjMatrix = matProjectionView;
[2834]792
[2759]793        glMatrixMode(GL_PROJECTION);
794        glLoadIdentity();
795
[2927]796        gluPerspective(fov, winAspectRatio, nearDist, farDist);
[2759]797
[2756]798        glMatrixMode(GL_MODELVIEW);
[2795]799        glLoadIdentity();
[2864]800
801        // set up the camera view
[2760]802        camera->SetupCameraView();
803
[2892]804               
[2864]805        /////////////////
806
[2894]807        Matrix4x4 matViewing, matProjection;
[2864]808
[2834]809        camera->GetModelViewMatrix(matViewing);
810        camera->GetProjectionMatrix(matProjection);
811
[2864]812        // store matrix for later use
[2834]813        matProjectionView = matViewing * matProjection;
814       
[2825]815        if (renderType == RenderState::DEFERRED)
816        {
817                // set modelview matrix for shaders
818                cgGLSetStateMatrixParameter(sModelViewProjMatrixParam,
819                                                                        CG_GL_MODELVIEW_PROJECTION_MATRIX,
820                                                                        CG_GL_MATRIX_IDENTITY);
821
822                static Matrix4x4 identity = IdentityMatrix();
[2840]823                cgGLSetMatrixParameterfc(Transform3::sModelMatrixParam, (const float *)identity.x);
[2834]824        }               
[2642]825}
826
827
[2792]828void KeyHorizontalMotion(float shift)
829{
[2888]830        Vector3 hvec = -camera->GetDirection();
[2792]831        hvec.z = 0;
832
833        Vector3 pos = camera->GetPosition();
834        pos += hvec * shift;
835       
836        camera->SetPosition(pos);
837}
838
839
[2794]840void KeyVerticalMotion(float shift)
841{
842        Vector3 uvec = Vector3(0, 0, shift);
843
844        Vector3 pos = camera->GetPosition();
845        pos += uvec;
846       
847        camera->SetPosition(pos);
848}
849
850
[2857]851// the main rendering loop
[2792]852void Display()
[2801]853{       
[2800]854        Vector3 oldPos = camera->GetPosition();
855
[2792]856        if (leftKeyPressed)
[2795]857                camera->Pitch(KeyRotationAngle());
[2792]858        if (rightKeyPressed)
[2795]859                camera->Pitch(-KeyRotationAngle());
[2792]860        if (upKeyPressed)
[2887]861                KeyHorizontalMotion(-KeyShift());
862        if (downKeyPressed)
[2795]863                KeyHorizontalMotion(KeyShift());
[2837]864        if (ascendKeyPressed)
865                KeyVerticalMotion(KeyShift());
866        if (descendKeyPressed)
[2795]867                KeyVerticalMotion(-KeyShift());
[2792]868
[2801]869        // place view on ground
870        if (!flyMode) PlaceViewer(oldPos);
[2800]871
[2826]872        if (showAlgorithmTime)
873        {
874                glFinish();
875                algTimer.Start();
876        }
[2809]877       
[2895]878
[2931]879
880        if ((!shadowMap || !shadowTraverser) && (showShadowMap || renderLightView))
881        {
882                if (!shadowMap)
883                        shadowMap = new ShadowMap(light, shadowSize, bvh->GetBox(), camera);
884
885                if (!shadowTraverser)
886                        shadowTraverser = CreateTraverser(shadowMap->GetShadowCamera());
887
888        }
889
890        // hack
891        int oldRenderType = renderType;
892
893        if (renderLightView)
894                renderType = RenderState::FIXED;
895
896
897        // render with the specified method (forward rendering, forward + depth, deferred)
[2825]898        switch (renderType)
899        {
900        case RenderState::FIXED:
901       
[2851]902                glEnable(GL_MULTISAMPLE_ARB);
[2879]903               
[2825]904                state.SetRenderType(RenderState::FIXED);
905                glEnable(GL_LIGHTING);
[2809]906
[2825]907                cgGLDisableProfile(RenderState::sCgFragmentProfile);
908                cgGLDisableProfile(RenderState::sCgVertexProfile);
[2809]909
[2829]910                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
911
[2825]912                break;
913
914        case RenderState::DEPTH_PASS:
[2851]915
916                glEnable(GL_MULTISAMPLE_ARB);
[2879]917               
[2857]918                cgGLDisableProfile(RenderState::sCgFragmentProfile);
919                cgGLDisableProfile(RenderState::sCgVertexProfile);
920
[2825]921                state.SetRenderType(RenderState::DEPTH_PASS);
[2857]922
923                // the scene is rendered withouth any shading   
[2825]924                glDisable(GL_LIGHTING);
[2809]925       
[2829]926                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
927                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
928
[2825]929                break;
930       
931        case RenderState::DEFERRED:
[2851]932
[2931]933                if (showShadowMap && !renderLightView)// && shadowChanged)
[2897]934                {
[2895]935                        shadowChanged = false;
936
937                        cgGLDisableProfile(RenderState::sCgFragmentProfile);
938                        cgGLDisableProfile(RenderState::sCgVertexProfile);
939
940                        state.SetRenderType(RenderState::DEPTH_PASS);
[2931]941                       
942                        // change CHC++ set of state variables (must be done for each change of camera because
943                        // otherwise the temporal coherency is broken
944                        BvhNode::SetCurrentState(1);
945
[2895]946                        // the scene is rendered withouth any shading   
[2911]947                        shadowMap->ComputeShadowMap(shadowTraverser, matProjectionView);
[2895]948
949                        // change back state
950                        BvhNode::SetCurrentState(0);
951
952                }
953
[2879]954                if (!fbo) InitFBO();
955
[2895]956
[2878]957                // multisampling does not work with deferred shading
[2851]958                glDisable(GL_MULTISAMPLE_ARB);
959
[2825]960                state.SetRenderType(RenderState::DEFERRED);
961
[2861]962                fbo->Bind();
[2825]963       
964                glPushAttrib(GL_VIEWPORT_BIT);
965                glViewport(0, 0, texWidth, texHeight);
966
967                cgGLEnableProfile(RenderState::sCgFragmentProfile);
968                cgGLBindProgram(RenderState::sCgMrtFragmentProgram);
969
970                cgGLEnableProfile(RenderState::sCgVertexProfile);
971                cgGLBindProgram(sCgMrtVertexProgram);
972
[2861]973                /// draw to 3 color buffers
[2825]974                glDrawBuffers(3, mrt);
975
[2829]976                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
977
[2825]978                break;
979        }
980
[2642]981
[2801]982        glDepthFunc(GL_LESS);
[2825]983
[2801]984        glDisable(GL_TEXTURE_2D);
985        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
[2825]986               
[2801]987
[2861]988        // reset lod levels for current frame
[2847]989        LODLevel::InitFrame(camera->GetPosition());
990
991
[2756]992        // bring eye modelview matrix up-to-date
993        SetupEyeView();
[2642]994
[2892]995        // set up lights
996        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
997        glLightfv(GL_LIGHT0, GL_POSITION, position);
[2795]998
[2892]999        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
1000        glLightfv(GL_LIGHT1, GL_POSITION, position1);
[2801]1001
[2826]1002
[2931]1003        if (renderLightView)
1004        {
1005                // change CHC++ set of state variables (must be done for each change of camera because
1006                // otherwise the temporal coherency is broken
1007                BvhNode::SetCurrentState(1);
1008                shadowMap->RenderShadowView(shadowTraverser, matProjectionView);
1009                BvhNode::SetCurrentState(0);
1010        }
1011        else
1012                // actually render the scene geometry using the specified algorithm
1013                traverser->RenderScene();
[2892]1014
[2931]1015
[2825]1016        /////////
[2809]1017        //-- do the rest of the rendering
[2801]1018
1019        glEnableClientState(GL_VERTEX_ARRAY);
1020        glEnableClientState(GL_NORMAL_ARRAY);
1021
[2893]1022       
[2801]1023        // reset depth pass and render visible objects
[2825]1024        if (renderType == RenderState::DEPTH_PASS)
[2801]1025        {
[2829]1026                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
[2801]1027                RenderVisibleObjects();
1028        }
1029
[2893]1030
[2796]1031        ///////////////
1032        //-- render sky
[2795]1033
[2894]1034        // q: should we render sky after deferred shading?
1035        // this would conveniently solves some issues (e.g, skys without shadows)
[2893]1036
[2796]1037        RenderSky();
[2893]1038       
[2801]1039
1040
[2825]1041        if (renderType == RenderState::DEFERRED)
1042        {
[2881]1043                FrameBufferObject::Release();
[2810]1044
[2825]1045                cgGLDisableProfile(RenderState::sCgVertexProfile);
1046                cgGLDisableProfile(RenderState::sCgFragmentProfile);
[2809]1047
[2927]1048                if (!ssaoShader) ssaoShader = new DeferredRenderer(texWidth, texHeight, camera, farDist / MAX_DEPTH_CONST);
[2895]1049               
[2903]1050                DeferredRenderer::SHADING_METHOD shadingMethod;
1051
1052                if (useAdvancedShading)
1053                {
1054                        if (useGlobIllum)
1055                                shadingMethod = DeferredRenderer::GI;
1056                        else
1057                                shadingMethod = DeferredRenderer::SSAO;
1058                }
1059                else
1060                        shadingMethod = DeferredRenderer::DEFAULT;
1061
1062
[2895]1063                ssaoShader->SetShadingMethod(shadingMethod);
1064                ssaoShader->SetSamplingMethod(samplingMethod);
1065                ssaoShader->SetUseTemporalCoherence(useTemporalCoherence);
[2879]1066
[2895]1067                ShadowMap *sm = showShadowMap ? shadowMap : NULL;
[2901]1068                ssaoShader->Render(fbo, oldViewProjMatrix, matProjectionView, ssaoTempCohFactor, sm);
[2825]1069        }
[2827]1070
[2893]1071
[2827]1072        state.SetRenderType(RenderState::FIXED);
[2893]1073        state.Reset();
[2827]1074
[2893]1075
1076        glDisableClientState(GL_VERTEX_ARRAY);
1077        glDisableClientState(GL_NORMAL_ARRAY);
[2931]1078       
1079        renderType = oldRenderType;
[2893]1080
1081
1082        ///////////
1083
1084
[2826]1085        if (showAlgorithmTime)
1086        {
1087                glFinish();
[2827]1088
[2826]1089                algTime = algTimer.Elapsedms();
[2827]1090                perfGraph->AddData(algTime);
[2828]1091
[2827]1092                perfGraph->Draw();
[2826]1093        }
[2827]1094        else
1095        {
1096                if (visMode) DisplayVisualization();
1097        }
[2825]1098
[2884]1099        glFlush();
[2847]1100
1101        const bool restart = true;
1102        elapsedTime = frameTimer.Elapsedms(restart);
1103
[2764]1104        DisplayStats();
[2767]1105
[2642]1106        glutSwapBuffers();
1107}
1108
1109
1110#pragma warning( disable : 4100 )
[2792]1111void KeyBoard(unsigned char c, int x, int y)
[2642]1112{
1113        switch(c)
1114        {
1115        case 27:
[2792]1116                CleanUp();
[2642]1117                exit(0);
1118                break;
1119        case 32: //space
[2800]1120                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
[2897]1121
1122                DEL_PTR(traverser);
1123                traverser = CreateTraverser(camera);
1124
[2931]1125                if (shadowTraverser)
[2897]1126                {
[2931]1127                        // shadow traverser has to be recomputed (this is done on demand)
[2897]1128                        DEL_PTR(shadowTraverser);
1129                }
1130
[2642]1131                break;
1132        case 'h':
1133        case 'H':
1134                showHelp = !showHelp;
1135                break;
1136        case '+':
[2867]1137                if (maxBatchSize < 10)
1138                        maxBatchSize = 10;
1139                else
1140                        maxBatchSize += 10;
1141
[2776]1142                traverser->SetMaxBatchSize(maxBatchSize);
[2642]1143                break;
1144        case '-':
[2776]1145                maxBatchSize -= 10;
1146                if (maxBatchSize < 0) maxBatchSize = 1;
1147                traverser->SetMaxBatchSize(maxBatchSize);               
[2642]1148                break;
[2837]1149        case 'M':
1150        case 'm':
1151                useMultiQueries = !useMultiQueries;
1152                traverser->SetUseMultiQueries(useMultiQueries);
1153                break;
1154        case '1':
1155                descendKeyPressed = true;
1156                break;
1157        case '2':
1158                ascendKeyPressed = true;
1159                break;
1160        case '3':
1161                if (trianglesPerVirtualLeaf >= 100)
1162                        trianglesPerVirtualLeaf -= 100;
1163                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1164                break;
1165        case '4':
1166                trianglesPerVirtualLeaf += 100;
1167                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1168                break;
1169        case '5':
[2776]1170                assumedVisibleFrames -= 1;
1171                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1172                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1173                break;
[2837]1174        case '6':
[2776]1175                assumedVisibleFrames += 1;
1176                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1177                break;
[2837]1178        case '7':
[2901]1179                ssaoTempCohFactor *= 0.5f;
[2776]1180                break;
[2767]1181        case '8':
[2901]1182                ssaoTempCohFactor *= 2.0f;
1183                //if (ssaoTempCohFactor > 1.0f) ssaoExpFactor = 1.0f;
[2837]1184                break;
[2865]1185        case '9':
1186                useLODs = !useLODs;
1187                SceneEntity::SetUseLODs(useLODs);
1188                break;
[2887]1189        case 'P':
1190        case 'p':
[2930]1191                samplingMethod = DeferredRenderer::SAMPLING_METHOD((samplingMethod + 1) % 3);
1192                cout << "ssao sampling method: " << samplingMethod << endl;
[2887]1193                break;
[2895]1194        case 'Y':
1195        case 'y':
1196                showShadowMap = !showShadowMap;
1197                break;
[2875]1198        case 'g':
[2903]1199        case 'G':
1200                useGlobIllum = !useGlobIllum;
1201                break;
[2875]1202        case 't':
1203        case 'T':
1204                useTemporalCoherence = !useTemporalCoherence;
1205                break;
[2792]1206        case 'o':
1207        case 'O':
[2642]1208                useOptimization = !useOptimization;
[2764]1209                traverser->SetUseOptimization(useOptimization);
[2767]1210                break;
1211        case 'a':
1212        case 'A':
[2931]1213                leftKeyPressed = true;
[2767]1214                break;
1215        case 'd':
1216        case 'D':
[2931]1217                rightKeyPressed = true;
[2767]1218                break;
1219        case 'w':
1220        case 'W':
[2931]1221                upKeyPressed = true;
[2767]1222                break;
[2829]1223        case 's':
1224        case 'S':
[2931]1225                downKeyPressed = true;
[2767]1226                break;
1227        case 'r':
1228        case 'R':
[2931]1229                useRenderQueue = !useRenderQueue;
1230                traverser->SetUseRenderQueue(useRenderQueue);
1231               
[2790]1232                break;
[2786]1233        case 'b':
1234        case 'B':
[2931]1235                useTightBounds = !useTightBounds;
1236                traverser->SetUseTightBounds(useTightBounds);
[2790]1237                break;
[2931]1238        case 'l':
1239        case 'L':
1240                renderLightView = !renderLightView;
1241                break;
[2642]1242        default:
1243                return;
1244        }
1245
1246        glutPostRedisplay();
1247}
1248
1249
[2792]1250void SpecialKeyUp(int c, int x, int y)
[2642]1251{
[2792]1252        switch (c)
1253        {
1254        case GLUT_KEY_LEFT:
1255                leftKeyPressed = false;
1256                break;
1257        case GLUT_KEY_RIGHT:
1258                rightKeyPressed = false;
1259                break;
1260        case GLUT_KEY_UP:
1261                upKeyPressed = false;
1262                break;
1263        case GLUT_KEY_DOWN:
1264                downKeyPressed = false;
1265                break;
1266        default:
1267                return;
1268        }
1269        //glutPostRedisplay();
1270}
1271
1272
1273void KeyUp(unsigned char c, int x, int y)
1274{
1275        switch (c)
1276        {
[2879]1277
[2792]1278        case 'A':
1279        case 'a':
1280                leftKeyPressed = false;
1281                break;
1282        case 'D':
1283        case 'd':
1284                rightKeyPressed = false;
1285                break;
1286        case 'W':
1287        case 'w':
1288                upKeyPressed = false;
1289                break;
[2829]1290        case 'S':
1291        case 's':
[2792]1292                downKeyPressed = false;
1293                break;
[2837]1294        case '1':
1295                descendKeyPressed = false;
[2794]1296                break;
[2837]1297        case '2':
1298                ascendKeyPressed = false;
[2794]1299                break;
1300       
[2792]1301        default:
1302                return;
1303        }
1304        //glutPostRedisplay();
1305}
1306
1307
1308void Special(int c, int x, int y)
1309{
[2642]1310        switch(c)
1311        {
1312        case GLUT_KEY_F1:
1313                showHelp = !showHelp;
1314                break;
[2790]1315        case GLUT_KEY_F2:
[2795]1316                visMode = !visMode;
[2790]1317                break;
1318        case GLUT_KEY_F3:
1319                showBoundingVolumes = !showBoundingVolumes;
1320                traverser->SetShowBounds(showBoundingVolumes);
1321                break;
1322        case GLUT_KEY_F4:
[2827]1323                showOptions = !showOptions;
[2790]1324                break;
1325        case GLUT_KEY_F5:
[2827]1326                showStatistics = !showStatistics;
[2790]1327                break;
[2800]1328        case GLUT_KEY_F6:
1329                flyMode = !flyMode;
1330                break;
[2801]1331        case GLUT_KEY_F7:
[2825]1332
1333                renderType = (renderType + 1) % 3;
1334                traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
1335               
[2801]1336                break;
[2803]1337        case GLUT_KEY_F8:
[2903]1338
1339                useAdvancedShading = !useAdvancedShading;
1340                //shadingMethod = (DeferredRenderer::SHADING_METHOD)((shadingMethod + 1) % 2);
1341
[2821]1342                break;
[2826]1343        case GLUT_KEY_F9:
1344                showAlgorithmTime = !showAlgorithmTime;
1345                break;
1346
[2642]1347        case GLUT_KEY_LEFT:
[2767]1348                {
[2792]1349                        leftKeyPressed = true;
[2795]1350                        camera->Pitch(KeyRotationAngle());
[2767]1351                }
[2642]1352                break;
1353        case GLUT_KEY_RIGHT:
[2767]1354                {
[2792]1355                        rightKeyPressed = true;
[2795]1356                        camera->Pitch(-KeyRotationAngle());
[2767]1357                }
[2642]1358                break;
1359        case GLUT_KEY_UP:
[2767]1360                {
[2792]1361                        upKeyPressed = true;
[2795]1362                        KeyHorizontalMotion(KeyShift());
[2767]1363                }
[2642]1364                break;
1365        case GLUT_KEY_DOWN:
[2767]1366                {
[2792]1367                        downKeyPressed = true;
[2795]1368                        KeyHorizontalMotion(-KeyShift());
[2767]1369                }
[2642]1370                break;
1371        default:
1372                return;
1373
1374        }
1375
1376        glutPostRedisplay();
1377}
[2767]1378
[2642]1379#pragma warning( default : 4100 )
1380
1381
[2792]1382void Reshape(int w, int h)
[2642]1383{
[2759]1384        winAspectRatio = 1.0f;
[2642]1385
1386        glViewport(0, 0, w, h);
1387       
1388        winWidth = w;
1389        winHeight = h;
1390
[2833]1391        if (w) winAspectRatio = (float) w / (float) h;
[2642]1392
[2758]1393        glMatrixMode(GL_PROJECTION);
1394        glLoadIdentity();
[2642]1395
[2927]1396        gluPerspective(fov, winAspectRatio, nearDist, farDist);
[2788]1397
[2758]1398        glMatrixMode(GL_MODELVIEW);
1399
[2642]1400        glutPostRedisplay();
1401}
1402
1403
[2792]1404void Mouse(int button, int state, int x, int y)
[2642]1405{
[2758]1406        if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
[2642]1407        {
1408                xEyeBegin = x;
1409                yMotionBegin = y;
1410
[2792]1411                glutMotionFunc(LeftMotion);
[2642]1412        }
[2758]1413        else if ((button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN))
[2642]1414        {
[2829]1415                xEyeBegin = x;
[2758]1416                yEyeBegin = y;
1417                yMotionBegin = y;
1418
[2792]1419                glutMotionFunc(RightMotion);
[2758]1420        }
1421        else if ((button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN))
1422        {
[2642]1423                horizontalMotionBegin = x;
1424                verticalMotionBegin = y;
[2792]1425                glutMotionFunc(MiddleMotion);
[2642]1426        }
1427
1428        glutPostRedisplay();
1429}
1430
[2758]1431
1432/**     rotation for left/right mouse drag
[2642]1433        motion for up/down mouse drag
1434*/
[2792]1435void LeftMotion(int x, int y)
[2642]1436{
[2758]1437        Vector3 viewDir = camera->GetDirection();
1438        Vector3 pos = camera->GetPosition();
1439
1440        // don't move in the vertical direction
[2764]1441        Vector3 horView(viewDir[0], viewDir[1], 0);
[2642]1442       
[2795]1443        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
[2756]1444
[2795]1445        camera->Pitch(eyeXAngle);
[2787]1446
[2888]1447        pos += horView * (yMotionBegin - y) * 0.2f;
[2795]1448       
[2758]1449        camera->SetPosition(pos);
[2642]1450       
1451        xEyeBegin = x;
1452        yMotionBegin = y;
[2758]1453
[2642]1454        glutPostRedisplay();
1455}
1456
[2758]1457
[2767]1458/**     rotation for left / right mouse drag
1459        motion for up / down mouse drag
[2758]1460*/
[2792]1461void RightMotion(int x, int y)
[2758]1462{
[2829]1463        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
[2795]1464        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
[2758]1465
[2795]1466        camera->Yaw(eyeYAngle);
[2829]1467        camera->Pitch(eyeXAngle);
[2780]1468
[2829]1469        xEyeBegin = x;
[2758]1470        yEyeBegin = y;
[2829]1471
[2758]1472        glutPostRedisplay();
1473}
1474
1475
[2642]1476// strafe
[2792]1477void MiddleMotion(int x, int y)
[2642]1478{
[2758]1479        Vector3 viewDir = camera->GetDirection();
1480        Vector3 pos = camera->GetPosition();
1481
[2642]1482        // the 90 degree rotated view vector
1483        // y zero so we don't move in the vertical
[2764]1484        Vector3 rVec(viewDir[0], viewDir[1], 0);
[2642]1485       
[2764]1486        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
[2758]1487        rVec = rot * rVec;
[2642]1488       
[2888]1489        pos -= rVec * (x - horizontalMotionBegin) * 0.1f;
[2764]1490        pos[2] += (verticalMotionBegin - y) * 0.1f;
[2642]1491
[2758]1492        camera->SetPosition(pos);
1493
[2642]1494        horizontalMotionBegin = x;
1495        verticalMotionBegin = y;
[2758]1496
[2642]1497        glutPostRedisplay();
1498}
1499
1500
[2756]1501void InitExtensions(void)
[2642]1502{
1503        GLenum err = glewInit();
[2756]1504
[2642]1505        if (GLEW_OK != err)
1506        {
1507                // problem: glewInit failed, something is seriously wrong
1508                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
1509                exit(1);
1510        }
[2756]1511        if  (!GLEW_ARB_occlusion_query)
[2642]1512        {
[2756]1513                printf("I require the GL_ARB_occlusion_query to work.\n");
[2642]1514                exit(1);
1515        }
1516}
1517
1518
[2826]1519void Begin2D()
[2642]1520{
1521        glDisable(GL_LIGHTING);
1522        glDisable(GL_DEPTH_TEST);
1523
[2826]1524        glMatrixMode(GL_PROJECTION);
[2642]1525        glPushMatrix();
1526        glLoadIdentity();
[2834]1527
[2826]1528        gluOrtho2D(0, winWidth, 0, winHeight);
[2642]1529
[2826]1530        glMatrixMode(GL_MODELVIEW);
[2642]1531        glPushMatrix();
1532        glLoadIdentity();
1533}
1534
1535
[2826]1536void End2D()
[2642]1537{
[2834]1538        glMatrixMode(GL_PROJECTION);
[2642]1539        glPopMatrix();
[2834]1540
[2642]1541        glMatrixMode(GL_MODELVIEW);
1542        glPopMatrix();
1543
1544        glEnable(GL_LIGHTING);
1545        glEnable(GL_DEPTH_TEST);
1546}
1547
1548
[2787]1549// displays the visualisation of culling algorithm
1550void DisplayVisualization()
[2796]1551{
[2787]1552        visualization->SetFrameId(traverser->GetCurrentFrameId());
1553       
[2792]1554        Begin2D();
[2642]1555        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1556        glEnable(GL_BLEND);
[2827]1557        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
[2642]1558
[2827]1559        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
[2642]1560        glDisable(GL_BLEND);
[2792]1561        End2D();
[2788]1562       
1563       
1564        AxisAlignedBox3 box = bvh->GetBox();
1565
[2838]1566        // hack: set far plane for viz
[2911]1567        //camera->SetFar(0.35f * Magnitude(box.Diagonal()));
[2913]1568        //camera->SetFar(1000);
[2796]1569
[2929]1570        //const float offs = box.Size().x * 0.3f;
[2932]1571        const float offs = box.Size().x * 0.6f;
[2834]1572       
[2838]1573        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
[2806]1574       
[2795]1575        visCamera->SetPosition(vizpos);
[2838]1576        visCamera->ResetPitchAndYaw();
[2892]1577       
[2834]1578        glPushAttrib(GL_VIEWPORT_BIT);
[2806]1579        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
[2796]1580
1581        glMatrixMode(GL_PROJECTION);
[2834]1582        glPushMatrix();
1583
[2787]1584        glLoadIdentity();
[2796]1585       
[2807]1586        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
[2787]1587
[2796]1588        glMatrixMode(GL_MODELVIEW);
[2834]1589        glPushMatrix();
[2787]1590
[2796]1591        visCamera->SetupCameraView();
[2806]1592
1593        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
1594        glMultMatrixf((float *)rotZ.x);
1595
[2887]1596        // inverse translation in order to fix current position
[2838]1597        Vector3 pos = camera->GetPosition();
[2806]1598        glTranslatef(-pos.x, -pos.y, -pos.z);
1599
1600
[2788]1601        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
1602        glLightfv(GL_LIGHT0, GL_POSITION, position);
[2787]1603
[2788]1604        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
1605        glLightfv(GL_LIGHT1, GL_POSITION, position1);
[2787]1606
[2642]1607        glClear(GL_DEPTH_BUFFER_BIT);
1608
[2888]1609
[2767]1610        ////////////
[2787]1611        //-- visualization of the occlusion culling
1612
[2767]1613        visualization->Render();
[2887]1614
[2767]1615       
[2834]1616        // reset previous settings
1617        glPopAttrib();
1618
1619        glMatrixMode(GL_PROJECTION);
1620        glPopMatrix();
1621        glMatrixMode(GL_MODELVIEW);
1622        glPopMatrix();
[2642]1623}
1624
[2767]1625
[2642]1626// cleanup routine after the main loop
[2756]1627void CleanUp()
[2642]1628{
[2756]1629        DEL_PTR(traverser);
[2796]1630        DEL_PTR(sceneQuery);
[2756]1631        DEL_PTR(bvh);
[2767]1632        DEL_PTR(visualization);
[2787]1633        DEL_PTR(camera);
[2793]1634        DEL_PTR(loader);
[2801]1635        DEL_PTR(renderQueue);
[2827]1636        DEL_PTR(perfGraph);
[2809]1637
[2879]1638        DEL_PTR(fbo);
1639        DEL_PTR(ssaoShader);
1640
[2810]1641        if (sCgMrtVertexProgram)
1642                cgDestroyProgram(sCgMrtVertexProgram);
[2827]1643        if (RenderState::sCgMrtFragmentProgram)
1644                cgDestroyProgram(RenderState::sCgMrtFragmentProgram);
1645        if (RenderState::sCgMrtFragmentTexProgram)
1646                cgDestroyProgram(RenderState::sCgMrtFragmentTexProgram);
[2861]1647       
[2809]1648        if (sCgContext)
1649                cgDestroyContext(sCgContext);
[2642]1650}
1651
1652
1653// this function inserts a dezimal point after each 1000
[2829]1654void CalcDecimalPoint(string &str, int d, int len)
[2642]1655{
[2827]1656        static vector<int> numbers;
1657        numbers.clear();
1658
[2829]1659        static string shortStr;
1660        shortStr.clear();
[2642]1661
[2829]1662        static char hstr[100];
1663
[2642]1664        while (d != 0)
1665        {
1666                numbers.push_back(d % 1000);
1667                d /= 1000;
1668        }
1669
1670        // first element without leading zeros
1671        if (numbers.size() > 0)
1672        {
[2800]1673                sprintf(hstr, "%d", numbers.back());
[2829]1674                shortStr.append(hstr);
[2642]1675        }
1676       
[2764]1677        for (int i = (int)numbers.size() - 2; i >= 0; i--)
[2642]1678        {
[2800]1679                sprintf(hstr, ",%03d", numbers[i]);
[2829]1680                shortStr.append(hstr);
[2642]1681        }
[2829]1682
1683        int dif = len - (int)shortStr.size();
1684
1685        for (int i = 0; i < dif; ++ i)
1686        {
1687                str += " ";
1688        }
1689
1690        str.append(shortStr);
[2764]1691}
1692
1693
1694void DisplayStats()
1695{
[2826]1696        static char msg[9][300];
[2764]1697
[2826]1698        static double frameTime = elapsedTime;
1699        static double renderTime = algTime;
1700
[2818]1701        const float expFactor = 0.1f;
[2767]1702
[2802]1703        // if some strange render time spike happened in this frame => don't count
[2826]1704        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1705       
1706        static float rTime = 1000.0f;
[2764]1707
[2826]1708        if (showAlgorithmTime)
1709        {
1710                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1711        }
[2802]1712
[2826]1713        accumulatedTime += elapsedTime;
1714
[2776]1715        if (accumulatedTime > 500) // update every fraction of a second
[2770]1716        {       
1717                accumulatedTime = 0;
1718
[2826]1719                if (frameTime) fps = 1e3f / (float)frameTime;
1720
1721                rTime = renderTime;
[2770]1722                renderedObjects = traverser->GetStats().mNumRenderedGeometry;
[2773]1723                renderedNodes = traverser->GetStats().mNumRenderedNodes;
1724                renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1725
[2770]1726                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1727                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1728                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1729                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1730                stateChanges = traverser->GetStats().mNumStateChanges;
[2800]1731                numBatches = traverser->GetStats().mNumBatches;
[2770]1732        }
1733
[2764]1734
[2826]1735        Begin2D();
[2808]1736
[2826]1737        glEnable(GL_BLEND);
1738        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
[2764]1739
[2826]1740        if (showHelp)
1741        {       
1742                DrawHelpMessage();
1743        }
1744        else
1745        {
[2829]1746                if (showOptions)
1747                {
1748                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1749                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1750                }
1751
1752                if (showStatistics)
1753                {
1754                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1755                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1756                }
1757
1758                glEnable(GL_TEXTURE_2D);
1759
[2827]1760                myfont.Begin();
[2769]1761
[2826]1762                if (showOptions)
1763                {
[2829]1764                        glColor3f(0.0f, 1.0f, 0.0f);
1765
[2826]1766                        int i = 0;
1767
1768                        static char *renderTypeStr[] = {"fixed function", "fixed function + depth pass", "deferred shading"};
[2825]1769       
[2826]1770                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1771                                                        useMultiQueries, useTightBounds, useRenderQueue);
[2792]1772
[2903]1773                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderTypeStr[renderType], useAdvancedShading);
[2808]1774
[2826]1775                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
[2808]1776
[2826]1777                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1778                                assumedVisibleFrames, maxBatchSize);
[2808]1779
[2826]1780                        for (int j = 0; j < 4; ++ j)
[2829]1781                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
[2826]1782                }
[2808]1783
[2786]1784                if (showStatistics)
[2764]1785                {
[2829]1786                        glColor3f(1.0f, 1.0f, 0.0f);
1787
[2826]1788                        string str;
1789                        string str2;
1790
[2829]1791                        int len = 10;
1792                        CalcDecimalPoint(str, renderedTriangles, len);
1793                        CalcDecimalPoint(str2, bvh->GetBvhStats().mTriangles, len);
[2826]1794
1795                        int i = 4;
1796
[2829]1797                        sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
[2826]1798                                renderedNodes, bvh->GetNumVirtualNodes(), str.c_str(), str2.c_str());
1799
1800                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1801                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1802
1803                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1804                                issuedQueries, stateChanges, numBatches);
1805
1806                        for (int j = 4; j < 7; ++ j)
[2829]1807                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
[2764]1808                }
[2790]1809
[2826]1810                glColor3f(1.0f, 1.0f, 1.0f);
1811                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
[2827]1812               
1813                if (!showAlgorithmTime)
1814                {
1815                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1816                }
1817                else
1818                {
1819                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1820                }
[2826]1821
[2829]1822                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
[2827]1823               
1824                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1825                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
[2764]1826        }
1827
[2826]1828        glDisable(GL_BLEND);
1829        glDisable(GL_TEXTURE_2D);
1830
[2792]1831        End2D();
[2764]1832}       
[2796]1833
1834
1835void RenderSky()
1836{
1837        SceneEntityContainer::const_iterator sit, sit_end = skyGeometry.end();
1838
1839        for (sit = skyGeometry.begin(); sit != sit_end; ++ sit)
1840                (*sit)->Render(&state);
[2801]1841}
[2796]1842
[2895]1843// render visible object from depth pass
[2801]1844void RenderVisibleObjects()
1845{
[2825]1846        state.SetRenderType(RenderState::FIXED);
[2796]1847        state.Reset();
[2801]1848
1849        glEnable(GL_LIGHTING);
1850        glDepthFunc(GL_LEQUAL);
1851
1852        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
1853
1854        SceneEntityContainer::const_iterator sit,
1855                sit_end = traverser->GetVisibleObjects().end();
1856
1857        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
1858                renderQueue->Enqueue(*sit);
1859               
1860        renderQueue->Apply();
1861
1862        glDepthFunc(GL_LESS);
1863}
1864
1865
1866void PlaceViewer(const Vector3 &oldPos)
1867{
1868        Vector3 playerPos = camera->GetPosition();
1869
[2843]1870        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
[2801]1871
[2853]1872        if (validIntersect)
[2848]1873                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
[2801]1874        {
1875                camera->SetPosition(playerPos);
1876        }
[2809]1877}
Note: See TracBrowser for help on using the repository browser.