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

Revision 3338, 71.1 KB checked in by mattausch, 15 years ago (diff)

worked on sampling

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