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

Revision 3151, 30.4 KB checked in by mattausch, 16 years ago (diff)

worked on ssao for interpolated normals

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