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

Revision 2850, 57.9 KB checked in by mattausch, 16 years ago (diff)

debug version before siggraph

Line 
1// occquery.cpp : Defines the entry point for the console application.
2//
3#include "glInterface.h"
4#include <math.h>
5#include <time.h>
6#include "common.h"
7#include "RenderTraverser.h"
8#include "SceneEntity.h"
9#include "Vector3.h"
10#include "Matrix4x4.h"
11#include "ResourceManager.h"
12#include "Bvh.h"
13#include "Camera.h"
14#include "Geometry.h"
15#include "BvhLoader.h"
16#include "FrustumCullingTraverser.h"
17#include "StopAndWaitTraverser.h"
18#include "CHCTraverser.h"
19#include "CHCPlusPlusTraverser.h"
20#include "Visualization.h"
21#include "RenderState.h"
22#include "Timer/PerfTimer.h"
23#include "SceneQuery.h"
24#include "RenderQueue.h"
25#include "Material.h"
26#include <Cg/cg.h>
27#include <Cg/cgGL.h>
28#include "glfont2.h"
29#include "PerformanceGraph.h"
30#include "Environment.h"
31#include "Halton.h"
32#include "Transform3.h"
33
34
35using namespace std;
36using namespace CHCDemoEngine;
37
38
39static Environment env;
40
41
42/////////////
43//-- fbos
44
45GLuint fbo;
46GLuint fbo1;
47GLuint fbo2;
48
49bool isFirstTexture = true;
50
51/////////////
52//-- renderbuffers
53
54
55GLuint depthBuffer;
56
57GLuint positionsBuffer;
58GLuint colorsBuffer;
59GLuint colorsBuffer1;
60GLuint colorsBuffer2;
61GLuint normalsBuffer;
62
63
64/////////////
65//-- textures
66
67
68GLuint positionsTex;
69GLuint colorsTex;
70GLuint colorsTex1;
71GLuint colorsTex2;
72
73GLuint normalsTex;
74
75GLuint noiseTex;
76
77GLuint fontTex;
78
79/// the renderable scene geometry
80SceneEntityContainer sceneEntities;
81// traverses and renders the hierarchy
82RenderTraverser *traverser = NULL;
83/// the hierarchy
84Bvh *bvh = NULL;
85/// handles scene loading
86ResourceManager *loader = NULL;
87/// the scene camera
88Camera *camera = NULL;
89/// the scene camera
90Camera *visCamera = NULL;
91/// the visualization
92Visualization *visualization = NULL;
93/// the current render state
94RenderState state;
95/// the rendering algorithm
96int renderMode = RenderTraverser::CHCPLUSPLUS;
97// eye near plane distance
98float nearDist = 0.2f;
99/// the pixel threshold where a node is still considered invisible
100int threshold;
101
102float fov = 50.0f;
103
104int assumedVisibleFrames = 10;
105int maxBatchSize = 50;
106
107int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
108
109SceneQuery *sceneQuery = NULL;
110RenderQueue *renderQueue = NULL;
111
112/// these values get scaled with the frame rate
113static float keyForwardMotion = 30.0f;
114static float keyRotation = 1.5f;
115
116/// elapsed time in milliseconds
117double elapsedTime = 1000.0f;
118double algTime = 1000.0f;
119
120static int winWidth = 1024;
121static int winHeight = 768;
122static float winAspectRatio = 1.0f;
123
124double accumulatedTime = 1000;
125float fps = 1e3f;
126
127float myfar = 0;
128
129glfont::GLFont myfont;
130
131// rendertexture
132static int texWidth = 1024;
133static int texHeight = 768;
134//static int texWidth = 2048;
135//static int texHeight = 2048;
136
137int renderedObjects = 0;
138int renderedNodes = 0;
139int renderedTriangles = 0;
140
141int issuedQueries = 0;
142int traversedNodes = 0;
143int frustumCulledNodes = 0;
144int queryCulledNodes = 0;
145int stateChanges = 0;
146int numBatches = 0;
147
148bool showHelp = false;
149bool showStatistics = false;
150bool showOptions = false;
151bool showBoundingVolumes = false;
152bool visMode = false;
153
154// mouse navigation state
155int xEyeBegin = 0;
156int yEyeBegin = 0;
157int yMotionBegin = 0;
158int verticalMotionBegin = 0;
159int horizontalMotionBegin = 0;
160
161bool useOptimization = false;
162bool useTightBounds = true;
163bool useRenderQueue = true;
164bool useMultiQueries = true;
165bool flyMode = true;
166
167SceneEntityContainer skyGeometry;
168
169bool leftKeyPressed = false;
170bool rightKeyPressed = false;
171bool upKeyPressed = false;
172bool downKeyPressed = false;
173bool descendKeyPressed = false;
174bool ascendKeyPressed = false;
175
176bool useSsao = false;
177
178bool showAlgorithmTime = false;
179
180GLubyte *randomNormals = NULL;
181
182PerfTimer frameTimer, algTimer;
183
184int renderType = RenderState::FIXED;
185
186PerformanceGraph *perfGraph = NULL;
187
188bool useFullScreen = false;
189
190float expFactor = 0.1f;
191
192// ssao number of samples
193//#define NUM_SAMPLES 8
194#define NUM_SAMPLES 16
195
196// ssao random spherical samples
197static float samples[NUM_SAMPLES * 2];
198
199static Matrix4x4 matProjectionView = IdentityMatrix();
200
201
202// function forward declarations
203void InitExtensions();
204void DisplayVisualization();
205void InitGLstate();
206void InitRenderTexture();
207void InitCg();
208void CleanUp();
209void SetupEyeView();
210void UpdateEyeMtx();
211void SetupLighting();
212void DisplayStats();
213void Output(int x, int y, const char *string);
214void DrawHelpMessage();
215void RenderSky();
216void RenderVisibleObjects();
217
218void Begin2D();
219void End2D();
220void KeyBoard(unsigned char c, int x, int y);
221void DrawStatistics();
222void Display();
223void Special(int c, int x, int y);
224void KeyUp(unsigned char c, int x, int y);
225void SpecialKeyUp(int c, int x, int y);
226void Reshape(int w, int h);
227void Mouse(int button, int state, int x, int y);
228void LeftMotion(int x, int y);
229void RightMotion(int x, int y);
230void MiddleMotion(int x, int y);
231void CalcDecimalPoint(string &str, int d);
232void ResetTraverser();
233
234void KeyHorizontalMotion(float shift);
235void KeyVerticalMotion(float shift);
236
237void PlaceViewer(const Vector3 &oldPos);
238void DisplayRenderTexture();
239
240
241inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
242inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
243
244void InitFBO();
245
246void CreateNoiseTex2D();
247
248void ComputeViewVectors(Vector3 &tl, Vector3 &tr, Vector3 &bl, Vector3 &br);
249
250void GenerateSamples();
251
252
253GLenum mrt[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
254
255
256/////////
257//-- cg stuff
258
259static CGcontext sCgContext = NULL;
260static CGprogram sCgMrtVertexProgram = NULL;
261static CGprogram sCgSsaoProgram = NULL;
262static CGprogram sCgDeferredProgram = NULL;
263
264static CGparameter sColorsTexParam;
265static CGparameter sPositionsTexParam;
266static CGparameter sNormalsTexParam;
267
268static CGparameter sColorsTexParamSsao;
269static CGparameter sPositionsTexParamSsao;
270static CGparameter sNormalsTexParamSsao;
271static CGparameter sNoiseTexParamSsao;
272
273static CGparameter sModelViewProjMatrixParam;
274static CGparameter sOldModelViewProjMatrixParam;
275static CGparameter sMaxDepthParam;
276static CGparameter sMaxDepthParamSsao;
277static CGparameter sMaxDepthParamTex;
278
279static CGparameter sSamplesParamSsao;
280static CGparameter sOldTexParamSsao;
281static CGparameter sNoiseMultiplierParam;
282static CGparameter sExpFactorParamSsao;
283
284
285static void cgErrorCallback()
286{
287        CGerror lastError = cgGetError();
288
289        if(lastError)
290        {
291                printf("%s\n\n", cgGetErrorString(lastError));
292                printf("%s\n", cgGetLastListing(sCgContext));
293                printf("Cg error, exiting...\n");
294
295                exit(0);
296        }
297}
298
299
300static void PrintGLerror(char *msg)
301{
302        GLenum errCode;
303        const GLubyte *errStr;
304       
305        if ((errCode = glGetError()) != GL_NO_ERROR)
306        {
307                errStr = gluErrorString(errCode);
308                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
309        }
310}
311
312
313int main(int argc, char* argv[])
314{
315        int returnCode = 0;
316
317        Vector3 camPos(.0f, .0f, .0f);
318        Vector3 camDir(.0f, 1.0f, .0f);
319
320        cout << "=== reading environment file === " << endl;
321
322        string envFileName = "default.env";
323        if (!env.Read(envFileName))
324        {
325                cerr << "loading environment " << envFileName << " failed!" << endl;
326        }
327        else
328        {
329                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
330                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
331                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
332
333                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
334                env.GetFloatParam(string("keyRotation"), keyRotation);
335
336                env.GetIntParam(string("winWidth"), winWidth);
337                env.GetIntParam(string("winHeight"), winHeight);
338
339                env.GetBoolParam(string("useFullScreen"), useFullScreen);
340                env.GetFloatParam(string("expFactor"), expFactor);
341                env.GetVectorParam(string("camPosition"), camPos);
342                env.GetVectorParam(string("camDirection"), camDir);
343
344                //env.GetStringParam(string("modelPath"), model_path);
345                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
346
347                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
348                cout << "maxBatchSize: " << maxBatchSize << endl;
349                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
350
351                cout << "keyForwardMotion: " << keyForwardMotion << endl;
352                cout << "keyRotation: " << keyRotation << endl;
353                cout << "winWidth: " << winWidth << endl;
354                cout << "winHeight: " << winHeight << endl;
355                cout << "useFullScreen: " << useFullScreen << endl;
356                cout << "camPosition: " << camPos << endl;
357                cout << "expFactor: " << expFactor << endl;
358                //cout << "model path: " << model_path << endl;
359        }
360
361        ///////////////////////////
362
363        camera = new Camera(winWidth, winHeight, fov);
364        camera->SetNear(nearDist);
365       
366        camera->SetDirection(camDir);
367        camera->SetPosition(camPos);
368
369        visCamera = new Camera(winWidth, winHeight, fov);
370
371        visCamera->SetNear(0.0f);
372        visCamera->Yaw(.5 * M_PI);
373
374        renderQueue = new RenderQueue(&state, camera);
375
376        glutInitWindowSize(winWidth, winHeight);
377        glutInit(&argc, argv);
378        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
379
380        //glutInitDisplayString("samples=2");
381
382        if (!useFullScreen)
383                glutCreateWindow("FriendlyCulling");
384        else
385        {
386                glutGameModeString( "1024x768:32@75" );
387                glutEnterGameMode();
388        }
389
390        glutDisplayFunc(Display);
391        glutKeyboardFunc(KeyBoard);
392        glutSpecialFunc(Special);
393        glutReshapeFunc(Reshape);
394        glutMouseFunc(Mouse);
395        glutIdleFunc(Display);
396        glutKeyboardUpFunc(KeyUp);
397        glutSpecialUpFunc(SpecialKeyUp);
398        glutIgnoreKeyRepeat(true);
399
400        // initialise gl graphics
401        InitExtensions();
402        InitGLstate();
403
404        glEnable(GL_MULTISAMPLE_ARB);
405        glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
406        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
407
408        InitFBO();
409       
410        LeftMotion(0, 0);
411        MiddleMotion(0, 0);
412
413        perfGraph = new PerformanceGraph(1000);
414
415        loader = new ResourceManager();
416
417        //const string filename("data/city/model/city.dem");
418        const string filename = string(model_path + "city.dem");
419
420        if (loader->Load(filename, sceneEntities))
421                cout << "scene " << filename << " loaded" << endl;
422        else
423        {
424                cerr << "loading scene " << filename << " failed" << endl;
425                CleanUp();
426                exit(0);
427        }
428
429        SceneEntityContainer dummy;
430
431        const string envname = string(model_path + "env.dem");
432
433        if (loader->Load(envname, skyGeometry))
434                cout << "sky box " << filename << " loaded" << endl;
435        else
436        {
437                cerr << "loading sky box " << filename << " failed" << endl;
438                CleanUp();
439                exit(0);
440        }
441
442        const string bvh_filename = string(model_path + "city.bvh");
443        BvhLoader bvhLoader;
444        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
445
446        if (!bvh)
447        {
448                cerr << "loading bvh " << bvh_filename << " failed" << endl;
449                CleanUp();
450                exit(0);
451        }
452
453        // set far plane based on scene extent
454        myfar = 10.0f * Magnitude(bvh->GetBox().Diagonal());
455        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
456
457        bvh->SetCamera(camera);
458       
459        InitCg();
460
461        // create noise texture for ssao
462        CreateNoiseTex2D();
463
464        // init render traverser
465        ResetTraverser();
466
467        visualization = new Visualization(bvh, camera, NULL, &state);
468
469        sceneQuery = new SceneQuery(bvh->GetBox(), traverser);
470
471        // frame time is restarted every frame
472        frameTimer.Start();
473
474
475        glutMainLoop();
476
477        // clean up
478        CleanUp();
479
480        return 0;
481}
482
483
484void InitCg(void)
485{
486        // Setup Cg
487        cgSetErrorCallback(cgErrorCallback);
488
489        // Create cgContext.
490        sCgContext = cgCreateContext();
491
492        // get the best profile for this hardware
493        RenderState::sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
494        //assert(sCgFragmentProfile != CG_PROFILE_UNKNOWN);
495        cgGLSetOptimalOptions(RenderState::sCgFragmentProfile);
496
497        RenderState::sCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
498        cgGLSetOptimalOptions(RenderState::sCgVertexProfile);
499
500        sCgMrtVertexProgram =
501                cgCreateProgramFromFile(sCgContext,
502                                                                CG_SOURCE,
503                                                                "src/shaders/mrt.cg",
504                                                                RenderState::sCgVertexProfile,
505                                                                "vtx",
506                                                                NULL);
507
508        if (sCgMrtVertexProgram != NULL)
509        {
510                cgGLLoadProgram(sCgMrtVertexProgram);
511
512                Transform3::sModelMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelMatrix");
513                sModelViewProjMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelViewProj");
514        }
515
516        RenderState::sCgMrtFragmentTexProgram =
517                cgCreateProgramFromFile(sCgContext,
518                                                                CG_SOURCE,
519                                                                "src/shaders/mrt.cg",
520                                                                RenderState::sCgFragmentProfile,
521                                                                "fragtex",
522                                                                NULL);
523
524        if (RenderState::sCgMrtFragmentTexProgram != NULL)
525        {
526                cgGLLoadProgram(RenderState::sCgMrtFragmentTexProgram);
527
528                sMaxDepthParamTex = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "maxDepth");
529                Material::sDiffuseTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "diffuse");
530                Material::sAmbientTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "ambient");
531
532                cgGLSetParameter1f(sMaxDepthParamTex, 10.0f / myfar);
533                Debug << "maxdepth: " << 10.0f / myfar << endl;
534        }
535        else
536                cerr << "fragment tex program failed to load" << endl;
537
538        RenderState::sCgMrtFragmentProgram =
539                cgCreateProgramFromFile(sCgContext,
540                                                                CG_SOURCE,
541                                                                "src/shaders/mrt.cg",
542                                                                RenderState::sCgFragmentProfile,
543                                                                "frag",
544                                                                NULL);
545
546        if (RenderState::sCgMrtFragmentProgram != NULL)
547        {
548                cgGLLoadProgram(RenderState::sCgMrtFragmentProgram);
549
550                sMaxDepthParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "maxDepth");
551                Material::sDiffuseParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "diffuse");
552                Material::sAmbientParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "ambient");
553
554                cgGLSetParameter1f(sMaxDepthParam, 10.0f / myfar);
555        }
556        else
557                cerr << "fragment program failed to load" << endl;
558
559        PrintGLerror("test");
560
561
562        ///////////////
563
564        sCgSsaoProgram =
565                cgCreateProgramFromFile(sCgContext,
566                                                                CG_SOURCE,
567                                                                "src/shaders/deferred.cg",
568                                                                RenderState::sCgFragmentProfile,
569                                                                "main_ssao",
570                                                                NULL);
571
572        if (sCgSsaoProgram != NULL)
573        {
574                cgGLLoadProgram(sCgSsaoProgram);
575
576                // we need size of texture for scaling
577                sPositionsTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "positions"); 
578                sColorsTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "colors"); 
579                sNormalsTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "normals"); 
580                sNoiseTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "noiseTexture");
581                sNoiseMultiplierParam = cgGetNamedParameter(sCgSsaoProgram, "noiseMultiplier");
582                sOldModelViewProjMatrixParam = cgGetNamedParameter(sCgSsaoProgram, "oldModelViewProj");
583                sMaxDepthParamSsao = cgGetNamedParameter(sCgSsaoProgram, "maxDepth");
584                sExpFactorParamSsao = cgGetNamedParameter(sCgSsaoProgram, "expFactor");
585
586                cgGLSetParameter1f(sMaxDepthParamSsao, myfar / 10.0f);
587                cgGLSetParameter1f(sExpFactorParamSsao, expFactor);
588
589                sSamplesParamSsao = cgGetNamedParameter(sCgSsaoProgram, "samples");
590                sOldTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "oldTex"); 
591
592                GenerateSamples(); cgGLSetParameterArray2f(sSamplesParamSsao, 0, NUM_SAMPLES, (const float *)samples);
593        }
594        else
595                cerr << "ssao program failed to load" << endl;
596
597       
598        sCgDeferredProgram =
599                cgCreateProgramFromFile(sCgContext,
600                                                                CG_SOURCE,
601                                                                "src/shaders/deferred.cg",
602                                                                RenderState::sCgFragmentProfile,
603                                                                "main",
604                                                                NULL);
605
606        if (sCgDeferredProgram != NULL)
607        {
608                cgGLLoadProgram(sCgDeferredProgram);
609
610                // we need size of texture for scaling
611                sPositionsTexParam = cgGetNamedParameter(sCgDeferredProgram, "positions"); 
612                sColorsTexParam = cgGetNamedParameter(sCgDeferredProgram, "colors"); 
613                sNormalsTexParam = cgGetNamedParameter(sCgDeferredProgram, "normals");
614        }
615        else
616                cerr << "deferred program failed to load" << endl;
617
618
619        PrintGLerror("init");
620
621        cout << "cg initialization successful" << endl;
622}
623
624
625void PrintFBOStatus(GLenum status)
626{
627        switch(status)
628        {
629        case GL_FRAMEBUFFER_COMPLETE_EXT:
630                cout << "frame buffer object created successfully" << endl;
631                break;
632        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
633                cerr << "incomplete attachment" << endl;
634                break;
635        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
636                cerr << "missing attachment" << endl;
637                break;
638        case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
639                cerr << "incomplete dimensions" << endl;
640                break;
641        case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
642                cerr << "incomplete formats" << endl;
643                break;
644        case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
645                cerr << "incomplete draw buffer" << endl;
646                break;
647        case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
648                cerr << "incomplete read buffer" << endl;
649                break;
650        case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
651                cerr << "framebuffer unsupported" << endl;
652                break;
653        default:
654                cerr << "unknown status code " << status << endl;
655        }
656}
657
658
659void InitFBO()
660{
661        glGenFramebuffersEXT(1, &fbo);
662        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
663
664       
665        ////////////
666        //-- colors buffer
667
668        glGenRenderbuffersEXT(1, &colorsBuffer);
669        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorsBuffer);
670       
671        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
672
673        int samples = 8;
674        //glEnable(GL_MULTISAMPLE_ARB);
675        //glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_RGBA8, texWidth, texHeight);
676        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorsBuffer);
677       
678        glGenTextures(1, &colorsTex);
679        glBindTexture(GL_TEXTURE_2D, colorsTex);
680
681        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
682        //glGenerateMipmapEXT(GL_TEXTURE_2D);
683        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorsTex, 0);
684
685        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
686        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
687
688        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
689        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
690
691
692        //////////
693        //-- positions buffer
694
695        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
696        glGenRenderbuffersEXT(1, &positionsBuffer);
697        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, positionsBuffer);
698        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
699
700        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_RENDERBUFFER_EXT, positionsBuffer);
701
702        glGenTextures(1, &positionsTex);
703        glBindTexture(GL_TEXTURE_2D, positionsTex);
704        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
705        //glGenerateMipmapEXT(GL_TEXTURE_2D);
706        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, positionsTex, 0);
707
708        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
709        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
710
711        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
712        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
713
714        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
715       
716       
717        ////////
718        //-- normals buffer
719
720        glGenRenderbuffersEXT(1, &normalsBuffer);
721        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, normalsBuffer);
722        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, texWidth, texHeight);
723       
724        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_RENDERBUFFER_EXT, normalsBuffer);
725
726        glGenTextures(1, &normalsTex);
727        glBindTexture(GL_TEXTURE_2D, normalsTex);
728        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
729        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_TEXTURE_2D, normalsTex, 0);
730
731        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
732        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
733
734        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
735        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
736
737        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
738
739
740        ///////////
741        //-- create depth buffer
742
743        glGenRenderbuffersEXT(1, &depthBuffer);
744        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer);
745        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, texWidth, texHeight);
746        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer);
747
748       
749        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
750       
751       
752
753        //////////////////////////////////
754
755
756
757        glGenFramebuffersEXT(1, &fbo1);
758        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo1);
759
760       
761        ////////////
762        //-- colors buffer
763
764        glGenRenderbuffersEXT(1, &colorsBuffer1);
765        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorsBuffer1);
766       
767        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
768        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorsBuffer1);
769       
770        glGenTextures(1, &colorsTex1);
771        glBindTexture(GL_TEXTURE_2D, colorsTex1);
772
773        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
774        //glGenerateMipmapEXT(GL_TEXTURE_2D);
775        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorsTex1, 0);
776
777        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
778        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
779
780        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
781        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
782
783        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
784        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
785
786        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
787
788
789
790        /////////////////////////
791
792        glGenFramebuffersEXT(1, &fbo2);
793        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo2);
794
795       
796        ////////////
797        //-- colors buffer
798
799        glGenRenderbuffersEXT(1, &colorsBuffer2);
800        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorsBuffer2);
801       
802        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
803        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorsBuffer2);
804       
805        glGenTextures(1, &colorsTex2);
806        glBindTexture(GL_TEXTURE_2D, colorsTex2);
807
808        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
809        //glGenerateMipmapEXT(GL_TEXTURE_2D);
810        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorsTex2, 0);
811
812        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
813        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
814
815        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
816        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
817
818        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
819        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
820
821        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
822        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
823
824        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
825
826        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
827
828        PrintGLerror("fbo");
829}
830
831
832bool InitFont(void)
833{
834        glEnable(GL_TEXTURE_2D);
835
836        glGenTextures(1, &fontTex);
837        glBindTexture(GL_TEXTURE_2D, fontTex);
838        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
839                return false;
840
841        glDisable(GL_TEXTURE_2D);
842       
843        return true;
844}
845
846
847void InitGLstate()
848{
849        glClearColor(0.5f, 0.5f, 0.8f, 0.0f);
850       
851        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
852        glPixelStorei(GL_PACK_ALIGNMENT,1);
853       
854        glDepthFunc(GL_LESS);
855        glEnable(GL_DEPTH_TEST);
856
857        SetupLighting();
858
859        glColor3f(1.0f, 1.0f, 1.0f);
860        glShadeModel(GL_SMOOTH);
861       
862        glMaterialf(GL_FRONT, GL_SHININESS, 64);
863        glEnable(GL_NORMALIZE);
864               
865        //glEnable(GL_ALPHA_TEST);
866        glDisable(GL_ALPHA_TEST);
867        glAlphaFunc(GL_GEQUAL, 0.8f);
868
869        glFrontFace(GL_CCW);
870        glCullFace(GL_BACK);
871        //glEnable(GL_CULL_FACE);
872       
873        glDisable(GL_CULL_FACE);
874        glDisable(GL_TEXTURE_2D);
875
876        GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
877        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
878        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
879
880        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
881        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
882        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
883
884        glDepthFunc(GL_LESS);
885
886        if (!InitFont())
887                cerr << "font creation failed" << endl;
888        else
889                cout << "successfully created font" << endl;
890}
891
892
893void DrawHelpMessage()
894{
895        const char *message[] =
896        {
897                "Help information",
898                "",
899                "'F1'           - shows/dismisses this message",
900                "'F2'           - shows/hides bird eye view",
901                "'F3'           - shows/hides bounds (boxes or tight bounds)",
902                "'F4',          - shows/hides parameters",
903                "'F5'           - shows/hides statistics",
904                "'F6',          - toggles between fly/walkmode",
905                "'F7',          - cycles throw render modes",
906                "'F8',          - enables/disables ambient occlusion (only deferred)",
907                "'F9',          - shows pure algorithm render time (using glFinish)",
908                "'SPACE'        - cycles through occlusion culling algorithms",
909                "",
910                "'MOUSE LEFT'        - turn left/right, move forward/backward",
911                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
912                "'MOUSE MIDDLE'      - move up/down, left/right",
913                "'CURSOR UP/DOWN'    - move forward/backward",
914                "'CURSOR LEFT/RIGHT' - turn left/right",
915                "",
916                "'-'/'+'        - decreases/increases max batch size",
917                "'1'/'2'        - downward/upward motion",
918                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
919                "'5'/'6'        - decreases/increases assumed visible frames",
920                "",
921                "'R'            - use render queue",
922                "'B'            - use tight bounds",
923                "'M'            - use multiqueries",
924                "'O'            - use CHC optimization (geometry queries for leaves)",
925                0,
926        };
927       
928       
929        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
930
931        glRecti(30, 30, winWidth - 30, winHeight - 30);
932
933        glEnd();
934
935        glColor3f(1.0f, 1.0f, 1.0f);
936       
937        glEnable(GL_TEXTURE_2D);
938        myfont.Begin();
939
940        int x = 40, y = 30;
941
942        for(int i = 0; message[i] != 0; ++ i)
943        {
944                if(message[i][0] == '\0')
945                {
946                        y += 15;
947                }
948                else
949                {
950                        myfont.DrawString(message[i], x, winHeight - y);
951                        y += 25;
952                }
953        }
954        glDisable(GL_TEXTURE_2D);
955}
956
957
958void ResetTraverser()
959{
960        DEL_PTR(traverser);
961
962        bvh->ResetNodeClassifications();
963
964        switch (renderMode)
965        {
966        case RenderTraverser::CULL_FRUSTUM:
967                traverser = new FrustumCullingTraverser();
968                break;
969        case RenderTraverser::STOP_AND_WAIT:
970                traverser = new StopAndWaitTraverser();
971                break;
972        case RenderTraverser::CHC:
973                traverser = new CHCTraverser();
974                break;
975        case RenderTraverser::CHCPLUSPLUS:
976                traverser = new CHCPlusPlusTraverser();
977                break;
978       
979        default:
980                traverser = new FrustumCullingTraverser();
981        }
982
983        traverser->SetCamera(camera);
984        traverser->SetHierarchy(bvh);
985        traverser->SetRenderQueue(renderQueue);
986        traverser->SetRenderState(&state);
987        traverser->SetUseOptimization(useOptimization);
988        traverser->SetUseRenderQueue(useRenderQueue);
989        traverser->SetVisibilityThreshold(threshold);
990        traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
991        traverser->SetMaxBatchSize(maxBatchSize);
992        traverser->SetUseMultiQueries(useMultiQueries);
993        traverser->SetUseTightBounds(useTightBounds);
994        traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
995        traverser->SetRenderQueue(renderQueue);
996}
997
998
999void SetupLighting()
1000{
1001        glEnable(GL_LIGHTING);
1002        glEnable(GL_LIGHT0);
1003        glEnable(GL_LIGHT1);
1004       
1005        GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0};
1006        GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
1007        GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
1008           
1009        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
1010
1011        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
1012        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
1013        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
1014
1015
1016        ////////////
1017        //-- second light
1018
1019        GLfloat ambient1[] = {0.2, 0.2, 0.2, 1.0};
1020        GLfloat diffuse1[] = {1.0, 1.0, 1.0, 1.0};
1021        //GLfloat diffuse1[] = {0.5, 0.5, 0.5, 1.0};
1022        GLfloat specular1[] = {0.0, 0.0, 0.0, 1.0};
1023
1024        glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
1025        glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
1026        glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
1027
1028       
1029        //////////////////////////////
1030
1031        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
1032        glLightfv(GL_LIGHT0, GL_POSITION, position);
1033
1034        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
1035        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1036
1037        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
1038        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1039        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
1040}
1041
1042
1043void SetupEyeView()
1044{
1045        Matrix4x4 matViewing, matProjection;
1046
1047        if (renderType == RenderState::DEFERRED)
1048        {
1049                cgGLSetMatrixParameterfc(sOldModelViewProjMatrixParam, (const float *)matProjectionView.x);
1050        }
1051
1052        glMatrixMode(GL_PROJECTION);
1053        glLoadIdentity();
1054
1055        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1056
1057        glMatrixMode(GL_MODELVIEW);
1058        glLoadIdentity();
1059        camera->SetupCameraView();
1060
1061        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
1062        glLightfv(GL_LIGHT0, GL_POSITION, position);
1063
1064        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
1065        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1066
1067       
1068        camera->GetModelViewMatrix(matViewing);
1069        camera->GetProjectionMatrix(matProjection);
1070
1071        matProjectionView = matViewing * matProjection;
1072       
1073        if (renderType == RenderState::DEFERRED)
1074        {
1075                // set modelview matrix for shaders
1076                cgGLSetStateMatrixParameter(sModelViewProjMatrixParam,
1077                                                                        CG_GL_MODELVIEW_PROJECTION_MATRIX,
1078                                                                        CG_GL_MATRIX_IDENTITY);
1079
1080                static Matrix4x4 identity = IdentityMatrix();
1081                cgGLSetMatrixParameterfc(Transform3::sModelMatrixParam, (const float *)identity.x);
1082        }               
1083}
1084
1085
1086void KeyHorizontalMotion(float shift)
1087{
1088        Vector3 hvec = camera->GetDirection();
1089        hvec.z = 0;
1090
1091        Vector3 pos = camera->GetPosition();
1092        pos += hvec * shift;
1093       
1094        camera->SetPosition(pos);
1095}
1096
1097
1098void KeyVerticalMotion(float shift)
1099{
1100        Vector3 uvec = Vector3(0, 0, shift);
1101
1102        Vector3 pos = camera->GetPosition();
1103        pos += uvec;
1104       
1105        camera->SetPosition(pos);
1106}
1107
1108
1109void Display()
1110{       
1111        Vector3 oldPos = camera->GetPosition();
1112
1113        if (leftKeyPressed)
1114                camera->Pitch(KeyRotationAngle());
1115        if (rightKeyPressed)
1116                camera->Pitch(-KeyRotationAngle());
1117        if (upKeyPressed)
1118                KeyHorizontalMotion(KeyShift());
1119        if (downKeyPressed)
1120                KeyHorizontalMotion(-KeyShift());
1121        if (ascendKeyPressed)
1122                KeyVerticalMotion(KeyShift());
1123        if (descendKeyPressed)
1124                KeyVerticalMotion(-KeyShift());
1125
1126        // place view on ground
1127        if (!flyMode) PlaceViewer(oldPos);
1128
1129        if (showAlgorithmTime)
1130        {
1131                glFinish();
1132                algTimer.Start();
1133        }
1134       
1135        // render without shading
1136        switch (renderType)
1137        {
1138        case RenderState::FIXED:
1139       
1140                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1141
1142                state.SetRenderType(RenderState::FIXED);
1143                glEnable(GL_LIGHTING);
1144
1145                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1146                cgGLDisableProfile(RenderState::sCgVertexProfile);
1147
1148                glDrawBuffers(1, mrt);
1149
1150                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1151
1152                break;
1153
1154        case RenderState::DEPTH_PASS:
1155                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1156
1157                state.SetRenderType(RenderState::DEPTH_PASS);
1158                glDisable(GL_LIGHTING);
1159
1160                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1161                cgGLDisableProfile(RenderState::sCgVertexProfile);
1162       
1163                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1164
1165                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1166
1167                glDrawBuffers(1, mrt);
1168
1169                break;
1170       
1171        case RenderState::DEFERRED:
1172                state.SetRenderType(RenderState::DEFERRED);
1173
1174                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
1175       
1176                glPushAttrib(GL_VIEWPORT_BIT);
1177                glViewport(0, 0, texWidth, texHeight);
1178
1179                cgGLEnableProfile(RenderState::sCgFragmentProfile);
1180                cgGLBindProgram(RenderState::sCgMrtFragmentProgram);
1181
1182                cgGLEnableProfile(RenderState::sCgVertexProfile);
1183                cgGLBindProgram(sCgMrtVertexProgram);
1184
1185                glDrawBuffers(3, mrt);
1186
1187                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1188
1189                break;
1190        }
1191
1192
1193        glDepthFunc(GL_LESS);
1194
1195        glDisable(GL_TEXTURE_2D);
1196        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1197               
1198
1199        LODLevel::InitFrame(camera->GetPosition());
1200
1201
1202        // bring eye modelview matrix up-to-date
1203        SetupEyeView();
1204
1205
1206        /*state.Reset();
1207        state.SetState(RenderState::RENDER);
1208       
1209        glEnableClientState(GL_VERTEX_ARRAY);
1210        glEnableClientState(GL_NORMAL_ARRAY);
1211
1212        for (int i = 0; i < loader->mSceneEntities.size(); ++ i)
1213        {
1214                SceneEntity *ent = loader->mSceneEntities[i];
1215
1216                ent->UpdateLODs(camera);
1217                ent->Render(&state);
1218        }*/
1219
1220        // actually render the scene geometry using one of the specified algorithms
1221        traverser->RenderScene();
1222
1223
1224
1225        /////////
1226        //-- do the rest of the rendering
1227
1228        glEnableClientState(GL_VERTEX_ARRAY);
1229        glEnableClientState(GL_NORMAL_ARRAY);
1230
1231
1232        // reset depth pass and render visible objects
1233        if (renderType == RenderState::DEPTH_PASS)
1234        {
1235                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1236                RenderVisibleObjects();
1237        }
1238       
1239
1240        ///////////////
1241        //-- render sky
1242
1243        RenderSky();
1244
1245        state.Reset();
1246
1247        glDisableClientState(GL_VERTEX_ARRAY);
1248        glDisableClientState(GL_NORMAL_ARRAY);
1249
1250        if (renderType == RenderState::DEFERRED)
1251        {
1252                glPopAttrib();
1253                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1254
1255                cgGLDisableProfile(RenderState::sCgVertexProfile);
1256                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1257
1258                glDrawBuffers(1, mrt);
1259
1260                DisplayRenderTexture();
1261        }
1262
1263       
1264        ///////////
1265
1266        state.SetRenderType(RenderState::FIXED);
1267
1268        if (showAlgorithmTime)
1269        {
1270                glFinish();
1271
1272                algTime = algTimer.Elapsedms();
1273                perfGraph->AddData(algTime);
1274
1275                perfGraph->Draw();
1276        }
1277        else
1278        {
1279                if (visMode) DisplayVisualization();
1280        }
1281
1282        glFlush();
1283
1284        const bool restart = true;
1285        elapsedTime = frameTimer.Elapsedms(restart);
1286
1287        DisplayStats();
1288
1289        isFirstTexture = !isFirstTexture;
1290
1291        glutSwapBuffers();
1292}
1293
1294
1295#pragma warning( disable : 4100 )
1296void KeyBoard(unsigned char c, int x, int y)
1297{
1298        switch(c)
1299        {
1300        case 27:
1301                CleanUp();
1302                exit(0);
1303                break;
1304        case 32: //space
1305                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
1306                ResetTraverser();
1307                break;
1308        case 'h':
1309        case 'H':
1310                showHelp = !showHelp;
1311                break;
1312        case '+':
1313                maxBatchSize += 10;
1314                traverser->SetMaxBatchSize(maxBatchSize);
1315                break;
1316        case '-':
1317                maxBatchSize -= 10;
1318                if (maxBatchSize < 0) maxBatchSize = 1;
1319                traverser->SetMaxBatchSize(maxBatchSize);               
1320                break;
1321        case 'M':
1322        case 'm':
1323                useMultiQueries = !useMultiQueries;
1324                traverser->SetUseMultiQueries(useMultiQueries);
1325                break;
1326        case '1':
1327                descendKeyPressed = true;
1328                break;
1329        case '2':
1330                ascendKeyPressed = true;
1331                break;
1332        case '3':
1333                if (trianglesPerVirtualLeaf >= 100)
1334                        trianglesPerVirtualLeaf -= 100;
1335                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1336                break;
1337        case '4':
1338                trianglesPerVirtualLeaf += 100;
1339                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1340                break;
1341        case '5':
1342                assumedVisibleFrames -= 1;
1343                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1344                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1345                break;
1346        case '6':
1347                assumedVisibleFrames += 1;
1348                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1349                break;
1350        case '7':
1351                expFactor *= 0.5f;
1352                break;
1353        case '8':
1354                expFactor *= 2.0f;
1355                if (expFactor > 1.0f) expFactor = 1.0f;
1356                break;
1357        case 'o':
1358        case 'O':
1359                useOptimization = !useOptimization;
1360                traverser->SetUseOptimization(useOptimization);
1361                break;
1362        case 'a':
1363        case 'A':
1364                        leftKeyPressed = true;
1365                break;
1366        case 'd':
1367        case 'D':
1368                        rightKeyPressed = true;
1369                break;
1370        case 'w':
1371        case 'W':
1372                        upKeyPressed = true;
1373                break;
1374        case 's':
1375        case 'S':
1376                        downKeyPressed = true;
1377                break;
1378        case 'r':
1379        case 'R':
1380                {
1381                        useRenderQueue = !useRenderQueue;
1382                        traverser->SetUseRenderQueue(useRenderQueue);
1383                }
1384                break;
1385        case 'b':
1386        case 'B':
1387                {
1388                        useTightBounds = !useTightBounds;
1389                        traverser->SetUseTightBounds(useTightBounds);
1390                }
1391                break;
1392        default:
1393                return;
1394        }
1395
1396        glutPostRedisplay();
1397}
1398
1399
1400void SpecialKeyUp(int c, int x, int y)
1401{
1402        switch (c)
1403        {
1404        case GLUT_KEY_LEFT:
1405                leftKeyPressed = false;
1406                break;
1407        case GLUT_KEY_RIGHT:
1408                rightKeyPressed = false;
1409                break;
1410        case GLUT_KEY_UP:
1411                upKeyPressed = false;
1412                break;
1413        case GLUT_KEY_DOWN:
1414                downKeyPressed = false;
1415                break;
1416        default:
1417                return;
1418        }
1419        //glutPostRedisplay();
1420}
1421
1422
1423void KeyUp(unsigned char c, int x, int y)
1424{
1425        switch (c)
1426        {
1427        case 'A':
1428        case 'a':
1429                leftKeyPressed = false;
1430                break;
1431        case 'D':
1432        case 'd':
1433                rightKeyPressed = false;
1434                break;
1435        case 'W':
1436        case 'w':
1437                upKeyPressed = false;
1438                break;
1439        case 'S':
1440        case 's':
1441                downKeyPressed = false;
1442                break;
1443        case '1':
1444                descendKeyPressed = false;
1445                break;
1446        case '2':
1447                ascendKeyPressed = false;
1448                break;
1449       
1450        default:
1451                return;
1452        }
1453        //glutPostRedisplay();
1454}
1455
1456
1457void Special(int c, int x, int y)
1458{
1459        switch(c)
1460        {
1461        case GLUT_KEY_F1:
1462                showHelp = !showHelp;
1463                break;
1464        case GLUT_KEY_F2:
1465                visMode = !visMode;
1466                break;
1467        case GLUT_KEY_F3:
1468                showBoundingVolumes = !showBoundingVolumes;
1469                traverser->SetShowBounds(showBoundingVolumes);
1470                break;
1471        case GLUT_KEY_F4:
1472                showOptions = !showOptions;
1473                break;
1474        case GLUT_KEY_F5:
1475                showStatistics = !showStatistics;
1476                break;
1477        case GLUT_KEY_F6:
1478                flyMode = !flyMode;
1479                break;
1480        case GLUT_KEY_F7:
1481
1482                renderType = (renderType + 1) % 3;
1483                traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
1484               
1485                break;
1486        case GLUT_KEY_F8:
1487                useSsao = !useSsao;
1488                break;
1489        case GLUT_KEY_F9:
1490                showAlgorithmTime = !showAlgorithmTime;
1491                break;
1492
1493        case GLUT_KEY_LEFT:
1494                {
1495                        leftKeyPressed = true;
1496                        camera->Pitch(KeyRotationAngle());
1497                }
1498                break;
1499        case GLUT_KEY_RIGHT:
1500                {
1501                        rightKeyPressed = true;
1502                        camera->Pitch(-KeyRotationAngle());
1503                }
1504                break;
1505        case GLUT_KEY_UP:
1506                {
1507                        upKeyPressed = true;
1508                        KeyHorizontalMotion(KeyShift());
1509                }
1510                break;
1511        case GLUT_KEY_DOWN:
1512                {
1513                        downKeyPressed = true;
1514                        KeyHorizontalMotion(-KeyShift());
1515                }
1516                break;
1517        default:
1518                return;
1519
1520        }
1521
1522        glutPostRedisplay();
1523}
1524
1525#pragma warning( default : 4100 )
1526
1527
1528void Reshape(int w, int h)
1529{
1530        winAspectRatio = 1.0f;
1531
1532        glViewport(0, 0, w, h);
1533       
1534        winWidth = w;
1535        winHeight = h;
1536
1537        if (w) winAspectRatio = (float) w / (float) h;
1538
1539        glMatrixMode(GL_PROJECTION);
1540        glLoadIdentity();
1541
1542        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1543
1544        glMatrixMode(GL_MODELVIEW);
1545
1546        glutPostRedisplay();
1547}
1548
1549
1550void Mouse(int button, int state, int x, int y)
1551{
1552        if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
1553        {
1554                xEyeBegin = x;
1555                yMotionBegin = y;
1556
1557                glutMotionFunc(LeftMotion);
1558        }
1559        else if ((button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN))
1560        {
1561                xEyeBegin = x;
1562                yEyeBegin = y;
1563                yMotionBegin = y;
1564
1565                glutMotionFunc(RightMotion);
1566        }
1567        else if ((button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN))
1568        {
1569                horizontalMotionBegin = x;
1570                verticalMotionBegin = y;
1571                glutMotionFunc(MiddleMotion);
1572        }
1573
1574        glutPostRedisplay();
1575}
1576
1577
1578/**     rotation for left/right mouse drag
1579        motion for up/down mouse drag
1580*/
1581void LeftMotion(int x, int y)
1582{
1583        Vector3 viewDir = camera->GetDirection();
1584        Vector3 pos = camera->GetPosition();
1585
1586        // don't move in the vertical direction
1587        Vector3 horView(viewDir[0], viewDir[1], 0);
1588       
1589        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1590
1591        camera->Pitch(eyeXAngle);
1592
1593        pos += horView * (yMotionBegin - y) * 0.2f;
1594       
1595        camera->SetPosition(pos);
1596       
1597        xEyeBegin = x;
1598        yMotionBegin = y;
1599
1600        glutPostRedisplay();
1601}
1602
1603
1604/**     rotation for left / right mouse drag
1605        motion for up / down mouse drag
1606*/
1607void RightMotion(int x, int y)
1608{
1609        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1610        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1611
1612        camera->Yaw(eyeYAngle);
1613        camera->Pitch(eyeXAngle);
1614
1615        xEyeBegin = x;
1616        yEyeBegin = y;
1617
1618        glutPostRedisplay();
1619}
1620
1621
1622// strafe
1623void MiddleMotion(int x, int y)
1624{
1625        Vector3 viewDir = camera->GetDirection();
1626        Vector3 pos = camera->GetPosition();
1627
1628        // the 90 degree rotated view vector
1629        // y zero so we don't move in the vertical
1630        Vector3 rVec(viewDir[0], viewDir[1], 0);
1631       
1632        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1633        rVec = rot * rVec;
1634       
1635        pos -= rVec * (x - horizontalMotionBegin) * 0.1f;
1636        pos[2] += (verticalMotionBegin - y) * 0.1f;
1637
1638        camera->SetPosition(pos);
1639
1640        horizontalMotionBegin = x;
1641        verticalMotionBegin = y;
1642
1643        glutPostRedisplay();
1644}
1645
1646
1647void InitExtensions(void)
1648{
1649        GLenum err = glewInit();
1650
1651        if (GLEW_OK != err)
1652        {
1653                // problem: glewInit failed, something is seriously wrong
1654                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
1655                exit(1);
1656        }
1657        if  (!GLEW_ARB_occlusion_query)
1658        {
1659                printf("I require the GL_ARB_occlusion_query to work.\n");
1660                exit(1);
1661        }
1662}
1663
1664
1665void Begin2D()
1666{
1667        glDisable(GL_LIGHTING);
1668        glDisable(GL_DEPTH_TEST);
1669
1670        glMatrixMode(GL_PROJECTION);
1671        glPushMatrix();
1672        glLoadIdentity();
1673
1674        gluOrtho2D(0, winWidth, 0, winHeight);
1675
1676        glMatrixMode(GL_MODELVIEW);
1677        glPushMatrix();
1678        glLoadIdentity();
1679}
1680
1681
1682void End2D()
1683{
1684        glMatrixMode(GL_PROJECTION);
1685        glPopMatrix();
1686
1687        glMatrixMode(GL_MODELVIEW);
1688        glPopMatrix();
1689
1690        glEnable(GL_LIGHTING);
1691        glEnable(GL_DEPTH_TEST);
1692}
1693
1694
1695// displays the visualisation of culling algorithm
1696void DisplayVisualization()
1697{
1698        visualization->SetFrameId(traverser->GetCurrentFrameId());
1699       
1700        Begin2D();
1701        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1702        glEnable(GL_BLEND);
1703        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
1704
1705        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
1706        glDisable(GL_BLEND);
1707        End2D();
1708       
1709       
1710        AxisAlignedBox3 box = bvh->GetBox();
1711
1712        // hack: set far plane for viz
1713        camera->SetFar(0.35f * Magnitude(box.Diagonal()));
1714
1715        const float offs = box.Size().x * 0.3f;
1716       
1717        //Vector3 vizpos = Vector3(box.Min().x, box.Min().y + box.Size().y * 0.5f, box.Min().z + box.Size().z * 50);
1718        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
1719       
1720        visCamera->SetPosition(vizpos);
1721        visCamera->ResetPitchAndYaw();
1722        //visCamera->Pitch(M_PI);
1723
1724        glPushAttrib(GL_VIEWPORT_BIT);
1725        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
1726
1727        glMatrixMode(GL_PROJECTION);
1728        glPushMatrix();
1729
1730        glLoadIdentity();
1731       
1732        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
1733
1734        glMatrixMode(GL_MODELVIEW);
1735        glPushMatrix();
1736
1737        visCamera->SetupCameraView();
1738
1739        //Matrix4x4 rotX = RotationXMatrix(camera->GetYaw());
1740        //glMultMatrixf((float *)rotX.x);
1741        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
1742        glMultMatrixf((float *)rotZ.x);
1743
1744        Vector3 pos = camera->GetPosition();
1745        glTranslatef(-pos.x, -pos.y, -pos.z);
1746
1747
1748        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
1749        glLightfv(GL_LIGHT0, GL_POSITION, position);
1750
1751        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
1752        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1753
1754        glClear(GL_DEPTH_BUFFER_BIT);
1755
1756
1757        ////////////
1758        //-- visualization of the occlusion culling
1759
1760        visualization->Render();
1761       
1762       
1763        // reset previous settings
1764        glPopAttrib();
1765
1766        glMatrixMode(GL_PROJECTION);
1767        glPopMatrix();
1768        glMatrixMode(GL_MODELVIEW);
1769        glPopMatrix();
1770}
1771
1772
1773// cleanup routine after the main loop
1774void CleanUp()
1775{
1776        DEL_PTR(traverser);
1777        DEL_PTR(sceneQuery);
1778        DEL_PTR(bvh);
1779        DEL_PTR(visualization);
1780        DEL_PTR(camera);
1781        DEL_PTR(loader);
1782        DEL_PTR(renderQueue);
1783        DEL_PTR(perfGraph);
1784
1785        if (sCgMrtVertexProgram)
1786                cgDestroyProgram(sCgMrtVertexProgram);
1787        if (RenderState::sCgMrtFragmentProgram)
1788                cgDestroyProgram(RenderState::sCgMrtFragmentProgram);
1789        if (RenderState::sCgMrtFragmentTexProgram)
1790                cgDestroyProgram(RenderState::sCgMrtFragmentTexProgram);
1791        if (sCgSsaoProgram)
1792                cgDestroyProgram(sCgSsaoProgram);
1793        if (sCgDeferredProgram)
1794                cgDestroyProgram(sCgDeferredProgram);
1795        if (sCgContext)
1796                cgDestroyContext(sCgContext);
1797
1798        glDeleteFramebuffersEXT(1, &fbo);
1799        glDeleteRenderbuffersEXT(1, &depthBuffer);
1800        glDeleteRenderbuffersEXT(1, &colorsBuffer);
1801        glDeleteRenderbuffersEXT(1, &normalsBuffer);
1802        glDeleteRenderbuffersEXT(1, &positionsBuffer);
1803
1804        glDeleteTextures(1, &colorsTex);
1805        glDeleteTextures(1, &normalsTex);
1806        glDeleteTextures(1, &positionsTex);
1807        glDeleteTextures(1, &noiseTex);
1808        glDeleteTextures(1, &fontTex);
1809}
1810
1811
1812// this function inserts a dezimal point after each 1000
1813void CalcDecimalPoint(string &str, int d, int len)
1814{
1815        static vector<int> numbers;
1816        numbers.clear();
1817
1818        static string shortStr;
1819        shortStr.clear();
1820
1821        static char hstr[100];
1822
1823        while (d != 0)
1824        {
1825                numbers.push_back(d % 1000);
1826                d /= 1000;
1827        }
1828
1829        // first element without leading zeros
1830        if (numbers.size() > 0)
1831        {
1832                sprintf(hstr, "%d", numbers.back());
1833                shortStr.append(hstr);
1834        }
1835       
1836        for (int i = (int)numbers.size() - 2; i >= 0; i--)
1837        {
1838                sprintf(hstr, ",%03d", numbers[i]);
1839                shortStr.append(hstr);
1840        }
1841
1842        int dif = len - (int)shortStr.size();
1843
1844        for (int i = 0; i < dif; ++ i)
1845        {
1846                str += " ";
1847        }
1848
1849        str.append(shortStr);
1850}
1851
1852
1853void DisplayStats()
1854{
1855        static char msg[9][300];
1856
1857        static double frameTime = elapsedTime;
1858        static double renderTime = algTime;
1859
1860        const float expFactor = 0.1f;
1861
1862        // if some strange render time spike happened in this frame => don't count
1863        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1864       
1865        static float rTime = 1000.0f;
1866
1867        if (showAlgorithmTime)
1868        {
1869                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1870        }
1871
1872        accumulatedTime += elapsedTime;
1873
1874        if (accumulatedTime > 500) // update every fraction of a second
1875        {       
1876                accumulatedTime = 0;
1877
1878                if (frameTime) fps = 1e3f / (float)frameTime;
1879
1880                rTime = renderTime;
1881                renderedObjects = traverser->GetStats().mNumRenderedGeometry;
1882                renderedNodes = traverser->GetStats().mNumRenderedNodes;
1883                renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1884
1885                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1886                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1887                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1888                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1889                stateChanges = traverser->GetStats().mNumStateChanges;
1890                numBatches = traverser->GetStats().mNumBatches;
1891        }
1892
1893
1894        Begin2D();
1895
1896        glEnable(GL_BLEND);
1897        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1898
1899        if (showHelp)
1900        {       
1901                DrawHelpMessage();
1902        }
1903        else
1904        {
1905                if (showOptions)
1906                {
1907                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1908                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1909                }
1910
1911                if (showStatistics)
1912                {
1913                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1914                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1915                }
1916
1917                glEnable(GL_TEXTURE_2D);
1918
1919                myfont.Begin();
1920
1921                if (showOptions)
1922                {
1923                        glColor3f(0.0f, 1.0f, 0.0f);
1924
1925                        int i = 0;
1926
1927                        static char *renderTypeStr[] = {"fixed function", "fixed function + depth pass", "deferred shading"};
1928       
1929                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1930                                                        useMultiQueries, useTightBounds, useRenderQueue);
1931
1932                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderTypeStr[renderType], useSsao);
1933
1934                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
1935
1936                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1937                                assumedVisibleFrames, maxBatchSize);
1938
1939                        for (int j = 0; j < 4; ++ j)
1940                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
1941                }
1942
1943                if (showStatistics)
1944                {
1945                        glColor3f(1.0f, 1.0f, 0.0f);
1946
1947                        string str;
1948                        string str2;
1949
1950                        int len = 10;
1951                        CalcDecimalPoint(str, renderedTriangles, len);
1952                        CalcDecimalPoint(str2, bvh->GetBvhStats().mTriangles, len);
1953
1954                        int i = 4;
1955
1956                        sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
1957                                renderedNodes, bvh->GetNumVirtualNodes(), str.c_str(), str2.c_str());
1958
1959                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1960                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1961
1962                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1963                                issuedQueries, stateChanges, numBatches);
1964
1965                        for (int j = 4; j < 7; ++ j)
1966                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
1967                }
1968
1969                glColor3f(1.0f, 1.0f, 1.0f);
1970                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
1971               
1972                if (!showAlgorithmTime)
1973                {
1974                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1975                }
1976                else
1977                {
1978                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1979                }
1980
1981                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
1982               
1983                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1984                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
1985        }
1986
1987        glDisable(GL_BLEND);
1988        glDisable(GL_TEXTURE_2D);
1989
1990        End2D();
1991}       
1992
1993
1994void RenderSky()
1995{
1996        SceneEntityContainer::const_iterator sit, sit_end = skyGeometry.end();
1997
1998        for (sit = skyGeometry.begin(); sit != sit_end; ++ sit)
1999                (*sit)->Render(&state);
2000}
2001
2002
2003void RenderVisibleObjects()
2004{
2005        state.SetRenderType(RenderState::FIXED);
2006        state.Reset();
2007
2008        glEnable(GL_LIGHTING);
2009        glDepthFunc(GL_LEQUAL);
2010
2011        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
2012
2013        SceneEntityContainer::const_iterator sit,
2014                sit_end = traverser->GetVisibleObjects().end();
2015
2016        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
2017                renderQueue->Enqueue(*sit);
2018               
2019        renderQueue->Apply();
2020
2021        glDepthFunc(GL_LESS);
2022}
2023
2024
2025void PlaceViewer(const Vector3 &oldPos)
2026{
2027        Vector3 playerPos = camera->GetPosition();
2028
2029        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
2030
2031        if (validIntersect )
2032                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
2033        {
2034                camera->SetPosition(playerPos);
2035        }
2036}
2037
2038
2039void DisplayRenderTexture3()
2040{
2041        glEnable(GL_TEXTURE_2D);
2042
2043        if (isFirstTexture)
2044                glBindTexture(GL_TEXTURE_2D, colorsTex1);
2045        else
2046                glBindTexture(GL_TEXTURE_2D, colorsTex2);
2047
2048        glDisable(GL_LIGHTING);
2049       
2050        glMatrixMode(GL_PROJECTION);
2051        glPushMatrix();
2052        glLoadIdentity();
2053
2054        glMatrixMode(GL_MODELVIEW);
2055        glPushMatrix();
2056        glLoadIdentity();
2057
2058        const float offs = 0.5f;
2059        glOrtho(-offs, offs, -offs, offs, 0, 1);
2060       
2061        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2062
2063        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
2064        glBegin(GL_QUADS);
2065
2066        glTexCoord2f(0, 0); glVertex3f(-offs, -offs, -0.5f);
2067        glTexCoord2f(1, 0); glVertex3f( offs, -offs, -0.5f);
2068        glTexCoord2f(1, 1); glVertex3f( offs,  offs, -0.5f);
2069        glTexCoord2f(0, 1); glVertex3f(-offs,  offs, -0.5f);
2070
2071        glEnd();
2072
2073        glEnable(GL_LIGHTING);
2074        glDisable(GL_TEXTURE_2D);
2075       
2076        glMatrixMode(GL_PROJECTION);
2077        glPopMatrix();
2078
2079        glMatrixMode(GL_MODELVIEW);
2080        glPopMatrix();
2081
2082        PrintGLerror("displaytexture3");
2083}
2084
2085
2086void DisplayRenderTexture()
2087{
2088        GLuint oldTex;
2089
2090        if (isFirstTexture)
2091        {
2092                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo1);
2093                oldTex = colorsTex2;
2094        }
2095        else
2096        {
2097                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo2);
2098                oldTex = colorsTex1;
2099        }
2100
2101        glPushAttrib(GL_VIEWPORT_BIT);
2102        glViewport(0, 0, texWidth, texHeight);
2103
2104        glDrawBuffers(1, mrt);
2105
2106        glDisable(GL_ALPHA_TEST);
2107        glDisable(GL_TEXTURE_2D);
2108        glDisable(GL_LIGHTING);
2109       
2110        glMatrixMode(GL_PROJECTION);
2111        glPushMatrix();
2112        glLoadIdentity();
2113
2114        glMatrixMode(GL_MODELVIEW);
2115        glPushMatrix();
2116        glLoadIdentity();
2117
2118        const float offs = 0.5f;
2119       
2120        glOrtho(-offs, offs, -offs, offs, 0, 1);
2121       
2122        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2123
2124        cgGLEnableProfile(RenderState::sCgFragmentProfile);
2125
2126        if (useSsao)
2127        {
2128                cgGLBindProgram(sCgSsaoProgram);
2129               
2130                cgGLSetTextureParameter(sPositionsTexParamSsao, positionsTex);
2131                cgGLEnableTextureParameter(sPositionsTexParamSsao);
2132
2133                cgGLSetTextureParameter(sColorsTexParamSsao, colorsTex);
2134                cgGLEnableTextureParameter(sColorsTexParamSsao);
2135
2136                cgGLSetTextureParameter(sNormalsTexParamSsao, normalsTex);
2137                cgGLEnableTextureParameter(sNormalsTexParamSsao);
2138
2139                cgGLSetTextureParameter(sNoiseTexParamSsao, noiseTex);
2140                cgGLEnableTextureParameter(sNoiseTexParamSsao);
2141
2142                cgGLSetTextureParameter(sOldTexParamSsao, oldTex);
2143                cgGLEnableTextureParameter(sOldTexParamSsao);
2144
2145                cgGLSetParameter1f(sNoiseMultiplierParam, RandomValue(3.0f, 17.0f));
2146                cgGLSetParameter1f(sExpFactorParamSsao, expFactor);
2147
2148                GenerateSamples(); cgGLSetParameterArray2f(sSamplesParamSsao, 0, NUM_SAMPLES, (const float *)samples);
2149        }
2150        else
2151        {
2152                cgGLBindProgram(sCgDeferredProgram);
2153
2154                cgGLSetTextureParameter(sPositionsTexParam, positionsTex);
2155                cgGLEnableTextureParameter(sPositionsTexParam);
2156
2157                cgGLSetTextureParameter(sColorsTexParam, colorsTex);
2158                cgGLEnableTextureParameter(sColorsTexParam);
2159
2160                cgGLSetTextureParameter(sNormalsTexParam, normalsTex);
2161                cgGLEnableTextureParameter(sNormalsTexParam);
2162        }
2163
2164        Vector3 tl, tr, bl, br;
2165        ComputeViewVectors(tl, tr, bl, br);
2166
2167        glColor3f(1.0f, 1.0f, 1.0f);
2168
2169        glBegin(GL_QUADS);
2170
2171        // note: slightly larger texture hides ambient occlusion error on border but costs resolution
2172        //float offs2 = 0.55f;
2173        float offs2 = 0.5f;
2174
2175        glColor3f(bl.x, bl.y, bl.z); glTexCoord2f(0, 0); glVertex3f(-offs2, -offs2, -0.5f);
2176        glColor3f(br.x, br.y, br.z); glTexCoord2f(1, 0); glVertex3f( offs2, -offs2, -0.5f);
2177        glColor3f(tr.x, tr.y, tr.z); glTexCoord2f(1, 1); glVertex3f( offs2,  offs2, -0.5f);
2178        glColor3f(tl.x, tl.y, tl.z); glTexCoord2f(0, 1); glVertex3f(-offs2,  offs2, -0.5f);
2179
2180        glEnd();
2181
2182       
2183        if (useSsao)
2184        {
2185                cgGLDisableTextureParameter(sColorsTexParamSsao);
2186                cgGLDisableTextureParameter(sPositionsTexParamSsao);
2187                cgGLDisableTextureParameter(sNormalsTexParamSsao);
2188                cgGLDisableTextureParameter(sNoiseTexParamSsao);
2189                cgGLDisableTextureParameter(sOldTexParamSsao);
2190        }
2191        else
2192        {
2193                cgGLDisableTextureParameter(sColorsTexParam);
2194                cgGLDisableTextureParameter(sPositionsTexParam);
2195                cgGLDisableTextureParameter(sNormalsTexParam);
2196        }
2197
2198        cgGLDisableProfile(RenderState::sCgFragmentProfile);
2199       
2200        glEnable(GL_LIGHTING);
2201        glDisable(GL_TEXTURE_2D);
2202       
2203        glMatrixMode(GL_PROJECTION);
2204        glPopMatrix();
2205
2206        glMatrixMode(GL_MODELVIEW);
2207        glPopMatrix();
2208
2209        glPopAttrib();
2210
2211        PrintGLerror("displaytexture");
2212
2213        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
2214
2215        DisplayRenderTexture3();
2216}
2217
2218#if 0
2219// kustls magic sample positions
2220void GenerateSamples()
2221{
2222        static const float mysamples[] =
2223        {
2224                -0.326212f, -0.405805f,
2225                -0.840144f, -0.07358f,
2226                -0.695914f, 0.457137f,
2227                -0.203345f, 0.620716,
2228                0.96234f, -0.194983f,
2229                0.473434f, -0.480026f,
2230                0.519456, 0.767022f,
2231                0.185461f, -0.893124f,
2232                0.507431f, 0.064425f,
2233                0.89642f, 0.412458f,
2234                -0.32194f, -0.932615f,
2235                -0.791559f, -0.597705f,
2236                0.326212f, 0.405805f,
2237                0.840144f, 0.07358f,
2238                0.695914f, -0.457137f,
2239                0.203345f, -0.620716,
2240                -0.96234f, 0.194983f,
2241                -0.473434f, 0.480026f,
2242                -0.519456, -0.767022f,
2243                -0.185461f, 0.893124f,
2244                -0.507431f, -0.064425f,
2245                -0.89642f, -0.412458f,
2246                0.32194f, 0.932615f,
2247                0.791559f, 0.597705f
2248        };
2249
2250        for (int i = 0; i < NUM_SAMPLES; ++ i)
2251        {
2252                samples[i] = mysamples[i];
2253        }
2254}
2255
2256#else
2257
2258
2259void GenerateSamples()
2260{
2261        static HaltonSequence halton;
2262
2263        float r[2];
2264
2265        // generates poisson distribution on disc
2266        float minDist = 2.0f / sqrt((float)NUM_SAMPLES);
2267
2268        //cout << "minDist before= " << minDist << endl;
2269
2270        for (int i = 0; i < NUM_SAMPLES * 2; i += 2)
2271        {
2272                int tries = 0, totalTries = 0;
2273
2274                // repeat until valid sample was found
2275                while (1)
2276                {
2277                        ++ tries;
2278                        ++ totalTries;
2279
2280                        halton.GetNext(2, r);
2281
2282                        //const float rx = RandomValue(-1, 1);
2283                        //const float ry = RandomValue(-1, 1);
2284
2285                        const float rx = r[0] * 2.0f - 1.0f;
2286                        const float ry = r[1] * 2.0f - 1.0f;
2287
2288                        // check if in disk, else exit early
2289                        if (rx * rx + ry * ry > 1)
2290                                continue;
2291
2292                        bool sampleValid = true;
2293
2294                        // check poisson property
2295                        for (int j = 0; ((j < i) && sampleValid); j += 2)
2296                        {
2297                                const float dist =
2298                                        sqrt((samples[j] - rx) * (samples[j] - rx) +
2299                                             (samples[j + 1] - ry) * (samples[j + 1] - ry));
2300                       
2301                                if (dist < minDist)
2302                                        sampleValid = false;
2303                        }
2304
2305                        if (sampleValid)
2306                        {
2307                                samples[i] = rx;
2308                                samples[i + 1]= ry;
2309                                break;
2310                        }
2311
2312                        if (tries > 2000)
2313                        {
2314                                minDist *= 0.9f;
2315                                tries = 0;
2316                        }
2317                }
2318                //cout << "sample: " << samples[i] << " " << i / 2 << " " << samples[i + 1] << " r: " << sqrt(samples[i] * samples[i]  + samples[i + 1] * samples[i + 1]) << " tries: " << totalTries << endl;
2319        }
2320
2321        //cout << "minDist after= " << minDist << endl;
2322}
2323
2324
2325#endif
2326
2327
2328void ComputeViewVectors(Vector3 &tl, Vector3 &tr, Vector3 &bl, Vector3 &br)
2329{
2330        float myfov = fov * M_PI / 180.0f;
2331
2332        const float w_far = 2.0f * tan(myfov / 2.0f);
2333        const float aspect = texWidth / texHeight;
2334
2335        const float h_far = w_far / aspect;
2336
2337        float t1 = h_far * 0.5f;
2338        float t2 = w_far * 0.5f;
2339
2340#if 0
2341        bl = Normalize(-Vector3(-t1, -t2, 1.0f));
2342        br = Normalize(-Vector3( t1, -t2, 1.0f));
2343        tl = Normalize(-Vector3(-t1,  t2, 1.0f));
2344        tr = Normalize(-Vector3( t1,  t2, 1.0f));
2345#else
2346        bl = -Normalize(camera->GetDirection());
2347        br = -Normalize(camera->GetDirection());
2348        tl = -Normalize(camera->GetDirection());
2349        tr = -Normalize(camera->GetDirection());
2350#endif
2351        // normalize to 0 .. 1
2352        bl = bl * 0.5f + 0.5f;
2353        br = br * 0.5f + 0.5f;
2354        tl = tl * 0.5f + 0.5f;
2355        tr = tr * 0.5f + 0.5f;
2356}
2357
2358
2359void CreateNoiseTex2D()
2360{
2361        randomNormals = new GLubyte[texWidth * texHeight * 3];
2362
2363        for (int i = 0; i < texWidth * texHeight * 3; i += 3)
2364        {
2365                // create random samples over sphere
2366                const float rx = RandomValue(0, 1);
2367                const float theta = 2.0f * acos(sqrt(1.0f - rx));
2368
2369                randomNormals[i + 0] = (GLubyte)((cos(theta) * 0.5f + 0.5f) * 255.0f);
2370                randomNormals[i + 1] = (GLubyte)((sin(theta) * 0.5f + 0.5f) * 255.0f);
2371                randomNormals[i + 2] = 0;
2372        }
2373
2374        glEnable(GL_TEXTURE_2D);
2375        glGenTextures(1, &noiseTex);
2376        glBindTexture(GL_TEXTURE_2D, noiseTex);
2377               
2378        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2379        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2380        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
2381        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
2382
2383        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, randomNormals);
2384        //gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, texWidth, texHeight, GL_RGB, GL_UNSIGNED_BYTE, randomNormals);
2385
2386        glBindTexture(GL_TEXTURE_2D, 0);
2387        glDisable(GL_TEXTURE_2D);
2388
2389        cout << "created noise texture" << endl;
2390        PrintGLerror("noisetexture");
2391}
Note: See TracBrowser for help on using the repository browser.