source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/DeferredRenderer.cpp @ 3362

Revision 3362, 43.0 KB checked in by mattausch, 15 years ago (diff)

cleaned up algorithm

Line 
1#include "DeferredRenderer.h"
2#include "FrameBufferObject.h"
3#include "RenderState.h"
4#include "SampleGenerator.h"
5#include "Vector3.h"
6#include "Camera.h"
7#include "shaderenv.h"
8#include "Halton.h"
9#include "ShadowMapping.h"
10#include "Light.h"
11#include "ShaderManager.h"
12#include "Texture.h"
13
14#include <math.h>
15
16#include <IL/il.h>
17#include <assert.h>
18
19
20#ifdef _CRT_SET
21        #define _CRTDBG_MAP_ALLOC
22        #include <stdlib.h>
23        #include <crtdbg.h>
24
25        // redefine new operator
26        #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
27        #define new DEBUG_NEW
28#endif
29
30
31using namespace std;
32
33
34static void startil()
35{
36        ilInit();
37        assert(ilGetError() == IL_NO_ERROR);
38}
39
40
41static void stopil()
42{
43        ilShutDown();
44        assert(ilGetError() == IL_NO_ERROR);
45}
46
47
48namespace CHCDemoEngine
49{
50
51static ShaderProgram *sCgSsaoProgram = NULL;
52static ShaderProgram *sCgGiProgram = NULL;
53
54static ShaderProgram *sCgDeferredProgram = NULL;
55static ShaderProgram *sCgAntiAliasingProgram = NULL;
56static ShaderProgram *sCgDeferredShadowProgram = NULL;
57
58static ShaderProgram *sCgCombineSsaoProgram = NULL;
59static ShaderProgram *sCgFilterSsaoProgram = NULL;
60static ShaderProgram *sCgCombineIllumProgram = NULL;
61static ShaderProgram *sCgLogLumProgram = NULL;
62static ShaderProgram *sCgToneProgram = NULL;
63static ShaderProgram *sCgDownSampleProgram = NULL;
64static ShaderProgram *sCgScaleDepthProgram = NULL;
65static ShaderProgram *sCgPrepareSsaoProgram = NULL;
66static ShaderProgram *sCgLenseFlareProgram = NULL;
67
68static ShaderProgram *sCgDOFProgram = NULL;
69
70
71static GLuint noiseTex2D = 0;
72static GLuint noiseTex1D = 0;
73static GLuint sampleTex2D = 0;
74
75
76static Sample2 samples2[NUM_PRECOMPUTED_SAMPLES];
77// ssao random spherical samples
78//static Sample2 samples2[NUM_SAMPLES];
79
80// pcf samples
81static Sample2 pcfSamples[NUM_PCF_TABS];
82// dof samples
83static Sample2 dofSamples[NUM_DOF_TABS];
84
85static Texture *sHaloTex[5];
86
87int DeferredRenderer::colorBufferIdx = 0;
88
89
90
91
92/** Helper method that computes the view vectors in the corners of the current view frustum.
93*/
94static void ComputeViewVectors(PerspectiveCamera *cam,
95                                                           Vector3 &bl,
96                                                           Vector3 &br,
97                                                           Vector3 &tl,
98                                                           Vector3 &tr)
99{
100        Vector3 ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr;
101        cam->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
102
103        bl = Normalize(nbl - fbl);
104        br = Normalize(nbr - fbr);
105        tl = Normalize(ntl - ftl);
106        tr = Normalize(ntr - ftr);
107}
108
109
110static float GaussianDistribution(float x, float y, float rho)
111{
112        float g = 1.0f / sqrtf(2.0f * M_PI * rho * rho);
113    g *= expf( -(x * x + y * y) / (2.0f * rho * rho));
114
115    return g;
116}
117
118
119static void PrintGLerror(char *msg)
120{
121        GLenum errCode;
122        const GLubyte *errStr;
123       
124        if ((errCode = glGetError()) != GL_NO_ERROR)
125        {
126                errStr = gluErrorString(errCode);
127                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
128        }
129}
130
131
132static Sample2 UnitTest(float x, float y, int wi, int he)
133{
134        Sample2 s;
135
136        s.x = float(floor(x * (float)wi - 0.5f) + 1.0f) / (float)wi;
137        s.y = float(floor(y * (float)he - 0.5f) + 1.0f) / (float)he;
138
139        return s;
140}
141
142
143static void ComputeSampleOffsets(float *sampleOffsets,
144                                                                 int imageW, int imageH,
145                                                                 float width,
146                                                                 int samples)
147{
148        const float xoffs = width / (float)imageW;
149        const float yoffs = width / (float)imageH;
150       
151        const int numSamples = (int)sqrt((float)samples);
152        const int startSamples = -numSamples / 2;
153        const int endSamples = numSamples + startSamples - 1;
154        //cout << startSamples << " " << endSamples << endl;
155
156        int idx = 0;
157
158        for (int x = startSamples; x <= endSamples; ++ x)
159        {
160                for (int y = startSamples; y <= endSamples; ++ y)
161                {
162                        sampleOffsets[idx + 0] = (float)x * xoffs;
163                        sampleOffsets[idx + 1] = (float)y * yoffs;
164                        idx += 2;
165                }
166        }
167}
168
169
170static float *GrabTexture(GLuint tex, int w, int h)
171{
172        glBindTexture(GL_TEXTURE_2D, tex);
173
174        float *data = new float[w * h * 3];
175
176        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_FLOAT, data);
177
178        glBindTexture(GL_TEXTURE_2D, 0);
179        glDisable(GL_TEXTURE_2D);
180
181        return data;
182}
183
184
185void DeferredRenderer::FlipFbos(FrameBufferObject *fbo)
186{
187        fbo->Bind();
188        colorBufferIdx = 3 - colorBufferIdx;
189        glDrawBuffers(1, mrt + colorBufferIdx);
190}
191
192
193void DeferredRenderer::DrawQuad(ShaderProgram *p)
194{
195        if (p) p->Bind();
196
197        // interpolate the view vector
198        Vector3 bl = mCornersView[0];
199        Vector3 br = mCornersView[1];
200        Vector3 tl = mCornersView[2];
201        Vector3 tr = mCornersView[3];
202
203        // note: slightly larger texture could hide ambient occlusion error on border but costs resolution
204        glBegin(GL_QUADS);
205
206        glTexCoord2f(0, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, bl.x, bl.y, bl.z); glVertex2f( .0f,  .0f);
207        glTexCoord2f(1, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, br.x, br.y, br.z); glVertex2f(1.0f,  .0f);
208        glTexCoord2f(1, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tr.x, tr.y, tr.z); glVertex2f(1.0f, 1.0f);
209        glTexCoord2f(0, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tl.x, tl.y, tl.z); glVertex2f( .0f, 1.0f);
210
211        glEnd();
212}
213
214/** Generate poisson disc distributed sample points on the unit disc
215*/
216static void GenerateSamples(int sampling)
217{
218        switch (sampling)
219        {
220        case DeferredRenderer::SAMPLING_POISSON:
221                {
222                        PoissonDiscSampleGenerator2D poisson(NUM_PRECOMPUTED_SAMPLES, 1.0f);
223                        poisson.Generate((float *)samples2);
224                }
225                break;
226        case DeferredRenderer::SAMPLING_QUADRATIC:
227                {
228                        //PoissonDiscSampleGenerator2D poisson(NUM_PRECOMPUTED_SAMPLES, 1.0f);
229                        //poisson.Generate((float *)samples2);
230                        QuadraticDiscSampleGenerator2D g(NUM_PRECOMPUTED_SAMPLES, 1.0f);
231                        g.Generate((float *)samples2);
232                }
233                break;
234        default: // SAMPLING_DEFAULT
235                {
236                        RandomSampleGenerator2D g(NUM_PRECOMPUTED_SAMPLES, 1.0f);
237                        g.Generate((float *)samples2);
238                }
239        }
240}
241
242
243static void CreateNoiseTex2D(int w, int h)
244{
245        //GLubyte *randomNormals = new GLubyte[mWidth * mHeight * 3];
246        Vector3 *randomNormals = new Vector3[w * h];
247
248        for (int i = 0; i < w * h; ++ i)
249        {
250                // create random samples on a circle
251                const float r = RandomValue(0, 1);
252
253                const float theta = 2.0f * acos(sqrt(1.0f - r));
254                //randomNormals[i] = Vector3(cos(theta), sin(theta), 0);
255                randomNormals[i] = Vector3(RandomValue(-M_PI, M_PI), 0, 0);
256                //Normalize(randomNormals[i]);
257        }
258
259
260        glEnable(GL_TEXTURE_2D);
261        glGenTextures(1, &noiseTex2D);
262        glBindTexture(GL_TEXTURE_2D, noiseTex2D);
263               
264        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
265        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
266        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
267        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
268        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
269        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
270
271        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_RGB, GL_FLOAT, (float *)randomNormals);
272
273        glBindTexture(GL_TEXTURE_2D, 0);
274        glDisable(GL_TEXTURE_2D);
275
276        delete [] randomNormals;
277
278        cout << "created noise texture" << endl;
279
280        PrintGLerror("noisetexture");
281}
282
283
284static void UpdateSampleTex(Sample2 *samples, int numSamples)
285{
286        glEnable(GL_TEXTURE_2D);
287        glBindTexture(GL_TEXTURE_2D, sampleTex2D);
288               
289        const int w = numSamples; const int h = 1;
290
291        float *tempBuffer = new float[numSamples * 3];
292
293        for (int i = 0; i < numSamples; ++ i)
294        {
295                tempBuffer[i * 3 + 0] = samples[i].x;
296                tempBuffer[i * 3 + 1] = samples[i].y;
297                tempBuffer[i * 3 + 2] = 0;
298        }
299
300        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGB, GL_FLOAT, (float *)tempBuffer);
301
302        glBindTexture(GL_TEXTURE_2D, 0);
303        glDisable(GL_TEXTURE_2D);
304
305        cout << "updated sample texture" << endl;
306
307        delete [] tempBuffer;
308
309        PrintGLerror("update sample tex");
310}
311
312
313static void CreateSampleTex(Sample2 *samples, int numSamples)
314{
315        glEnable(GL_TEXTURE_2D);
316        glGenTextures(1, &sampleTex2D);
317        glBindTexture(GL_TEXTURE_2D, sampleTex2D);
318               
319        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
320        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
321        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
322        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
323
324        const int w = numSamples; const int h = 1;
325
326        float *tempBuffer = new float[numSamples * 3];
327
328        for (int i = 0; i < numSamples; ++ i)
329        {
330                tempBuffer[i * 3 + 0] = samples[i].x;
331                tempBuffer[i * 3 + 1] = samples[i].y;
332                tempBuffer[i * 3 + 2] = 0;
333        }
334
335        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, w, h, 0, GL_RGB, GL_FLOAT, (float *)tempBuffer);
336
337        glBindTexture(GL_TEXTURE_2D, 0);
338        glDisable(GL_TEXTURE_2D);
339
340        cout << "created sample texture" << endl;
341
342        delete [] tempBuffer;
343
344        PrintGLerror("create sample tex");
345}
346
347
348static void PrepareLenseFlare()
349{
350        string textures[] = {"flare4.tga", "lens2.jpg", "lens3.jpg", "lens4.jpg", "lens1.jpg"};
351
352        // todo: delete halo textures
353        for (int i = 0; i < 5; ++ i)
354        {
355                sHaloTex[i] = new Texture(model_path + textures[i]);
356
357                sHaloTex[i]->SetBoundaryModeS(Texture::BORDER);
358                sHaloTex[i]->SetBoundaryModeT(Texture::BORDER);
359
360                sHaloTex[i]->Create();
361        }
362
363        cout << "prepared lense flare textures" << endl;
364
365        PrintGLerror("prepare lense flare");
366}
367
368
369DeferredRenderer::DeferredRenderer(int w, int h,
370                                                                   PerspectiveCamera *cam,
371                                                                   bool ssaoUseFullResolution):
372mWidth(w), mHeight(h),
373mCamera(cam),
374mUseTemporalCoherence(true),
375mRegenerateSamples(true),
376mSamplingMethod(SAMPLING_POISSON),
377mShadingMethod(DEFAULT),
378mIllumFboIndex(0),
379mSortSamples(true),
380mKernelRadius(1e-8f),
381mSampleIntensity(0.2f),
382mSunVisiblePixels(0),
383mSavedFrameNumber(-1),
384mSavedFrameSuffix(""),
385mMaxDistance(1e6f),
386mTempCohFactor(.0f),
387mUseToneMapping(false),
388mUseAntiAliasing(false),
389mUseDepthOfField(false),
390mSsaoUseFullResolution(ssaoUseFullResolution),
391mMaxConvergence(2000.0f),
392mSpatialWeight(.0f)
393{
394        ///////////
395        //-- the flip-flop fbos
396
397        int downSampledWidth, downSampledHeight;
398
399        if (mSsaoUseFullResolution)
400        {
401                downSampledWidth = w; downSampledHeight = h;
402                cout << "using full resolution ssao" << endl;
403        }
404        else
405        {
406                downSampledWidth = w / 2; downSampledHeight = h / 2;
407                cout << "using half resolution ssao" << endl;
408        }
409#if 1
410
411        /////////
412        //-- the illumination fbo is either half size or full size
413
414        mIllumFbo = new FrameBufferObject(downSampledWidth, downSampledHeight, FrameBufferObject::DEPTH_NONE);
415        mFBOs.push_back(mIllumFbo);
416
417        for (int i = 0; i < 4; ++ i)
418        {
419                mIllumFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
420                FrameBufferObject::InitBuffer(mIllumFbo, i);
421        }
422
423
424        ///////////////
425        //-- the downsampled ssao + color bleeding textures:
426        //-- as GI is mostly low frequency, we can use lower resolution to improve performance
427
428        mDownSampleFbo = new FrameBufferObject(downSampledWidth, downSampledHeight, FrameBufferObject::DEPTH_NONE);
429        // the downsampled color + depth buffer
430        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
431        // downsample buffer for the normal texture
432        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
433
434        for (int i = 0; i < 2; ++ i)
435        {
436                FrameBufferObject::InitBuffer(mDownSampleFbo, i);
437        }
438
439        mFBOs.push_back(mDownSampleFbo);
440
441
442        /////////
443        //-- temporal buffer
444
445        mTempFbo = new FrameBufferObject(mWidth, mHeight, FrameBufferObject::DEPTH_NONE);
446        mFBOs.push_back(mTempFbo);
447
448        mTempFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
449        mTempFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
450        FrameBufferObject::InitBuffer(mTempFbo, 0);
451        FrameBufferObject::InitBuffer(mTempFbo, 1);
452       
453
454        // create noise texture for ssao
455        // for performance reasons we use a smaller texture and repeat it over the screen
456        CreateNoiseTex2D(mIllumFbo->GetWidth() / 4, mIllumFbo->GetWidth() / 4);
457               
458        mProjViewMatrix = IdentityMatrix();
459        mOldProjViewMatrix = IdentityMatrix();
460
461        for (int i = 0; i < 4; ++ i)
462        {
463                mCornersView[i] = mOldCornersView[i] = Vector3::UNIT_X();
464        }
465
466        mEyePos = mOldEyePos = Vector3::ZERO();
467
468        PrepareLenseFlare();
469#endif
470        InitCg();
471}
472
473
474DeferredRenderer::~DeferredRenderer()
475{
476        CLEAR_CONTAINER(mFBOs);
477
478        glDeleteTextures(1, &noiseTex2D);
479        glDeleteTextures(1, &noiseTex1D);
480}
481
482
483void DeferredRenderer::InitCg()
484{       
485        ShaderManager *sm = ShaderManager::GetSingleton();
486
487        sCgDeferredProgram = sm->CreateFragmentProgram("deferred", "main", "DeferredFrag");
488        sCgDeferredShadowProgram = sm->CreateFragmentProgram("deferred", "main_shadow", "DeferredFragShadow");
489        sCgSsaoProgram = sm->CreateFragmentProgram("ssao", "main", "SsaoFrag");
490        sCgGiProgram = sm->CreateFragmentProgram("globillum", "main", "GiFrag");
491        sCgCombineIllumProgram = sm->CreateFragmentProgram("globillum", "combine", "CombineGi");
492
493        if (mSsaoUseFullResolution)
494        {
495                sCgFilterSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "FilterSsaoFullRes", "FilterSsao");
496        }
497        else
498        {
499                sCgFilterSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "FilterSsaoHalfRes", "FilterSsao");
500        }
501       
502        sCgCombineSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "CombineSsao", "CombineSsao");
503        sCgAntiAliasingProgram = sm->CreateFragmentProgram("antialiasing", "main", "AntiAliasing");
504        sCgToneProgram = sm->CreateFragmentProgram("tonemap", "ToneMap", "ToneMap");
505        sCgDownSampleProgram = sm->CreateFragmentProgram("deferred", "Output", "Output");
506        sCgScaleDepthProgram = sm->CreateFragmentProgram("deferred", "ScaleDepth", "ScaleDepth");
507        sCgLogLumProgram = sm->CreateFragmentProgram("tonemap", "CalcAvgLogLum", "AvgLogLum");
508        sCgPrepareSsaoProgram = sm->CreateFragmentProgram("deferred", "PrepareSsao", "PrepareSsao");
509        sCgLenseFlareProgram = sm->CreateFragmentProgram("lenseFlare", "LenseFlare", "LenseFlare");
510        sCgDOFProgram = sm->CreateFragmentProgram("depthOfField", "DepthOfField", "DepthOfField");
511
512
513        ///////////////////
514        //-- initialize program parameters
515
516        string ssaoParams[] =
517                {"colors", "normals", "oldTex", "noiseTex", "temporalCoherence",
518                 "samples", "bl", "br", "tl", "tr",
519                 "modelViewProj", "oldModelViewProj", "oldEyePos", "oldbl", "oldbr",
520                 "oldtl", "oldtr", "attribsTex", "kernelRadius", "sampleIntensity"};
521       
522        sCgSsaoProgram->AddParameters(ssaoParams, 0, 20);
523       
524        string giParams[] =
525                {"colors", "normals", "noiseTex", "oldSsaoTex", "oldIllumTex",
526                 "temporalCoherence", "samples", "bl", "br", "tl",
527                 "tr", "oldModelViewProj", "modelViewProj"};
528
529        sCgGiProgram->AddParameters(giParams, 0, 13);
530
531        string toneParams[] = {"colors", "imageKey", "whiteLum", "middleGrey"};
532        sCgToneProgram->AddParameters(toneParams, 0, 4);
533
534
535        ////////////////
536
537        string deferredShadowParams[] =
538                {"colors", "normals", "shadowMap", "noiseTex", "shadowMatrix",
539                 "sampleWidth", "lightDir", "eyePos", "samples", "weights"};
540       
541        sCgDeferredShadowProgram->AddParameters(deferredShadowParams, 0, 10);
542       
543        ////////////////
544
545        string combineIllumParams[] = {"colorsTex", "ssaoTex", "illumTex"};
546        sCgCombineIllumProgram->AddParameters(combineIllumParams, 0, 3);
547
548        ////////////////
549
550        string combineSsaoParams[] =
551                {"colorsTex", "ssaoTex", "bl", "br", "tl", "tr", "res", "maxConvergence", "spatialWeight"};
552
553        sCgCombineSsaoProgram->AddParameters(combineSsaoParams, 0, 9);
554
555       
556        ////////////////
557
558        string filterSsaoParams[] =
559                {"colorsTex", "ssaoTex", "bl", "br", "tl", "tr", "res", "maxConvergence", "spatialWeight"};
560        sCgFilterSsaoProgram->AddParameters(filterSsaoParams, 0, 9);
561
562
563        //////////////
564
565        string deferredParams[] = {"colors", "normals", "lightDir", "aoTex", "useAO"};
566        sCgDeferredProgram->AddParameters(deferredParams, 0, 5);
567
568        ///////////////////
569
570        string aaParams[] = {"colors", "normals", "offsets"};
571        sCgAntiAliasingProgram->AddParameters(aaParams, 0, 3);
572
573        /////////////////////
574
575        string downSampleParams[] = {"colors"};
576        sCgDownSampleProgram->AddParameters(downSampleParams, 0, 1);
577
578        /////////////////////
579
580        string scaleDepthParams[] = {"colors"};
581        sCgScaleDepthProgram->AddParameters(scaleDepthParams, 0, 1);
582
583        ////////////
584
585        sCgLogLumProgram->AddParameter("colors", 0);
586
587        ////////////////
588
589       
590        string prepareSsaoParams[] =
591                {"colorsTex", "normalsTex", "diffVals", "oldTex",
592                 "oldEyePos", "modelViewProj", "oldModelViewProj",
593                 "oldbl", "oldbr", "oldtl", "oldtr", "myTex"};
594        sCgPrepareSsaoProgram->AddParameters(prepareSsaoParams, 0, 12);
595
596
597        ////////////////
598       
599        string lenseFlareParams[] =
600                {"colorsTex", "flareTex1", "flareTex2", "flareTex3", "flareTex4",
601                 "flareTex5", "vectorToLight", "distanceToLight", "sunVisiblePixels"};
602
603        sCgLenseFlareProgram->AddParameters(lenseFlareParams, 0, 9);
604
605       
606        ////////////////
607       
608        string dofParams[] = {"colorsTex", "filterOffs", "sceneRange", "zFocus"};
609
610        sCgDOFProgram->AddParameters(dofParams, 0, 4);
611
612
613        /////////
614        //-- pcf tabs for shadowing
615
616        float filterWeights[NUM_PCF_TABS];
617        PoissonDiscSampleGenerator2D poisson2(NUM_PCF_TABS, 1.0f);
618        poisson2.Generate((float *)pcfSamples);
619
620        for (int i = 0; i < NUM_PCF_TABS; ++ i)
621        {
622                filterWeights[i] = GaussianDistribution(pcfSamples[i].x, pcfSamples[i].y, 1.0f);
623        }
624
625        sCgDeferredShadowProgram->SetArray2f(8, (float *)pcfSamples, NUM_PCF_TABS);
626        sCgDeferredShadowProgram->SetArray1f(9, (float *)filterWeights, NUM_PCF_TABS);
627
628
629        /////////
630        //-- pcf tabs for depth of field
631
632        // todo matt: it is stupid to put num samples and width of kernel into constructor => change this!!!
633        PoissonDiscSampleGenerator2D poisson3(NUM_DOF_TABS, 1.0f);
634        poisson3.Generate((float *)dofSamples);
635
636        for (int i = 0; i < NUM_DOF_TABS; ++ i)
637        {
638                dofSamples[i].x *= 1.0f / mWidth;
639                dofSamples[i].y *= 1.0f / mHeight;
640        }
641
642        //float dofWeights[NUM_PCF_TABS];
643        //sCgDOFProgram->SetArray1f(2, (float *)dofWeights, NUM_DOF_TABS);
644
645        PrintGLerror("init");
646}
647
648
649void DeferredRenderer::Render(FrameBufferObject *fbo,
650                                                          DirectionalLight *light,
651                                                          ShadowMap *shadowMap
652                                                          )
653{
654        InitFrame();
655
656        /*if (shadowMap)
657                FirstPassShadow(fbo, light, shadowMap);
658        else
659                FirstPass(fbo, light);
660        */
661
662        if (mShadingMethod != DEFAULT)
663        {
664                PrepareSsao(fbo); // downsample fbo buffers
665        }
666
667        // q: use antialiasing before or after ssao?
668        //if (useAntiAliasing) AntiAliasing(fbo, light);
669
670        switch (mShadingMethod)
671        {
672        case SSAO:
673                ComputeSsao(fbo, mTempCohFactor);
674                FilterSsao(fbo);
675                CombineSsao(fbo);
676
677                break;
678        case GI:
679                ComputeGlobIllum(fbo, mTempCohFactor);
680                CombineIllum(fbo);
681                break;
682        default:
683                // do nothing: standard deferred shading
684                break;
685        }
686
687        if (shadowMap)
688                FirstPassShadow(fbo, light, shadowMap);
689        else
690                FirstPass(fbo, light);
691
692        /// depth of field
693        if (mUseDepthOfField)
694        {
695                DepthOfField(fbo);
696        }
697
698        if (mUseToneMapping)
699        {
700                float imageKey, whiteLum, middleGrey;
701
702                ComputeToneParameters(fbo, light, imageKey, whiteLum, middleGrey);
703                ToneMap(fbo, imageKey, whiteLum, middleGrey);
704        }
705
706        /// compute lense flare
707        LenseFlare(fbo, light);
708
709        const bool saveFrame = (mSavedFrameNumber != -1);
710        const bool displayAfterAA = !saveFrame;
711
712        // multisampling is difficult / costly with deferred shading
713        // at least do some edge blurring
714        if (mUseAntiAliasing) AntiAliasing(fbo, light, displayAfterAA);
715       
716        /// store the current frame
717        if (saveFrame) SaveFrame(fbo);
718
719        // if it hasn't been done yet => just output the latest buffer
720        if (!mUseAntiAliasing || !displayAfterAA)
721        {
722                Output(fbo);
723        }
724
725        glEnable(GL_LIGHTING);
726        glDisable(GL_TEXTURE_2D);
727
728        glMatrixMode(GL_PROJECTION);
729        glPopMatrix();
730
731        glMatrixMode(GL_MODELVIEW);
732        glPopMatrix();
733
734        // viewport
735        glPopAttrib();
736
737        FrameBufferObject::Release();
738        ShaderManager::GetSingleton()->DisableFragmentProfile();
739}
740
741
742static inline float SqrMag(const Sample2 &s)
743{
744        return (s.x * s.x + s.y * s.y);
745}
746
747
748static inline float SqrDist(const Sample2 &a, const Sample2 &b)
749{
750        float x = a.x - b.x;
751        float y = a.y - b.y;
752       
753        return x * x + y * y;
754}
755
756
757static inline bool lt(const Sample2 &a, const Sample2 &b)
758{
759        return SqrMag(a) < SqrMag(b);
760}
761
762
763void DeferredRenderer::SortSamples()
764{
765        static Sample2 tempSamples[NUM_SAMPLES];
766        static bool checked[NUM_SAMPLES];
767
768        for (int i = 0; i < NUM_SAMPLES; ++ i)
769                checked[i] = false;
770
771        Sample2 currentSample;
772        currentSample.x = 0; currentSample.y = 0;
773        int ns = 0; // the next sample index
774
775        for (int i = 0; i < NUM_SAMPLES; ++ i)
776        {
777                float minLen = 1e20f;
778
779                for (int j = 0; j < NUM_SAMPLES; ++ j)
780                {
781                        if (checked[j]) continue;
782
783                        Sample2 s = samples2[j];
784                        const float len = SqrDist(s, currentSample);
785
786                        if (len < minLen)
787                        {
788                                minLen = len;
789                                ns = j;
790                        }
791                }
792
793                tempSamples[i] = samples2[ns];
794                currentSample = samples2[ns];
795
796                checked[ns] = true;
797        }
798
799        for (int i = 0; i < NUM_SAMPLES; ++ i)
800                samples2[i] = tempSamples[i];
801}
802
803
804void DeferredRenderer::ComputeSsao(FrameBufferObject *fbo, float tempCohFactor)
805{
806        GLuint colorsTex, normalsTex, attribsTex;
807
808        if (0)
809        {
810                colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
811                normalsTex = fbo->GetColorBuffer(1)->GetTexture();
812        }
813        else
814        {
815                normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
816                colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
817        }
818
819        attribsTex = fbo->GetColorBuffer(2)->GetTexture();
820
821
822        /////////
823        //-- flip flop between illumination buffers
824
825        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
826
827        glPushAttrib(GL_VIEWPORT_BIT);
828        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
829
830        // read the second buffer, write to the first buffer
831        mIllumFbo->Bind();
832        glDrawBuffers(2, mrt + mIllumFboIndex);
833
834        int i = 0;
835
836        sCgSsaoProgram->SetTexture(i ++, colorsTex);
837        sCgSsaoProgram->SetTexture(i ++, normalsTex);
838        sCgSsaoProgram->SetTexture(i ++, oldSsaoTex);
839        sCgSsaoProgram->SetTexture(i ++, noiseTex2D);
840
841        sCgSsaoProgram->SetValue1f(i ++, (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
842       
843
844        if (/*mUseTemporalCoherence || */mRegenerateSamples)
845        {
846                mRegenerateSamples = false;
847
848                // q: should we generate new samples or only rotate the old ones?
849                // in the first case, the sample patterns look nicer, but the kernel
850                // needs longer to converge
851                GenerateSamples(mSamplingMethod);
852
853                if (!sampleTex2D)
854                {
855                        CreateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
856                }
857                else
858                {
859                        UpdateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
860                }
861
862                //if (mSortSamples) { SortSamples(); }
863                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
864                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_PRECOMPUTED_SAMPLES);
865        }
866
867        sCgSsaoProgram->SetTexture(i, sampleTex2D);
868
869        ++ i;
870
871        for (int j = 0; j < 4; ++ j, ++ i)
872        {
873                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
874        }
875
876        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
877        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
878
879        Vector3 de;
880        de.x = mOldEyePos.x - mEyePos.x;
881        de.y = mOldEyePos.y - mEyePos.y;
882        de.z = mOldEyePos.z - mEyePos.z;
883
884        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
885
886        for (int j = 0; j < 4; ++ j, ++ i)
887        {
888                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
889        }
890
891        sCgSsaoProgram->SetTexture(i ++, attribsTex);
892        sCgSsaoProgram->SetValue1f(i ++, mKernelRadius);
893        sCgSsaoProgram->SetValue1f(i ++, mSampleIntensity * mKernelRadius);
894
895        DrawQuad(sCgSsaoProgram);
896        glPopAttrib();
897
898        PrintGLerror("ssao first pass");
899}
900
901
902static void SetVertex(float x, float y, float x_offs, float y_offs)
903{
904        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
905        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
906        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
907        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
908        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
909
910        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
911        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
912
913        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
914        glVertex2f(x, y);
915}
916
917
918void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo,
919                                                                        DirectionalLight *light,
920                                                                        bool displayFrame)
921{
922        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
923        GLuint colorsTex = colorBuffer->GetTexture();
924        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
925
926        // read the second buffer, write to the first buffer
927        if (!displayFrame)
928        {
929                FlipFbos(fbo);
930        }
931        else
932        {
933                // end of the pipeline => just draw image to screen
934                FrameBufferObject::Release();
935        }
936
937        // the neighbouring texels
938        float xOffs = 1.0f / fbo->GetWidth();
939        float yOffs = 1.0f / fbo->GetHeight();
940
941        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
942        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
943
944        float offsets[16];
945        int i = 0;
946
947        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
948        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
949        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
950        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
951        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
952        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
953        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
954        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
955
956        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
957
958        DrawQuad(sCgAntiAliasingProgram);
959
960        PrintGLerror("antialiasing");
961}
962
963
964void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
965{
966        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
967        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
968        //GLuint aoTex = fbo->GetColorBuffer(1)->GetTexture();
969        GLuint aoTex = mTempFbo->GetColorBuffer(1)->GetTexture();
970
971        FlipFbos(fbo);
972
973        const Vector3 lightDir = -light->GetDirection();
974
975        int i = 0;
976        sCgDeferredProgram->SetTexture(i ++, colorsTex);
977        sCgDeferredProgram->SetTexture(i ++, normalsTex);
978        sCgDeferredProgram->SetValue3f(i ++, lightDir.x, lightDir.y, lightDir.z);
979        sCgDeferredProgram->SetTexture(i ++, aoTex);
980        sCgDeferredProgram->SetValue1f(i ++, float(mShadingMethod == SSAO));
981
982        DrawQuad(sCgDeferredProgram);
983
984        PrintGLerror("deferred shading");
985}
986
987
988void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
989                                                                                float tempCohFactor)
990{
991#if 0
992        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
993        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
994#else
995        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
996        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
997#endif
998
999        glPushAttrib(GL_VIEWPORT_BIT);
1000        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
1001
1002        // read the second buffer, write to the first buffer
1003        mIllumFbo->Bind();
1004        glDrawBuffers(2, mrt + mIllumFboIndex);
1005
1006        // bind the old buffers for temporal coherence
1007        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1008        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
1009
1010        int i = 0;
1011
1012        sCgGiProgram->SetTexture(i ++, colorsTex);
1013        sCgGiProgram->SetTexture(i ++, normalsTex);
1014        sCgGiProgram->SetTexture(i ++, noiseTex2D);
1015        sCgGiProgram->SetTexture(i ++, oldSsaoTex);
1016        sCgGiProgram->SetTexture(i ++, oldIllumTex);
1017
1018        sCgGiProgram->SetValue1f(i ++,
1019                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
1020
1021        if (mUseTemporalCoherence || mRegenerateSamples)
1022        {
1023                mRegenerateSamples = false;
1024
1025                // q: should we generate new samples or only rotate the old ones?
1026                // in the first case, the sample patterns look nicer, but the kernel
1027                // needs longer to converge
1028                GenerateSamples(mSamplingMethod);
1029
1030                sCgGiProgram->SetArray2f(i ++, (float *)samples2, NUM_SAMPLES);
1031        }
1032
1033        Vector3 bl = mCornersView[0];
1034        Vector3 br = mCornersView[1];
1035        Vector3 tl = mCornersView[2];
1036        Vector3 tr = mCornersView[3];
1037
1038        sCgGiProgram->SetValue3f(i ++, bl.x, bl.y, bl.z);
1039        sCgGiProgram->SetValue3f(i ++, br.x, br.y, br.z);
1040        sCgGiProgram->SetValue3f(i ++, tl.x, tl.y, tl.z);
1041        sCgGiProgram->SetValue3f(i ++, tr.x, tr.y, tr.z);
1042
1043        sCgGiProgram->SetMatrix(i ++, mOldProjViewMatrix);
1044        sCgGiProgram->SetMatrix(i ++, mProjViewMatrix);
1045
1046
1047        DrawQuad(sCgGiProgram);
1048
1049        glPopAttrib();
1050
1051        PrintGLerror("globillum first pass");
1052}
1053
1054
1055void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
1056{
1057        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1058
1059        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1060        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
1061
1062        FlipFbos(fbo);
1063
1064        sCgCombineIllumProgram->SetTexture(0, colorsTex);
1065        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
1066        sCgCombineIllumProgram->SetTexture(2, illumTex);
1067       
1068        DrawQuad(sCgCombineIllumProgram);
1069
1070        PrintGLerror("combine");
1071}
1072
1073
1074void DeferredRenderer::FilterSsao(FrameBufferObject *fbo)
1075{
1076        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1077        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1078        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1079       
1080        mTempFbo->Bind();
1081        glDrawBuffers(1, mrt);
1082       
1083        int i = 0;
1084
1085        sCgFilterSsaoProgram->SetTexture(i ++, colorsTex);
1086        sCgFilterSsaoProgram->SetTexture(i ++, ssaoTex);
1087
1088        for (int j = 0; j < 4; ++ j, ++ i)
1089        {
1090                sCgFilterSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1091        }
1092
1093        sCgFilterSsaoProgram->SetValue2f(i ++, (float)mWidth, (float)mHeight);
1094        sCgFilterSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1095        sCgFilterSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1096
1097        DrawQuad(sCgFilterSsaoProgram);
1098        PrintGLerror("filter ssao");
1099}
1100
1101
1102void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
1103{
1104        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1105        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1106        //GLuint ssaoTex = fbo->GetColorBuffer(1)->GetTexture();
1107        GLuint ssaoTex = mTempFbo->GetColorBuffer(0)->GetTexture();
1108       
1109        mTempFbo->Bind();
1110        glDrawBuffers(1, mrt + 1);
1111        //FlipFbos(fbo);
1112
1113        int i = 0;
1114
1115        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
1116        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
1117
1118        for (int j = 0; j < 4; ++ j, ++ i)
1119        {
1120                sCgCombineSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1121        }
1122
1123        sCgCombineSsaoProgram->SetValue2f(i ++, mWidth, mHeight);
1124        sCgCombineSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1125        sCgCombineSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1126
1127        DrawQuad(sCgCombineSsaoProgram);
1128       
1129        PrintGLerror("combine ssao");
1130}
1131
1132
1133void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
1134                                                                           DirectionalLight *light,
1135                                                                           ShadowMap *shadowMap)
1136{
1137        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1138        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1139
1140        GLuint shadowTex = shadowMap->GetDepthTexture();
1141
1142        Matrix4x4 shadowMatrix;
1143        shadowMap->GetTextureMatrix(shadowMatrix);
1144
1145
1146        FlipFbos(fbo);
1147
1148        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
1149        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
1150        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
1151        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
1152        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
1153        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
1154
1155        const Vector3 lightDir = -light->GetDirection();
1156        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
1157        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
1158
1159        DrawQuad(sCgDeferredShadowProgram);
1160
1161        PrintGLerror("deferred shading + shadows");
1162}
1163
1164
1165void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
1166                                                                                         DirectionalLight *light,
1167                                                                                         float &imageKey,
1168                                                                                         float &whiteLum,
1169                                                                                         float &middleGrey)
1170{
1171        // hack: estimate value where sky burns out
1172        whiteLum = log(WHITE_LUMINANCE);
1173       
1174        ////////////////////
1175        //-- linear interpolate brightness key depending on the current sun position
1176
1177        const float minKey = 0.09f;
1178        const float maxKey = 0.36f;
1179
1180        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
1181        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
1182
1183
1184        //////////
1185        //-- compute avg loglum
1186
1187        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1188        GLuint colorsTex = colorBuffer->GetTexture();
1189
1190        FlipFbos(fbo);
1191       
1192        sCgLogLumProgram->SetTexture(0, colorsTex);
1193        DrawQuad(sCgLogLumProgram);
1194       
1195        PrintGLerror("ToneMapParams");
1196
1197
1198        ///////////////////
1199        //-- compute avg loglum in scene using mipmapping
1200
1201        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
1202        glGenerateMipmapEXT(GL_TEXTURE_2D);
1203}
1204
1205
1206static void ExportData(float *data, int w, int h)
1207{
1208        startil();
1209
1210        cout << "w: " << w << " h: " << h << endl;
1211        ILstring filename = ILstring("downsample2.jpg");
1212        ilRegisterType(IL_FLOAT);
1213
1214        const int depth = 1;
1215        const int bpp = 4;
1216
1217        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
1218        {
1219                cerr << "IL error " << ilGetError() << endl;
1220                stopil();
1221                return;
1222        }
1223
1224        if (!ilSaveImage(filename))
1225        {
1226                cerr << "TGA write error " << ilGetError() << endl;
1227        }
1228
1229        stopil();
1230}
1231
1232
1233void DeferredRenderer::PrepareSsao(FrameBufferObject *fbo)
1234{
1235        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1236        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1237        GLuint diffVals = fbo->GetColorBuffer(2)->GetTexture();
1238
1239        // flip flop between illumination buffers
1240        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1241        GLuint myTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
1242
1243        int i = 0;
1244
1245        sCgPrepareSsaoProgram->SetTexture(i ++, colorsTex);
1246        sCgPrepareSsaoProgram->SetTexture(i ++, normalsTex);
1247        sCgPrepareSsaoProgram->SetTexture(i ++, diffVals);
1248        sCgPrepareSsaoProgram->SetTexture(i ++, oldTex);
1249
1250        Vector3 de;
1251        de.x = mOldEyePos.x - mEyePos.x;
1252        de.y = mOldEyePos.y - mEyePos.y;
1253        de.z = mOldEyePos.z - mEyePos.z;
1254
1255        sCgPrepareSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
1256
1257        sCgPrepareSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
1258        sCgPrepareSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
1259
1260
1261        for (int j = 0; j < 4; ++ j, ++ i)
1262        {
1263                sCgPrepareSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
1264        }
1265
1266        sCgPrepareSsaoProgram->SetTexture(i ++, myTex);
1267
1268        glPushAttrib(GL_VIEWPORT_BIT);
1269        glViewport(0, 0, mDownSampleFbo->GetWidth(), mDownSampleFbo->GetHeight());
1270       
1271        mDownSampleFbo->Bind();
1272
1273        // prepare downsampled depth and normal texture for ssao
1274        glDrawBuffers(2, mrt);
1275
1276        DrawQuad(sCgPrepareSsaoProgram);
1277       
1278        glPopAttrib();
1279        PrintGLerror("prepareSsao");
1280}
1281
1282
1283void DeferredRenderer::DownSample(FrameBufferObject *fbo,
1284                                                                  int bufferIdx,
1285                                                                  FrameBufferObject *downSampleFbo,
1286                                                                  int downSampleBufferIdx,
1287                                                                  ShaderProgram *program)
1288{
1289        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
1290        GLuint tex = buffer->GetTexture();
1291
1292        glPushAttrib(GL_VIEWPORT_BIT);
1293        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
1294       
1295        downSampleFbo->Bind();
1296
1297        program->SetTexture(0, tex);
1298        glDrawBuffers(1, mrt + downSampleBufferIdx);
1299
1300        DrawQuad(program);
1301       
1302        glPopAttrib();
1303        PrintGLerror("downsample");
1304}
1305
1306
1307void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
1308                                                           float imageKey,
1309                                                           float whiteLum,
1310                                                           float middleGrey)
1311{
1312        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1313        GLuint colorsTex = colorBuffer->GetTexture();
1314       
1315
1316        FlipFbos(fbo);
1317
1318        sCgToneProgram->SetTexture(0, colorsTex);
1319        sCgToneProgram->SetValue1f(1, imageKey);
1320        sCgToneProgram->SetValue1f(2, whiteLum);
1321        sCgToneProgram->SetValue1f(3, middleGrey);
1322
1323        DrawQuad(sCgToneProgram);
1324
1325        PrintGLerror("ToneMap");
1326}
1327
1328
1329void DeferredRenderer::Output(FrameBufferObject *fbo)
1330{
1331        glPushAttrib(GL_VIEWPORT_BIT);
1332        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
1333       
1334        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1335        GLuint colorsTex = colorBuffer->GetTexture();
1336
1337        sCgDownSampleProgram->SetTexture(0, colorsTex);
1338
1339        FrameBufferObject::Release();
1340        DrawQuad(sCgDownSampleProgram);
1341
1342        PrintGLerror("Output");
1343}
1344
1345
1346void DeferredRenderer::InitFrame()
1347{
1348        for (int i = 0; i < 4; ++ i)
1349        {
1350                mOldCornersView[i] = mCornersView[i];
1351        }
1352
1353        mOldProjViewMatrix = mProjViewMatrix;
1354        mOldEyePos = mEyePos;
1355        mEyePos = mCamera->GetPosition();
1356
1357        // hack: temporarily change far to improve precision
1358        const float oldFar = mCamera->GetFar();
1359        const float oldNear = mCamera->GetNear();
1360       
1361
1362        Matrix4x4 matViewing, matProjection;
1363
1364
1365        ///////////////////
1366
1367        // use view orientation as we assume that the eye point is always in the center
1368        // of our coordinate system, this way we have the highest precision near the eye point
1369        mCamera->GetViewOrientationMatrix(matViewing);
1370        mCamera->GetProjectionMatrix(matProjection);
1371
1372        mProjViewMatrix = matViewing * matProjection;
1373        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1374       
1375
1376        // switch roles of old and new fbo
1377        // the algorihm uses two input fbos, where the one
1378        // contais the color buffer from the last frame,
1379        // the other one will be written
1380
1381        mIllumFboIndex = 2 - mIllumFboIndex;
1382       
1383        // enable fragment shading
1384        ShaderManager::GetSingleton()->EnableFragmentProfile();
1385
1386        glDisable(GL_ALPHA_TEST);
1387        glDisable(GL_TEXTURE_2D);
1388        glDisable(GL_LIGHTING);
1389        glDisable(GL_BLEND);
1390        glDisable(GL_DEPTH_TEST);
1391
1392        glPolygonMode(GL_FRONT, GL_FILL);
1393
1394        glMatrixMode(GL_PROJECTION);
1395        glPushMatrix();
1396        glLoadIdentity();
1397
1398        gluOrtho2D(0, 1, 0, 1);
1399
1400
1401        glMatrixMode(GL_MODELVIEW);
1402        glPushMatrix();
1403        glLoadIdentity();
1404
1405       
1406        glPushAttrib(GL_VIEWPORT_BIT);
1407        glViewport(0, 0, mWidth, mHeight);
1408
1409        // revert to old far and near plane
1410        mCamera->SetFar(oldFar);
1411        mCamera->SetNear(oldNear);
1412}
1413
1414
1415void DeferredRenderer::LenseFlare(FrameBufferObject *fbo,
1416                                                                  DirectionalLight *light                                                       
1417                                                                  )
1418{
1419        // light source visible?
1420        if (!mSunVisiblePixels) return;
1421
1422        // the sun is a large distance in the reverse light direction
1423        // => extrapolate light pos
1424        const Vector3 lightPos = light->GetDirection() * -1e3f;
1425
1426        float w;
1427        Vector3 projLightPos = mProjViewMatrix.Transform(w, lightPos, 1.0f);
1428        projLightPos /= w;
1429        projLightPos = projLightPos * 0.5f + Vector3(0.5f);
1430
1431        // vector to light from screen center in texture space
1432        Vector3 vectorToLight = projLightPos - Vector3(0.5f);
1433        vectorToLight.z = .0f;
1434
1435        const float distanceToLight = Magnitude(vectorToLight);
1436        vectorToLight /= distanceToLight;
1437        //cout << "dist " << distanceToLight << " v " << vectorToLight << endl;
1438
1439
1440        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1441        GLuint colorsTex = colorBuffer->GetTexture();
1442       
1443        FlipFbos(fbo);
1444
1445        int i = 0;
1446
1447        sCgLenseFlareProgram->SetTexture(i ++, colorsTex);
1448        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[0]->GetId());
1449        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[1]->GetId());
1450        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[2]->GetId());
1451        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[3]->GetId());
1452        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[4]->GetId());
1453        sCgLenseFlareProgram->SetValue2f(i ++, vectorToLight.x, vectorToLight.y);
1454        sCgLenseFlareProgram->SetValue1f(i ++, distanceToLight);
1455        sCgLenseFlareProgram->SetValue1f(i ++, (float)mSunVisiblePixels);
1456
1457        DrawQuad(sCgLenseFlareProgram);
1458
1459        PrintGLerror("LenseFlare");
1460}
1461
1462
1463void DeferredRenderer::DepthOfField(FrameBufferObject *fbo)
1464{
1465        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1466        GLuint colorsTex = colorBuffer->GetTexture();
1467       
1468        FlipFbos(fbo);
1469
1470        int i = 0;
1471
1472        const float zFocus = 7.0f;
1473
1474        sCgDOFProgram->SetTexture(i ++, colorsTex);
1475        sCgDOFProgram->SetArray2f(i ++, (float *)dofSamples, NUM_DOF_TABS);
1476        sCgDOFProgram->SetValue1f(i ++, min(mCamera->GetFar(), mMaxDistance) - mCamera->GetNear());
1477        sCgDOFProgram->SetValue1f(i ++, zFocus);
1478
1479        DrawQuad(sCgDOFProgram);
1480
1481        PrintGLerror("LenseFlare");
1482}
1483
1484
1485void DeferredRenderer::SaveFrame(FrameBufferObject *fbo)
1486{
1487        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1488        GLuint colorsTex = colorBuffer->GetTexture();
1489
1490        GLubyte *data = new GLubyte[mWidth * mHeight * 4];
1491
1492        // grab texture data
1493        glEnable(GL_TEXTURE_2D);
1494        glBindTexture(GL_TEXTURE_2D, colorsTex);
1495        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
1496
1497        glBindTexture(GL_TEXTURE_2D, 0);
1498        glDisable(GL_TEXTURE_2D);
1499
1500        /////////////////
1501
1502        startil();
1503
1504        static char imageName[200];
1505        sprintf(imageName, "%s_%05d.tga", mSavedFrameSuffix.c_str(), mSavedFrameNumber);
1506
1507        //cout << "writing " << imageName << endl;
1508
1509        ILstring fileName = ILstring(imageName);
1510        ilRegisterType(IL_FLOAT);
1511
1512        const int depth = 1;
1513        const int bpp = 4;
1514
1515        if (!ilTexImage(mWidth, mHeight, depth, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data))
1516        {
1517                cerr << "IL error " << ilGetError() << endl;
1518                stopil();
1519                return;
1520        }
1521
1522        ilEnable(IL_FILE_OVERWRITE);
1523
1524        if (!ilSaveImage(fileName))
1525        {
1526                cerr << "TGA write error " << ilGetError() << endl;
1527        }
1528
1529        //cout << "wrote " << fileName << endl;
1530
1531        delete [] data;
1532        stopil();
1533
1534        PrintGLerror("Store frame");
1535}
1536
1537
1538void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
1539{
1540        mUseTemporalCoherence = temporal;
1541}
1542
1543
1544void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
1545{
1546        if (s != mSamplingMethod)
1547        {
1548                mSamplingMethod = s;
1549                mRegenerateSamples = true;
1550        }
1551}
1552
1553
1554void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
1555{
1556        if (s != mShadingMethod)
1557        {
1558                mShadingMethod = s;
1559                mRegenerateSamples = true;
1560        }
1561}
1562
1563
1564#if TODO
1565
1566void DeferredRenderer::SetNumSamples(int numSamples)
1567{
1568        mNumSamples = numSamples;
1569}
1570
1571#endif
1572
1573
1574void DeferredRenderer::SetSampleIntensity(float sampleIntensity)
1575{
1576        mSampleIntensity = sampleIntensity;
1577        mRegenerateSamples = true;
1578}
1579
1580
1581void DeferredRenderer::SetKernelRadius(float kernelRadius)
1582{
1583        mKernelRadius = kernelRadius;
1584        mRegenerateSamples = true;
1585}
1586
1587
1588/*void DeferredRenderer::SetSortSamples(bool sortSamples)
1589{
1590        mSortSamples = sortSamples;
1591}*/
1592
1593
1594void DeferredRenderer::SetSunVisiblePixels(int pixels)
1595{
1596        mSunVisiblePixels = pixels;
1597}
1598
1599
1600void DeferredRenderer::SetMaxDistance(float maxDist)
1601{
1602        mMaxDistance = maxDist;
1603}
1604
1605
1606void DeferredRenderer::SetUseToneMapping(bool toneMapping)
1607{
1608        mUseToneMapping = toneMapping;
1609}
1610       
1611
1612void DeferredRenderer::SetUseAntiAliasing(bool antiAliasing)
1613{
1614        mUseAntiAliasing = antiAliasing;
1615}
1616
1617
1618void DeferredRenderer::SetUseDepthOfField(bool dof)
1619{
1620        mUseDepthOfField = dof;
1621}
1622
1623
1624void DeferredRenderer::SetTemporalCoherenceFactorForSsao(float factor)
1625{
1626        mTempCohFactor = factor;
1627}
1628
1629
1630void DeferredRenderer::SetSaveFrame(const string &suffix, int frameNumber)
1631{
1632        mSavedFrameSuffix = suffix;
1633        mSavedFrameNumber = frameNumber;
1634}
1635
1636
1637void DeferredRenderer::SetMaxConvergence(float c)
1638{
1639        mMaxConvergence = c;
1640}
1641
1642
1643void DeferredRenderer::SetSpatialWeight(float w)
1644{
1645        mSpatialWeight = w;
1646}
1647
1648
1649} // namespace
Note: See TracBrowser for help on using the repository browser.