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

Revision 3206, 32.2 KB checked in by mattausch, 16 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 <math.h>
13
14#include <IL/il.h>
15#include <assert.h>
16
17
18#ifdef _CRT_SET
19        #define _CRTDBG_MAP_ALLOC
20        #include <stdlib.h>
21        #include <crtdbg.h>
22
23        // redefine new operator
24        #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
25        #define new DEBUG_NEW
26#endif
27
28
29using namespace std;
30
31
32static void startil()
33{
34        ilInit();
35        assert(ilGetError() == IL_NO_ERROR);
36}
37
38
39static void stopil()
40{
41        ilShutDown();
42        assert(ilGetError() == IL_NO_ERROR);
43}
44
45
46namespace CHCDemoEngine
47{
48
49static ShaderProgram *sCgSsaoProgram = NULL;
50static ShaderProgram *sCgGiProgram = NULL;
51
52static ShaderProgram *sCgDeferredProgram = NULL;
53static ShaderProgram *sCgAntiAliasingProgram = NULL;
54static ShaderProgram *sCgDeferredShadowProgram = NULL;
55
56static ShaderProgram *sCgCombineSsaoProgram = NULL;
57static ShaderProgram *sCgCombineIllumProgram = NULL;
58static ShaderProgram *sCgLogLumProgram = NULL;
59static ShaderProgram *sCgToneProgram = NULL;
60static ShaderProgram *sCgDownSampleProgram = NULL;
61static ShaderProgram *sCgScaleDepthProgram = NULL;
62static ShaderProgram *sCgPrepareSsaoProgram = NULL;
63
64
65static GLuint noiseTex2D = 0;
66static GLuint noiseTex1D = 0;
67
68
69// ssao random spherical samples
70static Sample2 samples2[NUM_SAMPLES];
71// number of pcf tabs
72static Sample2 pcfSamples[NUM_PCF_TABS];
73
74
75static float ssaoFilterOffsets[NUM_SSAO_FILTER_SAMPLES * 2];
76static float ssaoFilterWeights[NUM_SSAO_FILTER_SAMPLES];
77
78
79int DeferredRenderer::colorBufferIdx = 0;
80
81
82/** Helper method that computes the view vectors in the corners of the current view frustum.
83*/
84static void ComputeViewVectors(PerspectiveCamera *cam, Vector3 &bl, Vector3 &br, Vector3 &tl, Vector3 &tr)
85{
86        Vector3 ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr;
87        cam->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
88
89        bl = Normalize(nbl - fbl);
90        br = Normalize(nbr - fbr);
91        tl = Normalize(ntl - ftl);
92        tr = Normalize(ntr - ftr);
93}
94
95
96static float GaussianDistribution(float x, float y, float rho)
97{
98        float g = 1.0f / sqrtf(2.0f * M_PI * rho * rho);
99    g *= expf( -(x * x + y * y) / (2.0f * rho * rho));
100
101    return g;
102}
103
104
105static void PrintGLerror(char *msg)
106{
107        GLenum errCode;
108        const GLubyte *errStr;
109       
110        if ((errCode = glGetError()) != GL_NO_ERROR)
111        {
112                errStr = gluErrorString(errCode);
113                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
114        }
115}
116
117
118static Sample2 UnitTest(float x, float y, int wi, int he)
119{
120        Sample2 s;
121
122        s.x = float(floor(x * (float)wi - 0.5f) + 1.0f) / (float)wi;
123        s.y = float(floor(y * (float)he - 0.5f) + 1.0f) / (float)he;
124
125        return s;
126}
127
128
129static void ComputeSampleOffsets(float *sampleOffsets,
130                                                                 int imageW, int imageH,
131                                                                 float width,
132                                                                 int samples)
133{
134        const float xoffs = width / (float)imageW;
135        const float yoffs = width / (float)imageH;
136       
137        const int numSamples = (int)sqrt((float)samples);
138        const int startSamples = -numSamples / 2;
139        const int endSamples = numSamples + startSamples - 1;
140        //cout << startSamples << " " << endSamples << endl;
141
142        int idx = 0;
143
144        for (int x = startSamples; x <= endSamples; ++ x)
145        {
146                for (int y = startSamples; y <= endSamples; ++ y)
147                {
148                        sampleOffsets[idx + 0] = (float)x * xoffs;
149                        sampleOffsets[idx + 1] = (float)y * yoffs;
150                        idx += 2;
151                }
152        }
153}
154
155
156void DeferredRenderer::FlipFbos(FrameBufferObject *fbo)
157{
158        fbo->Bind();
159        colorBufferIdx = 3 - colorBufferIdx;
160        glDrawBuffers(1, mrt + colorBufferIdx);
161}
162
163
164void DeferredRenderer::DrawQuad(ShaderProgram *p)
165{
166        if (p) p->Bind();
167
168        // interpolate the view vector
169        Vector3 bl = mCornersView[0];
170        Vector3 br = mCornersView[1];
171        Vector3 tl = mCornersView[2];
172        Vector3 tr = mCornersView[3];
173
174        // note: slightly larger texture could hide ambient occlusion error on border but costs resolution
175        glBegin(GL_QUADS);
176
177        glTexCoord2f(0, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, bl.x, bl.y, bl.z); glVertex2f( .0f,  .0f);
178        glTexCoord2f(1, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, br.x, br.y, br.z); glVertex2f(1.0f,  .0f);
179        glTexCoord2f(1, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tr.x, tr.y, tr.z); glVertex2f(1.0f, 1.0f);
180        glTexCoord2f(0, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tl.x, tl.y, tl.z); glVertex2f( .0f, 1.0f);
181
182        glEnd();
183}
184
185
186/** Generate poisson disc distributed sample points on the unit disc
187*/
188static void GenerateSamples(int sampling)
189{
190        switch (sampling)
191        {
192        case DeferredRenderer::SAMPLING_POISSON:
193                {
194                        PoissonDiscSampleGenerator2 poisson(NUM_SAMPLES, 1.0f);
195                        poisson.Generate((float *)samples2);
196                }
197                break;
198        case DeferredRenderer::SAMPLING_QUADRATIC:
199                {
200                        QuadraticDiscSampleGenerator2 g(NUM_SAMPLES, 1.0f);
201                        g.Generate((float *)samples2);
202                }
203                break;
204        default: // SAMPLING_DEFAULT
205                {
206                        RandomSampleGenerator2 g(NUM_SAMPLES, 1.0f);
207                        g.Generate((float *)samples2);
208                }
209        }
210}
211
212
213static void CreateNoiseTex2D(int w, int h)
214{
215        //GLubyte *randomNormals = new GLubyte[mWidth * mHeight * 3];
216        float *randomNormals = new float[w * h * 3];
217
218        static HaltonSequence halton;
219        float r[2];
220
221        for (int i = 0; i < w * h * 3; i += 3)
222        {
223                // create random samples on a circle
224                r[0] = RandomValue(0, 1);
225                //halton.GetNext(1, r);
226
227                const float theta = 2.0f * acos(sqrt(1.0f - r[0]));
228               
229                randomNormals[i + 0] = cos(theta);
230                randomNormals[i + 1] = sin(theta);
231                randomNormals[i + 2] = 0;
232        }
233
234        glEnable(GL_TEXTURE_2D);
235        glGenTextures(1, &noiseTex2D);
236        glBindTexture(GL_TEXTURE_2D, noiseTex2D);
237               
238        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
239        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
240        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
241        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
242
243        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_RGB, GL_FLOAT, randomNormals);
244
245        glBindTexture(GL_TEXTURE_2D, 0);
246        glDisable(GL_TEXTURE_2D);
247
248        delete [] randomNormals;
249
250        cout << "created noise texture" << endl;
251
252        PrintGLerror("noisetexture");
253}
254
255
256static void CreateNoiseTex1D(int w)
257{
258        float *randomValues = new float[w * 3];
259
260        static HaltonSequence halton;
261       
262        randomValues[0] = randomValues[1] = randomValues[2] = 0;
263
264        for (int i = 3; i < w * 3; i += 3)
265        {
266                // create random samples on a circle
267                randomValues[i + 0] = 20.0f * RandomValue(0, 1) / 512.0f;
268                randomValues[i + 1] = 20.0f * RandomValue(0, 1) / 384.0f;
269                randomValues[i + 2] = 0;
270        }
271
272        glEnable(GL_TEXTURE_2D);
273        glGenTextures(1, &noiseTex1D);
274        glBindTexture(GL_TEXTURE_2D, noiseTex1D);
275               
276        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
277        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
278        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
279        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
280
281        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, 1, 0, GL_RGB, GL_FLOAT, randomValues);
282
283        glBindTexture(GL_TEXTURE_2D, 0);
284        glDisable(GL_TEXTURE_2D);
285
286        delete [] randomValues;
287
288        cout << "created noise texture 1D" << endl;
289
290        PrintGLerror("noisetexture 1D");
291}
292
293
294DeferredRenderer::DeferredRenderer(int w, int h, PerspectiveCamera *cam):
295mWidth(w), mHeight(h),
296mCamera(cam),
297mUseTemporalCoherence(true),
298mRegenerateSamples(true),
299mSamplingMethod(SAMPLING_POISSON),
300mShadingMethod(DEFAULT),
301mIllumFboIndex(0),
302mSortSamples(true)
303{
304        ///////////
305        //-- the flip-flop fbos
306
307        const int dsw = w / 2; const int dsh = h / 2;
308        //const int dsw = w; const int dsh = h;
309
310        mIllumFbo = new FrameBufferObject(dsw, dsh, FrameBufferObject::DEPTH_NONE);
311        //mIllumFbo = new FrameBufferObject(w, h, FrameBufferObject::DEPTH_NONE);
312
313        mFBOs.push_back(mIllumFbo);
314
315        for (int i = 0; i < 4; ++ i)
316        {
317                mIllumFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
318                FrameBufferObject::InitBuffer(mIllumFbo, i);
319        }
320
321
322        ///////////////
323        //-- the downsampled ssao + color bleeding textures: as GI is mostly low frequency, we can use lower resolution toimprove performance
324
325        mDownSampleFbo = new FrameBufferObject(dsw, dsh, FrameBufferObject::DEPTH_NONE);
326        // the downsampled color + depth buffer
327        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
328        // downsample buffer for the normal texture
329        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST);
330
331        for (int i = 0; i < 2; ++ i)
332        {
333                FrameBufferObject::InitBuffer(mDownSampleFbo, i);
334        }
335
336        mFBOs.push_back(mDownSampleFbo);
337
338        // create noise texture for ssao
339        // for performance reasons we use a smaller texture and repeat it over the screen
340        CreateNoiseTex2D(mIllumFbo->GetWidth() / 4, mIllumFbo->GetWidth() / 4);
341       
342        mProjViewMatrix = IdentityMatrix();
343        mOldProjViewMatrix = IdentityMatrix();
344
345        for (int i = 0; i < 4; ++ i)
346        {
347                mCornersView[i] = mOldCornersView[i] = Vector3::UNIT_X();
348        }
349
350        mEyePos = mOldEyePos = Vector3::ZERO();
351
352        InitCg();
353}
354
355
356DeferredRenderer::~DeferredRenderer()
357{
358        CLEAR_CONTAINER(mFBOs);
359
360        glDeleteTextures(1, &noiseTex2D);
361        glDeleteTextures(1, &noiseTex1D);
362}
363
364
365void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
366{
367        mUseTemporalCoherence = temporal;
368}
369
370
371
372void DeferredRenderer::InitCg()
373{       
374        ShaderManager *sm = ShaderManager::GetSingleton();
375
376        sCgDeferredProgram = sm->CreateFragmentProgram("deferred", "main", "deferredFrag");
377        sCgDeferredShadowProgram = sm->CreateFragmentProgram("deferred", "main_shadow", "deferredFragShader");
378        sCgSsaoProgram = sm->CreateFragmentProgram("ssao", "main", "ssaoFrag");
379        sCgGiProgram = sm->CreateFragmentProgram("globillum", "main", "giFrag");
380        sCgCombineIllumProgram = sm->CreateFragmentProgram("globillum", "combine", "combineGi");
381        sCgCombineSsaoProgram = sm->CreateFragmentProgram("combineSsao", "combine", "combineSsao");
382        sCgAntiAliasingProgram = sm->CreateFragmentProgram("antialiasing", "main", "antiAliasing");
383        sCgToneProgram = sm->CreateFragmentProgram("tonemap", "ToneMap", "toneMap");
384        sCgDownSampleProgram = sm->CreateFragmentProgram("deferred", "Output", "Output");
385        sCgScaleDepthProgram = sm->CreateFragmentProgram("deferred", "ScaleDepth", "ScaleDepth");
386        sCgLogLumProgram = sm->CreateFragmentProgram("tonemap", "CalcAvgLogLum", "avgLogLum");
387        sCgPrepareSsaoProgram = sm->CreateFragmentProgram("deferred", "PrepareSsao", "PrepareSsao");
388
389
390        ///////////////////
391        //-- initialize program parameters
392
393        string ssaoParams[] =
394                {"colors", "normals", "oldTex", "noiseTex", "temporalCoherence",
395                 "samples", "bl", "br", "tl", "tr",
396                 "modelViewProj", "oldModelViewProj", "oldEyePos", "oldbl", "oldbr",
397                 "oldtl", "oldtr", "attribsTex"};
398        sCgSsaoProgram->AddParameters(ssaoParams, 0, 18);
399       
400        string giParams[] =
401                {"colors", "normals", "noiseTex", "oldSsaoTex", "oldIllumTex",
402                 "temporalCoherence", "samples", "bl", "br", "tl",
403                 "tr", "oldModelViewProj", "modelViewProj"};
404        sCgGiProgram->AddParameters(giParams, 0, 13);
405
406        string toneParams[] = {"colors", "imageKey", "whiteLum", "middleGrey"};
407        sCgToneProgram->AddParameters(toneParams, 0, 4);
408
409
410        ////////////////
411
412        string deferredShadowParams[] =
413                {"colors", "normals", "shadowMap", "noiseTex", "shadowMatrix",
414                 "sampleWidth", "lightDir", "eyePos", "samples", "weights"};
415       
416        sCgDeferredShadowProgram->AddParameters(deferredShadowParams, 0, 10);
417       
418        ////////////////
419
420        string combineIllumParams[] = {"colorsTex", "ssaoTex", "illumTex"};
421        sCgCombineIllumProgram->AddParameters(combineIllumParams, 0, 3);
422
423        ////////////////
424
425        string combineSsaoParams[] =
426                {"colorsTex", "normalsTex", "ssaoTex", "filterOffs",
427                 "filterWeights", "modelViewProj", "bl", "br", "tl", "tr", "w", "h"};
428        sCgCombineSsaoProgram->AddParameters(combineSsaoParams, 0, 12);
429
430        //////////////
431
432        string deferredParams[] = {"colors", "normals", "lightDir"};
433        sCgDeferredProgram->AddParameters(deferredParams, 0, 3);
434
435        ///////////////////
436
437        string aaParams[] = {"colors", "normals", "offsets"};
438        sCgAntiAliasingProgram->AddParameters(aaParams, 0, 3);
439
440        /////////////////////
441
442        string downSampleParams[] = {"colors"};
443        sCgDownSampleProgram->AddParameters(downSampleParams, 0, 1);
444
445        /////////////////////
446
447        string scaleDepthParams[] = {"colors"};
448        sCgScaleDepthProgram->AddParameters(scaleDepthParams, 0, 1);
449
450        ////////////
451
452        sCgLogLumProgram->AddParameter("colors", 0);
453
454        ////////////////
455
456       
457        string prepareSsaoParams[] =
458                {"colorsTex", "normalsTex", "diffVals", "oldTex",
459                 "oldEyePos", "modelViewProj", "oldModelViewProj",
460                 "oldbl", "oldbr", "oldtl", "oldtr"};
461
462        sCgPrepareSsaoProgram->AddParameters(prepareSsaoParams, 0, 11);
463
464
465        ////////////////
466
467        const float filterWidth = 1.0f;
468
469        PoissonDiscSampleGenerator2 poisson(NUM_SSAO_FILTER_SAMPLES, 1.0f);
470        poisson.Generate((float *)ssaoFilterOffsets);
471
472        const float xoffs = (float)filterWidth / mWidth;
473        const float yoffs = (float)filterWidth / mHeight;
474
475        for (int i = 0; i < NUM_SSAO_FILTER_SAMPLES; ++ i)
476        {
477                float x = ssaoFilterOffsets[2 * i + 0];
478                float y = ssaoFilterOffsets[2 * i + 1];
479
480                ssaoFilterWeights[i] = GaussianDistribution(x, y, 1.0f);
481                //ssaoFilterWeights[i] = 1.0f;
482
483                ssaoFilterOffsets[2 * i + 0] *= xoffs;
484                ssaoFilterOffsets[2 * i + 1] *= yoffs;
485        }
486
487
488        /////////
489        //-- pcf tabs for shadowing
490
491        float filterWeights[NUM_PCF_TABS];
492        PoissonDiscSampleGenerator2 poisson2(NUM_PCF_TABS, 1.0f);
493        poisson2.Generate((float *)pcfSamples);
494
495        for (int i = 0; i < NUM_PCF_TABS; ++ i)
496        {
497                filterWeights[i] = GaussianDistribution(pcfSamples[i].x, pcfSamples[i].y, 1.0f);
498        }
499
500        sCgDeferredShadowProgram->SetArray2f(8, (float *)pcfSamples, NUM_PCF_TABS);
501        sCgDeferredShadowProgram->SetArray1f(9, (float *)filterWeights, NUM_PCF_TABS);
502
503        PrintGLerror("init");
504}
505
506
507void DeferredRenderer::Render(FrameBufferObject *fbo,
508                                                          float tempCohFactor,
509                                                          DirectionalLight *light,
510                                                          bool useToneMapping,
511                                                          bool useAntiAliasing,
512                                                          ShadowMap *shadowMap
513                                                          )
514{
515        InitFrame();
516
517        if (shadowMap)
518                FirstPassShadow(fbo, light, shadowMap);
519        else
520                FirstPass(fbo, light);
521
522        if (mShadingMethod != 0)
523        {
524                // downsample fbo buffers
525                PrepareSsao(fbo);
526        }
527
528        // multisampling is difficult / costly with deferred shading
529        // at least do some edge blurring
530        //if (useAntiAliasing) AntiAliasing(fbo, light);
531
532        switch (mShadingMethod)
533        {
534        case SSAO:
535                ComputeSsao(fbo, tempCohFactor);
536                CombineSsao(fbo);
537                break;
538        case GI:
539                ComputeGlobIllum(fbo, tempCohFactor);
540                CombineIllum(fbo);
541                break;
542        default: // DEFAULT
543                // do nothing: standard deferred shading
544                break;
545        }
546
547        if (useToneMapping)
548        {
549                float imageKey, whiteLum, middleGrey;
550
551                ComputeToneParameters(fbo, light, imageKey, whiteLum, middleGrey);
552                ToneMap(fbo, imageKey, whiteLum, middleGrey);
553        }
554
555        // multisampling is difficult / costly with deferred shading
556        // at least do some edge blurring
557        if (useAntiAliasing) AntiAliasing(fbo, light); else
558        Output(fbo); // just output the latest buffer
559
560        glEnable(GL_LIGHTING);
561        glDisable(GL_TEXTURE_2D);
562
563        glMatrixMode(GL_PROJECTION);
564        glPopMatrix();
565
566        glMatrixMode(GL_MODELVIEW);
567        glPopMatrix();
568
569        // viewport
570        glPopAttrib();
571
572        FrameBufferObject::Release();
573        ShaderManager::GetSingleton()->DisableFragmentProfile();
574}
575
576
577
578static inline float SqrMag(const Sample2 &s)
579{
580        return (s.x * s.x + s.y * s.y);
581}
582
583
584static inline float SqrDist(const Sample2 &a, const Sample2 &b)
585{
586        float x = a.x - b.x;
587        float y = a.y - b.y;
588       
589        return x * x + y * y;
590}
591
592
593static inline bool lt(const Sample2 &a, const Sample2 &b)
594{
595        return SqrMag(a) < SqrMag(b);
596}
597
598
599void DeferredRenderer::SortSamples()
600{
601        static Sample2 tempSamples[NUM_SAMPLES];
602        static bool checked[NUM_SAMPLES];
603
604        for (int i = 0; i < NUM_SAMPLES; ++ i)
605                checked[i] = false;
606
607        Sample2 currentSample;
608        currentSample.x = 0; currentSample.y = 0;
609        int ns = 0; // the next sample index
610
611        for (int i = 0; i < NUM_SAMPLES; ++ i)
612        {
613                float minLen = 1e20f;
614
615                for (int j = 0; j < NUM_SAMPLES; ++ j)
616                {
617                        if (checked[j]) continue;
618
619                        Sample2 s = samples2[j];
620                        const float len = SqrDist(s, currentSample);
621
622                        if (len < minLen)
623                        {
624                                minLen = len;
625                                ns = j;
626                        }
627                }
628
629                tempSamples[i] = samples2[ns];
630                currentSample = samples2[ns];
631                checked[ns] = true;
632        }
633
634        for (int i = 0; i < NUM_SAMPLES; ++ i)
635                samples2[i] = tempSamples[i];
636}
637
638
639void DeferredRenderer::ComputeSsao(FrameBufferObject *fbo, float tempCohFactor)
640{
641        GLuint colorsTex, normalsTex, attribsTex;
642
643        if (0)
644        {
645                colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
646                normalsTex = fbo->GetColorBuffer(1)->GetTexture();
647        }
648        else
649        {
650                normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
651                colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
652        }
653
654        attribsTex = fbo->GetColorBuffer(2)->GetTexture();
655
656        // flip flop between illumination buffers
657        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
658
659        glPushAttrib(GL_VIEWPORT_BIT);
660        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
661
662        // read the second buffer, write to the first buffer
663        mIllumFbo->Bind();
664        glDrawBuffers(1, mrt + mIllumFboIndex);
665
666        int i = 0;
667
668        sCgSsaoProgram->SetTexture(i ++, colorsTex);
669        sCgSsaoProgram->SetTexture(i ++, normalsTex);
670        sCgSsaoProgram->SetTexture(i ++, oldTex);
671        sCgSsaoProgram->SetTexture(i ++, noiseTex2D);
672
673        sCgSsaoProgram->SetValue1f(i ++, (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
674       
675        if (mUseTemporalCoherence || mRegenerateSamples)
676        {
677                mRegenerateSamples = false;
678
679                // q: should we generate new samples or only rotate the old ones?
680                // in the first case, the sample patterns look nicer, but the kernel
681                // needs longer to converge
682                GenerateSamples(mSamplingMethod);
683
684                //if (mSortSamples) { SortSamples(); }
685                sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
686        }
687       
688        ++ i;
689
690        for (int j = 0; j < 4; ++ j, ++ i)
691                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
692
693        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
694        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
695
696        Vector3 de;
697        de.x = mOldEyePos.x - mEyePos.x;
698        de.y = mOldEyePos.y - mEyePos.y;
699        de.z = mOldEyePos.z - mEyePos.z;
700
701        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
702
703        for (int j = 0; j < 4; ++ j, ++ i)
704                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
705
706        sCgSsaoProgram->SetTexture(i ++, attribsTex);
707
708
709        DrawQuad(sCgSsaoProgram);
710
711        glPopAttrib();
712
713        PrintGLerror("ssao first pass");
714}
715
716
717static void SetVertex(float x, float y, float x_offs, float y_offs)
718{
719        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
720        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
721        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
722        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
723        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
724
725        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
726        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
727
728        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
729        glVertex2f(x, y);
730}
731
732
733void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo, DirectionalLight *light)
734{
735        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
736        GLuint colorsTex = colorBuffer->GetTexture();
737        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
738
739        // read the second buffer, write to the first buffer
740        //FlipFbos(fbo);
741        // end of the pipeline => just draw image to screen
742        FrameBufferObject::Release();
743
744        // the neighbouring texels
745        float xOffs = 1.0f / fbo->GetWidth();
746        float yOffs = 1.0f / fbo->GetHeight();
747
748        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
749        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
750
751        float offsets[16];
752        int i = 0;
753
754        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
755        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
756        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
757        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
758        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
759        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
760        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
761        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
762
763        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
764
765        DrawQuad(sCgAntiAliasingProgram);
766
767        PrintGLerror("antialiasing");
768}
769
770
771void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
772{
773        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
774        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
775
776        FlipFbos(fbo);
777
778        const Vector3 lightDir = -light->GetDirection();
779
780        sCgDeferredProgram->SetTexture(0, colorsTex);
781        sCgDeferredProgram->SetTexture(1, normalsTex);
782        sCgDeferredProgram->SetValue3f(2, lightDir.x, lightDir.y, lightDir.z);
783       
784        DrawQuad(sCgDeferredProgram);
785
786        PrintGLerror("deferred shading");
787}
788
789
790void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
791                                                                                float tempCohFactor)
792{
793#if 0
794        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
795        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
796#else
797        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
798        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
799#endif
800
801        glPushAttrib(GL_VIEWPORT_BIT);
802        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
803
804        // read the second buffer, write to the first buffer
805        mIllumFbo->Bind();
806
807        glDrawBuffers(2, mrt + mIllumFboIndex);
808
809        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
810        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
811
812        int i = 0;
813
814        sCgGiProgram->SetTexture(i ++, colorsTex);
815        sCgGiProgram->SetTexture(i ++, normalsTex);
816        sCgGiProgram->SetTexture(i ++, noiseTex2D);
817        sCgGiProgram->SetTexture(i ++, oldSsaoTex);
818        sCgGiProgram->SetTexture(i ++, oldIllumTex);
819
820        sCgGiProgram->SetValue1f(i ++,
821                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
822
823        if (mUseTemporalCoherence || mRegenerateSamples)
824        {
825                mRegenerateSamples = false;
826
827                // q: should we generate new samples or only rotate the old ones?
828                // in the first case, the sample patterns look nicer, but the kernel
829                // needs longer to converge
830                GenerateSamples(mSamplingMethod);
831
832                sCgGiProgram->SetArray2f(i ++, (float *)samples2, NUM_SAMPLES);
833        }
834
835        Vector3 bl = mCornersView[0];
836        Vector3 br = mCornersView[1];
837        Vector3 tl = mCornersView[2];
838        Vector3 tr = mCornersView[3];
839
840        sCgGiProgram->SetValue3f(i ++, bl.x, bl.y, bl.z);
841        sCgGiProgram->SetValue3f(i ++, br.x, br.y, br.z);
842        sCgGiProgram->SetValue3f(i ++, tl.x, tl.y, tl.z);
843        sCgGiProgram->SetValue3f(i ++, tr.x, tr.y, tr.z);
844
845        sCgGiProgram->SetMatrix(i ++, mOldProjViewMatrix);
846        sCgGiProgram->SetMatrix(i ++, mProjViewMatrix);
847
848
849        DrawQuad(sCgGiProgram);
850
851        glPopAttrib();
852
853        PrintGLerror("globillum first pass");
854}
855
856
857void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
858{
859        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
860
861        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
862        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
863
864        FlipFbos(fbo);
865
866        sCgCombineIllumProgram->SetTexture(0, colorsTex);
867        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
868        sCgCombineIllumProgram->SetTexture(2, illumTex);
869       
870        DrawQuad(sCgCombineIllumProgram);
871
872        PrintGLerror("combine");
873}
874
875
876void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
877{
878        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
879        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
880        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
881       
882        FlipFbos(fbo);
883
884        int i = 0;
885
886        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
887        sCgCombineSsaoProgram->SetTexture(i ++, normalsTex);
888        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
889
890        sCgCombineSsaoProgram->SetArray2f(i ++, (float *)ssaoFilterOffsets, NUM_SSAO_FILTER_SAMPLES);
891        sCgCombineSsaoProgram->SetArray1f(i ++, (float *)ssaoFilterWeights, NUM_SSAO_FILTER_SAMPLES);
892       
893        sCgCombineSsaoProgram->SetMatrix(i++, mProjViewMatrix);
894
895        for (int j = 0; j < 4; ++ j, ++ i)
896                sCgCombineSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
897
898        sCgCombineSsaoProgram->SetValue1f(i ++, mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetWidth());
899        sCgCombineSsaoProgram->SetValue1f(i ++, mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetHeight());
900
901        DrawQuad(sCgCombineSsaoProgram);
902       
903        PrintGLerror("combine ssao");
904}
905
906
907void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
908                                                                           DirectionalLight *light,
909                                                                           ShadowMap *shadowMap)
910{
911        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
912        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
913
914        GLuint shadowTex = shadowMap->GetDepthTexture();
915
916        Matrix4x4 shadowMatrix;
917        shadowMap->GetTextureMatrix(shadowMatrix);
918
919
920        FlipFbos(fbo);
921
922        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
923        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
924        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
925        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
926        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
927        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
928
929        const Vector3 lightDir = -light->GetDirection();
930        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
931        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
932
933        DrawQuad(sCgDeferredShadowProgram);
934
935        PrintGLerror("deferred shading + shadows");
936}
937
938
939void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
940{
941        if (s != mSamplingMethod)
942        {
943                mSamplingMethod = s;
944                mRegenerateSamples = true;
945        }
946}
947
948
949void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
950{
951        if (s != mShadingMethod)
952        {
953                mShadingMethod = s;
954                mRegenerateSamples = true;
955        }
956}
957
958
959void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
960                                                                                         DirectionalLight *light,
961                                                                                         float &imageKey,
962                                                                                         float &whiteLum,
963                                                                                         float &middleGrey)
964{
965        // hack: estimate value where sky burns out
966        whiteLum = log(WHITE_LUMINANCE);
967       
968        ////////////////////
969        //-- linear interpolate brightness key depending on the current sun position
970
971        const float minKey = 0.09f;
972        const float maxKey = 0.36f;
973
974        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
975        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
976
977
978        //////////
979        //-- compute avg loglum
980
981        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
982        GLuint colorsTex = colorBuffer->GetTexture();
983
984        FlipFbos(fbo);
985       
986        sCgLogLumProgram->SetTexture(0, colorsTex);
987        DrawQuad(sCgLogLumProgram);
988       
989        PrintGLerror("ToneMapParams");
990
991
992        ///////////////////
993        //-- compute avg loglum in scene using mipmapping
994
995        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
996        glGenerateMipmapEXT(GL_TEXTURE_2D);
997}
998
999
1000static void ExportData(float *data, int w, int h)
1001{
1002        startil();
1003
1004        cout << "w: " << w << " h: " << h << endl;
1005        ILstring filename = ILstring("downsample2.jpg");
1006        ilRegisterType(IL_FLOAT);
1007
1008        const int depth = 1;
1009        const int bpp = 4;
1010
1011        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
1012        {
1013                cerr << "IL error " << ilGetError() << endl;
1014                stopil();
1015                return;
1016        }
1017
1018        if (!ilSaveImage(filename))
1019        {
1020                cerr << "TGA write error " << ilGetError() << endl;
1021        }
1022
1023        stopil();
1024}
1025
1026
1027void DeferredRenderer::PrepareSsao(FrameBufferObject *fbo)
1028{
1029        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1030        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1031        GLuint diffVals = fbo->GetColorBuffer(2)->GetTexture();
1032        // flip flop between illumination buffers
1033        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1034
1035        int i = 0;
1036
1037        sCgPrepareSsaoProgram->SetTexture(i ++, colorsTex);
1038        sCgPrepareSsaoProgram->SetTexture(i ++, normalsTex);
1039        sCgPrepareSsaoProgram->SetTexture(i ++, diffVals);
1040        sCgPrepareSsaoProgram->SetTexture(i ++, oldTex);
1041
1042        Vector3 de;
1043        de.x = mOldEyePos.x - mEyePos.x;
1044        de.y = mOldEyePos.y - mEyePos.y;
1045        de.z = mOldEyePos.z - mEyePos.z;
1046
1047        sCgPrepareSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
1048
1049        sCgPrepareSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
1050        sCgPrepareSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
1051
1052        for (int j = 0; j < 4; ++ j, ++ i)
1053                sCgPrepareSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
1054
1055        glPushAttrib(GL_VIEWPORT_BIT);
1056        glViewport(0, 0, mDownSampleFbo->GetWidth(), mDownSampleFbo->GetHeight());
1057       
1058        mDownSampleFbo->Bind();
1059
1060// prepare downsampled color and normal texture for ssao
1061        glDrawBuffers(2, mrt);
1062
1063        DrawQuad(sCgPrepareSsaoProgram);
1064       
1065        glPopAttrib();
1066        PrintGLerror("prepareSsao");
1067}
1068
1069
1070
1071void DeferredRenderer::DownSample(FrameBufferObject *fbo,
1072                                                                  int bufferIdx,
1073                                                                  FrameBufferObject *downSampleFbo,
1074                                                                  int downSampleBufferIdx,
1075                                                                  ShaderProgram *program)
1076{
1077        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
1078        GLuint tex = buffer->GetTexture();
1079
1080        glPushAttrib(GL_VIEWPORT_BIT);
1081        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
1082       
1083        downSampleFbo->Bind();
1084
1085        program->SetTexture(0, tex);
1086        glDrawBuffers(1, mrt + downSampleBufferIdx);
1087
1088        DrawQuad(program);
1089       
1090        glPopAttrib();
1091        PrintGLerror("downsample");
1092}
1093
1094
1095void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
1096                                                           float imageKey,
1097                                                           float whiteLum,
1098                                                           float middleGrey)
1099{
1100        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1101        GLuint colorsTex = colorBuffer->GetTexture();
1102        //FrameBufferObject::Release();
1103
1104        FlipFbos(fbo);
1105
1106        sCgToneProgram->SetTexture(0, colorsTex);
1107        sCgToneProgram->SetValue1f(1, imageKey);
1108        sCgToneProgram->SetValue1f(2, whiteLum);
1109        sCgToneProgram->SetValue1f(3, middleGrey);
1110
1111        DrawQuad(sCgToneProgram);
1112
1113        PrintGLerror("ToneMap");
1114}
1115
1116
1117void DeferredRenderer::Output(FrameBufferObject *fbo)
1118{
1119        glPushAttrib(GL_VIEWPORT_BIT);
1120        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
1121       
1122        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1123        GLuint colorsTex = colorBuffer->GetTexture();
1124
1125        sCgDownSampleProgram->SetTexture(0, colorsTex);
1126
1127        FrameBufferObject::Release();
1128        DrawQuad(sCgDownSampleProgram);
1129
1130        PrintGLerror("output");
1131}
1132
1133
1134void DeferredRenderer::InitFrame()
1135{
1136        for (int i = 0; i < 4; ++ i)
1137                mOldCornersView[i] = mCornersView[i];
1138
1139        mOldProjViewMatrix = mProjViewMatrix;
1140        mOldEyePos = mEyePos;
1141        mEyePos = mCamera->GetPosition();
1142
1143        // hack: temporarily change far to improve precision
1144        const float oldFar = mCamera->GetFar();
1145        const float oldNear = mCamera->GetNear();
1146       
1147
1148        Matrix4x4 matViewing, matProjection;
1149
1150
1151        ///////////////////
1152
1153
1154        mCamera->GetViewOrientationMatrix(matViewing);
1155        mCamera->GetProjectionMatrix(matProjection);
1156
1157        mProjViewMatrix = matViewing * matProjection;
1158        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1159       
1160
1161        // switch roles of old and new fbo
1162        // the algorihm uses two input fbos, where the one
1163        // contais the color buffer from the last frame,
1164        // the other one will be written
1165
1166        mIllumFboIndex = 2 - mIllumFboIndex;
1167       
1168        // enable fragment shading
1169        ShaderManager::GetSingleton()->EnableFragmentProfile();
1170
1171        glDisable(GL_ALPHA_TEST);
1172        glDisable(GL_TEXTURE_2D);
1173        glDisable(GL_LIGHTING);
1174        glDisable(GL_BLEND);
1175        glDisable(GL_DEPTH_TEST);
1176
1177        glPolygonMode(GL_FRONT, GL_FILL);
1178
1179        glMatrixMode(GL_PROJECTION);
1180        glPushMatrix();
1181        glLoadIdentity();
1182
1183        gluOrtho2D(0, 1, 0, 1);
1184
1185
1186        glMatrixMode(GL_MODELVIEW);
1187        glPushMatrix();
1188        glLoadIdentity();
1189
1190       
1191        glPushAttrib(GL_VIEWPORT_BIT);
1192        glViewport(0, 0, mWidth, mHeight);
1193
1194        // revert to old far and near plane
1195        mCamera->SetFar(oldFar);
1196        mCamera->SetNear(oldNear);
1197}
1198
1199} // namespace
Note: See TracBrowser for help on using the repository browser.