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

Revision 3353, 71.2 KB checked in by mattausch, 15 years ago (diff)

something strange happening in sibenik: reprojection not working!!

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