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

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

nix geht

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_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        PrintGLerror("here4");
287        glEnable(GL_TEXTURE_2D);
288        glBindTexture(GL_TEXTURE_2D, sampleTex2D);
289               
290        const int w = numSamples; const int h = 1;
291
292        float *tempBuffer = new float[numSamples * 3];
293
294        for (int i = 0; i < numSamples; ++ i)
295        {
296                tempBuffer[i * 3 + 0] = samples[i].x;
297                tempBuffer[i * 3 + 1] = samples[i].y;
298                tempBuffer[i * 3 + 2] = 0;
299        }
300
301        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGB, GL_FLOAT, (float *)tempBuffer);
302
303        glBindTexture(GL_TEXTURE_2D, 0);
304        glDisable(GL_TEXTURE_2D);
305
306        cout << "updated sample texture" << endl;
307
308        delete [] tempBuffer;
309
310        PrintGLerror("update sample tex");
311}
312
313
314static void CreateSampleTex(Sample2 *samples, int numSamples)
315{
316        glEnable(GL_TEXTURE_2D);
317        glGenTextures(1, &sampleTex2D);
318        glBindTexture(GL_TEXTURE_2D, sampleTex2D);
319               
320        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
321        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
322        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
323        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
324
325        const int w = numSamples; const int h = 1;
326
327        float *tempBuffer = new float[numSamples * 3];
328
329        for (int i = 0; i < numSamples; ++ i)
330        {
331                tempBuffer[i * 3 + 0] = samples[i].x;
332                tempBuffer[i * 3 + 1] = samples[i].y;
333                tempBuffer[i * 3 + 2] = 0;
334        }
335
336        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, w, h, 0, GL_RGB, GL_FLOAT, (float *)tempBuffer);
337
338        glBindTexture(GL_TEXTURE_2D, 0);
339        glDisable(GL_TEXTURE_2D);
340
341        cout << "created sample texture" << endl;
342
343        delete [] tempBuffer;
344
345        PrintGLerror("create sample tex");
346}
347
348
349static void PrepareLenseFlare()
350{
351        string textures[] = {"flare4.tga", "lens2.jpg", "lens3.jpg", "lens4.jpg", "lens1.jpg"};
352
353        // todo: delete halo textures
354        for (int i = 0; i < 5; ++ i)
355        {
356                sHaloTex[i] = new Texture(model_path + textures[i]);
357
358                sHaloTex[i]->SetBoundaryModeS(Texture::BORDER);
359                sHaloTex[i]->SetBoundaryModeT(Texture::BORDER);
360
361                sHaloTex[i]->Create();
362        }
363
364        cout << "prepared lense flare textures" << endl;
365
366        PrintGLerror("prepare lense flare");
367}
368
369
370DeferredRenderer::DeferredRenderer(int w, int h,
371                                                                   PerspectiveCamera *cam,
372                                                                   bool ssaoUseFullResolution):
373mWidth(w), mHeight(h),
374mCamera(cam),
375mUseTemporalCoherence(true),
376mRegenerateSamples(true),
377mSamplingMethod(SAMPLING_POISSON),
378mShadingMethod(DEFAULT),
379mIllumFboIndex(0),
380mSortSamples(true),
381mKernelRadius(1e-8f),
382mSampleIntensity(0.2f),
383mSunVisiblePixels(0),
384mSavedFrameNumber(-1),
385mSavedFrameSuffix(""),
386mMaxDistance(1e6f),
387mTempCohFactor(.0f),
388mUseToneMapping(false),
389mUseAntiAliasing(false),
390mUseDepthOfField(false),
391mSsaoUseFullResolution(ssaoUseFullResolution),
392mMaxConvergence(2000.0f),
393mSpatialWeight(.0f)
394{
395        ///////////
396        //-- the flip-flop fbos
397
398        int downSampledWidth, downSampledHeight;
399
400        if (mSsaoUseFullResolution)
401        {
402                downSampledWidth = w; downSampledHeight = h;
403                cout << "using full resolution ssao" << endl;
404        }
405        else
406        {
407                downSampledWidth = w / 2; downSampledHeight = h / 2;
408                cout << "using half resolution ssao" << endl;
409        }
410
411
412        /////////
413        //-- the illumination fbo is either half size or full size
414
415        mIllumFbo = new FrameBufferObject(downSampledWidth, downSampledHeight, FrameBufferObject::DEPTH_NONE);
416        mFBOs.push_back(mIllumFbo);
417
418        for (int i = 0; i < 4; ++ i)
419        {
420                mIllumFbo->AddColorBuffer(ColorBufferObject::R_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
421                FrameBufferObject::InitBuffer(mIllumFbo, i);
422        }
423
424
425        ///////////////
426        //-- the downsampled ssao + color bleeding textures:
427        //-- as GI is mostly low frequency, we can use lower resolution to improve performance
428
429        mDownSampleFbo = new FrameBufferObject(downSampledWidth, downSampledHeight, FrameBufferObject::DEPTH_NONE);
430        // the downsampled color + depth buffer
431        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
432        // downsample buffer for the normal texture
433        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
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(2, 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                        cout<<"here34"<<endl;
849                }
850                else
851                {
852                        UpdateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
853                }
854
855
856                //if (mSortSamples) { SortSamples(); }
857                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
858                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_PRECOMPUTED_SAMPLES);
859        }
860
861        sCgSsaoProgram->SetTexture(i, sampleTex2D);
862
863        ++ i;
864
865        for (int j = 0; j < 4; ++ j, ++ i)
866        {
867                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
868        }
869
870        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
871        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
872
873        Vector3 de;
874        de.x = mOldEyePos.x - mEyePos.x;
875        de.y = mOldEyePos.y - mEyePos.y;
876        de.z = mOldEyePos.z - mEyePos.z;
877
878        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
879
880        for (int j = 0; j < 4; ++ j, ++ i)
881        {
882                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
883        }
884
885        sCgSsaoProgram->SetTexture(i ++, attribsTex);
886        sCgSsaoProgram->SetValue1f(i ++, mKernelRadius);
887        sCgSsaoProgram->SetValue1f(i ++, mSampleIntensity * mKernelRadius);
888
889        DrawQuad(sCgSsaoProgram);
890        glPopAttrib();
891
892        PrintGLerror("ssao first pass");
893}
894
895
896static void SetVertex(float x, float y, float x_offs, float y_offs)
897{
898        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
899        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
900        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
901        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
902        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
903
904        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
905        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
906
907        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
908        glVertex2f(x, y);
909}
910
911
912void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo,
913                                                                        DirectionalLight *light,
914                                                                        bool displayFrame)
915{
916        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
917        GLuint colorsTex = colorBuffer->GetTexture();
918        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
919
920        // read the second buffer, write to the first buffer
921        if (!displayFrame)
922        {
923                FlipFbos(fbo);
924        }
925        else
926        {
927                // end of the pipeline => just draw image to screen
928                FrameBufferObject::Release();
929        }
930
931        // the neighbouring texels
932        float xOffs = 1.0f / fbo->GetWidth();
933        float yOffs = 1.0f / fbo->GetHeight();
934
935        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
936        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
937
938        float offsets[16];
939        int i = 0;
940
941        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
942        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
943        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
944        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
945        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
946        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
947        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
948        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
949
950        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
951
952        DrawQuad(sCgAntiAliasingProgram);
953
954        PrintGLerror("antialiasing");
955}
956
957
958void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
959{
960        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
961        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
962
963        FlipFbos(fbo);
964
965        const Vector3 lightDir = -light->GetDirection();
966
967        sCgDeferredProgram->SetTexture(0, colorsTex);
968        sCgDeferredProgram->SetTexture(1, normalsTex);
969        sCgDeferredProgram->SetValue3f(2, lightDir.x, lightDir.y, lightDir.z);
970       
971        DrawQuad(sCgDeferredProgram);
972
973        PrintGLerror("deferred shading");
974}
975
976
977void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
978                                                                                float tempCohFactor)
979{
980#if 0
981        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
982        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
983#else
984        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
985        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
986#endif
987
988        glPushAttrib(GL_VIEWPORT_BIT);
989        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
990
991        // read the second buffer, write to the first buffer
992        mIllumFbo->Bind();
993        glDrawBuffers(2, mrt + mIllumFboIndex);
994
995        // bind the old buffers for temporal coherence
996        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
997        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
998
999        int i = 0;
1000
1001        sCgGiProgram->SetTexture(i ++, colorsTex);
1002        sCgGiProgram->SetTexture(i ++, normalsTex);
1003        sCgGiProgram->SetTexture(i ++, noiseTex2D);
1004        sCgGiProgram->SetTexture(i ++, oldSsaoTex);
1005        sCgGiProgram->SetTexture(i ++, oldIllumTex);
1006
1007        sCgGiProgram->SetValue1f(i ++,
1008                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
1009
1010        if (mUseTemporalCoherence || mRegenerateSamples)
1011        {
1012                mRegenerateSamples = false;
1013
1014                // q: should we generate new samples or only rotate the old ones?
1015                // in the first case, the sample patterns look nicer, but the kernel
1016                // needs longer to converge
1017                GenerateSamples(mSamplingMethod);
1018
1019                sCgGiProgram->SetArray2f(i ++, (float *)samples2, NUM_SAMPLES);
1020        }
1021
1022        Vector3 bl = mCornersView[0];
1023        Vector3 br = mCornersView[1];
1024        Vector3 tl = mCornersView[2];
1025        Vector3 tr = mCornersView[3];
1026
1027        sCgGiProgram->SetValue3f(i ++, bl.x, bl.y, bl.z);
1028        sCgGiProgram->SetValue3f(i ++, br.x, br.y, br.z);
1029        sCgGiProgram->SetValue3f(i ++, tl.x, tl.y, tl.z);
1030        sCgGiProgram->SetValue3f(i ++, tr.x, tr.y, tr.z);
1031
1032        sCgGiProgram->SetMatrix(i ++, mOldProjViewMatrix);
1033        sCgGiProgram->SetMatrix(i ++, mProjViewMatrix);
1034
1035
1036        DrawQuad(sCgGiProgram);
1037
1038        glPopAttrib();
1039
1040        PrintGLerror("globillum first pass");
1041}
1042
1043
1044void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
1045{
1046        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1047
1048        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1049        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
1050
1051        FlipFbos(fbo);
1052
1053        sCgCombineIllumProgram->SetTexture(0, colorsTex);
1054        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
1055        sCgCombineIllumProgram->SetTexture(2, illumTex);
1056       
1057        DrawQuad(sCgCombineIllumProgram);
1058
1059        PrintGLerror("combine");
1060}
1061
1062
1063void DeferredRenderer::FilterSsao(FrameBufferObject *fbo)
1064{
1065        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1066        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1067        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1068       
1069        mTempFbo->Bind();
1070        glDrawBuffers(1, mrt);
1071       
1072        int i = 0;
1073
1074        sCgFilterSsaoProgram->SetTexture(i ++, colorsTex);
1075        sCgFilterSsaoProgram->SetTexture(i ++, ssaoTex);
1076
1077        for (int j = 0; j < 4; ++ j, ++ i)
1078        {
1079                sCgFilterSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1080        }
1081
1082        sCgFilterSsaoProgram->SetValue2f(i ++, (float)mWidth, (float)mHeight);
1083        sCgFilterSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1084        sCgFilterSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1085
1086        DrawQuad(sCgFilterSsaoProgram);
1087        PrintGLerror("filter ssao");
1088}
1089
1090
1091void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
1092{
1093        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1094        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1095        GLuint ssaoTex = mTempFbo->GetColorBuffer(0)->GetTexture();
1096       
1097        FlipFbos(fbo);
1098
1099        int i = 0;
1100
1101        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
1102        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
1103
1104        for (int j = 0; j < 4; ++ j, ++ i)
1105        {
1106                sCgCombineSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1107        }
1108
1109        sCgCombineSsaoProgram->SetValue2f(i ++, mWidth, mHeight);
1110        sCgCombineSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1111        sCgCombineSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1112
1113        DrawQuad(sCgCombineSsaoProgram);
1114       
1115        PrintGLerror("combine ssao");
1116}
1117
1118
1119void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
1120                                                                           DirectionalLight *light,
1121                                                                           ShadowMap *shadowMap)
1122{
1123        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1124        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1125
1126        GLuint shadowTex = shadowMap->GetDepthTexture();
1127
1128        Matrix4x4 shadowMatrix;
1129        shadowMap->GetTextureMatrix(shadowMatrix);
1130
1131
1132        FlipFbos(fbo);
1133
1134        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
1135        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
1136        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
1137        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
1138        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
1139        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
1140
1141        const Vector3 lightDir = -light->GetDirection();
1142        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
1143        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
1144
1145        DrawQuad(sCgDeferredShadowProgram);
1146
1147        PrintGLerror("deferred shading + shadows");
1148}
1149
1150
1151void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
1152                                                                                         DirectionalLight *light,
1153                                                                                         float &imageKey,
1154                                                                                         float &whiteLum,
1155                                                                                         float &middleGrey)
1156{
1157        // hack: estimate value where sky burns out
1158        whiteLum = log(WHITE_LUMINANCE);
1159       
1160        ////////////////////
1161        //-- linear interpolate brightness key depending on the current sun position
1162
1163        const float minKey = 0.09f;
1164        const float maxKey = 0.36f;
1165
1166        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
1167        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
1168
1169
1170        //////////
1171        //-- compute avg loglum
1172
1173        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1174        GLuint colorsTex = colorBuffer->GetTexture();
1175
1176        FlipFbos(fbo);
1177       
1178        sCgLogLumProgram->SetTexture(0, colorsTex);
1179        DrawQuad(sCgLogLumProgram);
1180       
1181        PrintGLerror("ToneMapParams");
1182
1183
1184        ///////////////////
1185        //-- compute avg loglum in scene using mipmapping
1186
1187        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
1188        glGenerateMipmapEXT(GL_TEXTURE_2D);
1189}
1190
1191
1192static void ExportData(float *data, int w, int h)
1193{
1194        startil();
1195
1196        cout << "w: " << w << " h: " << h << endl;
1197        ILstring filename = ILstring("downsample2.jpg");
1198        ilRegisterType(IL_FLOAT);
1199
1200        const int depth = 1;
1201        const int bpp = 4;
1202
1203        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
1204        {
1205                cerr << "IL error " << ilGetError() << endl;
1206                stopil();
1207                return;
1208        }
1209
1210        if (!ilSaveImage(filename))
1211        {
1212                cerr << "TGA write error " << ilGetError() << endl;
1213        }
1214
1215        stopil();
1216}
1217
1218
1219void DeferredRenderer::PrepareSsao(FrameBufferObject *fbo)
1220{
1221        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1222        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1223        GLuint diffVals = fbo->GetColorBuffer(2)->GetTexture();
1224
1225        // flip flop between illumination buffers
1226        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1227        GLuint myTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
1228
1229        int i = 0;
1230
1231        sCgPrepareSsaoProgram->SetTexture(i ++, colorsTex);
1232        sCgPrepareSsaoProgram->SetTexture(i ++, normalsTex);
1233        sCgPrepareSsaoProgram->SetTexture(i ++, diffVals);
1234        sCgPrepareSsaoProgram->SetTexture(i ++, oldTex);
1235
1236        Vector3 de;
1237        de.x = mOldEyePos.x - mEyePos.x;
1238        de.y = mOldEyePos.y - mEyePos.y;
1239        de.z = mOldEyePos.z - mEyePos.z;
1240
1241        sCgPrepareSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
1242
1243        sCgPrepareSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
1244        sCgPrepareSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
1245
1246
1247        for (int j = 0; j < 4; ++ j, ++ i)
1248        {
1249                sCgPrepareSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
1250        }
1251
1252        sCgPrepareSsaoProgram->SetTexture(i ++, myTex);
1253
1254        glPushAttrib(GL_VIEWPORT_BIT);
1255        glViewport(0, 0, mDownSampleFbo->GetWidth(), mDownSampleFbo->GetHeight());
1256       
1257        mDownSampleFbo->Bind();
1258
1259        // prepare downsampled depth and normal texture for ssao
1260        glDrawBuffers(2, mrt);
1261
1262        DrawQuad(sCgPrepareSsaoProgram);
1263       
1264        glPopAttrib();
1265        PrintGLerror("prepareSsao");
1266}
1267
1268
1269void DeferredRenderer::DownSample(FrameBufferObject *fbo,
1270                                                                  int bufferIdx,
1271                                                                  FrameBufferObject *downSampleFbo,
1272                                                                  int downSampleBufferIdx,
1273                                                                  ShaderProgram *program)
1274{
1275        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
1276        GLuint tex = buffer->GetTexture();
1277
1278        glPushAttrib(GL_VIEWPORT_BIT);
1279        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
1280       
1281        downSampleFbo->Bind();
1282
1283        program->SetTexture(0, tex);
1284        glDrawBuffers(1, mrt + downSampleBufferIdx);
1285
1286        DrawQuad(program);
1287       
1288        glPopAttrib();
1289        PrintGLerror("downsample");
1290}
1291
1292
1293void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
1294                                                           float imageKey,
1295                                                           float whiteLum,
1296                                                           float middleGrey)
1297{
1298        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1299        GLuint colorsTex = colorBuffer->GetTexture();
1300       
1301
1302        FlipFbos(fbo);
1303
1304        sCgToneProgram->SetTexture(0, colorsTex);
1305        sCgToneProgram->SetValue1f(1, imageKey);
1306        sCgToneProgram->SetValue1f(2, whiteLum);
1307        sCgToneProgram->SetValue1f(3, middleGrey);
1308
1309        DrawQuad(sCgToneProgram);
1310
1311        PrintGLerror("ToneMap");
1312}
1313
1314
1315void DeferredRenderer::Output(FrameBufferObject *fbo)
1316{
1317        glPushAttrib(GL_VIEWPORT_BIT);
1318        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
1319       
1320        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1321        GLuint colorsTex = colorBuffer->GetTexture();
1322
1323        sCgDownSampleProgram->SetTexture(0, colorsTex);
1324
1325        FrameBufferObject::Release();
1326        DrawQuad(sCgDownSampleProgram);
1327
1328        PrintGLerror("Output");
1329}
1330
1331
1332void DeferredRenderer::InitFrame()
1333{
1334        for (int i = 0; i < 4; ++ i)
1335        {
1336                mOldCornersView[i] = mCornersView[i];
1337        }
1338
1339        mOldProjViewMatrix = mProjViewMatrix;
1340        mOldEyePos = mEyePos;
1341        mEyePos = mCamera->GetPosition();
1342
1343        // hack: temporarily change far to improve precision
1344        const float oldFar = mCamera->GetFar();
1345        const float oldNear = mCamera->GetNear();
1346       
1347
1348        Matrix4x4 matViewing, matProjection;
1349
1350
1351        ///////////////////
1352
1353        // use view orientation as we assume that the eye point is always in the center
1354        // of our coordinate system, this way we have the highest precision near the eye point
1355        mCamera->GetViewOrientationMatrix(matViewing);
1356        mCamera->GetProjectionMatrix(matProjection);
1357
1358        mProjViewMatrix = matViewing * matProjection;
1359        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1360       
1361
1362        // switch roles of old and new fbo
1363        // the algorihm uses two input fbos, where the one
1364        // contais the color buffer from the last frame,
1365        // the other one will be written
1366
1367        mIllumFboIndex = 2 - mIllumFboIndex;
1368       
1369        // enable fragment shading
1370        ShaderManager::GetSingleton()->EnableFragmentProfile();
1371
1372        glDisable(GL_ALPHA_TEST);
1373        glDisable(GL_TEXTURE_2D);
1374        glDisable(GL_LIGHTING);
1375        glDisable(GL_BLEND);
1376        glDisable(GL_DEPTH_TEST);
1377
1378        glPolygonMode(GL_FRONT, GL_FILL);
1379
1380        glMatrixMode(GL_PROJECTION);
1381        glPushMatrix();
1382        glLoadIdentity();
1383
1384        gluOrtho2D(0, 1, 0, 1);
1385
1386
1387        glMatrixMode(GL_MODELVIEW);
1388        glPushMatrix();
1389        glLoadIdentity();
1390
1391       
1392        glPushAttrib(GL_VIEWPORT_BIT);
1393        glViewport(0, 0, mWidth, mHeight);
1394
1395        // revert to old far and near plane
1396        mCamera->SetFar(oldFar);
1397        mCamera->SetNear(oldNear);
1398}
1399
1400
1401void DeferredRenderer::LenseFlare(FrameBufferObject *fbo,
1402                                                                  DirectionalLight *light                                                       
1403                                                                  )
1404{
1405        // light source visible?
1406        if (!mSunVisiblePixels) return;
1407
1408        // the sun is a large distance in the reverse light direction
1409        // => extrapolate light pos
1410        const Vector3 lightPos = light->GetDirection() * -1e3f;
1411
1412        float w;
1413        Vector3 projLightPos = mProjViewMatrix.Transform(w, lightPos, 1.0f);
1414        projLightPos /= w;
1415        projLightPos = projLightPos * 0.5f + Vector3(0.5f);
1416
1417        // vector to light from screen center in texture space
1418        Vector3 vectorToLight = projLightPos - Vector3(0.5f);
1419        vectorToLight.z = .0f;
1420
1421        const float distanceToLight = Magnitude(vectorToLight);
1422        vectorToLight /= distanceToLight;
1423        //cout << "dist " << distanceToLight << " v " << vectorToLight << endl;
1424
1425
1426        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1427        GLuint colorsTex = colorBuffer->GetTexture();
1428       
1429        FlipFbos(fbo);
1430
1431        int i = 0;
1432
1433        sCgLenseFlareProgram->SetTexture(i ++, colorsTex);
1434        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[0]->GetId());
1435        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[1]->GetId());
1436        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[2]->GetId());
1437        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[3]->GetId());
1438        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[4]->GetId());
1439        sCgLenseFlareProgram->SetValue2f(i ++, vectorToLight.x, vectorToLight.y);
1440        sCgLenseFlareProgram->SetValue1f(i ++, distanceToLight);
1441        sCgLenseFlareProgram->SetValue1f(i ++, (float)mSunVisiblePixels);
1442
1443        DrawQuad(sCgLenseFlareProgram);
1444
1445        PrintGLerror("LenseFlare");
1446}
1447
1448
1449void DeferredRenderer::DepthOfField(FrameBufferObject *fbo)
1450{
1451        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1452        GLuint colorsTex = colorBuffer->GetTexture();
1453       
1454        FlipFbos(fbo);
1455
1456        int i = 0;
1457
1458        const float zFocus = 7.0f;
1459
1460        sCgDOFProgram->SetTexture(i ++, colorsTex);
1461        sCgDOFProgram->SetArray2f(i ++, (float *)dofSamples, NUM_DOF_TABS);
1462        sCgDOFProgram->SetValue1f(i ++, min(mCamera->GetFar(), mMaxDistance) - mCamera->GetNear());
1463        sCgDOFProgram->SetValue1f(i ++, zFocus);
1464
1465        DrawQuad(sCgDOFProgram);
1466
1467        PrintGLerror("LenseFlare");
1468}
1469
1470
1471void DeferredRenderer::SaveFrame(FrameBufferObject *fbo)
1472{
1473        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1474        GLuint colorsTex = colorBuffer->GetTexture();
1475
1476        GLubyte *data = new GLubyte[mWidth * mHeight * 4];
1477
1478        // grab texture data
1479        glEnable(GL_TEXTURE_2D);
1480        glBindTexture(GL_TEXTURE_2D, colorsTex);
1481        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
1482
1483        glBindTexture(GL_TEXTURE_2D, 0);
1484        glDisable(GL_TEXTURE_2D);
1485
1486        /////////////////
1487
1488        startil();
1489
1490        static char imageName[200];
1491        sprintf(imageName, "%s_%05d.tga", mSavedFrameSuffix.c_str(), mSavedFrameNumber);
1492
1493        ILstring fileName = ILstring(imageName);
1494        ilRegisterType(IL_FLOAT);
1495
1496        const int depth = 1;
1497        const int bpp = 4;
1498
1499        if (!ilTexImage(mWidth, mHeight, depth, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data))
1500        {
1501                cerr << "IL error " << ilGetError() << endl;
1502                stopil();
1503                return;
1504        }
1505
1506        ilEnable(IL_FILE_OVERWRITE);
1507
1508        if (!ilSaveImage(fileName))
1509        {
1510                cerr << "TGA write error " << ilGetError() << endl;
1511        }
1512
1513        delete [] data;
1514        stopil();
1515
1516        PrintGLerror("Store frame");
1517}
1518
1519
1520void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
1521{
1522        mUseTemporalCoherence = temporal;
1523}
1524
1525
1526void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
1527{
1528        if (s != mSamplingMethod)
1529        {
1530                mSamplingMethod = s;
1531                mRegenerateSamples = true;
1532        }
1533}
1534
1535
1536void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
1537{
1538        if (s != mShadingMethod)
1539        {
1540                mShadingMethod = s;
1541                mRegenerateSamples = true;
1542        }
1543}
1544
1545
1546#if TODO
1547
1548void DeferredRenderer::SetNumSamples(int numSamples)
1549{
1550        mNumSamples = numSamples;
1551}
1552
1553#endif
1554
1555
1556void DeferredRenderer::SetSampleIntensity(float sampleIntensity)
1557{
1558        mSampleIntensity = sampleIntensity;
1559        mRegenerateSamples = true;
1560}
1561
1562
1563void DeferredRenderer::SetKernelRadius(float kernelRadius)
1564{
1565        mKernelRadius = kernelRadius;
1566        mRegenerateSamples = true;
1567}
1568
1569
1570/*void DeferredRenderer::SetSortSamples(bool sortSamples)
1571{
1572        mSortSamples = sortSamples;
1573}*/
1574
1575
1576void DeferredRenderer::SetSunVisiblePixels(int pixels)
1577{
1578        mSunVisiblePixels = pixels;
1579}
1580
1581
1582void DeferredRenderer::SetMaxDistance(float maxDist)
1583{
1584        mMaxDistance = maxDist;
1585}
1586
1587
1588void DeferredRenderer::SetUseToneMapping(bool toneMapping)
1589{
1590        mUseToneMapping = toneMapping;
1591}
1592       
1593
1594void DeferredRenderer::SetUseAntiAliasing(bool antiAliasing)
1595{
1596        mUseAntiAliasing = antiAliasing;
1597}
1598
1599
1600void DeferredRenderer::SetUseDepthOfField(bool dof)
1601{
1602        mUseDepthOfField = dof;
1603}
1604
1605
1606void DeferredRenderer::SetTemporalCoherenceFactorForSsao(float factor)
1607{
1608        mTempCohFactor = factor;
1609}
1610
1611
1612void DeferredRenderer::SetSaveFrame(const string &suffix, int frameNumber)
1613{
1614        mSavedFrameSuffix = suffix;
1615        mSavedFrameNumber = frameNumber;
1616}
1617
1618
1619void DeferredRenderer::SetMaxConvergence(float c)
1620{
1621        mMaxConvergence = c;
1622}
1623
1624
1625void DeferredRenderer::SetSpatialWeight(float w)
1626{
1627        mSpatialWeight = w;
1628}
1629
1630
1631} // namespace
Note: See TracBrowser for help on using the repository browser.