3 This file is part of libmspgl
4 Copyright © 2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
14 #include "shadowmap.h"
22 ShadowMap::ShadowMap(unsigned s, const Scene &c, const Light &l):
29 depth_buf.set_min_filter(LINEAR);
30 depth_buf.set_compare_enabled(true);
31 depth_buf.set_compare_func(LEQUAL);
32 depth_buf.set_wrap(CLAMP_TO_EDGE);
33 depth_buf.storage(DEPTH_COMPONENT, size, size);
34 fbo.attach(DEPTH_ATTACHMENT, depth_buf, 0);
37 void ShadowMap::set_target(const Vector3 &t, float r)
43 void ShadowMap::set_texture_unit(unsigned u)
48 void ShadowMap::prepare()
50 Vector4 lpos = light.get_position();
53 /* XXX Not really proper way to support positional lights, but good
54 enough when the light source is far away */
58 float d = sqrt(lpos.x*lpos.x+lpos.y*lpos.y+lpos.z*lpos.z);
65 if(abs(lpos.z)>=abs(lpos.x) && abs(lpos.z)>=abs(lpos.y))
67 float d = sqrt(lpos.x*lpos.x+lpos.z*lpos.z);
70 matrix[8] = -lpos.x/d;
71 matrix[1] = -lpos.x*lpos.y/d;
73 matrix[9] = -lpos.z*lpos.y/d;
77 float d = sqrt(lpos.x*lpos.x+lpos.y*lpos.y);
78 matrix[0] = -lpos.y/d;
81 matrix[1] = -lpos.x*lpos.z/d;
82 matrix[5] = -lpos.y*lpos.z/d;
90 matrix[12] = -(target.x*matrix[0]+target.y*matrix[4]+target.z*matrix[8]);
91 matrix[13] = -(target.x*matrix[1]+target.y*matrix[5]+target.z*matrix[9]);
92 matrix[14] = -(target.x*matrix[2]+target.y*matrix[6]+target.z*matrix[10]);
99 MatrixStack::Push push_mv(MatrixStack::modelview());
100 MatrixStack::Push push_proj(MatrixStack::projection());
102 MatrixStack::projection() = Matrix::ortho(-radius, radius, -radius, radius, -radius, radius);
103 MatrixStack::modelview() = matrix;
105 Bind bind_fbo(fbo, true);
106 fbo.clear(DEPTH_BUFFER_BIT);
107 scene.render("shadow");
110 depth_buf.bind_to(unit);
111 float diam = radius*2;
112 float s_eq[4] = { matrix[0]/diam, matrix[4]/diam, matrix[8]/diam, matrix[12]/diam+0.5 };
113 float t_eq[4] = { matrix[1]/diam, matrix[5]/diam, matrix[9]/diam, matrix[13]/diam+0.5 };
114 float r_eq[4] = { -matrix[2]/diam, -matrix[6]/diam, -matrix[10]/diam, 0.5-matrix[14]/diam-4.0/size };
115 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
116 glTexGenfv(GL_S, GL_EYE_PLANE, s_eq);
117 enable(GL_TEXTURE_GEN_S);
118 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
119 glTexGenfv(GL_T, GL_EYE_PLANE, t_eq);
120 enable(GL_TEXTURE_GEN_T);
121 glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
122 glTexGenfv(GL_R, GL_EYE_PLANE, r_eq);
123 enable(GL_TEXTURE_GEN_R);
125 TexUnit::activate(0);
128 void ShadowMap::cleanup()
130 Texture::unbind_from(unit);
131 disable(GL_TEXTURE_GEN_S);
132 disable(GL_TEXTURE_GEN_T);
133 disable(GL_TEXTURE_GEN_R);
134 TexUnit::activate(0);