]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Remove the deprecated ProgramBuilder class
[libs/gl.git] / source / program.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <set>
4 #include <msp/core/hash.h>
5 #include <msp/core/maputils.h>
6 #include <msp/gl/extensions/arb_shader_objects.h>
7 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
8 #include <msp/gl/extensions/arb_vertex_shader.h>
9 #include <msp/gl/extensions/ext_gpu_shader4.h>
10 #include <msp/gl/extensions/nv_non_square_matrices.h>
11 #include <msp/io/print.h>
12 #include <msp/strings/format.h>
13 #include "buffer.h"
14 #include "error.h"
15 #include "misc.h"
16 #include "program.h"
17 #include "programcompiler.h"
18 #include "resources.h"
19 #include "shader.h"
20
21 using namespace std;
22
23 namespace Msp {
24 namespace GL {
25
26 Program::Program()
27 {
28         init();
29 }
30
31 Program::Program(const std::string &source)
32 {
33         init();
34
35         ProgramCompiler compiler;
36         if(source.find(';')==string::npos && source.size()>5 && !source.compare(source.size()-5, 5, ".glsl"))
37         {
38                 if(RefPtr<IO::Seekable> io = Resources::get_builtins().open(source))
39                         compiler.compile(*io, source);
40                 else
41                         throw IO::file_not_found(source);
42         }
43         else
44                 compiler.compile(source);
45         compiler.add_shaders(*this);
46         link();
47 }
48
49 Program::Program(const string &vert, const string &frag)
50 {
51         init();
52
53         attach_shader_owned(new VertexShader(vert));
54         attach_shader_owned(new FragmentShader(frag));
55         link();
56 }
57
58 void Program::init()
59 {
60         static Require _req(ARB_shader_objects);
61
62         linked = false;
63         id = glCreateProgram();
64 }
65
66 Program::~Program()
67 {
68         for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
69                 delete *i;
70         glDeleteProgram(id);
71 }
72
73 void Program::attach_shader(Shader &shader)
74 {
75         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
76         {
77                 glAttachShader(id, shader.get_id());
78                 shaders.push_back(&shader);
79         }
80 }
81
82 void Program::attach_shader_owned(Shader *shader)
83 {
84         attach_shader(*shader);
85         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
86                 owned_data.push_back(shader);
87 }
88
89 void Program::detach_shader(Shader &shader)
90 {
91         ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
92         if(i!=shaders.end())
93         {
94                 shaders.erase(i, shaders.end());
95                 glDetachShader(id, shader.get_id());
96         }
97 }
98
99 void Program::bind_attribute(unsigned index, const string &name)
100 {
101         static Require _req(ARB_vertex_shader);
102         glBindAttribLocation(id, index, name.c_str());
103 }
104
105 void Program::bind_attribute(VertexComponent comp, const string &name)
106 {
107         bind_attribute(get_component_type(comp), name);
108 }
109
110 void Program::bind_fragment_data(unsigned index, const string &name)
111 {
112         static Require _req(EXT_gpu_shader4);
113         glBindFragDataLocation(id, index, name.c_str());
114 }
115
116 void Program::link()
117 {
118         for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
119                 if(!(*i)->is_compiled())
120                         (*i)->compile();
121
122         uniforms.clear();
123
124         glLinkProgram(id);
125         linked = get_program_i(id, GL_LINK_STATUS);
126         if(!linked)
127                 throw compile_error(get_info_log());
128
129 #ifdef DEBUG
130         std::string info_log = get_info_log();
131         if(!info_log.empty())
132                 IO::print("Program link info log:\n%s", info_log);
133 #endif
134
135         query_uniforms();
136         query_attributes();
137
138         for(UniformMap::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
139                 require_type(i->second.type);
140         for(AttributeMap::const_iterator i=attributes.begin(); i!=attributes.end(); ++i)
141                 require_type(i->second.type);
142 }
143
144 void Program::require_type(GLenum t)
145 {
146         switch(t)
147         {
148         case GL_FLOAT_MAT2x3:
149         case GL_FLOAT_MAT2x4:
150         case GL_FLOAT_MAT3x2:
151         case GL_FLOAT_MAT3x4:
152         case GL_FLOAT_MAT4x2:
153         case GL_FLOAT_MAT4x3:
154                 { static Require _req(NV_non_square_matrices); }
155                 break;
156         }
157 }
158
159 void Program::query_uniforms()
160 {
161         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
162         vector<UniformInfo *> uniforms_by_index(count);
163         for(unsigned i=0; i<count; ++i)
164         {
165                 char name[128];
166                 int len = 0;
167                 int size;
168                 GLenum type;
169                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
170                 if(len && strncmp(name, "gl_", 3))
171                 {
172                         /* Some implementations report the first element of a uniform array,
173                         others report just the name of the array itself. */
174                         if(len>3 && !strcmp(name+len-3, "[0]"))
175                                 name[len-3] = 0;
176
177                         UniformInfo &info = uniforms[name];
178                         info.block = 0;
179                         info.name = name;
180                         info.size = size;
181                         info.array_stride = 0;
182                         info.matrix_stride = 0;
183                         info.type = type;
184                         uniforms_by_index[i] = &info;
185                 }
186         }
187
188         if(ARB_uniform_buffer_object)
189                 query_uniform_blocks(uniforms_by_index);
190
191         UniformBlockInfo &default_block = uniform_blocks[string()];
192         default_block.data_size = 0;
193         default_block.bind_point = -1;
194
195         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
196                 if(!i->second.block)
197                 {
198                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
199                         i->second.block = &default_block;
200                         default_block.uniforms.push_back(&i->second);
201                 }
202
203         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
204
205         string layout_descriptor;
206         for(UniformBlockMap::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
207                 layout_descriptor += format("%d:%x\n", i->second.bind_point, i->second.layout_hash);
208         uniform_layout_hash = hash32(layout_descriptor);
209 }
210
211 void Program::query_uniform_blocks(const vector<UniformInfo *> &uniforms_by_index)
212 {
213         uniform_blocks.clear();
214
215         std::set<unsigned> used_bind_points;
216         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
217         for(unsigned i=0; i<count; ++i)
218         {
219                 char name[128];
220                 int len;
221                 glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
222                 UniformBlockInfo &info = uniform_blocks[name];
223                 info.name = name;
224
225                 int value;
226                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
227                 info.data_size = value;
228
229                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
230                 vector<int> indices(value);
231                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
232                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
233                 {
234                         if(!uniforms_by_index[*j])
235                                 throw logic_error("Program::link");
236                         info.uniforms.push_back(uniforms_by_index[*j]);
237                         uniforms_by_index[*j]->block = &info;
238                 }
239
240                 vector<unsigned> indices2(indices.begin(), indices.end());
241                 vector<int> values(indices.size());
242                 glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
243                 for(unsigned j=0; j<indices.size(); ++j)
244                         uniforms_by_index[indices[j]]->location = values[j];
245
246                 indices2.clear();
247                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
248                         if(uniforms_by_index[*j]->size>1)
249                                 indices2.push_back(*j);
250                 if(!indices2.empty())
251                 {
252                         glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
253                         for(unsigned j=0; j<indices2.size(); ++j)
254                                 uniforms_by_index[indices2[j]]->array_stride = values[j];
255                 }
256
257                 indices2.clear();
258                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
259                 {
260                         GLenum t = uniforms_by_index[*j]->type;
261                         if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
262                                 t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
263                                 t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
264                                 indices2.push_back(*j);
265                 }
266                 if(!indices2.empty())
267                 {
268                         glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
269                         for(unsigned j=0; j<indices2.size(); ++j)
270                                 uniforms_by_index[indices2[j]]->matrix_stride = values[j];
271                 }
272
273                 sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
274                 info.layout_hash = compute_layout_hash(info.uniforms);
275                 unsigned n_bindings = BufferRange::get_n_uniform_buffer_bindings();
276                 info.bind_point = info.layout_hash%n_bindings;
277                 while(used_bind_points.count(info.bind_point))
278                         info.bind_point = (info.bind_point+1)%n_bindings;
279                 glUniformBlockBinding(id, i, info.bind_point);
280                 used_bind_points.insert(info.bind_point);
281         }
282 }
283
284 void Program::query_attributes()
285 {
286         unsigned count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
287         for(unsigned i=0; i<count; ++i)
288         {
289                 char name[128];
290                 int len = 0;
291                 int size;
292                 GLenum type;
293                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
294                 if(len && strncmp(name, "gl_", 3))
295                 {
296                         if(len>3 && !strcmp(name+len-3, "[0]"))
297                                 name[len-3] = 0;
298
299                         AttributeInfo &info = attributes[name];
300                         info.name = name;
301                         info.location = glGetAttribLocation(id, name);
302                         info.size = size;
303                         info.type = type;
304                 }
305         }
306 }
307
308 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
309 {
310         string layout_descriptor;
311         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
312                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
313         return hash32(layout_descriptor);
314 }
315
316 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
317 {
318         return uni1->location<uni2->location;
319 }
320
321 string Program::get_info_log() const
322 {
323         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
324         string log(len+1, 0);
325         glGetProgramInfoLog(id, len+1, &len, &log[0]);
326         log.erase(len);
327         return log;
328 }
329
330 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
331 {
332         return get_item(uniform_blocks, name);
333 }
334
335 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
336 {
337         return get_item(uniforms, name);
338 }
339
340 int Program::get_uniform_location(const string &n) const
341 {
342         if(n[n.size()-1]==']')
343                 throw invalid_argument("Program::get_uniform_location");
344
345         UniformMap::const_iterator i = uniforms.find(n);
346         if(i==uniforms.end())
347                 return -1;
348
349         return i->second.block->bind_point<0 ? i->second.location : -1;
350 }
351
352 const Program::AttributeInfo &Program::get_attribute_info(const string &name) const
353 {
354         return get_item(attributes, name);
355 }
356
357 int Program::get_attribute_location(const string &n) const
358 {
359         if(n[n.size()-1]==']')
360                 throw invalid_argument("Program::get_attribute_location");
361
362         AttributeMap::const_iterator i = attributes.find(n);
363         return i!=attributes.end() ? i->second.location : -1;
364 }
365
366 void Program::bind() const
367 {
368         if(!linked)
369                 throw invalid_operation("Program::bind");
370
371         if(!set_current(this))
372                 return;
373
374         glUseProgram(id);
375 }
376
377 void Program::unbind()
378 {
379         if(!set_current(0))
380                 return;
381
382         glUseProgram(0);
383 }
384
385
386 Program::Loader::Loader(Program &p):
387         DataFile::ObjectLoader<Program>(p)
388 {
389         add("attribute",       &Loader::attribute);
390         add("fragment_shader", &Loader::fragment_shader);
391         add("geometry_shader", &Loader::geometry_shader);
392         add("vertex_shader",   &Loader::vertex_shader);
393 }
394
395 void Program::Loader::finish()
396 {
397         obj.link();
398 }
399
400 void Program::Loader::attribute(unsigned i, const string &n)
401 {
402         obj.bind_attribute(i, n);
403 }
404
405 void Program::Loader::fragment_shader(const string &src)
406 {
407         obj.attach_shader_owned(new FragmentShader(src));
408 }
409
410 void Program::Loader::geometry_shader(const string &src)
411 {
412         obj.attach_shader_owned(new GeometryShader(src));
413 }
414
415 void Program::Loader::vertex_shader(const string &src)
416 {
417         obj.attach_shader_owned(new VertexShader(src));
418 }
419
420 } // namespace GL
421 } // namespace Msp