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

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