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

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