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

Revision 3347, 42.3 KB checked in by mattausch, 15 years ago (diff)

1 rendertarget not working perfectly

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
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
435        for (int i = 0; i < 2; ++ i)
436        {
437                FrameBufferObject::InitBuffer(mDownSampleFbo, i);
438        }
439
440        mFBOs.push_back(mDownSampleFbo);
441
442
443        /////////
444        //-- temporal buffer
445
446        mTempFbo = new FrameBufferObject(mWidth, mHeight, FrameBufferObject::DEPTH_NONE);
447        mFBOs.push_back(mTempFbo);
448
449        mTempFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
450        FrameBufferObject::InitBuffer(mTempFbo, 0);
451       
452
453        // create noise texture for ssao
454        // for performance reasons we use a smaller texture and repeat it over the screen
455        CreateNoiseTex2D(mIllumFbo->GetWidth() / 4, mIllumFbo->GetWidth() / 4);
456               
457        mProjViewMatrix = IdentityMatrix();
458        mOldProjViewMatrix = IdentityMatrix();
459
460        for (int i = 0; i < 4; ++ i)
461        {
462                mCornersView[i] = mOldCornersView[i] = Vector3::UNIT_X();
463        }
464
465        mEyePos = mOldEyePos = Vector3::ZERO();
466
467        PrepareLenseFlare();
468
469        InitCg();
470}
471
472
473DeferredRenderer::~DeferredRenderer()
474{
475        CLEAR_CONTAINER(mFBOs);
476
477        glDeleteTextures(1, &noiseTex2D);
478        glDeleteTextures(1, &noiseTex1D);
479}
480
481
482void DeferredRenderer::InitCg()
483{       
484        ShaderManager *sm = ShaderManager::GetSingleton();
485
486        sCgDeferredProgram = sm->CreateFragmentProgram("deferred", "main", "DeferredFrag");
487        sCgDeferredShadowProgram = sm->CreateFragmentProgram("deferred", "main_shadow", "DeferredFragShadow");
488        sCgSsaoProgram = sm->CreateFragmentProgram("ssao", "main", "SsaoFrag");
489        sCgGiProgram = sm->CreateFragmentProgram("globillum", "main", "GiFrag");
490        sCgCombineIllumProgram = sm->CreateFragmentProgram("globillum", "combine", "CombineGi");
491
492        if (mSsaoUseFullResolution)
493        {
494                sCgFilterSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "FilterSsaoFullRes", "FilterSsao");
495        }
496        else
497        {
498                sCgFilterSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "FilterSsaoHalfRes", "FilterSsao");
499        }
500       
501        sCgCombineSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "CombineSsao", "CombineSsao");
502        sCgAntiAliasingProgram = sm->CreateFragmentProgram("antialiasing", "main", "AntiAliasing");
503        sCgToneProgram = sm->CreateFragmentProgram("tonemap", "ToneMap", "ToneMap");
504        sCgDownSampleProgram = sm->CreateFragmentProgram("deferred", "Output", "Output");
505        sCgScaleDepthProgram = sm->CreateFragmentProgram("deferred", "ScaleDepth", "ScaleDepth");
506        sCgLogLumProgram = sm->CreateFragmentProgram("tonemap", "CalcAvgLogLum", "AvgLogLum");
507        sCgPrepareSsaoProgram = sm->CreateFragmentProgram("deferred", "PrepareSsao", "PrepareSsao");
508        sCgLenseFlareProgram = sm->CreateFragmentProgram("lenseFlare", "LenseFlare", "LenseFlare");
509        sCgDOFProgram = sm->CreateFragmentProgram("depthOfField", "DepthOfField", "DepthOfField");
510
511
512        ///////////////////
513        //-- initialize program parameters
514
515        string ssaoParams[] =
516                {"colors", "normals", "oldTex", "noiseTex", "temporalCoherence",
517                 "samples", "bl", "br", "tl", "tr",
518                 "modelViewProj", "oldModelViewProj", "oldEyePos", "oldbl", "oldbr",
519                 "oldtl", "oldtr", "attribsTex", "kernelRadius", "sampleIntensity"};
520       
521        sCgSsaoProgram->AddParameters(ssaoParams, 0, 20);
522       
523        string giParams[] =
524                {"colors", "normals", "noiseTex", "oldSsaoTex", "oldIllumTex",
525                 "temporalCoherence", "samples", "bl", "br", "tl",
526                 "tr", "oldModelViewProj", "modelViewProj"};
527
528        sCgGiProgram->AddParameters(giParams, 0, 13);
529
530        string toneParams[] = {"colors", "imageKey", "whiteLum", "middleGrey"};
531        sCgToneProgram->AddParameters(toneParams, 0, 4);
532
533
534        ////////////////
535
536        string deferredShadowParams[] =
537                {"colors", "normals", "shadowMap", "noiseTex", "shadowMatrix",
538                 "sampleWidth", "lightDir", "eyePos", "samples", "weights"};
539       
540        sCgDeferredShadowProgram->AddParameters(deferredShadowParams, 0, 10);
541       
542        ////////////////
543
544        string combineIllumParams[] = {"colorsTex", "ssaoTex", "illumTex"};
545        sCgCombineIllumProgram->AddParameters(combineIllumParams, 0, 3);
546
547        ////////////////
548
549        string combineSsaoParams[] =
550                {"colorsTex", "ssaoTex", "bl", "br", "tl", "tr", "res", "maxConvergence", "spatialWeight"};
551
552        sCgCombineSsaoProgram->AddParameters(combineSsaoParams, 0, 9);
553
554       
555        ////////////////
556
557        string filterSsaoParams[] =
558                {"colorsTex", "ssaoTex", "bl", "br", "tl", "tr", "res", "maxConvergence", "spatialWeight"};
559        sCgFilterSsaoProgram->AddParameters(filterSsaoParams, 0, 9);
560
561
562        //////////////
563
564        string deferredParams[] = {"colors", "normals", "lightDir"};
565        sCgDeferredProgram->AddParameters(deferredParams, 0, 3);
566
567        ///////////////////
568
569        string aaParams[] = {"colors", "normals", "offsets"};
570        sCgAntiAliasingProgram->AddParameters(aaParams, 0, 3);
571
572        /////////////////////
573
574        string downSampleParams[] = {"colors"};
575        sCgDownSampleProgram->AddParameters(downSampleParams, 0, 1);
576
577        /////////////////////
578
579        string scaleDepthParams[] = {"colors"};
580        sCgScaleDepthProgram->AddParameters(scaleDepthParams, 0, 1);
581
582        ////////////
583
584        sCgLogLumProgram->AddParameter("colors", 0);
585
586        ////////////////
587
588       
589        string prepareSsaoParams[] =
590                {"colorsTex", "normalsTex", "diffVals", "oldTex",
591                 "oldEyePos", "modelViewProj", "oldModelViewProj",
592                 "oldbl", "oldbr", "oldtl", "oldtr", "myTex"};
593        sCgPrepareSsaoProgram->AddParameters(prepareSsaoParams, 0, 12);
594
595
596        ////////////////
597       
598        string lenseFlareParams[] =
599                {"colorsTex", "flareTex1", "flareTex2", "flareTex3", "flareTex4",
600                 "flareTex5", "vectorToLight", "distanceToLight", "sunVisiblePixels"};
601
602        sCgLenseFlareProgram->AddParameters(lenseFlareParams, 0, 9);
603
604       
605        ////////////////
606       
607        string dofParams[] = {"colorsTex", "filterOffs", "sceneRange", "zFocus"};
608
609        sCgDOFProgram->AddParameters(dofParams, 0, 4);
610
611
612        /////////
613        //-- pcf tabs for shadowing
614
615        float filterWeights[NUM_PCF_TABS];
616        PoissonDiscSampleGenerator2D poisson2(NUM_PCF_TABS, 1.0f);
617        poisson2.Generate((float *)pcfSamples);
618
619        for (int i = 0; i < NUM_PCF_TABS; ++ i)
620        {
621                filterWeights[i] = GaussianDistribution(pcfSamples[i].x, pcfSamples[i].y, 1.0f);
622        }
623
624        sCgDeferredShadowProgram->SetArray2f(8, (float *)pcfSamples, NUM_PCF_TABS);
625        sCgDeferredShadowProgram->SetArray1f(9, (float *)filterWeights, NUM_PCF_TABS);
626
627
628        /////////
629        //-- pcf tabs for depth of field
630
631        // todo matt: it is stupid to put num samples and width of kernel into constructor => change this!!!
632        PoissonDiscSampleGenerator2D poisson3(NUM_DOF_TABS, 1.0f);
633        poisson3.Generate((float *)dofSamples);
634
635        for (int i = 0; i < NUM_DOF_TABS; ++ i)
636        {
637                dofSamples[i].x *= 1.0f / mWidth;
638                dofSamples[i].y *= 1.0f / mHeight;
639        }
640
641        //float dofWeights[NUM_PCF_TABS];
642        //sCgDOFProgram->SetArray1f(2, (float *)dofWeights, NUM_DOF_TABS);
643
644        PrintGLerror("init");
645}
646
647
648void DeferredRenderer::Render(FrameBufferObject *fbo,
649                                                          DirectionalLight *light,
650                                                          ShadowMap *shadowMap
651                                                          )
652{
653        InitFrame();
654
655        if (shadowMap)
656                FirstPassShadow(fbo, light, shadowMap);
657        else
658                FirstPass(fbo, light);
659
660        if (mShadingMethod != 0)
661        {
662                PrepareSsao(fbo); // downsample fbo buffers
663        }
664
665        // q: use antialiasing before or after ssao?
666        //if (useAntiAliasing) AntiAliasing(fbo, light);
667
668        switch (mShadingMethod)
669        {
670        case SSAO:
671                ComputeSsao(fbo, mTempCohFactor);
672                FilterSsao(fbo);
673                CombineSsao(fbo);
674                break;
675        case GI:
676                ComputeGlobIllum(fbo, mTempCohFactor);
677                CombineIllum(fbo);
678                break;
679        default:
680                // do nothing: standard deferred shading
681                break;
682        }
683
684        /// depth of field
685        if (mUseDepthOfField)
686        {
687                DepthOfField(fbo);
688        }
689
690        if (mUseToneMapping)
691        {
692                float imageKey, whiteLum, middleGrey;
693
694                ComputeToneParameters(fbo, light, imageKey, whiteLum, middleGrey);
695                ToneMap(fbo, imageKey, whiteLum, middleGrey);
696        }
697
698        /// compute lense flare
699        LenseFlare(fbo, light);
700
701        const bool saveFrame = (mSavedFrameNumber != -1);
702        const bool displayAfterAA = !saveFrame;
703
704        // multisampling is difficult / costly with deferred shading
705        // at least do some edge blurring
706        if (mUseAntiAliasing) AntiAliasing(fbo, light, displayAfterAA);
707       
708        /// store the current frame
709        if (saveFrame) SaveFrame(fbo);
710
711        // if it hasn't been done yet => just output the latest buffer
712        if (!mUseAntiAliasing || !displayAfterAA)
713        {
714                Output(fbo);
715        }
716
717        glEnable(GL_LIGHTING);
718        glDisable(GL_TEXTURE_2D);
719
720        glMatrixMode(GL_PROJECTION);
721        glPopMatrix();
722
723        glMatrixMode(GL_MODELVIEW);
724        glPopMatrix();
725
726        // viewport
727        glPopAttrib();
728
729        FrameBufferObject::Release();
730        ShaderManager::GetSingleton()->DisableFragmentProfile();
731}
732
733
734static inline float SqrMag(const Sample2 &s)
735{
736        return (s.x * s.x + s.y * s.y);
737}
738
739
740static inline float SqrDist(const Sample2 &a, const Sample2 &b)
741{
742        float x = a.x - b.x;
743        float y = a.y - b.y;
744       
745        return x * x + y * y;
746}
747
748
749static inline bool lt(const Sample2 &a, const Sample2 &b)
750{
751        return SqrMag(a) < SqrMag(b);
752}
753
754
755void DeferredRenderer::SortSamples()
756{
757        static Sample2 tempSamples[NUM_SAMPLES];
758        static bool checked[NUM_SAMPLES];
759
760        for (int i = 0; i < NUM_SAMPLES; ++ i)
761                checked[i] = false;
762
763        Sample2 currentSample;
764        currentSample.x = 0; currentSample.y = 0;
765        int ns = 0; // the next sample index
766
767        for (int i = 0; i < NUM_SAMPLES; ++ i)
768        {
769                float minLen = 1e20f;
770
771                for (int j = 0; j < NUM_SAMPLES; ++ j)
772                {
773                        if (checked[j]) continue;
774
775                        Sample2 s = samples2[j];
776                        const float len = SqrDist(s, currentSample);
777
778                        if (len < minLen)
779                        {
780                                minLen = len;
781                                ns = j;
782                        }
783                }
784
785                tempSamples[i] = samples2[ns];
786                currentSample = samples2[ns];
787
788                checked[ns] = true;
789        }
790
791        for (int i = 0; i < NUM_SAMPLES; ++ i)
792                samples2[i] = tempSamples[i];
793}
794
795
796void DeferredRenderer::ComputeSsao(FrameBufferObject *fbo, float tempCohFactor)
797{
798        GLuint colorsTex, normalsTex, attribsTex;
799
800        if (0)
801        {
802                colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
803                normalsTex = fbo->GetColorBuffer(1)->GetTexture();
804        }
805        else
806        {
807                normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
808                colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
809        }
810
811        attribsTex = fbo->GetColorBuffer(2)->GetTexture();
812
813
814        /////////
815        //-- flip flop between illumination buffers
816
817        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
818
819        glPushAttrib(GL_VIEWPORT_BIT);
820        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
821
822        // read the second buffer, write to the first buffer
823        mIllumFbo->Bind();
824        glDrawBuffers(1, mrt + mIllumFboIndex);
825
826        int i = 0;
827
828        sCgSsaoProgram->SetTexture(i ++, colorsTex);
829        sCgSsaoProgram->SetTexture(i ++, normalsTex);
830        sCgSsaoProgram->SetTexture(i ++, oldSsaoTex);
831        sCgSsaoProgram->SetTexture(i ++, noiseTex2D);
832
833        sCgSsaoProgram->SetValue1f(i ++, (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
834       
835
836        if (/*mUseTemporalCoherence || */mRegenerateSamples)
837        {
838                mRegenerateSamples = false;
839
840                // q: should we generate new samples or only rotate the old ones?
841                // in the first case, the sample patterns look nicer, but the kernel
842                // needs longer to converge
843                GenerateSamples(mSamplingMethod);
844
845                if (!sampleTex2D)
846                {
847                        CreateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
848                }
849                else
850                {
851                        UpdateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
852                }
853
854
855                //if (mSortSamples) { SortSamples(); }
856                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
857                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_PRECOMPUTED_SAMPLES);
858        }
859
860        sCgSsaoProgram->SetTexture(i, sampleTex2D);
861
862        ++ i;
863
864        for (int j = 0; j < 4; ++ j, ++ i)
865        {
866                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
867        }
868
869        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
870        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
871
872        Vector3 de;
873        de.x = mOldEyePos.x - mEyePos.x;
874        de.y = mOldEyePos.y - mEyePos.y;
875        de.z = mOldEyePos.z - mEyePos.z;
876
877        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
878
879        for (int j = 0; j < 4; ++ j, ++ i)
880        {
881                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
882        }
883
884        sCgSsaoProgram->SetTexture(i ++, attribsTex);
885        sCgSsaoProgram->SetValue1f(i ++, mKernelRadius);
886        sCgSsaoProgram->SetValue1f(i ++, mSampleIntensity * mKernelRadius);
887
888        DrawQuad(sCgSsaoProgram);
889        glPopAttrib();
890
891        PrintGLerror("ssao first pass");
892}
893
894
895static void SetVertex(float x, float y, float x_offs, float y_offs)
896{
897        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
898        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
899        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
900        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
901        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
902
903        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
904        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
905
906        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
907        glVertex2f(x, y);
908}
909
910
911void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo,
912                                                                        DirectionalLight *light,
913                                                                        bool displayFrame)
914{
915        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
916        GLuint colorsTex = colorBuffer->GetTexture();
917        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
918
919        // read the second buffer, write to the first buffer
920        if (!displayFrame)
921        {
922                FlipFbos(fbo);
923        }
924        else
925        {
926                // end of the pipeline => just draw image to screen
927                FrameBufferObject::Release();
928        }
929
930        // the neighbouring texels
931        const float xOffs = 1.0f / fbo->GetWidth();
932        const float yOffs = 1.0f / fbo->GetHeight();
933
934        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
935        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
936
937        float offsets[16];
938        int i = 0;
939
940        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
941        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
942        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
943        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
944        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
945        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
946        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
947        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
948
949        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
950
951        DrawQuad(sCgAntiAliasingProgram);
952
953        PrintGLerror("antialiasing");
954}
955
956
957void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
958{
959        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
960        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
961
962        FlipFbos(fbo);
963
964        const Vector3 lightDir = -light->GetDirection();
965
966        sCgDeferredProgram->SetTexture(0, colorsTex);
967        sCgDeferredProgram->SetTexture(1, normalsTex);
968        sCgDeferredProgram->SetValue3f(2, lightDir.x, lightDir.y, lightDir.z);
969       
970        DrawQuad(sCgDeferredProgram);
971
972        PrintGLerror("deferred shading");
973}
974
975
976void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
977                                                                                float tempCohFactor)
978{
979#if 0
980        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
981        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
982#else
983        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
984        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
985#endif
986
987        glPushAttrib(GL_VIEWPORT_BIT);
988        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
989
990        // read the second buffer, write to the first buffer
991        mIllumFbo->Bind();
992        glDrawBuffers(2, mrt + mIllumFboIndex);
993
994        // bind the old buffers for temporal coherence
995        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
996        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
997
998        int i = 0;
999
1000        sCgGiProgram->SetTexture(i ++, colorsTex);
1001        sCgGiProgram->SetTexture(i ++, normalsTex);
1002        sCgGiProgram->SetTexture(i ++, noiseTex2D);
1003        sCgGiProgram->SetTexture(i ++, oldSsaoTex);
1004        sCgGiProgram->SetTexture(i ++, oldIllumTex);
1005
1006        sCgGiProgram->SetValue1f(i ++,
1007                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
1008
1009        if (mUseTemporalCoherence || mRegenerateSamples)
1010        {
1011                mRegenerateSamples = false;
1012
1013                // q: should we generate new samples or only rotate the old ones?
1014                // in the first case, the sample patterns look nicer, but the kernel
1015                // needs longer to converge
1016                GenerateSamples(mSamplingMethod);
1017
1018                sCgGiProgram->SetArray2f(i ++, (float *)samples2, NUM_SAMPLES);
1019        }
1020
1021        Vector3 bl = mCornersView[0];
1022        Vector3 br = mCornersView[1];
1023        Vector3 tl = mCornersView[2];
1024        Vector3 tr = mCornersView[3];
1025
1026        sCgGiProgram->SetValue3f(i ++, bl.x, bl.y, bl.z);
1027        sCgGiProgram->SetValue3f(i ++, br.x, br.y, br.z);
1028        sCgGiProgram->SetValue3f(i ++, tl.x, tl.y, tl.z);
1029        sCgGiProgram->SetValue3f(i ++, tr.x, tr.y, tr.z);
1030
1031        sCgGiProgram->SetMatrix(i ++, mOldProjViewMatrix);
1032        sCgGiProgram->SetMatrix(i ++, mProjViewMatrix);
1033
1034
1035        DrawQuad(sCgGiProgram);
1036
1037        glPopAttrib();
1038
1039        PrintGLerror("globillum first pass");
1040}
1041
1042
1043void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
1044{
1045        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1046
1047        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1048        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
1049
1050        FlipFbos(fbo);
1051
1052        sCgCombineIllumProgram->SetTexture(0, colorsTex);
1053        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
1054        sCgCombineIllumProgram->SetTexture(2, illumTex);
1055       
1056        DrawQuad(sCgCombineIllumProgram);
1057
1058        PrintGLerror("combine");
1059}
1060
1061
1062void DeferredRenderer::FilterSsao(FrameBufferObject *fbo)
1063{
1064        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1065        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1066        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1067       
1068        mTempFbo->Bind();
1069        glDrawBuffers(1, mrt);
1070       
1071        int i = 0;
1072
1073        sCgFilterSsaoProgram->SetTexture(i ++, colorsTex);
1074        sCgFilterSsaoProgram->SetTexture(i ++, ssaoTex);
1075
1076        for (int j = 0; j < 4; ++ j, ++ i)
1077        {
1078                sCgFilterSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1079        }
1080
1081        sCgFilterSsaoProgram->SetValue2f(i ++, (float)mWidth, (float)mHeight);
1082        sCgFilterSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1083        sCgFilterSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1084
1085        DrawQuad(sCgFilterSsaoProgram);
1086        PrintGLerror("filter ssao");
1087}
1088
1089
1090void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
1091{
1092        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1093        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1094        GLuint ssaoTex = mTempFbo->GetColorBuffer(0)->GetTexture();
1095       
1096        FlipFbos(fbo);
1097
1098        int i = 0;
1099
1100        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
1101        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
1102
1103        for (int j = 0; j < 4; ++ j, ++ i)
1104        {
1105                sCgCombineSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1106        }
1107
1108        sCgCombineSsaoProgram->SetValue2f(i ++, mWidth, mHeight);
1109        sCgCombineSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1110        sCgCombineSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1111
1112        DrawQuad(sCgCombineSsaoProgram);
1113       
1114        PrintGLerror("combine ssao");
1115}
1116
1117
1118void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
1119                                                                           DirectionalLight *light,
1120                                                                           ShadowMap *shadowMap)
1121{
1122        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1123        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1124
1125        GLuint shadowTex = shadowMap->GetDepthTexture();
1126
1127        Matrix4x4 shadowMatrix;
1128        shadowMap->GetTextureMatrix(shadowMatrix);
1129
1130
1131        FlipFbos(fbo);
1132
1133        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
1134        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
1135        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
1136        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
1137        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
1138        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
1139
1140        const Vector3 lightDir = -light->GetDirection();
1141        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
1142        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
1143
1144        DrawQuad(sCgDeferredShadowProgram);
1145
1146        PrintGLerror("deferred shading + shadows");
1147}
1148
1149
1150void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
1151                                                                                         DirectionalLight *light,
1152                                                                                         float &imageKey,
1153                                                                                         float &whiteLum,
1154                                                                                         float &middleGrey)
1155{
1156        // hack: estimate value where sky burns out
1157        whiteLum = log(WHITE_LUMINANCE);
1158       
1159        ////////////////////
1160        //-- linear interpolate brightness key depending on the current sun position
1161
1162        const float minKey = 0.09f;
1163        const float maxKey = 0.36f;
1164
1165        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
1166        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
1167
1168
1169        //////////
1170        //-- compute avg loglum
1171
1172        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1173        GLuint colorsTex = colorBuffer->GetTexture();
1174
1175        FlipFbos(fbo);
1176       
1177        sCgLogLumProgram->SetTexture(0, colorsTex);
1178        DrawQuad(sCgLogLumProgram);
1179       
1180        PrintGLerror("ToneMapParams");
1181
1182
1183        ///////////////////
1184        //-- compute avg loglum in scene using mipmapping
1185
1186        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
1187        glGenerateMipmapEXT(GL_TEXTURE_2D);
1188}
1189
1190
1191static void ExportData(float *data, int w, int h)
1192{
1193        startil();
1194
1195        cout << "w: " << w << " h: " << h << endl;
1196        ILstring filename = ILstring("downsample2.jpg");
1197        ilRegisterType(IL_FLOAT);
1198
1199        const int depth = 1;
1200        const int bpp = 4;
1201
1202        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
1203        {
1204                cerr << "IL error " << ilGetError() << endl;
1205                stopil();
1206                return;
1207        }
1208
1209        if (!ilSaveImage(filename))
1210        {
1211                cerr << "TGA write error " << ilGetError() << endl;
1212        }
1213
1214        stopil();
1215}
1216
1217
1218void DeferredRenderer::PrepareSsao(FrameBufferObject *fbo)
1219{
1220        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1221        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1222        GLuint diffVals = fbo->GetColorBuffer(2)->GetTexture();
1223
1224        // flip flop between illumination buffers
1225        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1226        GLuint myTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
1227
1228        int i = 0;
1229
1230        sCgPrepareSsaoProgram->SetTexture(i ++, colorsTex);
1231        sCgPrepareSsaoProgram->SetTexture(i ++, normalsTex);
1232        sCgPrepareSsaoProgram->SetTexture(i ++, diffVals);
1233        sCgPrepareSsaoProgram->SetTexture(i ++, oldTex);
1234
1235        Vector3 de;
1236        de.x = mOldEyePos.x - mEyePos.x;
1237        de.y = mOldEyePos.y - mEyePos.y;
1238        de.z = mOldEyePos.z - mEyePos.z;
1239
1240        sCgPrepareSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
1241
1242        sCgPrepareSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
1243        sCgPrepareSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
1244
1245
1246        for (int j = 0; j < 4; ++ j, ++ i)
1247        {
1248                sCgPrepareSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
1249        }
1250
1251        sCgPrepareSsaoProgram->SetTexture(i ++, myTex);
1252
1253        glPushAttrib(GL_VIEWPORT_BIT);
1254        glViewport(0, 0, mDownSampleFbo->GetWidth(), mDownSampleFbo->GetHeight());
1255       
1256        mDownSampleFbo->Bind();
1257
1258        // prepare downsampled depth and normal texture for ssao
1259        glDrawBuffers(2, mrt);
1260
1261        DrawQuad(sCgPrepareSsaoProgram);
1262       
1263        glPopAttrib();
1264        PrintGLerror("prepareSsao");
1265}
1266
1267
1268void DeferredRenderer::DownSample(FrameBufferObject *fbo,
1269                                                                  int bufferIdx,
1270                                                                  FrameBufferObject *downSampleFbo,
1271                                                                  int downSampleBufferIdx,
1272                                                                  ShaderProgram *program)
1273{
1274        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
1275        GLuint tex = buffer->GetTexture();
1276
1277        glPushAttrib(GL_VIEWPORT_BIT);
1278        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
1279       
1280        downSampleFbo->Bind();
1281
1282        program->SetTexture(0, tex);
1283        glDrawBuffers(1, mrt + downSampleBufferIdx);
1284
1285        DrawQuad(program);
1286       
1287        glPopAttrib();
1288        PrintGLerror("downsample");
1289}
1290
1291
1292void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
1293                                                           float imageKey,
1294                                                           float whiteLum,
1295                                                           float middleGrey)
1296{
1297        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1298        GLuint colorsTex = colorBuffer->GetTexture();
1299       
1300
1301        FlipFbos(fbo);
1302
1303        sCgToneProgram->SetTexture(0, colorsTex);
1304        sCgToneProgram->SetValue1f(1, imageKey);
1305        sCgToneProgram->SetValue1f(2, whiteLum);
1306        sCgToneProgram->SetValue1f(3, middleGrey);
1307
1308        DrawQuad(sCgToneProgram);
1309
1310        PrintGLerror("ToneMap");
1311}
1312
1313
1314void DeferredRenderer::Output(FrameBufferObject *fbo)
1315{
1316        glPushAttrib(GL_VIEWPORT_BIT);
1317        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
1318       
1319        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1320        GLuint colorsTex = colorBuffer->GetTexture();
1321
1322        sCgDownSampleProgram->SetTexture(0, colorsTex);
1323
1324        FrameBufferObject::Release();
1325        DrawQuad(sCgDownSampleProgram);
1326
1327        PrintGLerror("Output");
1328}
1329
1330
1331void DeferredRenderer::InitFrame()
1332{
1333        for (int i = 0; i < 4; ++ i)
1334        {
1335                mOldCornersView[i] = mCornersView[i];
1336        }
1337
1338        mOldProjViewMatrix = mProjViewMatrix;
1339        mOldEyePos = mEyePos;
1340        mEyePos = mCamera->GetPosition();
1341
1342        // hack: temporarily change far to improve precision
1343        const float oldFar = mCamera->GetFar();
1344        const float oldNear = mCamera->GetNear();
1345       
1346
1347        Matrix4x4 matViewing, matProjection;
1348
1349
1350        ///////////////////
1351
1352        // use view orientation as we assume that the eye point is always in the center
1353        // of our coordinate system, this way we have the highest precision near the eye point
1354        mCamera->GetViewOrientationMatrix(matViewing);
1355        mCamera->GetProjectionMatrix(matProjection);
1356
1357        mProjViewMatrix = matViewing * matProjection;
1358        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1359       
1360
1361        // switch roles of old and new fbo
1362        // the algorihm uses two input fbos, where the one
1363        // contais the color buffer from the last frame,
1364        // the other one will be written
1365
1366        mIllumFboIndex = 2 - mIllumFboIndex;
1367       
1368        // enable fragment shading
1369        ShaderManager::GetSingleton()->EnableFragmentProfile();
1370
1371        glDisable(GL_ALPHA_TEST);
1372        glDisable(GL_TEXTURE_2D);
1373        glDisable(GL_LIGHTING);
1374        glDisable(GL_BLEND);
1375        glDisable(GL_DEPTH_TEST);
1376
1377        glPolygonMode(GL_FRONT, GL_FILL);
1378
1379        glMatrixMode(GL_PROJECTION);
1380        glPushMatrix();
1381        glLoadIdentity();
1382
1383        gluOrtho2D(0, 1, 0, 1);
1384
1385        glMatrixMode(GL_MODELVIEW);
1386        glPushMatrix();
1387        glLoadIdentity();
1388       
1389        glPushAttrib(GL_VIEWPORT_BIT);
1390        glViewport(0, 0, mWidth, mHeight);
1391
1392        // revert to old far and near plane
1393        mCamera->SetFar(oldFar);
1394        mCamera->SetNear(oldNear);
1395}
1396
1397
1398void DeferredRenderer::LenseFlare(FrameBufferObject *fbo,
1399                                                                  DirectionalLight *light                                                       
1400                                                                  )
1401{
1402        // light source visible?
1403        if (!mSunVisiblePixels) return;
1404
1405        // the sun is a large distance in the reverse light direction
1406        // => extrapolate light pos
1407        const Vector3 lightPos = light->GetDirection() * -1e3f;
1408
1409        float w;
1410        Vector3 projLightPos = mProjViewMatrix.Transform(w, lightPos, 1.0f);
1411        projLightPos /= w;
1412        projLightPos = projLightPos * 0.5f + Vector3(0.5f);
1413
1414        // vector to light from screen center in texture space
1415        Vector3 vectorToLight = projLightPos - Vector3(0.5f);
1416        vectorToLight.z = .0f;
1417
1418        const float distanceToLight = Magnitude(vectorToLight);
1419        vectorToLight /= distanceToLight;
1420        //cout << "dist " << distanceToLight << " v " << vectorToLight << endl;
1421
1422
1423        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1424        GLuint colorsTex = colorBuffer->GetTexture();
1425       
1426        FlipFbos(fbo);
1427
1428        int i = 0;
1429
1430        sCgLenseFlareProgram->SetTexture(i ++, colorsTex);
1431        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[0]->GetId());
1432        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[1]->GetId());
1433        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[2]->GetId());
1434        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[3]->GetId());
1435        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[4]->GetId());
1436        sCgLenseFlareProgram->SetValue2f(i ++, vectorToLight.x, vectorToLight.y);
1437        sCgLenseFlareProgram->SetValue1f(i ++, distanceToLight);
1438        sCgLenseFlareProgram->SetValue1f(i ++, (float)mSunVisiblePixels);
1439
1440        DrawQuad(sCgLenseFlareProgram);
1441
1442        PrintGLerror("LenseFlare");
1443}
1444
1445
1446void DeferredRenderer::DepthOfField(FrameBufferObject *fbo)
1447{
1448        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1449        GLuint colorsTex = colorBuffer->GetTexture();
1450       
1451        FlipFbos(fbo);
1452
1453        int i = 0;
1454
1455        const float zFocus = 7.0f;
1456
1457        sCgDOFProgram->SetTexture(i ++, colorsTex);
1458        sCgDOFProgram->SetArray2f(i ++, (float *)dofSamples, NUM_DOF_TABS);
1459        sCgDOFProgram->SetValue1f(i ++, min(mCamera->GetFar(), mMaxDistance) - mCamera->GetNear());
1460        sCgDOFProgram->SetValue1f(i ++, zFocus);
1461
1462        DrawQuad(sCgDOFProgram);
1463
1464        PrintGLerror("LenseFlare");
1465}
1466
1467
1468void DeferredRenderer::SaveFrame(FrameBufferObject *fbo)
1469{
1470        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1471        GLuint colorsTex = colorBuffer->GetTexture();
1472
1473        GLubyte *data = new GLubyte[mWidth * mHeight * 4];
1474
1475        // grab texture data
1476        glEnable(GL_TEXTURE_2D);
1477        glBindTexture(GL_TEXTURE_2D, colorsTex);
1478        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
1479
1480        glBindTexture(GL_TEXTURE_2D, 0);
1481        glDisable(GL_TEXTURE_2D);
1482
1483        /////////////////
1484
1485        startil();
1486
1487        static char imageName[200];
1488        sprintf(imageName, "%s_%05d.tga", mSavedFrameSuffix.c_str(), mSavedFrameNumber);
1489
1490        ILstring fileName = ILstring(imageName);
1491        ilRegisterType(IL_FLOAT);
1492
1493        const int depth = 1;
1494        const int bpp = 4;
1495
1496        if (!ilTexImage(mWidth, mHeight, depth, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data))
1497        {
1498                cerr << "IL error " << ilGetError() << endl;
1499                stopil();
1500                return;
1501        }
1502
1503        ilEnable(IL_FILE_OVERWRITE);
1504
1505        if (!ilSaveImage(fileName))
1506        {
1507                cerr << "TGA write error " << ilGetError() << endl;
1508        }
1509
1510        delete [] data;
1511        stopil();
1512
1513        PrintGLerror("Store frame");
1514}
1515
1516
1517void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
1518{
1519        mUseTemporalCoherence = temporal;
1520}
1521
1522
1523void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
1524{
1525        if (s != mSamplingMethod)
1526        {
1527                mSamplingMethod = s;
1528                mRegenerateSamples = true;
1529        }
1530}
1531
1532
1533void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
1534{
1535        if (s != mShadingMethod)
1536        {
1537                mShadingMethod = s;
1538                mRegenerateSamples = true;
1539        }
1540}
1541
1542
1543#if TODO
1544
1545void DeferredRenderer::SetNumSamples(int numSamples)
1546{
1547        mNumSamples = numSamples;
1548}
1549
1550#endif
1551
1552
1553void DeferredRenderer::SetSampleIntensity(float sampleIntensity)
1554{
1555        mSampleIntensity = sampleIntensity;
1556        mRegenerateSamples = true;
1557}
1558
1559
1560void DeferredRenderer::SetKernelRadius(float kernelRadius)
1561{
1562        mKernelRadius = kernelRadius;
1563        mRegenerateSamples = true;
1564}
1565
1566
1567/*void DeferredRenderer::SetSortSamples(bool sortSamples)
1568{
1569        mSortSamples = sortSamples;
1570}*/
1571
1572
1573void DeferredRenderer::SetSunVisiblePixels(int pixels)
1574{
1575        mSunVisiblePixels = pixels;
1576}
1577
1578
1579void DeferredRenderer::SetMaxDistance(float maxDist)
1580{
1581        mMaxDistance = maxDist;
1582}
1583
1584
1585void DeferredRenderer::SetUseToneMapping(bool toneMapping)
1586{
1587        mUseToneMapping = toneMapping;
1588}
1589       
1590
1591void DeferredRenderer::SetUseAntiAliasing(bool antiAliasing)
1592{
1593        mUseAntiAliasing = antiAliasing;
1594}
1595
1596
1597void DeferredRenderer::SetUseDepthOfField(bool dof)
1598{
1599        mUseDepthOfField = dof;
1600}
1601
1602
1603void DeferredRenderer::SetTemporalCoherenceFactorForSsao(float factor)
1604{
1605        mTempCohFactor = factor;
1606}
1607
1608
1609void DeferredRenderer::SetSaveFrame(const string &suffix, int frameNumber)
1610{
1611        mSavedFrameSuffix = suffix;
1612        mSavedFrameNumber = frameNumber;
1613}
1614
1615
1616void DeferredRenderer::SetMaxConvergence(float c)
1617{
1618        mMaxConvergence = c;
1619}
1620
1621
1622void DeferredRenderer::SetSpatialWeight(float w)
1623{
1624        mSpatialWeight = w;
1625}
1626
1627
1628} // namespace
Note: See TracBrowser for help on using the repository browser.