18 ShadowMap::ShadowMap(unsigned s, const Renderable &r, const Light &l):
26 depth_buf.set_min_filter(LINEAR);
27 depth_buf.set_compare_enabled(true);
28 depth_buf.set_compare_func(LEQUAL);
29 depth_buf.set_wrap(CLAMP_TO_EDGE);
30 depth_buf.storage(DEPTH_COMPONENT, size, size);
31 fbo.attach(DEPTH_ATTACHMENT, depth_buf, 0);
32 fbo.require_complete();
38 void ShadowMap::set_target(const Vector3 &t, float r)
44 void ShadowMap::set_darkness(float d)
47 throw invalid_argument("ShadowMap::set_darkness");
49 shdata.uniform("shadow_darkness", d);
52 void ShadowMap::set_depth_bias(float b)
55 throw invalid_argument("ShadowMap::set_depth_bias");
60 void ShadowMap::set_texture_unit(unsigned u)
65 shdata.uniform("shadow", i);
66 shdata.uniform("shadow_unit", i);
69 void ShadowMap::setup_frame() const
74 renderable.setup_frame();
77 const Vector4 &lpos = light.get_position();
81 /* XXX Not really proper way to support positional lights, but good
82 enough when the light source is far away */
83 back = Vector3(lpos)-target;
91 up = Vector3(0, 0, 1);
93 up = Vector3(0, 1, 0);
95 Vector3 right = normalize(cross(up, back));
98 columns[0] = Vector4(right, 0.0f);
99 columns[1] = Vector4(normalize(cross(back, right)), 0.0f);
100 columns[2] = Vector4(back, 0.0f);
101 columns[3] = Vector4(target, 1.0f);
102 light_matrix = Matrix::from_columns(columns);
103 view_matrix = invert(light_matrix);
105 MatrixStack::Push push_mv(MatrixStack::modelview());
106 MatrixStack::Push push_proj(MatrixStack::projection());
108 MatrixStack::projection() = Matrix::ortho(-radius, radius, -radius, radius, -radius, radius);
109 MatrixStack::modelview() = view_matrix;
111 Bind bind_fbo(fbo, true);
112 Bind bind_depth(DepthTest::lequal());
113 fbo.clear(DEPTH_BUFFER_BIT);
114 renderable.render("shadow");
117 void ShadowMap::finish_frame() const
119 renderable.finish_frame();
123 void ShadowMap::render(Renderer &renderer, const Tag &tag) const
125 if(!enabled_passes.count(tag))
126 return renderer.render(renderable, tag);
128 const float *matrix = view_matrix.data();
130 // Has side effect of changing the current unit
131 depth_buf.bind_to(unit);
132 float diam = radius*2;
133 TexGen tg_s, tg_t, tg_r;
134 tg_s.set_plane(Vector4(matrix[0]/diam, matrix[4]/diam, matrix[8]/diam, matrix[12]/diam+0.5f));
135 tg_t.set_plane(Vector4(matrix[1]/diam, matrix[5]/diam, matrix[9]/diam, matrix[13]/diam+0.5f));
136 tg_r.set_plane(Vector4(-matrix[2]/diam, -matrix[6]/diam, -matrix[10]/diam, 0.5f-matrix[14]/diam-depth_bias/size));
137 tg_s.bind_to(unit, SCOORD);
138 tg_t.bind_to(unit, TCOORD);
139 tg_r.bind_to(unit, RCOORD);
141 Renderer::Push _push_rend(renderer);
142 renderer.add_shader_data(shdata);
143 renderer.render(renderable, tag);
145 Texture::unbind_from(unit);
146 TexGen::unbind_from(unit, SCOORD);
147 TexGen::unbind_from(unit, TCOORD);
148 TexGen::unbind_from(unit, RCOORD);