source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/ShadowMapping.cpp @ 2919

Revision 2919, 11.3 KB checked in by mattausch, 16 years ago (diff)
Line 
1#include "ShadowMapping.h"
2#include "FrameBufferObject.h"
3#include "RenderState.h"
4#include "RenderTraverser.h"
5#include "Light.h"
6#include "Polygon3.h"
7#include "Polyhedron.h"
8
9#include <IL/il.h>
10#include <assert.h>
11
12
13using namespace std;
14
15
16namespace CHCDemoEngine
17{
18
19
20static Polyhedron *polyhedron = NULL;
21
22
23static void PrintGLerror(char *msg)
24{
25        GLenum errCode;
26        const GLubyte *errStr;
27       
28        if ((errCode = glGetError()) != GL_NO_ERROR)
29        {
30                errStr = gluErrorString(errCode);
31                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
32        }
33}
34
35
36
37static CGprogram sCgShadowProgram;
38static CGparameter sShadowParam;
39
40
41static void GrabDepthBuffer(float *data, GLuint depthTexture)
42{
43        glEnable(GL_TEXTURE_2D);
44        glBindTexture(GL_TEXTURE_2D, depthTexture);
45
46        glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);
47
48        glBindTexture(GL_TEXTURE_2D, 0);
49        glDisable(GL_TEXTURE_2D);
50}
51
52
53static void ExportDepthBuffer(float *data, int size)
54{
55        ilInit();
56        assert(ilGetError() == IL_NO_ERROR);
57
58        ILstring filename = ILstring("shadow.tga");
59        ilRegisterType(IL_FLOAT);
60
61        const int depth = 1;
62        const int bpp = 1;
63
64        if (!ilTexImage(size, size, depth, bpp, IL_LUMINANCE, IL_FLOAT, data))
65        {
66                cerr << "IL error " << ilGetError() << endl;
67       
68                ilShutDown();
69                assert(ilGetError() == IL_NO_ERROR);
70
71                return;
72        }
73
74        if (!ilSaveImage(filename))
75        {
76                cerr << "TGA write error " << ilGetError() << endl;
77        }
78
79        ilShutDown();
80        assert(ilGetError() == IL_NO_ERROR);
81
82        cout << "exported depth buffer" << endl;
83}
84
85
86
87ShadowMap::ShadowMap(Light *light, int size, const AxisAlignedBox3 &sceneBox, Camera *cam):
88mSceneBox(sceneBox), mSize(size), mCamera(cam), mLight(light)
89{
90        mFbo = new FrameBufferObject(size, size, FrameBufferObject::DEPTH_32, true);
91        // the diffuse color buffer
92        mFbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, false);
93
94        mShadowCam = new Camera(mSceneBox.Size().x * 0.5f, mSceneBox.Size().y * 0.5f);
95        mShadowCam->SetOrtho(true);
96}
97
98
99ShadowMap::~ShadowMap()
100{
101        DEL_PTR(mFbo);
102        DEL_PTR(mShadowCam);
103}
104
105
106void ShadowMap::DrawPolys()
107{
108        if (!polyhedron) return;
109
110        for (size_t i = 0; i < polyhedron->NumPolygons(); ++ i)
111        {
112                float r = (float)i / polyhedron->NumPolygons();
113                float g = 1;
114                float b = 1;
115
116                glColor3f(r, g, b);
117
118                glBegin(GL_LINE_LOOP);
119
120                Polygon3 *poly = polyhedron->GetPolygons()[i];
121
122                for (size_t j = 0; j < poly->mVertices.size(); ++ j)
123                {
124                        Vector3 v = poly->mVertices[j];
125                        glVertex3d(v.x, v.y, v.z);
126                }
127
128                glEnd();
129        }
130}
131
132
133void ShadowMap::IncludeLightVolume(const Polyhedron &polyhedron,
134                                                                   VertexArray &frustumPoints,
135                                                                   const Vector3 lightDir,
136                                                                   const AxisAlignedBox3 &sceneBox
137                                                                   )
138{
139        // we don't need closed form anymore => just store vertices
140        VertexArray vertices;
141        polyhedron.CollectVertices(vertices);
142
143        // we 'look' at each point and calculate intersections of rays with scene bounding box
144        VertexArray::const_iterator it, it_end = vertices.end();
145
146        for (it = vertices.begin(); it != it_end; ++ it)
147        {
148                Vector3 v  = *it;
149
150                frustumPoints.push_back(v);
151               
152                // hack: get point surely outside of box
153                v -= Magnitude(mSceneBox.Diagonal()) * lightDir;
154
155                SimpleRay ray(v, lightDir);
156
157                float tNear, tFar;
158
159                if (sceneBox.Intersects(ray, tNear, tFar))
160                {
161                        Vector3 newpt = ray.Extrap(tNear);
162                        frustumPoints.push_back(newpt);                 
163                }
164        }
165}
166
167
168float ShadowMap::ComputeN() const
169{
170        const float n = mShadowCam->GetNear();
171        const float f = mShadowCam->GetFar();
172
173        const float d = fabs(f - n);
174       
175        const float dotProd = DotProd(mCamera->GetDirection(), mShadowCam->GetDirection());
176        const float sinGamma = sin(fabs(acos(dotProd)));
177
178        return (n + sqrt(n * (n + d * sinGamma))) /  sinGamma;
179}
180
181
182Matrix4x4 ShadowMap::CalcLispSMTransform(const Matrix4x4 &lightProjView, const AxisAlignedBox3 &extremalPoints)
183{
184        Matrix4x4 lispMtx;
185
186        ///////////////
187        //-- We apply the lispsm algorithm in order to calculate an optimal light projection matrix
188
189        const float n = 1e20f;//ComputeN();
190
191        cout << "n: " << n << endl;
192
193        const Vector3 nearPt = mShadowCam->GetNear() * mShadowCam->GetDirection() + mShadowCam->GetPosition();
194
195        //get the coordinates of the near camera point in light space
196        const Vector3 lsNear = lightProjView * nearPt;
197
198        //c start has the x and y coordinate of e, the z coord of B.min()
199        const Vector3 startPt = Vector3(lsNear.x, lsNear.y, extremalPoints.Min().y);
200
201        // the new projection center
202        const Vector3 unit_y = Vector3(0, 1, 0);
203        Vector3 projCenter = startPt - unit_y * n;
204
205        //construct a translation that moves to the projection center
206        const Matrix4x4 projectionCenter = TranslationMatrix(-projCenter);
207
208        // light space y size
209        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
210
211        lispMtx = GetFrustum(-1.0, 1.0, -1.0, 1.0, n, n + d);
212
213        cout << "lispsm\n" << lispMtx << endl;
214
215        lispMtx *= projectionCenter;
216
217        // transform into OpenGL right handed system
218        Matrix4x4 scale = ScaleMatrix(1.0f, 1.0f, -1.0f);
219
220        lispMtx *= scale;
221       
222        return IdentityMatrix();
223}
224
225
226Vector3 ShadowMap::GetProjViewDir(const Matrix4x4 &lightSpace) const
227{
228        //get the point in the LVS volume that is nearest to the camera
229        const V3 e = getNearCameraPointE(fs);
230        //construct edge to transform into light-space
231        const V3 b = e+fs.getEyeDir();
232        //transform to light-space
233        const V3 e_lp = lightSpace.mulHomogenPoint(e);
234        const V3 b_lp = lightSpace.mulHomogenPoint(b);
235        V3 projDir(b_lp-e_lp);
236        //project the view direction into the shadow map plane
237        projDir.y() = 0.0;
238        return projDir;
239}
240
241
242bool ShadowMap::CalcLightProjection(Matrix4x4 &lightProj)
243{
244        DEL_PTR(polyhedron);
245
246
247        ///////////////////
248        //-- First step: calc frustum clipped by scene box
249
250        polyhedron = CalcClippedFrustum(mSceneBox);
251
252        if (!polyhedron) return false; // something is wrong
253
254        // include the part of the light volume that "sees" the frustum
255        // we only require frustum vertices
256
257        VertexArray frustumPoints;
258        IncludeLightVolume(*polyhedron, frustumPoints, mShadowCam->GetDirection(), mSceneBox);
259
260
261        ///////////////
262        //-- transform points from world view to light view and calculate extremal points
263
264        AxisAlignedBox3 extremalPoints;
265        extremalPoints.Initialize();
266
267        Matrix4x4 lightView;
268        mShadowCam->GetModelViewMatrix(lightView);
269
270        VertexArray::const_iterator it, it_end = frustumPoints.end();
271               
272        for (it = frustumPoints.begin(); it != it_end; ++ it)
273        {
274                Vector3 pt = *it;
275                pt = lightView * pt;
276
277                extremalPoints.Include(pt);
278        }
279
280        lightProj = IdentityMatrix(); // we use directional lights
281
282        Matrix4x4 shadowView;
283        mShadowCam->GetModelViewMatrix(shadowView);
284
285        Vector3 projViewDir =
286        //do Light Space Perspective shadow mapping
287        //rotate the lightspace so that the proj light view always points upwards
288        //calculate a frame matrix that uses the projViewDir[light-space] as up vector
289        //look(from position, into the direction of the projected direction, with unchanged up-vector)
290        Matrix4x4 frame = LookAt(Vector3(0), projViewDir, Vector3(0, 0, 1));
291        lightProj *= frame;
292
293        const Matrix4x4 matLispSM =
294                CalcLispSMTransform(shadowView * lightProj, extremalPoints);
295
296        lightProj *= matLispSM;
297
298        // focus projection matrix on the extremal points => scale to unit cube
299        lightProj *= GetFittingProjectionMatrix(extremalPoints);
300
301        // we have to flip the signs in order tp opengl style projection matrix
302        Matrix4x4 scale = ScaleMatrix(-1, -1, -1);
303        lightProj *= scale;
304       
305        return true;
306}
307
308
309Polyhedron *ShadowMap::CalcClippedFrustum(const AxisAlignedBox3 &box) const
310{
311        Vector3 ftl, ftr, fbl, fbr;
312        Vector3 ntl, ntr, nbl, nbr;
313
314        VertexArray sides[6];
315
316        mCamera->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
317
318        for (int i = 0; i < 6; ++ i)
319                sides[i].resize(4);
320       
321        // left, right
322        sides[0][0] = ftl; sides[0][1] = fbl; sides[0][2] = nbl; sides[0][3] = ntl;
323        sides[1][0] = fbr; sides[1][1] = ftr; sides[1][2] = ntr; sides[1][3] = nbr;
324        // bottom, top
325        sides[2][0] = fbl; sides[2][1] = fbr; sides[2][2] = nbr; sides[2][3] = nbl;
326        sides[3][0] = ftr; sides[3][1] = ftl; sides[3][2] = ntl; sides[3][3] = ntr;
327        // near, far
328        sides[4][0] = ntr; sides[4][1] = ntl; sides[4][2] = nbl; sides[4][3] = nbr;
329        sides[5][0] = ftl; sides[5][1] = ftr; sides[5][2] = fbr; sides[5][3] = fbl;
330
331        //////////
332        //-- compute polyhedron
333
334        PolygonContainer polygons;
335
336        for (int i = 0; i < 6; ++ i)
337        {
338                Polygon3 *poly = new Polygon3(sides[i]);
339                polygons.push_back(poly);
340        }
341
342        Polyhedron *p = new Polyhedron(polygons);
343        Polyhedron *clippedPolyhedron = box.CalcIntersection(*p);
344       
345        DEL_PTR(p);
346       
347
348        return clippedPolyhedron;
349}
350
351
352void ShadowMap::ComputeShadowMap(RenderTraverser *renderer, const Matrix4x4 &projView)
353{
354        const float xlen = Magnitude(mSceneBox.Diagonal() * 0.5f);
355        const float ylen = Magnitude(mSceneBox.Diagonal() * 0.5f);
356       
357        const Vector3 dir = mLight->GetDirection();
358        //const Vector3 dir(0, 0, 1);
359
360        mShadowCam->SetDirection(dir);
361       
362        //cout << "lightdir: " << mShadowCam->GetDirection() << endl;
363
364        // set position so that we can see the whole scene
365        Vector3 pos = mSceneBox.Center();
366
367        //Matrix4x4 camView;
368        //mCamera->GetModelViewMatrix(camView);
369
370        pos -= dir * Magnitude(mSceneBox.Diagonal() * 0.5f);
371        mShadowCam->SetPosition(pos);
372
373        mFbo->Bind();
374       
375        glDrawBuffers(1, mrt);
376
377        glPushAttrib(GL_VIEWPORT_BIT);
378        glViewport(0, 0, mSize, mSize);
379
380        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
381
382        glDisable(GL_LIGHTING);
383        glDisable(GL_TEXTURE_2D);
384        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
385
386        glPolygonOffset(1.0f, 2000.0f);
387        glEnable(GL_POLYGON_OFFSET_FILL);
388
389        glShadeModel(GL_FLAT);
390        glEnable(GL_DEPTH_TEST);
391
392        // setup projection
393        /*glMatrixMode(GL_PROJECTION);
394        glLoadIdentity();
395        glOrtho(+xlen, -xlen, +ylen, -ylen, 0.0f, Magnitude(mSceneBox.Diagonal()));
396
397        Matrix4x4 dummyMat;
398        glGetFloatv(GL_PROJECTION_MATRIX, (float *)dummyMat.x);
399        cout << "old:\n" << dummyMat << endl;
400        */
401
402        Matrix4x4 lightView, lightProj;
403
404        mShadowCam->GetModelViewMatrix(lightView);
405        CalcLightProjection(lightProj);
406
407        glMatrixMode(GL_PROJECTION);
408        glPushMatrix();
409        glLoadMatrixf((float *)lightProj.x);
410
411        mLightProjView = lightView * lightProj;
412
413        //cout << "new:\n" << lightProj << endl;
414
415        glMatrixMode(GL_MODELVIEW);
416        glPushMatrix();
417        glLoadIdentity();
418
419        mShadowCam->SetupCameraView();
420
421
422        //////////////
423        //-- compute texture matrix
424        static Matrix4x4 biasMatrix(0.5f, 0.0f, 0.0f, 0.5f,
425                                                                0.0f, 0.5f, 0.0f, 0.5f,
426                                                                0.0f, 0.0f, 0.5f, 0.5f,
427                                                                0.0f, 0.0f, 0.0f, 1.0f);
428
429        mTextureMatrix = mLightProjView * biasMatrix;
430
431
432
433
434        /////////////
435        //-- render scene into shadow map
436
437        renderer->RenderScene();
438
439       
440        glDisable(GL_POLYGON_OFFSET_FILL);
441        glMatrixMode(GL_MODELVIEW);
442        glPopMatrix();
443
444        glMatrixMode(GL_PROJECTION);
445        glPopMatrix();
446
447        glPopAttrib();
448#if 0
449        float *data = new float[mSize * mSize];
450
451        GrabDepthBuffer(data, mFbo->GetDepthTex());
452        ExportDepthBuffer(data, mSize);
453
454        delete [] data;
455       
456        PrintGLerror("shadow map");
457#endif
458        FrameBufferObject::Release();
459}
460
461
462void ShadowMap::GetTextureMatrix(Matrix4x4 &m) const
463{
464        m = mTextureMatrix;
465}
466
467 
468unsigned int ShadowMap::GetShadowTexture() const
469{
470        return mFbo->GetDepthTex();
471}
472
473
474
475} // namespace
Note: See TracBrowser for help on using the repository browser.