]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Complete rewrite of extension handling
[libs/gl.git] / source / program.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <msp/core/hash.h>
4 #include <msp/core/maputils.h>
5 #include <msp/strings/format.h>
6 #include "arb_shader_objects.h"
7 #include "arb_uniform_buffer_object.h"
8 #include "arb_vertex_shader.h"
9 #include "buffer.h"
10 #include "error.h"
11 #include "program.h"
12 #include "shader.h"
13
14 using namespace std;
15
16 namespace {
17
18 const char *standard_vertex_src[] =
19 {
20         "n",   "attribute vec3 tangent;\n",
21         "n",   "attribute vec3 binormal;\n",
22         "t|n", "varying vec2 v_texcoord;\n",
23         "s",   "varying vec3 v_shadowcoord;\n",
24         "!lm", "varying vec4 v_color;\n",
25         "l!n", "varying vec3 v_normal;\n",
26         "l",   "varying vec3 v_light_dir;\n",
27         "p|e", "varying vec3 v_eye_dir;\n",
28         "r",   "vec4 transform_vertex(vec4);\n",
29         "lr",  "vec3 transform_normal(vec3);\n",
30          0,    "void main()\n",
31          0,    "{\n",
32         "r",   "\tvec4 eye_pos = transform_vertex(gl_Vertex);\n",
33         "!r",  "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
34          0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
35         "lr",  "\tvec3 eye_normal = transform_normal(gl_Normal);\n",
36         "l!r", "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
37         "l!n", "\tv_normal = eye_normal;\n",
38         "nr",  "\tvec3 eye_tangent = transform_normal(tangent);\n",
39         "n!r", "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
40         "nr",  "\tvec3 eye_binormal = transform_normal(binormal);\n",
41         "n!r", "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
42         "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
43         "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
44         "l!n", "\tv_light_dir = eye_light_dir;\n",
45         "p|e", "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
46         "p|en",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
47         "p|e!n", "\tv_eye_dir = eye_dir;\n",
48         "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
49         "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[3], eye_pos), dot(gl_EyePlaneT[3], eye_pos), dot(gl_EyePlaneR[3], eye_pos));\n",
50         "!lm", "\tv_color = gl_Color;\n",
51          0,    "}",
52         0, 0
53 };
54
55 const char *standard_fragment_src[] =
56 {
57         "t",   "uniform sampler2D texture;\n",
58         "n",   "uniform sampler2D normalmap;\n",
59         "s",   "uniform sampler2DShadow shadow;\n",
60         "e",   "uniform samplerCube environment;\n",
61         "e",   "uniform float reflectivity;\n",
62         "t|n", "varying vec2 v_texcoord;\n",
63         "s",   "varying vec3 v_shadowcoord;\n",
64         "!lm", "varying vec4 v_color;\n",
65         "l!n", "varying vec3 v_normal;\n",
66         "l",   "varying vec3 v_light_dir;\n",
67         "p|e", "varying vec3 v_eye_dir;\n",
68          0,    "void main()\n",
69          0,    "{\n",
70         "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
71         "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
72         "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
73         "p",   "\tvec3 half_dir = normalize(v_eye_dir+v_light_dir);\n",
74         "p",   "\tfloat l_specular = pow(max(dot(half_dir, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
75         "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
76         /* XXX This is incorrect with normal mapping, since the vectors are in TBN
77         space but environment map is expected to be in eye space */
78         "e",   "\tvec4 reflection = textureCube(environment, n_normal*(dot(n_normal, v_eye_dir)*2.0)-v_eye_dir);\n",
79         "t",   "\tvec4 tex_sample = texture2D(texture, v_texcoord);\n",
80          0,    "\tgl_FragColor.rgb = ",
81         "!t!l!m", "vec3(1.0)",
82         "t",     "tex_sample.rgb",
83         "l|mt",  "*",
84         "!lm",   "v_color.rgb",
85         "l",     "((l_diffuse",
86         "lm",    "*gl_FrontLightProduct[0].diffuse.rgb",
87         "p",     "+l_specular",
88         "pm",    "*gl_FrontLightProduct[0].specular.rgb",
89         "l",     ")",
90         "s",     "*l_shadow",
91         "lm",    "+gl_FrontLightModelProduct.sceneColor.rgb",
92         "l",     ")",
93         "e",     "+reflection.rgb*reflectivity",
94          0,      ";\n",
95          0,    "\tgl_FragColor.a = ",
96         "!m",    "1.0",
97         "!lm",   "v_color.a",
98         "lm",    "gl_FrontMaterial.diffuse.a",
99         "t",     "*tex_sample.a",
100          0,      ";\n",
101          0,    "}\n",
102         0, 0
103 };
104
105 }
106
107 namespace Msp {
108 namespace GL {
109
110 Program::Program()
111 {
112         init();
113 }
114
115 Program::Program(const StandardFeatures &features)
116 {
117         init();
118
119         add_standard_shaders(features);
120         if(!features.transform)
121                 link();
122 }
123
124 Program::Program(const string &vert, const string &frag)
125 {
126         init();
127
128         attach_shader_owned(new Shader(VERTEX_SHADER, vert));
129         attach_shader_owned(new Shader(FRAGMENT_SHADER, frag));
130         link();
131 }
132
133 void Program::init()
134 {
135         static Require _req(ARB_shader_objects);
136
137         linked = false;
138         id = glCreateProgram();
139 }
140
141 Program::~Program()
142 {
143         for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
144                 delete *i;
145         glDeleteProgram(id);
146 }
147
148 void Program::attach_shader(Shader &shader)
149 {
150         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
151         {
152                 glAttachShader(id, shader.get_id());
153                 shaders.push_back(&shader);
154         }
155 }
156
157 void Program::attach_shader_owned(Shader *shader)
158 {
159         attach_shader(*shader);
160         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
161                 owned_data.push_back(shader);
162 }
163
164 void Program::detach_shader(Shader &shader)
165 {
166         ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
167         if(i!=shaders.end())
168         {
169                 shaders.erase(i, shaders.end());
170                 glDetachShader(id, shader.get_id());
171         }
172 }
173
174 void Program::add_standard_shaders(const StandardFeatures &features)
175 {
176         string flags = features.create_flags();
177         string vertex_src = process_standard_source(standard_vertex_src, flags);
178         string fragment_src = process_standard_source(standard_fragment_src, flags);
179         attach_shader_owned(new Shader(VERTEX_SHADER, vertex_src));
180         attach_shader_owned(new Shader(FRAGMENT_SHADER, fragment_src));
181 }
182
183 string Program::process_standard_source(const char **source, const string &flags)
184 {
185         string result;
186
187         for(unsigned i=0; source[i+1]; i+=2)
188         {
189                 if(source[i])
190                 {
191                         bool cond = true;
192                         char oper = '&';
193                         for(const char *c=source[i]; *c; ++c)
194                         {
195                                 if(*c>='a' && *c<='z')
196                                 {
197                                         bool found = (flags.find(*c)!=string::npos);
198                                         if(oper=='|')
199                                                 cond = (cond || found);
200                                         else if(oper=='!')
201                                                 cond = (cond && !found);
202                                         else if(oper=='&')
203                                                 cond = (cond && found);
204                                         oper = '&';
205                                 }
206                                 else
207                                         oper = *c;
208                         }
209
210                         if(!cond)
211                                 continue;
212                 }
213
214                 result += source[i+1];
215         }
216
217         return result;
218 }
219
220 void Program::bind_attribute(unsigned index, const string &name)
221 {
222         static Require _req(ARB_vertex_shader);
223         glBindAttribLocation(id, index, name.c_str());
224 }
225
226 void Program::link()
227 {
228         for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
229                 if(!(*i)->is_compiled())
230                         (*i)->compile();
231
232         uniforms.clear();
233
234         glLinkProgram(id);
235         int value;
236         glGetProgramiv(id, GL_LINK_STATUS, &value);
237         if(!(linked = value))
238                 throw compile_error(get_info_log());
239
240         glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &value);
241         unsigned count = value;
242         vector<UniformInfo *> uniforms_by_index(count);
243         for(unsigned i=0; i<count; ++i)
244         {
245                 char name[128];
246                 int len = 0;
247                 int size;
248                 GLenum type;
249                 glGetActiveUniform(id, i, 128, &len, &size, &type, name);
250                 if(len && strncmp(name, "gl_", 3))
251                 {
252                         UniformInfo &info = uniforms[name];
253                         info.block = 0;
254                         info.name = name;
255                         info.size = size;
256                         info.array_stride = 0;
257                         info.matrix_stride = 0;
258                         info.type = type;
259                         uniforms_by_index[i] = &info;
260                 }
261         }
262
263         if(ARB_uniform_buffer_object)
264         {
265                 glGetProgramiv(id, GL_ACTIVE_UNIFORM_BLOCKS, &value);
266                 count = value;
267                 for(unsigned i=0; i<count; ++i)
268                 {
269                         char name[128];
270                         int len;
271                         glGetActiveUniformBlockName(id, i, 128, &len, name);
272                         UniformBlockInfo &info = uniform_blocks[name];
273                         info.name = name;
274
275                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
276                         info.data_size = value;
277
278                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
279                         vector<int> indices(value);
280                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
281                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
282                         {
283                                 if(!uniforms_by_index[*j])
284                                         throw logic_error("Program::link");
285                                 info.uniforms.push_back(uniforms_by_index[*j]);
286                                 uniforms_by_index[*j]->block = &info;
287                         }
288
289                         vector<unsigned> indices2(indices.begin(), indices.end());
290                         vector<int> values(indices.size());
291                         glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
292                         for(unsigned j=0; j<indices.size(); ++j)
293                                 uniforms_by_index[indices[j]]->location = values[j];
294
295                         indices2.clear();
296                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
297                                 if(uniforms_by_index[*j]->size>1)
298                                         indices2.push_back(*j);
299                         if(!indices2.empty())
300                         {
301                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
302                                 for(unsigned j=0; j<indices2.size(); ++j)
303                                         uniforms_by_index[indices[j]]->array_stride = values[j];
304                         }
305
306                         indices2.clear();
307                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
308                         {
309                                 GLenum t = uniforms_by_index[*j]->type;
310                                 if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
311                                         t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
312                                         t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
313                                         indices2.push_back(*j);
314                         }
315                         if(!indices2.empty())
316                         {
317                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
318                                 for(unsigned j=0; j<indices2.size(); ++j)
319                                         uniforms_by_index[indices[j]]->matrix_stride = values[j];
320                         }
321
322                         sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
323                         info.layout_hash = compute_layout_hash(info.uniforms);
324                         info.bind_point = info.layout_hash%BufferRange::get_n_uniform_buffer_bindings();
325                         glUniformBlockBinding(id, i, info.bind_point);
326                 }
327         }
328
329         vector<const UniformInfo *> blockless_uniforms;
330         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
331                 if(!i->second.block)
332                 {
333                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
334                         blockless_uniforms.push_back(&i->second);
335                 }
336
337         uniform_layout_hash = compute_layout_hash(blockless_uniforms);
338 }
339
340 unsigned Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
341 {
342         string layout_descriptor;
343         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
344                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
345         return hash32(layout_descriptor);
346 }
347
348 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
349 {
350         return uni1->location<uni2->location;
351 }
352
353 string Program::get_info_log() const
354 {
355         GLsizei len = 0;
356         glGetProgramiv(id, GL_INFO_LOG_LENGTH, &len);
357         char *buf = new char[len+1];
358         glGetProgramInfoLog(id, len+1, &len, buf);
359         string log(buf, len);
360         delete[] buf;
361         return log;
362 }
363
364 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
365 {
366         return get_item(uniform_blocks, name);
367 }
368
369 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
370 {
371         return get_item(uniforms, name);
372 }
373
374 int Program::get_uniform_location(const string &n) const
375 {
376         UniformMap::const_iterator i = uniforms.find(n);
377         if(i==uniforms.end())
378         {
379                 if(n[n.size()-1]==']')
380                 {
381                         string::size_type open_bracket = n.rfind('[');
382                         if(open_bracket!=string::npos)
383                         {
384                                 /* The requested name looks like an array.  glGetActiveUniform only
385                                 gives us the first element of the array, so try to look that up and
386                                 add an offset. */
387                                 unsigned offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
388                                 i = uniforms.find(n.substr(0, open_bracket)+"[0]");
389                                 if(i!=uniforms.end() && !i->second.block && offset<i->second.size)
390                                         return i->second.location+offset;
391                         }
392                 }
393                 return -1;
394         }
395
396         return i->second.block ? -1 : i->second.location;
397 }
398
399 void Program::bind() const
400 {
401         if(!linked)
402                 throw invalid_operation("Program::bind");
403
404         if(!set_current(this))
405                 return;
406
407         glUseProgram(id);
408 }
409
410 void Program::unbind()
411 {
412         if(!set_current(0))
413                 return;
414
415         glUseProgram(0);
416 }
417
418
419 Program::StandardFeatures::StandardFeatures():
420         texture(false),
421         material(false),
422         lighting(false),
423         specular(false),
424         normalmap(false),
425         shadow(false),
426         reflection(false),
427         transform(false)
428 { }
429
430 string Program::StandardFeatures::create_flags() const
431 {
432         string flags;
433         if(texture)
434                 flags += 't';
435         if(material)
436                 flags += 'm';
437         if(lighting)
438         {
439                 flags += 'l';
440                 if(specular)
441                         flags += 'p';
442                 if(normalmap)
443                         flags += 'n';
444         }
445         if(shadow)
446                 flags += 's';
447         if(reflection)
448                 flags += 'e';
449         if(transform)
450                 flags += 'r';
451
452         return flags;
453 }
454
455
456 Program::Loader::Loader(Program &p):
457         DataFile::ObjectLoader<Program>(p)
458 {
459         add("attribute",       &Loader::attribute);
460         add("fragment_shader", &Loader::fragment_shader);
461         add("standard",        &Loader::standard);
462         add("vertex_shader",   &Loader::vertex_shader);
463 }
464
465 void Program::Loader::finish()
466 {
467         obj.link();
468 }
469
470 void Program::Loader::attribute(unsigned i, const string &n)
471 {
472         obj.bind_attribute(i, n);
473 }
474
475 void Program::Loader::fragment_shader(const string &src)
476 {
477         obj.attach_shader_owned(new Shader(FRAGMENT_SHADER, src));
478 }
479
480 void Program::Loader::standard()
481 {
482         StandardFeatures feat;
483         load_sub(feat);
484         obj.add_standard_shaders(feat);
485 }
486
487 void Program::Loader::vertex_shader(const string &src)
488 {
489         obj.attach_shader_owned(new Shader(VERTEX_SHADER, src));
490 }
491
492
493 Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
494         DataFile::ObjectLoader<StandardFeatures>(f)
495 {
496         add("lighting",  &StandardFeatures::lighting);
497         add("material",  &StandardFeatures::material);
498         add("normalmap", &StandardFeatures::normalmap);
499         add("shadow",    &StandardFeatures::shadow);
500         add("specular",  &StandardFeatures::specular);
501         add("texture",   &StandardFeatures::texture);
502         add("transform", &StandardFeatures::transform);
503 }
504
505 } // namespace GL
506 } // namespace Msp