15 WeakPtr<Sampler> ShadowMap::shadow_sampler;
17 ShadowMap::ShadowMap(unsigned s, Renderable &r, const Light &l):
25 sampler = shadow_sampler;
28 sampler = new Sampler;
29 sampler->set_filter(LINEAR);
30 sampler->set_compare(LEQUAL);
31 sampler->set_wrap(CLAMP_TO_EDGE);
32 shadow_sampler = sampler;
34 depth_buf.storage(DEPTH_COMPONENT32F, size, size, 1);
35 fbo.attach(DEPTH_ATTACHMENT, depth_buf, 0);
36 fbo.require_complete();
41 void ShadowMap::set_target(const Vector3 &t, float r)
47 void ShadowMap::set_darkness(float d)
50 throw invalid_argument("ShadowMap::set_darkness");
52 shdata.uniform("shadow_darkness", d);
55 void ShadowMap::set_depth_bias(float b)
58 throw invalid_argument("ShadowMap::set_depth_bias");
63 void ShadowMap::setup_frame(Renderer &renderer)
69 renderable.setup_frame(renderer);
72 camera.set_object_matrix(*light.get_matrix());
73 camera.set_position(target);
74 // TODO support point and spot lights with a frustum projection.
75 // Omnidirectional lights also need a cube shadow map.
76 camera.set_orthographic(radius*2, radius*2);
77 camera.set_depth_clip(-radius, radius);
79 shadow_matrix = camera.get_object_matrix();
80 shadow_matrix.scale(radius*2, radius*2, -radius*2);
81 shadow_matrix.translate(-0.5, -0.5, depth_bias/size-0.5);
82 shadow_matrix.invert();
84 BindRestore bind_fbo(fbo);
85 Bind bind_depth(DepthTest::lequal());
86 fbo.clear(DEPTH_BUFFER_BIT);
88 Renderer::Push push(renderer);
89 renderer.set_camera(camera);
91 renderer.render(renderable, "shadow");
94 void ShadowMap::finish_frame()
96 renderable.finish_frame();
100 void ShadowMap::render(Renderer &renderer, const Tag &tag) const
102 if(!enabled_passes.count(tag))
103 return renderer.render(renderable, tag);
105 Renderer::Push _push_rend(renderer);
107 unsigned unit = renderer.allocate_effect_texunit();
109 shdata.uniform("shadow_map", iunit);
111 Bind _bind_sampler(*sampler, unit);
112 Bind _bind_depth(depth_buf, unit);
114 if(const Camera *camera = renderer.get_camera())
115 /* Multiply by camera's object matrix to form a matrix that transforms
116 from eye space to shadow space. */
117 shdata.uniform("shd_eye_matrix", shadow_matrix*camera->get_object_matrix());
119 shdata.uniform("shd_eye_matrix", shadow_matrix);
121 renderer.add_shader_data(shdata);
122 renderer.render(renderable, tag);