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

Revision 3054, 46.1 KB checked in by mattausch, 16 years ago (diff)

worked on render queue

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