]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Drop Id tags and copyright notices from files
[libs/gl.git] / source / program.cpp
1 #include <algorithm>
2 #include "arb_shader_objects.h"
3 #include "arb_vertex_shader.h"
4 #include "except.h"
5 #include "extension.h"
6 #include "program.h"
7 #include "shader.h"
8
9 using namespace std;
10
11 namespace {
12
13 const char *standard_vertex_src[] =
14 {
15         "n",   "attribute vec3 tangent;\n",
16         "n",   "attribute vec3 binormal;\n",
17         "t|n", "varying vec2 v_texcoord;\n",
18         "s",   "varying vec3 v_shadowcoord;\n",
19         "!lm", "varying vec4 v_color;\n",
20         "l!n", "varying vec3 v_normal;\n",
21         "l",   "varying vec3 v_light_dir;\n",
22         "p",   "varying vec3 v_eye_dir;\n",
23          0,    "void main()\n",
24          0,    "{\n",
25          0,    "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
26          0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
27         "l",   "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
28         "l!n", "\tv_normal = eye_normal;\n",
29         "n",   "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
30         "n",   "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
31         "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
32         "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
33         "l!n", "\tv_light_dir = eye_light_dir;\n",
34         "p",   "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
35         "pn",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
36         "p!n", "\tv_eye_dir = eye_dir;\n",
37         "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
38         "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[3], eye_pos), dot(gl_EyePlaneT[3], eye_pos), dot(gl_EyePlaneR[3], eye_pos));\n",
39         "!lm", "\tv_color = gl_Color;\n",
40          0,    "}",
41         0, 0
42 };
43
44 const char *standard_fragment_src[] =
45 {
46         "t",   "uniform sampler2D texture;\n",
47         "n",   "uniform sampler2D normalmap;\n",
48         "s",   "uniform sampler2DShadow shadow;\n",
49         "t|n", "varying vec2 v_texcoord;\n",
50         "s",   "varying vec3 v_shadowcoord;\n",
51         "!lm", "varying vec4 v_color;\n",
52         "l!n", "varying vec3 v_normal;\n",
53         "l",   "varying vec3 v_light_dir;\n",
54         "p",   "varying vec3 v_eye_dir;\n",
55          0,    "void main()\n",
56          0,    "{\n",
57         "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
58         "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
59         "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
60         "p",   "\tvec3 half = normalize(v_eye_dir+v_light_dir);\n",
61         "p",   "\tfloat l_specular = pow(max(dot(half, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
62         "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
63          0,    "\tgl_FragColor = ",
64         "!t!l!m", "vec4(1.0, 1.0, 1.0, 1.0)",
65         "t",     "texture2D(texture, v_texcoord)",
66         "l|mt",  "*",
67         "!lm",   "v_color",
68         "l",     "((l_diffuse",
69         "lm",    "*gl_FrontLightProduct[0].diffuse",
70         "p",     "+l_specular",
71         "pm",    "*gl_FrontLightProduct[0].specular",
72         "l",     ")",
73         "s",     "*l_shadow",
74         "lm",    "+gl_FrontLightModelProduct.sceneColor",
75         "l",     ")",
76          0,      ";\n",
77          0,    "}\n",
78         0, 0
79 };
80
81 }
82
83 namespace Msp {
84 namespace GL {
85
86 Program::Program():
87         del_shaders(false)
88 {
89         init();
90 }
91
92 Program::Program(const StandardFeatures &features):
93         del_shaders(true)
94 {
95         init();
96
97         add_standard_shaders(features);
98         link();
99 }
100
101 Program::Program(const string &vert, const string &frag):
102         del_shaders(true)
103 {
104         init();
105
106         attach_shader(*new Shader(VERTEX_SHADER, vert));
107         attach_shader(*new Shader(FRAGMENT_SHADER, frag));
108         link();
109 }
110
111 void Program::init()
112 {
113         static RequireExtension _ext("GL_ARB_shader_objects");
114
115         linked = false;
116         id = glCreateProgramObjectARB();
117 }
118
119 Program::~Program()
120 {
121         if(del_shaders)
122         {
123                 for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
124                         delete *i;
125         }
126         glDeleteObjectARB(id);
127 }
128
129 void Program::attach_shader(Shader &shader)
130 {
131         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
132         {
133                 glAttachObjectARB(id, shader.get_id());
134                 shaders.push_back(&shader);
135         }
136 }
137
138 void Program::detach_shader(Shader &shader)
139 {
140         list<Shader *>::iterator i = remove(shaders.begin(), shaders.end(), &shader);
141         if(i!=shaders.end())
142         {
143                 shaders.erase(i, shaders.end());
144                 glDetachObjectARB(id, shader.get_id());
145         }
146 }
147
148 void Program::add_standard_shaders(const StandardFeatures &features)
149 {
150         string flags = features.create_flags();
151         string vertex_src = process_standard_source(standard_vertex_src, flags);
152         string fragment_src = process_standard_source(standard_fragment_src, flags);
153         attach_shader(*new Shader(VERTEX_SHADER, vertex_src));
154         attach_shader(*new Shader(FRAGMENT_SHADER, fragment_src));
155 }
156
157 string Program::process_standard_source(const char **source, const string &flags)
158 {
159         string result;
160
161         for(unsigned i=0; source[i+1]; i+=2)
162         {
163                 if(source[i])
164                 {
165                         bool cond = true;
166                         char oper = '&';
167                         for(const char *c=source[i]; *c; ++c)
168                         {
169                                 if(*c>='a' && *c<='z')
170                                 {
171                                         bool found = (flags.find(*c)!=string::npos);
172                                         if(oper=='|')
173                                                 cond = (cond || found);
174                                         else if(oper=='!')
175                                                 cond = (cond && !found);
176                                         else if(oper=='&')
177                                                 cond = (cond && found);
178                                         oper = '&';
179                                 }
180                                 else
181                                         oper = *c;
182                         }
183
184                         if(!cond)
185                                 continue;
186                 }
187
188                 result += source[i+1];
189         }
190
191         return result;
192 }
193
194 void Program::set_del_shaders(bool ds)
195 {
196         del_shaders = ds;
197 }
198
199 void Program::bind_attribute(unsigned index, const string &name)
200 {
201         static RequireExtension _ext("GL_ARB_vertex_shader");
202         glBindAttribLocationARB(id, index, name.c_str());
203 }
204
205 void Program::link()
206 {
207         for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
208                 if(!(*i)->is_compiled())
209                         (*i)->compile();
210
211         uniforms.clear();
212
213         glLinkProgramARB(id);
214         int value;
215         glGetObjectParameterivARB(id, GL_OBJECT_LINK_STATUS_ARB, &value);
216         if(!(linked = value))
217                 throw CompileError(get_info_log());
218
219         glGetObjectParameterivARB(id, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &value);
220         for(int i=0; i<value; ++i)
221         {
222                 UniformInfo info;
223                 char name[128];
224                 int len = 0;
225                 glGetActiveUniformARB(id, i, 128, &len, &info.size, &info.type, name);
226                 if(len)
227                 {
228                         info.name = name;
229                         info.location = glGetUniformLocationARB(id, name);
230                         uniforms[name] = info;
231                 }
232         }
233 }
234
235 string Program::get_info_log() const
236 {
237         GLsizei len = 0;
238         glGetObjectParameterivARB(id, GL_OBJECT_INFO_LOG_LENGTH_ARB, &len);
239         char log[len+1];
240         glGetInfoLogARB(id, len+1, &len, log);
241         return string(log, len);
242 }
243
244 void Program::bind() const
245 {
246         if(!linked)
247                 throw InvalidState("Program is not linked");
248
249         if(!set_current(this))
250                 return;
251
252         glUseProgramObjectARB(id);
253 }
254
255 int Program::get_uniform_location(const string &n) const
256 {
257         map<string, UniformInfo>::const_iterator i = uniforms.find(n);
258         if(i==uniforms.end())
259                 return -1;
260
261         return i->second.location;
262 }
263
264 void Program::unbind()
265 {
266         if(!set_current(0))
267                 return;
268
269         glUseProgramObjectARB(0);
270 }
271
272
273 Program::StandardFeatures::StandardFeatures():
274         texture(false),
275         material(false),
276         lighting(false),
277         specular(false),
278         normalmap(false),
279         shadow(false)
280 { }
281
282 string Program::StandardFeatures::create_flags() const
283 {
284         string flags;
285         if(texture)
286                 flags += 't';
287         if(material)
288                 flags += 'm';
289         if(lighting)
290         {
291                 flags += 'l';
292                 if(specular)
293                         flags += 'p';
294                 if(normalmap)
295                         flags += 'n';
296         }
297         if(shadow)
298                 flags += 's';
299
300         return flags;
301 }
302
303
304 Program::Loader::Loader(Program &p):
305         DataFile::ObjectLoader<Program>(p)
306 {
307         obj.set_del_shaders(true);
308
309         add("attribute",       &Loader::attribute);
310         add("fragment_shader", &Loader::fragment_shader);
311         add("standard",        &Loader::standard);
312         add("vertex_shader",   &Loader::vertex_shader);
313 }
314
315 void Program::Loader::finish()
316 {
317         obj.link();
318 }
319
320 void Program::Loader::attribute(unsigned i, const string &n)
321 {
322         obj.bind_attribute(i, n);
323 }
324
325 void Program::Loader::fragment_shader(const string &src)
326 {
327         obj.attach_shader(*new Shader(FRAGMENT_SHADER, src));
328 }
329
330 void Program::Loader::standard()
331 {
332         StandardFeatures feat;
333         load_sub(feat);
334         obj.add_standard_shaders(feat);
335 }
336
337 void Program::Loader::vertex_shader(const string &src)
338 {
339         obj.attach_shader(*new Shader(VERTEX_SHADER, src));
340 }
341
342
343 Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
344         DataFile::ObjectLoader<StandardFeatures>(f)
345 {
346         add("lighting",  &StandardFeatures::lighting);
347         add("material",  &StandardFeatures::material);
348         add("normalmap", &StandardFeatures::normalmap);
349         add("shadow",    &StandardFeatures::shadow);
350         add("specular",  &StandardFeatures::specular);
351         add("texture",   &StandardFeatures::texture);
352 }
353
354 } // namespace GL
355 } // namespace Msp