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

Revision 3226, 60.3 KB checked in by mattausch, 16 years ago (diff)

worked on submission

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