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