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

Revision 2925, 15.4 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
87static AxisAlignedBox3 GetExtremalPoints(const Matrix4x4 &m,
88                                                                                 const VertexArray &pts)
89{
90        AxisAlignedBox3 extremalPoints;
91        extremalPoints.Initialize();
92
93        VertexArray::const_iterator it, it_end = pts.end();
94               
95        for (it = pts.begin(); it != it_end; ++ it)
96        {
97                Vector3 pt = *it;
98                pt = m * pt;
99
100                extremalPoints.Include(pt);
101        }
102
103        return extremalPoints;
104}
105
106
107ShadowMap::ShadowMap(Light *light, int size, const AxisAlignedBox3 &sceneBox, Camera *cam):
108mSceneBox(sceneBox), mSize(size), mCamera(cam), mLight(light)
109{
110        mFbo = new FrameBufferObject(size, size, FrameBufferObject::DEPTH_32, true);
111        // the diffuse color buffer
112        mFbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, false);
113
114        mShadowCam = new Camera(mSceneBox.Size().x * 0.5f, mSceneBox.Size().y * 0.5f);
115        mShadowCam->SetOrtho(true);
116}
117
118
119ShadowMap::~ShadowMap()
120{
121        DEL_PTR(mFbo);
122        DEL_PTR(mShadowCam);
123}
124
125
126void ShadowMap::DrawPolys()
127{
128        if (!polyhedron) return;
129
130        for (size_t i = 0; i < polyhedron->NumPolygons(); ++ i)
131        {
132                float r = (float)i / polyhedron->NumPolygons();
133                float g = 1;
134                float b = 1;
135
136                glColor3f(r, g, b);
137
138                glBegin(GL_LINE_LOOP);
139
140                Polygon3 *poly = polyhedron->GetPolygons()[i];
141
142                for (size_t j = 0; j < poly->mVertices.size(); ++ j)
143                {
144                        Vector3 v = poly->mVertices[j];
145                        glVertex3d(v.x, v.y, v.z);
146                }
147
148                glEnd();
149        }
150}
151
152
153void ShadowMap::IncludeLightVolume(const Polyhedron &polyhedron,
154                                                                   VertexArray &frustumPoints,
155                                                                   const Vector3 lightDir,
156                                                                   const AxisAlignedBox3 &sceneBox
157                                                                   )
158{
159        // we don't need closed form anymore => just store vertices
160        VertexArray vertices;
161        polyhedron.CollectVertices(vertices);
162
163        // we 'look' at each point and calculate intersections of rays with scene bounding box
164        VertexArray::const_iterator it, it_end = vertices.end();
165
166        for (it = vertices.begin(); it != it_end; ++ it)
167        {
168                Vector3 v  = *it;
169
170                frustumPoints.push_back(v);
171               
172                // hack: get point surely outside of box
173                v -= Magnitude(mSceneBox.Diagonal()) * lightDir;
174
175                SimpleRay ray(v, lightDir);
176
177                float tNear, tFar;
178
179                if (sceneBox.Intersects(ray, tNear, tFar))
180                {
181                        Vector3 newpt = ray.Extrap(tNear);
182                        frustumPoints.push_back(newpt);                 
183                }
184        }
185}
186
187
188float ShadowMap::ComputeN(const AxisAlignedBox3 &extremalPoints) const
189{
190        const float n = mCamera->GetNear();
191       
192        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
193       
194        const float dotProd = DotProd(mCamera->GetDirection(), mShadowCam->GetDirection());
195        const float sinGamma = sin(fabs(acos(dotProd)));
196
197        return (n + sqrt(n * (n + d * sinGamma))) /  sinGamma;
198}
199
200
201Matrix4x4 ShadowMap::CalcLispSMTransform(const Matrix4x4 &lightSpace,
202                                                                                 const AxisAlignedBox3 &extremalPoints,
203                                                                                 const VertexArray &body
204                                                                                 )
205{
206        AxisAlignedBox3 bounds_ls = GetExtremalPoints(lightSpace, body);
207        //return IdentityMatrix();
208
209        ///////////////
210        //-- We apply the lispsm algorithm in order to calculate an optimal light projection matrix
211        //-- first find the free parameter values n, and P (the projection center), and the projection depth
212
213        //const float n = 1e6f;
214        const float n = ComputeN(bounds_ls);
215
216        cout << "n: " << n << endl;
217
218        const Vector3 nearPt = GetNearCameraPointE(body);
219        const float dummy = 0;
220        //get the coordinates of the near camera point in light space
221        const Vector3 lsNear = lightSpace * nearPt;
222
223        //c start has the x and y coordinate of e,  the z coord of the near plane of the light volume
224        const Vector3 startPt = Vector3(lsNear.x, lsNear.y, bounds_ls.Max().z);
225
226        cout << "mx: " <<  bounds_ls.Max() << endl;
227        cout << "mn: " << bounds_ls.Min() << endl;
228
229        // the new projection center
230        Vector3 projCenter = startPt + Vector3::UNIT_Z() * n * 1000;
231
232        cout <<"start: " << startPt << " " << projCenter << " " << Distance(lightSpace * mCamera->GetPosition(), startPt) << endl;
233
234        //construct a translation that moves to the projection center
235        const Matrix4x4 projectionCenter = TranslationMatrix(-projCenter);
236
237        // light space y size
238        const float d = fabs(bounds_ls.Max()[2] - bounds_ls.Min()[2])+dummy;
239
240        const float dy = fabs(bounds_ls.Max()[1] - bounds_ls.Min()[1]);
241        const float dx = fabs(bounds_ls.Max()[0] - bounds_ls.Min()[0]);
242
243        cout << "d: " << d << " dy: " << dy << " dx: " << dx << endl;
244
245       
246
247        ////////
248        //-- now apply these values to construct the perspective lispsm matrix
249
250        Matrix4x4 matLispSM;
251       
252        matLispSM = GetFrustum(-1.0, 1.0, -1.0, 1.0, n+dummy, n + d);
253
254        //cout << "lispsm\n" << matLispSM << endl;
255
256        // translate to the projection center
257        matLispSM = projectionCenter * matLispSM;
258
259        //cout << "new\n" << matLispSM << endl;
260
261        // transform into OpenGL right handed system
262        Matrix4x4 refl = ScaleMatrix(1.0f, 1.0f, -1.0f);
263        matLispSM *= refl;
264       
265        return matLispSM;
266}
267
268#if 0
269Vector3 ShadowMap::GetNearCameraPointE(const VertexArray &pts) const
270{
271        float maxDist = -1e25f;
272        Vector3 nearest = Vector3::ZERO();
273
274        Matrix4x4 eyeView;
275        mCamera->GetModelViewMatrix(eyeView);
276
277        VertexArray newPts;
278        polyhedron->CollectVertices(newPts);
279       
280        //the LVS volume is always in front of the camera
281        VertexArray::const_iterator it, it_end = pts.end();     
282
283        for (it = pts.begin(); it != it_end; ++ it)
284        {
285                Vector3 pt = *it;
286                Vector3 ptE = eyeView * pt;
287//cout<<"i"<< pt.z;
288                if (ptE.z > 0) cerr <<"should not happen " << ptE.z << endl;
289                else
290                if (ptE.z > maxDist)
291                {
292                        cout << " d " << ptE.z;
293       
294                        maxDist = ptE.z;
295                        nearest = pt;
296                }
297        }
298
299        //      Invert(eyeView); return eyeView * nearest;
300        return nearest;
301}
302
303#else
304
305Vector3 ShadowMap::GetNearCameraPointE(const VertexArray &pts) const
306{
307        VertexArray newPts;
308        polyhedron->CollectVertices(newPts);
309
310        Vector3 nearest = Vector3::ZERO();
311        float minDist = 1e25f;
312
313        const Vector3 camPos = mCamera->GetPosition();
314
315        VertexArray::const_iterator it, it_end = newPts.end();
316
317        for (it = newPts.begin(); it != it_end; ++ it)
318        {
319                Vector3 pt = *it;
320
321                const float dist = SqrDistance(pt, camPos);
322
323                if (dist < minDist)
324                {
325                        minDist = dist;
326                        nearest = pt;
327                }
328        }
329
330        return nearest;
331}
332
333#endif
334
335Vector3 ShadowMap::GetProjViewDir(const Matrix4x4 &lightSpace, const VertexArray &pts) const
336{
337        //get the point in the LVS volume that is nearest to the camera
338        const Vector3 e = GetNearCameraPointE(pts);
339
340        //construct edge to transform into light-space
341        const Vector3 b = e + mCamera->GetDirection();
342        //transform to light-space
343        const Vector3 e_lp = lightSpace * e;
344        const Vector3 b_lp = lightSpace * b;
345
346        Vector3 projDir(b_lp - e_lp);
347
348        Matrix4x4 dummy = lightSpace;
349        Invert(dummy);
350        Vector3 dummyVec = dummy * e_lp;
351        Vector3 dummyVec2 = dummy * b_lp;
352
353        //projDir.z = -projDir.z;
354
355        cout << "dummy: " << Normalize(dummyVec2 - dummyVec) << endl;
356        //project the view direction into the shadow map plane
357        projDir.y = 0.0;
358
359        return Normalize(projDir);
360        //return projDir;
361}
362
363
364bool ShadowMap::CalcLightProjection(Matrix4x4 &lightProj)
365{
366        ///////////////////
367        //-- First step: calc frustum clipped by scene box
368
369        DEL_PTR(polyhedron);
370        polyhedron = CalcClippedFrustum(mSceneBox);
371
372        if (!polyhedron) return false; // something is wrong
373
374        // include the part of the light volume that "sees" the frustum
375        // we only require frustum vertices
376
377        VertexArray frustumPoints;
378        IncludeLightVolume(*polyhedron, frustumPoints, mShadowCam->GetDirection(), mSceneBox);
379
380
381        ///////////////
382        //-- transform points from world view to light view and calculate extremal points
383
384        Matrix4x4 lightView;
385        mShadowCam->GetModelViewMatrix(lightView);
386
387        const AxisAlignedBox3 extremalPoints = GetExtremalPoints(lightView, frustumPoints);
388
389        // we use directional lights, so the projection can be set to identity
390        lightProj = IdentityMatrix();
391
392        // switch coordinate system to that used in the lispsm algorithm for calculations
393        Matrix4x4 transform2LispSM = ZeroMatrix();
394
395        transform2LispSM.x[0][0] =  1.0f;
396        transform2LispSM.x[1][2] = -1.0f; // y => -z
397        transform2LispSM.x[2][1] =  1.0f; // z => y
398        transform2LispSM.x[3][3] =  1.0f;
399
400        //switch to the lightspace used in the article
401        lightProj = lightProj * transform2LispSM;
402
403        const Vector3 projViewDir = GetProjViewDir(lightView * lightProj, frustumPoints);
404
405
406        cout << "projViewDir: " << projViewDir << " orig " << mCamera->GetDirection() << endl;
407
408        //do Light Space Perspective shadow mapping
409        //rotate the lightspace so that the projected light view always points upwards
410        //calculate a frame matrix that uses the projViewDir[lightspace] as up vector
411        //look(from position, into the direction of the projected direction, with unchanged up-vector)
412        const Matrix4x4 frame = LookAt(Vector3::ZERO(), projViewDir, Vector3::UNIT_Y());
413
414        cout << "frame\n " << frame << endl;
415        lightProj = lightProj * frame;
416
417        cout << "here9\n" << lightProj << endl;
418
419        const Matrix4x4 matLispSM =
420                CalcLispSMTransform(lightView * lightProj, extremalPoints, frustumPoints);
421
422        Vector3 mydummy = projViewDir;//Vector3::UNIT_Z();
423        //cout << "transformed unit z vector: " << Normalize(lightView * lightProj * mydummy) << endl;
424        cout << "transformed unit z vector: " << Normalize(frame * mydummy) << endl;
425
426        lightProj = lightProj * matLispSM;
427
428        // change back to GL coordinate system
429        Matrix4x4 transformToGL = ZeroMatrix();
430       
431        transformToGL.x[0][0] =  1.0f;
432        transformToGL.x[1][2] =  1.0f; // z => y
433        transformToGL.x[2][1] = -1.0f; // y => -z
434        transformToGL.x[3][3] =  1.0f;
435
436        lightProj = lightProj * transformToGL;
437        //cout << "here4 \n" << lightProj << endl;
438
439        AxisAlignedBox3 lightPts = GetExtremalPoints(lightView * lightProj, frustumPoints);
440
441        //cout << "ma2: " << lightPts.Max() << endl;
442        //cout << "mi2: " << lightPts.Min() << endl;
443
444        // focus projection matrix on the extremal points => scale to unit cube
445        Matrix4x4 scaleTranslate = GetFittingProjectionMatrix(lightPts);
446        lightProj *= scaleTranslate;
447
448        cout << "max: " << lightProj * extremalPoints.Max() << endl;
449        cout << "min: " << lightProj * extremalPoints.Min() << endl;
450
451        // we have to flip the signs in order to tranform to opengl right handed system
452        Matrix4x4 refl = ScaleMatrix(1, 1, -1);
453        lightProj *= refl;
454       
455        return true;
456}
457
458
459Polyhedron *ShadowMap::CalcClippedFrustum(const AxisAlignedBox3 &box) const
460{
461        Vector3 ftl, ftr, fbl, fbr;
462        Vector3 ntl, ntr, nbl, nbr;
463
464        VertexArray sides[6];
465
466        mCamera->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
467
468        for (int i = 0; i < 6; ++ i)
469                sides[i].resize(4);
470       
471        // left, right
472        sides[0][0] = ftl; sides[0][1] = fbl; sides[0][2] = nbl; sides[0][3] = ntl;
473        sides[1][0] = fbr; sides[1][1] = ftr; sides[1][2] = ntr; sides[1][3] = nbr;
474        // bottom, top
475        sides[2][0] = fbl; sides[2][1] = fbr; sides[2][2] = nbr; sides[2][3] = nbl;
476        sides[3][0] = ftr; sides[3][1] = ftl; sides[3][2] = ntl; sides[3][3] = ntr;
477        // near, far
478        sides[4][0] = ntr; sides[4][1] = ntl; sides[4][2] = nbl; sides[4][3] = nbr;
479        sides[5][0] = ftl; sides[5][1] = ftr; sides[5][2] = fbr; sides[5][3] = fbl;
480
481        //////////
482        //-- compute polyhedron
483
484        PolygonContainer polygons;
485
486        for (int i = 0; i < 6; ++ i)
487        {
488                Polygon3 *poly = new Polygon3(sides[i]);
489                polygons.push_back(poly);
490        }
491
492        Polyhedron *p = new Polyhedron(polygons);
493        Polyhedron *clippedPolyhedron = box.CalcIntersection(*p);
494       
495        DEL_PTR(p);
496       
497
498        return clippedPolyhedron;
499}
500
501
502void ShadowMap::ComputeShadowMap(RenderTraverser *renderer, const Matrix4x4 &projView)
503{
504        const float xlen = Magnitude(mSceneBox.Diagonal() * 0.5f);
505        const float ylen = Magnitude(mSceneBox.Diagonal() * 0.5f);
506       
507        //const Vector3 dir = mLight->GetDirection();
508        const Vector3 dir(0, 0, -1);
509
510        mShadowCam->SetDirection(dir);
511       
512        //cout << "lightdir: " << mShadowCam->GetDirection() << endl;
513
514        // set position so that we can see the whole scene
515        Vector3 pos = mSceneBox.Center();
516
517        //Matrix4x4 camView;
518        //mCamera->GetModelViewMatrix(camView);
519
520        pos -= dir * Magnitude(mSceneBox.Diagonal() * 0.1f);
521        mShadowCam->SetPosition(pos);
522
523        mFbo->Bind();
524       
525        glDrawBuffers(1, mrt);
526
527        glPushAttrib(GL_VIEWPORT_BIT);
528        glViewport(0, 0, mSize, mSize);
529
530        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
531
532        glDisable(GL_LIGHTING);
533        glDisable(GL_TEXTURE_2D);
534        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
535
536        glPolygonOffset(1.0f, 2000.0f);
537        glEnable(GL_POLYGON_OFFSET_FILL);
538
539        glShadeModel(GL_FLAT);
540        glEnable(GL_DEPTH_TEST);
541
542        // setup projection
543        /*glMatrixMode(GL_PROJECTION);
544        glLoadIdentity();
545        glOrtho(+xlen, -xlen, +ylen, -ylen, 0.0f, Magnitude(mSceneBox.Diagonal()));
546
547        Matrix4x4 dummyMat;
548        glGetFloatv(GL_PROJECTION_MATRIX, (float *)dummyMat.x);
549        cout << "old:\n" << dummyMat << endl;
550        */
551
552        Matrix4x4 lightView, lightProj;
553
554        mShadowCam->GetModelViewMatrix(lightView);
555        CalcLightProjection(lightProj);
556
557        glMatrixMode(GL_PROJECTION);
558        glPushMatrix();
559        glLoadMatrixf((float *)lightProj.x);
560
561        mLightProjView = lightView * lightProj;
562
563        //cout << "new:\n" << lightProj << endl;
564
565        glMatrixMode(GL_MODELVIEW);
566        glPushMatrix();
567        glLoadIdentity();
568
569        mShadowCam->SetupCameraView();
570
571
572        //////////////
573        //-- compute texture matrix
574
575        static Matrix4x4 biasMatrix(0.5f, 0.0f, 0.0f, 0.5f,
576                                                                0.0f, 0.5f, 0.0f, 0.5f,
577                                                                0.0f, 0.0f, 0.5f, 0.5f,
578                                                                0.0f, 0.0f, 0.0f, 1.0f);
579
580        mTextureMatrix = mLightProjView * biasMatrix;
581
582
583
584
585        /////////////
586        //-- render scene into shadow map
587
588        renderer->RenderScene();
589
590       
591        glDisable(GL_POLYGON_OFFSET_FILL);
592        glMatrixMode(GL_MODELVIEW);
593        glPopMatrix();
594
595        glMatrixMode(GL_PROJECTION);
596        glPopMatrix();
597
598        glPopAttrib();
599#if 0
600        float *data = new float[mSize * mSize];
601
602        GrabDepthBuffer(data, mFbo->GetDepthTex());
603        ExportDepthBuffer(data, mSize);
604
605        delete [] data;
606       
607        PrintGLerror("shadow map");
608#endif
609        FrameBufferObject::Release();
610}
611
612
613void ShadowMap::GetTextureMatrix(Matrix4x4 &m) const
614{
615        m = mTextureMatrix;
616}
617
618 
619unsigned int ShadowMap::GetShadowTexture() const
620{
621        return mFbo->GetDepthTex();
622}
623
624
625
626} // namespace
Note: See TracBrowser for help on using the repository browser.