]> git.tdb.fi Git - libs/gl.git/blob - source/lighting.cpp
Only check against number of light units when binding Lighting
[libs/gl.git] / source / lighting.cpp
1 #include <stdexcept>
2 #include "error.h"
3 #include "light.h"
4 #include "lighting.h"
5 #include "lightunit.h"
6 #include "matrix.h"
7 #include "misc.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13
14 Lighting::Lighting():
15         ambient(0.2),
16         sky_direction(0, 0, 1),
17         horizon_angle(Geometry::Angle<float>::zero())
18 { }
19
20 void Lighting::set_ambient(const Color &a)
21 {
22         ambient = a;
23 }
24
25 void Lighting::set_sky_color(const Color &s)
26 {
27         sky_color = s;
28 }
29
30 void Lighting::set_sky_direction(const Vector3 &d)
31 {
32         sky_direction = d;
33 }
34
35 void Lighting::set_horizon_angle(const Geometry::Angle<float> &a)
36 {
37         horizon_angle = a;
38 }
39
40 void Lighting::attach(unsigned i, const Light &l)
41 {
42         if(i>=lights.size())
43                 lights.resize(i+1);
44
45         lights[i] = &l;
46         if(current()==this)
47                 l.bind_to(i);
48 }
49
50 void Lighting::detach(unsigned i)
51 {
52         if(i>=lights.size())
53                 return;
54
55         lights[i] = 0;
56         if(current()==this)
57                 Light::unbind_from(i);
58 }
59
60 void Lighting::update_shader_data(ProgramData &shdata, const Matrix &view_matrix) const
61 {
62         shdata.uniform("ambient_color", ambient);
63         shdata.uniform("sky_color", sky_color);
64         shdata.uniform("eye_sky_dir", Vector3(view_matrix*Vector4(sky_direction, 0.0f)));
65         shdata.uniform("horizon_limit", horizon_angle.radians());
66
67         for(unsigned i=0; i<lights.size(); ++i)
68                 if(lights[i])
69                         lights[i]->update_shader_data(shdata, view_matrix, i);
70 }
71
72 void Lighting::bind() const
73 {
74         if(lights.size()>LightUnit::get_n_units())
75                 throw invalid_operation("Lighting::bind");
76
77         if(!set_current(this))
78                 return;
79
80         enable(GL_LIGHTING);
81         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &ambient.r);
82         for(unsigned i=0; i<lights.size(); ++i)
83                 if(lights[i])
84                         lights[i]->bind_to(i);
85 }
86
87 void Lighting::unbind()
88 {
89         const Lighting *old = current();
90         if(!set_current(0))
91                 return;
92
93         for(unsigned i=0; i<old->lights.size(); ++i)
94                 if(old->lights[i])
95                         Light::unbind_from(i);
96
97         disable(GL_LIGHTING);
98 }
99
100 } // namespace GL
101 } // namespace Msp