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

Revision 2947, 17.6 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
19static CGprogram sCgShadowProgram;
20static CGparameter sShadowParam;
21
22
23static Polyhedron *polyhedron = NULL;
24static Polyhedron *lightPoly = NULL;
25
26
27static void PrintGLerror(char *msg)
28{
29        GLenum errCode;
30        const GLubyte *errStr;
31       
32        if ((errCode = glGetError()) != GL_NO_ERROR)
33        {
34                errStr = gluErrorString(errCode);
35                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
36        }
37}
38
39
40static Polyhedron *CreatePolyhedron(const Matrix4x4 &lightMatrix,
41                                                                        const AxisAlignedBox3 &sceneBox)
42{
43        Frustum frustum(lightMatrix);
44
45        vector<Plane3> clipPlanes;
46
47        for (int i = 0; i < 6; ++ i)
48        {
49                ////////////
50                //-- normalize the coefficients
51
52                // the clipping planes look outward the frustum,
53                // so distances > 0 mean that a point is outside
54                const float invLength = -1.0f / Magnitude(frustum.mClipPlanes[i].mNormal);
55
56                frustum.mClipPlanes[i].mD *= invLength;
57                frustum.mClipPlanes[i].mNormal *= invLength;
58        }
59
60        // first create near plane because of precision issues
61        clipPlanes.push_back(frustum.mClipPlanes[4]);
62
63        clipPlanes.push_back(frustum.mClipPlanes[0]);
64        clipPlanes.push_back(frustum.mClipPlanes[1]);
65        clipPlanes.push_back(frustum.mClipPlanes[2]);
66        clipPlanes.push_back(frustum.mClipPlanes[3]);
67        clipPlanes.push_back(frustum.mClipPlanes[5]);
68
69        return Polyhedron::CreatePolyhedron(clipPlanes, sceneBox);
70}
71
72
73static void GrabDepthBuffer(float *data, GLuint depthTexture)
74{
75        glEnable(GL_TEXTURE_2D);
76        glBindTexture(GL_TEXTURE_2D, depthTexture);
77
78        glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);
79
80        glBindTexture(GL_TEXTURE_2D, 0);
81        glDisable(GL_TEXTURE_2D);
82}
83
84
85static void ExportDepthBuffer(float *data, int size)
86{
87        ilInit();
88        assert(ilGetError() == IL_NO_ERROR);
89
90        ILstring filename = ILstring("shadow.tga");
91        ilRegisterType(IL_FLOAT);
92
93        const int depth = 1;
94        const int bpp = 1;
95
96        if (!ilTexImage(size, size, depth, bpp, IL_LUMINANCE, IL_FLOAT, data))
97        {
98                cerr << "IL error " << ilGetError() << endl;
99       
100                ilShutDown();
101                assert(ilGetError() == IL_NO_ERROR);
102
103                return;
104        }
105
106        if (!ilSaveImage(filename))
107        {
108                cerr << "TGA write error " << ilGetError() << endl;
109        }
110
111        ilShutDown();
112        assert(ilGetError() == IL_NO_ERROR);
113
114        cout << "exported depth buffer" << endl;
115}
116
117
118
119static AxisAlignedBox3 GetExtremalPoints(const Matrix4x4 &m,
120                                                                                 const VertexArray &pts)
121{
122        AxisAlignedBox3 extremalPoints;
123        extremalPoints.Initialize();
124
125        VertexArray::const_iterator it, it_end = pts.end();
126               
127        for (it = pts.begin(); it != it_end; ++ it)
128        {
129                Vector3 pt = *it;
130                pt = m * pt;
131
132                extremalPoints.Include(pt);
133        }
134
135        return extremalPoints;
136}
137
138
139ShadowMap::ShadowMap(Light *light, int size, const AxisAlignedBox3 &sceneBox, Camera *cam):
140mSceneBox(sceneBox), mSize(size), mCamera(cam), mLight(light)
141{
142        mFbo = new FrameBufferObject(size, size, FrameBufferObject::DEPTH_32, true);
143        // need a color buffer to keep opengl happy
144        mFbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, false);
145
146        mShadowCam = new Camera(mSize, mSize);
147        mShadowCam->SetOrtho(true);
148}
149
150
151ShadowMap::~ShadowMap()
152{
153        DEL_PTR(mFbo);
154        DEL_PTR(mShadowCam);
155}
156
157
158static void DrawPoly(Polyhedron *poly, const Vector3 &color)
159{
160        if (!poly) return;
161
162        for (size_t i = 0; i < poly->NumPolygons(); ++ i)
163        {
164                glColor3f(color.x, color.y, color.z);
165
166                glBegin(GL_LINE_LOOP);
167
168                Polygon3 *p = poly->GetPolygons()[i];
169
170                for (size_t j = 0; j < p->mVertices.size(); ++ j)
171                {
172                        Vector3 v = p->mVertices[j];
173                        glVertex3d(v.x, v.y, v.z);
174                }
175
176                glEnd();
177        }
178}
179
180
181void ShadowMap::DrawPolys()
182{
183        DrawPoly(lightPoly, Vector3(1, 0, 1));
184        DrawPoly(polyhedron, Vector3(0, 1, 0));
185}
186
187
188// z0 is the point that lies on the parallel plane to the near plane through e (A)
189//and on the near plane of the C frustum (the plane z = bZmax) and on the line x = e.x
190Vector3 ShadowMap::GetLightSpaceZ0(const Matrix4x4 &lightSpace,
191                                                                   const Vector3 &e,
192                                                                   const float maxZ,
193                                                                   const Vector3 &eyeDir) const
194{
195        // to calculate the parallel plane to the near plane through e we
196        // calculate the plane A with the three points
197        Plane3 planeA(e, eyeDir);
198
199        planeA.Transform(lightSpace);
200       
201        // get the parameters of A from the plane equation n dot d = 0
202        const float d = planeA.mD;
203        const Vector3 n = planeA.mNormal;
204       
205        // transform to light space
206        const Vector3 e_ls = lightSpace * e;
207
208        Vector3 z0;
209
210        z0.x = e_ls.x;
211        z0.y = (d - n.z * maxZ - n.x * e_ls.x) / n.y;
212        z0.z = maxZ;
213
214        return z0;
215        //return V3(e_ls.x(),(d-n.z()*b_lsZmax-n.x()*e_ls.x())/n.y(),b_lsZmax);
216}
217
218
219float ShadowMap::ComputeNOpt(const Matrix4x4 &lightSpace,
220                                                         const AxisAlignedBox3 &extremalPoints,
221                                                         const VertexArray &body) const
222{
223        const Vector3 nearPt = GetNearCameraPointE(body);
224        const Vector3 eyeDir = mCamera->GetDirection();
225
226        Matrix4x4 eyeView;
227        mCamera->GetModelViewMatrix(eyeView);
228
229        const Matrix4x4 invLightSpace = Invert(lightSpace);
230
231        const Vector3 z0_ls = GetLightSpaceZ0(lightSpace, nearPt, extremalPoints.Max().z, eyeDir);
232        const Vector3 z1_ls = Vector3(z0_ls.x, z0_ls.y, extremalPoints.Min().z);
233       
234        // transform back to world space
235        const Vector3 z0_ws = invLightSpace * z0_ls;
236        const Vector3 z1_ws = invLightSpace * z1_ls;
237
238        // transform to eye space
239        const Vector3 z0_es = eyeView * z0_ws;
240        const Vector3 z1_es = eyeView * z1_ws;
241
242        const float z0 = z0_es.z;
243        const float z1 = z1_es.z;
244
245        cout << "z0 ls: " << z0_ls << " z1 ls: " << z1_ls << endl;
246        cout << "z0: " << z0_es << " z1: " << z1_es << endl;
247
248        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
249
250        const float n = d / (sqrt(z1 / z0) - 1.0f);
251
252        return n;
253}
254
255
256float ShadowMap::ComputeN(const AxisAlignedBox3 &extremalPoints) const
257{
258        const float nearPlane = mCamera->GetNear();
259       
260        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
261       
262        const float dotProd = DotProd(mCamera->GetDirection(), mShadowCam->GetDirection());
263        const float sinGamma = sin(fabs(acos(dotProd)));
264
265        // test for values close to zero
266        if (sinGamma < 1e-6f) return 1e6f;
267       
268        return (nearPlane + sqrt(nearPlane * (nearPlane + d * sinGamma))) /  sinGamma;
269}
270
271
272Matrix4x4 ShadowMap::CalcLispSMTransform(const Matrix4x4 &lightSpace,
273                                                                                 const AxisAlignedBox3 &extremalPoints,
274                                                                                 const VertexArray &body
275                                                                                 )
276{
277        AxisAlignedBox3 bounds_ls = GetExtremalPoints(lightSpace, body);
278
279        ///////////////
280        //-- We apply the lispsm algorithm in order to calculate an optimal light projection matrix
281        //-- first find the free parameter values n, and P (the projection center), and the projection depth
282
283        const float n = ComputeN(bounds_ls);
284        //const float n = ComputeNOpt(lightSpace, extremalPoints, body); cout << "n: " << n << endl;
285
286        if (n >= 1e6f) // light direction nearly parallel to view => switch to uniform
287                return IdentityMatrix();
288
289        const Vector3 nearPt = GetNearCameraPointE(body);
290       
291        //get the coordinates of the near camera point in light space
292        const Vector3 lsNear = lightSpace * nearPt;
293
294        // the start point has the x and y coordinate of e, the z coord of the near plane of the light volume
295        const Vector3 startPt = Vector3(lsNear.x, lsNear.y, bounds_ls.Max().z);
296       
297        // the new projection center
298        const Vector3 projCenter = startPt + Vector3::UNIT_Z() * n;
299
300        //construct a translation that moves to the projection center
301        const Matrix4x4 projectionCenter = TranslationMatrix(-projCenter);
302
303        // light space y size
304        const float d = fabs(bounds_ls.Max()[2] - bounds_ls.Min()[2]);
305
306        const float dy = fabs(bounds_ls.Max()[1] - bounds_ls.Min()[1]);
307        const float dx = fabs(bounds_ls.Max()[0] - bounds_ls.Min()[0]);
308
309       
310
311        //////////
312        //-- now apply these values to construct the perspective lispsm matrix
313
314        Matrix4x4 matLispSM;
315       
316        matLispSM = GetFrustum(-1.0, 1.0, -1.0, 1.0, n, n + d);
317
318        // translate to the projection center
319        matLispSM = projectionCenter * matLispSM;
320
321        // transform into OpenGL right handed system
322        Matrix4x4 refl = ScaleMatrix(1.0f, 1.0f, -1.0f);
323        matLispSM *= refl;
324       
325        return matLispSM;
326}
327
328#if 0
329Vector3 ShadowMap::GetNearCameraPointE(const VertexArray &pts) const
330{
331        float maxDist = -1e25f;
332        Vector3 nearest = Vector3::ZERO();
333
334        Matrix4x4 eyeView;
335        mCamera->GetModelViewMatrix(eyeView);
336
337        VertexArray newPts;
338        polyhedron->CollectVertices(newPts);
339       
340        //the LVS volume is always in front of the camera
341        VertexArray::const_iterator it, it_end = pts.end();     
342
343        for (it = pts.begin(); it != it_end; ++ it)
344        {
345                Vector3 pt = *it;
346                Vector3 ptE = eyeView * pt;
347               
348                if (ptE.z > 0) cerr <<"should not happen " << ptE.z << endl;
349                else
350                if (ptE.z > maxDist)
351                {
352                        cout << " d " << ptE.z;
353       
354                        maxDist = ptE.z;
355                        nearest = pt;
356                }
357        }
358
359        //      return Invert(eyeView) * nearest;
360        return nearest;
361}
362
363#else
364
365Vector3 ShadowMap::GetNearCameraPointE(const VertexArray &pts) const
366{
367        VertexArray newPts;
368        polyhedron->CollectVertices(newPts);
369
370        Vector3 nearest = Vector3::ZERO();
371        float minDist = 1e25f;
372
373        const Vector3 camPos = mCamera->GetPosition();
374
375        VertexArray::const_iterator it, it_end = newPts.end();
376
377        for (it = newPts.begin(); it != it_end; ++ it)
378        {
379                Vector3 pt = *it;
380
381                const float dist = SqrDistance(pt, camPos);
382
383                if (dist < minDist)
384                {
385                        minDist = dist;
386                        nearest = pt;
387                }
388        }
389
390        return nearest;
391}
392
393#endif
394
395Vector3 ShadowMap::GetProjViewDir(const Matrix4x4 &lightSpace,
396                                                                  const VertexArray &pts) const
397{
398        //get the point in the LVS volume that is nearest to the camera
399        const Vector3 e = GetNearCameraPointE(pts);
400
401        //construct edge to transform into light-space
402        const Vector3 b = e + mCamera->GetDirection();
403        //transform to light-space
404        const Vector3 e_lp = lightSpace * e;
405        const Vector3 b_lp = lightSpace * b;
406
407        Vector3 projDir(b_lp - e_lp);
408
409        //project the view direction into the shadow map plane
410        projDir.y = .0f;
411
412        return Normalize(projDir);
413}
414
415
416bool ShadowMap::CalcLightProjection(Matrix4x4 &lightProj)
417{
418        ///////////////////
419        //-- First step: calc frustum clipped by scene box
420
421        DEL_PTR(polyhedron);
422        polyhedron = CalcClippedFrustum(mSceneBox);
423
424        if (!polyhedron) return false; // something is wrong
425
426        // include the part of the light volume that "sees" the frustum
427        // we only require frustum vertices
428
429        VertexArray frustumPoints;
430        IncludeLightVolume(*polyhedron, frustumPoints, mLight->GetDirection(), mSceneBox);
431
432
433        ///////////////
434        //-- transform points from world view to light view and calculate extremal points
435
436        Matrix4x4 lightView;
437        mShadowCam->GetModelViewMatrix(lightView);
438
439        const AxisAlignedBox3 extremalPoints = GetExtremalPoints(lightView, frustumPoints);
440
441        // we use directional lights, so the projection can be set to identity
442        lightProj = IdentityMatrix();
443
444        // switch coordinate system to that used in the lispsm algorithm for calculations
445        Matrix4x4 transform2LispSM = ZeroMatrix();
446
447        transform2LispSM.x[0][0] =  1.0f;
448        transform2LispSM.x[1][2] =  -1.0f; // y => -z
449        transform2LispSM.x[2][1] =  1.0f; // z => y
450        transform2LispSM.x[3][3] =  1.0f;
451
452
453        //switch to the lightspace used in the article
454        lightProj *= transform2LispSM;
455
456        const Vector3 projViewDir = GetProjViewDir(lightView * lightProj, frustumPoints);
457
458        //do Light Space Perspective shadow mapping
459        //rotate the lightspace so that the projected light view always points upwards
460        //calculate a frame matrix that uses the projViewDir[lightspace] as up vector
461        //look(from position, into the direction of the projected direction, with unchanged up-vector)
462        //const Matrix4x4 frame = MyLookAt2(Vector3::ZERO(), projViewDir, Vector3::UNIT_Y());
463        const Matrix4x4 frame = LookAt(Vector3::ZERO(), projViewDir, Vector3::UNIT_Y());
464
465        lightProj *= frame;
466
467        const Matrix4x4 matLispSM =
468                CalcLispSMTransform(lightView * lightProj, extremalPoints, frustumPoints);
469
470        lightProj *= matLispSM;
471
472        // change back to GL coordinate system
473        Matrix4x4 transformToGL = ZeroMatrix();
474       
475        transformToGL.x[0][0] =   1.0f;
476        transformToGL.x[1][2] =   1.0f; // z => y
477        transformToGL.x[2][1] =  -1.0f; // y => -z
478        transformToGL.x[3][3] =   1.0f;
479
480        lightProj *= transformToGL;
481
482        AxisAlignedBox3 lightPts = GetExtremalPoints(lightView * lightProj, frustumPoints);
483
484        // focus projection matrix on the extremal points => scale to unit cube
485        Matrix4x4 scaleTranslate = GetFittingProjectionMatrix(lightPts);
486
487        lightProj = lightProj * scaleTranslate;
488
489        Matrix4x4 mymat = lightView * lightProj;
490
491        AxisAlignedBox3 lightPtsNew = GetExtremalPoints(mymat, frustumPoints);
492
493        // we have to flip the signs in order to tranform to opengl right handed system
494        Matrix4x4 refl = ScaleMatrix(1, 1, -1);
495        lightProj *= refl;
496       
497        return true;
498}
499
500
501Polyhedron *ShadowMap::CalcClippedFrustum(const AxisAlignedBox3 &box) const
502{
503        Polyhedron *p = mCamera->ComputeFrustum();
504       
505        Polyhedron *clippedPolyhedron = box.CalcIntersection(*p);
506
507        DEL_PTR(p);
508       
509        return clippedPolyhedron;
510}
511
512
513//calculates the up vector for the light coordinate frame
514static Vector3 CalcUpVec(const Vector3 viewDir, const Vector3 lightDir)
515{
516        //we do what gluLookAt does...
517        //left is the normalized vector perpendicular to lightDir and viewDir
518        //this means left is the normalvector of the yz-plane from the paper
519        Vector3 left = CrossProd(lightDir, viewDir);
520       
521        //we now can calculate the rotated(in the yz-plane) viewDir vector
522        //and use it as up vector in further transformations
523        Vector3 up = CrossProd(left, lightDir);
524
525        return Normalize(up);
526}
527
528
529void ShadowMap::GetTextureMatrix(Matrix4x4 &m) const
530{
531        m = mTextureMatrix;
532}
533
534 
535unsigned int ShadowMap::GetDepthTexture() const
536{
537        return mFbo->GetDepthTex();
538}
539
540unsigned int ShadowMap::GetShadowColorTexture() const
541{
542        return mFbo->GetColorBuffer(0)->GetTexture();
543       
544}
545
546
547void ShadowMap::IncludeLightVolume(const Polyhedron &polyhedron,
548                                                                   VertexArray &frustumPoints,
549                                                                   const Vector3 lightDir,
550                                                                   const AxisAlignedBox3 &sceneBox
551                                                                   )
552{
553        // we don't need closed form anymore => just store vertices
554        VertexArray vertices;
555        polyhedron.CollectVertices(vertices);
556
557        // we 'look' at each point and calculate intersections of rays with scene bounding box
558        VertexArray::const_iterator it, it_end = vertices.end();
559
560        for (it = vertices.begin(); it != it_end; ++ it)
561        {
562                Vector3 v  = *it;
563
564                frustumPoints.push_back(v);
565               
566                // hack: start at point which is guaranteed to be outside of box
567                v -= Magnitude(mSceneBox.Diagonal()) * lightDir;
568
569                SimpleRay ray(v, lightDir);
570
571                float tNear, tFar;
572
573                if (sceneBox.Intersects(ray, tNear, tFar))
574                {
575                        Vector3 newpt = ray.Extrap(tNear);
576                        frustumPoints.push_back(newpt);                 
577                }
578        }
579}
580
581
582void ShadowMap::ComputeShadowMap(RenderTraverser *renderer, const Matrix4x4 &projView)
583{
584        mFbo->Bind();
585       
586        glDrawBuffers(1, mrt);
587
588        glPushAttrib(GL_VIEWPORT_BIT);
589        glViewport(0, 0, mSize, mSize);
590
591        glDisable(GL_LIGHTING);
592        //glDisable(GL_TEXTURE_2D);
593        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
594
595        glShadeModel(GL_FLAT);
596
597
598        /////////////
599        //-- render scene into shadow map
600
601        _Render(renderer);
602
603
604        //////////////
605        //-- compute texture matrix
606
607        static Matrix4x4 biasMatrix(0.5f, 0.0f, 0.0f, 0.5f,
608                                                                0.0f, 0.5f, 0.0f, 0.5f,
609                                                                0.0f, 0.0f, 0.5f, 0.5f,
610                                                                0.0f, 0.0f, 0.0f, 1.0f);
611
612        mTextureMatrix = mLightProjView * biasMatrix;
613
614        glPopAttrib();
615       
616        glShadeModel(GL_SMOOTH);
617        glEnable(GL_LIGHTING);
618        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
619
620#if 0
621        float *data = new float[mSize * mSize];
622
623        GrabDepthBuffer(data, mFbo->GetDepthTex());
624        ExportDepthBuffer(data, mSize);
625
626        delete [] data;
627       
628        PrintGLerror("shadow map");
629#endif
630       
631        FrameBufferObject::Release();
632}
633
634
635void ShadowMap::RenderShadowView(RenderTraverser *renderer, const Matrix4x4 &projView)
636{
637        glEnable(GL_LIGHTING);
638       
639        _Render(renderer);
640       
641        /*glDisable(GL_LIGHTING);
642        glDisable(GL_DEPTH_TEST);
643
644        //glLineWidth(2);
645        Polyhedron *hpoly = CreatePolyhedron(projView, mSceneBox);
646        DrawPoly(hpoly, Vector3(1, 1, 1));
647
648        DEL_PTR(hpoly);
649
650        glEnable(GL_LIGHTING);
651        glEnable(GL_DEPTH_TEST);*/
652
653        glDisable(GL_POLYGON_OFFSET_FILL);
654}
655
656
657void ShadowMap::_Render(RenderTraverser *renderer)
658{
659        const Vector3 dir = mLight->GetDirection();
660        //const Vector3 dir(0, 0, -1);
661
662        mShadowCam->SetDirection(dir);
663
664        // set position so that we can see the whole scene
665        Vector3 pos = mSceneBox.Center();
666        pos -= dir * Magnitude(mSceneBox.Diagonal() * 0.5f);
667
668        mShadowCam->SetPosition(mCamera->GetPosition());
669
670        Vector3 upVec = CalcUpVec(mCamera->GetDirection(), dir);
671        Matrix4x4 lightView = LookAt(mShadowCam->GetPosition(), dir, upVec);
672
673        mShadowCam->mViewOrientation = lightView;
674
675        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
676
677        glPolygonOffset(5.0f, 100.0f);
678        glEnable(GL_POLYGON_OFFSET_FILL);
679       
680        Matrix4x4 lightProj;
681        CalcLightProjection(lightProj);
682
683        glMatrixMode(GL_PROJECTION);
684        glPushMatrix();
685        glLoadMatrixf((float *)lightProj.x);
686
687        mLightProjView = lightView * lightProj;
688
689        DEL_PTR(lightPoly);
690        lightPoly = CreatePolyhedron(mLightProjView, mSceneBox);
691
692        glMatrixMode(GL_MODELVIEW);
693        glPushMatrix();
694        glLoadIdentity();
695
696        //glDisable(GL_CULL_FACE);
697        mShadowCam->SetupCameraView();
698
699       
700        /////////////
701        //-- render scene into shadow map
702
703        renderer->RenderScene();
704
705
706        glMatrixMode(GL_MODELVIEW);
707        glPopMatrix();
708
709        glMatrixMode(GL_PROJECTION);
710        glPopMatrix();
711
712       
713        glDisable(GL_POLYGON_OFFSET_FILL);
714}
715} // namespace
Note: See TracBrowser for help on using the repository browser.