]> git.tdb.fi Git - libs/gl.git/blob - source/core/program.cpp
33c53cd7755fe4f0e4d7b1bd293c2f6af30c8748
[libs/gl.git] / source / core / program.cpp
1 #include <cstring>
2 #include <set>
3 #include <msp/core/algorithm.h>
4 #include <msp/core/hash.h>
5 #include <msp/core/maputils.h>
6 #include <msp/core/raii.h>
7 #include <msp/gl/extensions/arb_es2_compatibility.h>
8 #include <msp/gl/extensions/arb_fragment_shader.h>
9 #include <msp/gl/extensions/arb_gl_spirv.h>
10 #include <msp/gl/extensions/arb_geometry_shader4.h>
11 #include <msp/gl/extensions/arb_separate_shader_objects.h>
12 #include <msp/gl/extensions/arb_shader_objects.h>
13 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
14 #include <msp/gl/extensions/arb_vertex_shader.h>
15 #include <msp/gl/extensions/ext_gpu_shader4.h>
16 #include <msp/gl/extensions/khr_debug.h>
17 #include <msp/gl/extensions/nv_non_square_matrices.h>
18 #include <msp/io/print.h>
19 #include <msp/strings/format.h>
20 #include "buffer.h"
21 #include "error.h"
22 #include "misc.h"
23 #include "program.h"
24 #include "resources.h"
25 #include "shader.h"
26 #include "glsl/compiler.h"
27
28 using namespace std;
29
30 namespace Msp {
31 namespace GL {
32
33 Program::Program()
34 {
35         init();
36 }
37
38 Program::Program(const string &source)
39 {
40         init();
41
42         GlslModule mod;
43         mod.set_source(source);
44         add_stages(mod);
45
46         link();
47         module = 0;
48 }
49
50 Program::Program(const string &vert, const string &frag)
51 {
52         init();
53
54 #pragma GCC diagnostic push
55 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
56         attach_shader_owned(new VertexShader(vert));
57         attach_shader_owned(new FragmentShader(frag));
58 #pragma GCC diagnostic pop
59         link();
60 }
61
62 Program::Program(const Module &mod, const map<string, int> &spec_values)
63 {
64         init();
65         add_stages(mod, spec_values);
66         link();
67 }
68
69 void Program::init()
70 {
71         static Require _req(ARB_shader_objects);
72
73         id = glCreateProgram();
74         fill(stage_ids, stage_ids+MAX_STAGES, 0);
75         module = 0;
76         transient = 0;
77         linked = false;
78 }
79
80 Program::~Program()
81 {
82         for(unsigned i=0; i<MAX_STAGES; ++i)
83                 if(stage_ids[i])
84                         glDeleteShader(stage_ids[i]);
85         glDeleteProgram(id);
86 }
87
88 void Program::add_stages(const Module &mod, const map<string, int> &spec_values)
89 {
90         if(has_stages())
91                 throw invalid_operation("Program::add_stages");
92
93         switch(mod.get_format())
94         {
95         case Module::GLSL: return add_glsl_stages(static_cast<const GlslModule &>(mod), spec_values);
96         case Module::SPIR_V: return add_spirv_stages(static_cast<const SpirVModule &>(mod), spec_values);
97         default: throw invalid_argument("Program::add_stages");
98         }
99 }
100
101 bool Program::has_stages() const
102 {
103         for(unsigned i=0; i<MAX_STAGES; ++i)
104                 if(stage_ids[i])
105                         return true;
106         return false;
107 }
108
109 unsigned Program::add_stage(Stage type)
110 {
111         GLenum gl_type;
112         switch(type)
113         {
114         case VERTEX: { static Require _req(ARB_vertex_shader); gl_type = GL_VERTEX_SHADER; } break;
115         case GEOMETRY: { static Require _req(ARB_geometry_shader4); gl_type = GL_GEOMETRY_SHADER; } break;
116         case FRAGMENT: { static Require _req(ARB_fragment_shader); gl_type = GL_FRAGMENT_SHADER; } break;
117         default: throw invalid_argument("Program::add_stage");
118         }
119
120         if(stage_ids[type])
121                 throw invalid_operation("Program::add_stage");
122
123         unsigned stage_id = glCreateShader(gl_type);
124         stage_ids[type] = stage_id;
125         glAttachShader(id, stage_id);
126
127 #ifdef DEBUG
128         if(!debug_name.empty() && KHR_debug)
129                 set_stage_debug_name(stage_id, type);
130 #endif
131
132         return stage_id;
133 }
134
135 void Program::add_glsl_stages(const GlslModule &mod, const map<string, int> &spec_values)
136 {
137         module = &mod;
138
139         SL::Compiler compiler;
140         compiler.set_source(mod.get_prepared_source(), "<module>");
141         compiler.specialize(spec_values);
142         compiler.compile(SL::Compiler::PROGRAM);
143 #ifdef DEBUG
144         string diagnostics = compiler.get_diagnostics();
145         if(!diagnostics.empty())
146                 IO::print("Program diagnostics:\n%s\n", diagnostics);
147 #endif
148
149         vector<SL::Stage::Type> stages = compiler.get_stages();
150         for(vector<SL::Stage::Type>::const_iterator i=stages.begin(); i!=stages.end(); ++i)
151         {
152                 unsigned stage_id = 0;
153                 switch(*i)
154                 {
155                 case SL::Stage::VERTEX: stage_id = add_stage(VERTEX); break;
156                 case SL::Stage::GEOMETRY: stage_id = add_stage(GEOMETRY); break;
157                 case SL::Stage::FRAGMENT: stage_id = add_stage(FRAGMENT); break;
158                 default: throw invalid_operation("Program::add_glsl_stages");
159                 }
160
161                 string stage_src = compiler.get_stage_glsl(*i);
162                 const char *src_ptr = stage_src.data();
163                 int src_len = stage_src.size();
164                 glShaderSource(stage_id, 1, &src_ptr, &src_len);
165
166                 if(*i==SL::Stage::VERTEX)
167                 {
168                         const map<string, unsigned> &attribs = compiler.get_vertex_attributes();
169                         for(map<string, unsigned>::const_iterator j=attribs.begin(); j!=attribs.end(); ++j)
170                                 glBindAttribLocation(id, j->second, j->first.c_str());
171                 }
172
173                 if(*i==SL::Stage::FRAGMENT && EXT_gpu_shader4)
174                 {
175                         const map<string, unsigned> &frag_outs = compiler.get_fragment_outputs();
176                         for(map<string, unsigned>::const_iterator j=frag_outs.begin(); j!=frag_outs.end(); ++j)
177                                 glBindFragDataLocation(id, j->second, j->first.c_str());
178                 }
179
180                 compile_glsl_stage(stage_id);
181         }
182
183         if(!transient)
184                 transient = new TransientData;
185         transient->textures = compiler.get_texture_bindings();
186         transient->blocks = compiler.get_uniform_block_bindings();
187 }
188
189 void Program::compile_glsl_stage(unsigned stage_id)
190 {
191         glCompileShader(stage_id);
192         bool compiled = get_shader_i(stage_id, GL_COMPILE_STATUS);
193
194         GLsizei info_log_len = get_shader_i(stage_id, GL_INFO_LOG_LENGTH);
195         string info_log(info_log_len+1, 0);
196         glGetShaderInfoLog(stage_id, info_log_len+1, &info_log_len, &info_log[0]);
197         info_log.erase(info_log_len);
198         if(module && module->get_format()==Module::GLSL)
199                 info_log = static_cast<const GlslModule *>(module)->get_source_map().translate_errors(info_log);
200
201         if(!compiled)
202                 throw compile_error(info_log);
203 #ifdef DEBUG
204         if(!info_log.empty())
205                 IO::print("Shader compile info log:\n%s", info_log);
206 #endif
207 }
208
209 void Program::add_spirv_stages(const SpirVModule &mod, const map<string, int> &spec_values)
210 {
211         static Require _req(ARB_gl_spirv);
212         static Require _req2(ARB_ES2_compatibility);
213
214         module = &mod;
215
216         const vector<SpirVModule::EntryPoint> &entry_points = mod.get_entry_points();
217         unsigned n_stages = 0;
218         unsigned used_stage_ids[MAX_STAGES];
219         for(vector<SpirVModule::EntryPoint>::const_iterator i=entry_points.begin(); i!=entry_points.end(); ++i)
220         {
221                 unsigned stage_id = 0;
222                 switch(i->stage)
223                 {
224                 case SpirVModule::VERTEX: stage_id = add_stage(VERTEX); break;
225                 case SpirVModule::GEOMETRY: stage_id = add_stage(GEOMETRY); break;
226                 case SpirVModule::FRAGMENT: stage_id = add_stage(FRAGMENT); break;
227                 default: throw invalid_operation("Program::add_spirv_stages");
228                 }
229
230                 used_stage_ids[n_stages++] = stage_id;
231         }
232
233         const vector<UInt32> &code = mod.get_code();
234         glShaderBinary(n_stages, used_stage_ids, GL_SHADER_BINARY_FORMAT_SPIR_V, &code[0], code.size()*4);
235
236         if(!spec_values.empty() && !transient)
237                 transient = new TransientData;
238
239         const vector<SpirVModule::Constant> &spec_consts = mod.get_spec_constants();
240         vector<unsigned> spec_id_array;
241         vector<unsigned> spec_value_array;
242         spec_id_array.reserve(spec_consts.size());
243         spec_value_array.reserve(spec_consts.size());
244         for(vector<SpirVModule::Constant>::const_iterator i=spec_consts.begin(); i!=spec_consts.end(); ++i)
245         {
246                 map<string, int>::const_iterator j = spec_values.find(i->name);
247                 if(j!=spec_values.end())
248                 {
249                         spec_id_array.push_back(i->constant_id);
250                         spec_value_array.push_back(j->second);
251                         transient->spec_values[i->constant_id] = j->second;
252                 }
253         }
254
255         vector<SpirVModule::EntryPoint>::const_iterator j=entry_points.begin();
256         for(unsigned i=0; i<MAX_STAGES; ++i)
257                 if(stage_ids[i])
258                         glSpecializeShader(stage_ids[i], j->name.c_str(), spec_id_array.size(), &spec_id_array[0], &spec_value_array[0]);
259 }
260
261 #pragma GCC diagnostic push
262 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
263 void Program::attach_shader(Shader &shader)
264 {
265         unsigned shader_id = shader.steal_id();
266         if(!shader_id)
267                 throw invalid_argument("Program::attach_shader");
268
269         int type;
270         glGetShaderiv(shader_id, GL_SHADER_TYPE, &type);
271         switch(type)
272         {
273         case GL_VERTEX_SHADER: stage_ids[VERTEX] = shader_id; break;
274         case GL_GEOMETRY_SHADER: stage_ids[GEOMETRY] = shader_id; break;
275         case GL_FRAGMENT_SHADER: stage_ids[FRAGMENT] = shader_id; break;
276         }
277
278         glAttachShader(id, shader_id);
279         compile_glsl_stage(shader_id);
280 }
281
282 void Program::attach_shader_owned(Shader *shader)
283 {
284         attach_shader(*shader);
285         delete shader;
286 }
287
288 void Program::detach_shader(Shader &)
289 {
290 }
291
292 const vector<Shader *> &Program::get_attached_shaders() const
293 {
294         static vector<Shader *> dummy;
295         return dummy;
296 }
297
298 void Program::bind_attribute(unsigned index, const string &name)
299 {
300         static Require _req(ARB_vertex_shader);
301         glBindAttribLocation(id, index, name.c_str());
302 }
303
304 void Program::bind_attribute(VertexAttribute attr, const string &name)
305 {
306         bind_attribute(get_attribute_semantic(attr), name);
307 }
308
309 void Program::bind_fragment_data(unsigned index, const string &name)
310 {
311         static Require _req(EXT_gpu_shader4);
312         glBindFragDataLocation(id, index, name.c_str());
313 }
314 #pragma GCC diagnostic pop
315
316 void Program::link()
317 {
318         if(!has_stages())
319                 throw invalid_operation("Program::link");
320
321         uniforms.clear();
322         uniform_blocks.clear();
323         attributes.clear();
324
325         glLinkProgram(id);
326         linked = get_program_i(id, GL_LINK_STATUS);
327
328         GLsizei info_log_len = get_program_i(id, GL_INFO_LOG_LENGTH);
329         string info_log(info_log_len+1, 0);
330         glGetProgramInfoLog(id, info_log_len+1, &info_log_len, &info_log[0]);
331         info_log.erase(info_log_len);
332         if(module && module->get_format()==Module::GLSL)
333                 info_log = static_cast<const GlslModule *>(module)->get_source_map().translate_errors(info_log);
334
335         if(!linked)
336                 throw compile_error(info_log);
337 #ifdef DEBUG
338         if(!info_log.empty())
339                 IO::print("Program link info log:\n%s", info_log);
340 #endif
341
342         if(module->get_format()==Module::GLSL)
343         {
344                 query_uniforms();
345                 query_attributes();
346                 if(transient)
347                 {
348                         for(unsigned i=0; i<uniform_blocks.size(); ++i)
349                         {
350                                 map<string, unsigned>::const_iterator j = transient->blocks.find(uniform_blocks[i].name);
351                                 if(j!=transient->blocks.end())
352                                 {
353                                         glUniformBlockBinding(id, i, j->second);
354                                         uniform_blocks[i].bind_point = j->second;
355                                 }
356                         }
357
358                         Conditional<BindRestore> _bind(!ARB_separate_shader_objects, this);
359                         for(map<string, unsigned>::const_iterator i=transient->textures.begin(); i!=transient->textures.end(); ++i)
360                         {
361                                 int location = get_uniform_location(i->first);
362                                 if(location>=0)
363                                 {
364                                         if(ARB_separate_shader_objects)
365                                                 glProgramUniform1i(id, location, i->second);
366                                         else
367                                                 glUniform1i(location, i->second);
368                                 }
369                         }
370                 }
371         }
372         else if(module->get_format()==Module::SPIR_V)
373         {
374                 collect_uniforms();
375                 collect_attributes();
376         }
377
378         delete transient;
379         transient = 0;
380
381         for(vector<UniformInfo>::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
382                 require_type(i->type);
383         for(vector<AttributeInfo>::const_iterator i=attributes.begin(); i!=attributes.end(); ++i)
384                 require_type(i->type);
385 }
386
387 void Program::query_uniforms()
388 {
389         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
390         uniforms.reserve(count);
391         vector<string> uniform_names(count);
392         for(unsigned i=0; i<count; ++i)
393         {
394                 char name[128];
395                 int len = 0;
396                 int size;
397                 GLenum type;
398                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
399                 if(len && strncmp(name, "gl_", 3))
400                 {
401                         /* Some implementations report the first element of a uniform array,
402                         others report just the name of the array itself. */
403                         if(len>3 && !strcmp(name+len-3, "[0]"))
404                                 name[len-3] = 0;
405
406                         uniforms.push_back(UniformInfo());
407                         UniformInfo &info = uniforms.back();
408                         info.name = name;
409                         info.tag = name;
410                         info.array_size = size;
411                         info.type = from_gl_type(type);
412                         uniform_names[i] = name;
413                 }
414         }
415
416         sort_member(uniforms, &UniformInfo::tag);
417
418         if(ARB_uniform_buffer_object)
419         {
420                 vector<UniformInfo *> uniforms_by_index(count);
421                 for(unsigned i=0; i<count; ++i)
422                         if(!uniform_names[i].empty())
423                                 // The element is already known to be present
424                                 uniforms_by_index[i] = &*lower_bound_member(uniforms, Tag(uniform_names[i]), &UniformInfo::tag);
425                 query_uniform_blocks(uniforms_by_index);
426         }
427
428         uniform_blocks.push_back(UniformBlockInfo());
429         UniformBlockInfo &default_block = uniform_blocks.back();
430
431         for(vector<UniformInfo>::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
432                 if(!i->block)
433                 {
434                         i->location = glGetUniformLocation(id, i->name.c_str());
435                         i->block = &default_block;
436                         default_block.uniforms.push_back(&*i);
437
438                         if(is_image(i->type) && i->location>=0)
439                                 glGetUniformiv(id, i->location, &i->binding);
440                 }
441
442         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
443
444         update_layout_hash();
445 }
446
447 void Program::query_uniform_blocks(const vector<UniformInfo *> &uniforms_by_index)
448 {
449         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
450         // Reserve an extra index for the default block
451         uniform_blocks.reserve(count+1);
452         for(unsigned i=0; i<count; ++i)
453         {
454                 char name[128];
455                 int len;
456                 glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
457                 uniform_blocks.push_back(UniformBlockInfo());
458                 UniformBlockInfo &info = uniform_blocks.back();
459                 info.name = name;
460
461                 int value;
462                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
463                 info.data_size = value;
464
465                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_BINDING, &value);
466                 info.bind_point = value;
467
468                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
469                 vector<int> indices(value);
470                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
471                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
472                 {
473                         if(!uniforms_by_index[*j])
474                                 throw logic_error("Program::link");
475                         info.uniforms.push_back(uniforms_by_index[*j]);
476                         uniforms_by_index[*j]->block = &info;
477                 }
478
479                 vector<unsigned> query_indices(indices.begin(), indices.end());
480                 vector<int> values(indices.size());
481                 glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_OFFSET, &values[0]);
482                 for(unsigned j=0; j<indices.size(); ++j)
483                         uniforms_by_index[indices[j]]->offset = values[j];
484
485                 query_indices.clear();
486                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
487                         if(uniforms_by_index[*j]->array_size>1)
488                                 query_indices.push_back(*j);
489                 if(!query_indices.empty())
490                 {
491                         glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
492                         for(unsigned j=0; j<query_indices.size(); ++j)
493                                 uniforms_by_index[query_indices[j]]->array_stride = values[j];
494                 }
495
496                 query_indices.clear();
497                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
498                 {
499                         DataType t = uniforms_by_index[*j]->type;
500                         if(is_matrix(t))
501                                 query_indices.push_back(*j);
502                 }
503                 if(!query_indices.empty())
504                 {
505                         glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
506                         for(unsigned j=0; j<query_indices.size(); ++j)
507                                 uniforms_by_index[query_indices[j]]->matrix_stride = values[j];
508                 }
509
510                 sort(info.uniforms, uniform_location_compare);
511                 info.layout_hash = compute_layout_hash(info.uniforms);
512         }
513 }
514
515 void Program::query_attributes()
516 {
517         unsigned count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
518         attributes.reserve(count);
519         for(unsigned i=0; i<count; ++i)
520         {
521                 char name[128];
522                 int len = 0;
523                 int size;
524                 GLenum type;
525                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
526                 if(len && strncmp(name, "gl_", 3))
527                 {
528                         if(len>3 && !strcmp(name+len-3, "[0]"))
529                                 name[len-3] = 0;
530
531                         attributes.push_back(AttributeInfo());
532                         AttributeInfo &info = attributes.back();
533                         info.name = name;
534                         info.location = glGetAttribLocation(id, name);
535                         info.array_size = size;
536                         info.type = from_gl_type(type);
537                 }
538         }
539 }
540
541 void Program::collect_uniforms()
542 {
543         const SpirVModule &mod = static_cast<const SpirVModule &>(*module);
544
545         // Prepare the default block
546         uniform_blocks.push_back(UniformBlockInfo());
547         vector<vector<string> > block_uniform_names(1);
548
549         const vector<SpirVModule::Variable> &variables = mod.get_variables();
550         for(vector<SpirVModule::Variable>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
551         {
552                 if(i->storage==SpirVModule::UNIFORM && i->struct_type)
553                 {
554                         uniform_blocks.push_back(UniformBlockInfo());
555                         UniformBlockInfo &info = uniform_blocks.back();
556                         info.name = i->struct_type->name;
557                         info.bind_point = i->binding;
558                         info.data_size = i->struct_type->size;
559
560                         string prefix;
561                         if(!i->name.empty())
562                                 prefix = i->struct_type->name+".";
563                         block_uniform_names.push_back(vector<string>());
564                         collect_block_uniforms(*i->struct_type, prefix, 0, block_uniform_names.back());
565                 }
566                 else if(i->storage==SpirVModule::UNIFORM_CONSTANT && i->location>=0)
567                 {
568                         block_uniform_names[0].push_back(i->name);
569                         uniforms.push_back(UniformInfo());
570                         UniformInfo &info = uniforms.back();
571                         info.name = i->name;
572                         info.tag = i->name;
573                         info.location = i->location;
574                         info.binding = i->binding;
575                         info.array_size = i->array_size;
576                         info.type = i->type;
577                 }
578         }
579
580         sort_member(uniforms, &UniformInfo::tag);
581
582         for(unsigned i=0; i<uniform_blocks.size(); ++i)
583         {
584                 UniformBlockInfo &block = uniform_blocks[i];
585                 const vector<string> &names = block_uniform_names[i];
586                 for(vector<string>::const_iterator j=names.begin(); j!=names.end(); ++j)
587                 {
588                         // The element is already known to be present
589                         UniformInfo &uni = *lower_bound_member(uniforms, Tag(*j), &UniformInfo::tag);
590                         block.uniforms.push_back(&uni);
591                         uni.block = &block;
592                 }
593                 sort(block.uniforms, uniform_location_compare);
594                 block.layout_hash = compute_layout_hash(block.uniforms);
595         }
596
597         update_layout_hash();
598 }
599
600 void Program::collect_block_uniforms(const SpirVModule::Structure &strct, const string &prefix, unsigned base_offset, vector<string> &uniform_names)
601 {
602         for(vector<SpirVModule::StructMember>::const_iterator i=strct.members.begin(); i!=strct.members.end(); ++i)
603         {
604                 unsigned offset = base_offset+i->offset;
605                 if(i->struct_type)
606                 {
607                         unsigned array_size = i->array_size;
608                         if(i->array_size_spec)
609                         {
610                                 array_size = i->array_size_spec->i_value;
611                                 if(transient)
612                                 {
613                                         map<unsigned, int>::const_iterator j = transient->spec_values.find(i->array_size_spec->constant_id);
614                                         if(j!=transient->spec_values.end())
615                                                 array_size = j->second;
616                                 }
617                         }
618
619                         if(array_size)
620                         {
621                                 for(unsigned j=0; j<array_size; ++j, offset+=i->array_stride)
622                                         collect_block_uniforms(*i->struct_type, format("%s%s[%d].", prefix, i->name, j), offset, uniform_names);
623                         }
624                         else
625                                 collect_block_uniforms(*i->struct_type, prefix+i->name+".", offset, uniform_names);
626                 }
627                 else
628                 {
629                         string name = prefix+i->name;
630                         uniform_names.push_back(name);
631                         uniforms.push_back(UniformInfo());
632                         UniformInfo &info = uniforms.back();
633                         info.name = name;
634                         info.tag = name;
635                         info.offset = offset;
636                         info.array_size = i->array_size;
637                         info.array_stride = i->array_stride;
638                         info.matrix_stride = i->matrix_stride;
639                         info.type = i->type;
640                 }
641         }
642 }
643
644 void Program::collect_attributes()
645 {
646         const SpirVModule &mod = static_cast<const SpirVModule &>(*module);
647
648         const vector<SpirVModule::EntryPoint> &entry_points = mod.get_entry_points();
649         for(vector<SpirVModule::EntryPoint>::const_iterator i=entry_points.begin(); i!=entry_points.end(); ++i)
650                 if(i->stage==SpirVModule::VERTEX && i->name=="main")
651                 {
652                         for(vector<const SpirVModule::Variable *>::const_iterator j=i->globals.begin(); j!=i->globals.end(); ++j)
653                                 if((*j)->storage==SpirVModule::INPUT)
654                                 {
655                                         attributes.push_back(AttributeInfo());
656                                         AttributeInfo &info = attributes.back();
657                                         info.name = (*j)->name;
658                                         info.location = (*j)->location;
659                                         info.array_size = (*j)->array_size;
660                                         info.type = (*j)->type;
661                                 }
662                 }
663 }
664
665 void Program::update_layout_hash()
666 {
667         string layout_descriptor;
668         for(vector<UniformBlockInfo>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
669                 layout_descriptor += format("%d:%x\n", i->bind_point, i->layout_hash);
670         uniform_layout_hash = hash32(layout_descriptor);
671 }
672
673 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
674 {
675         string layout_descriptor;
676         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
677                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->array_size);
678         return hash32(layout_descriptor);
679 }
680
681 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
682 {
683         return uni1->location<uni2->location;
684 }
685
686 string Program::get_info_log() const
687 {
688         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
689         string log(len+1, 0);
690         glGetProgramInfoLog(id, len+1, &len, &log[0]);
691         log.erase(len);
692         return log;
693 }
694
695 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
696 {
697         for(vector<UniformBlockInfo>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
698                 if(i->name==name)
699                         return *i;
700         throw key_error(name);
701 }
702
703 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
704 {
705         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, Tag(name), &UniformInfo::tag);
706         if(i==uniforms.end() || i->name!=name)
707                 throw key_error(name);
708         return *i;
709 }
710
711 const Program::UniformInfo &Program::get_uniform_info(Tag tag) const
712 {
713         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, tag, &UniformInfo::tag);
714         if(i==uniforms.end() || i->tag!=tag)
715                 throw key_error(tag);
716         return *i;
717 }
718
719 int Program::get_uniform_location(const string &name) const
720 {
721         if(name[name.size()-1]==']')
722                 throw invalid_argument("Program::get_uniform_location");
723
724         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, Tag(name), &UniformInfo::tag);
725         return i!=uniforms.end() && i->name==name && i->block->bind_point<0 ? i->location : -1;
726 }
727
728 int Program::get_uniform_location(Tag tag) const
729 {
730         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, tag, &UniformInfo::tag);
731         return i!=uniforms.end() && i->tag==tag && i->block->bind_point<0 ? i->location : -1;
732 }
733
734 int Program::get_uniform_binding(Tag tag) const
735 {
736         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, tag, &UniformInfo::tag);
737         return i!=uniforms.end() && i->tag==tag ? i->binding : -1;
738 }
739
740 const Program::AttributeInfo &Program::get_attribute_info(const string &name) const
741 {
742         vector<AttributeInfo>::const_iterator i = lower_bound_member(attributes, name, &AttributeInfo::name);
743         if(i==attributes.end() || i->name!=name)
744                 throw key_error(name);
745         return *i;
746 }
747
748 int Program::get_attribute_location(const string &name) const
749 {
750         if(name[name.size()-1]==']')
751                 throw invalid_argument("Program::get_attribute_location");
752
753         vector<AttributeInfo>::const_iterator i = lower_bound_member(attributes, name, &AttributeInfo::name);
754         return i!=attributes.end() && i->name==name ? i->location : -1;
755 }
756
757 void Program::bind() const
758 {
759         if(!linked)
760                 throw invalid_operation("Program::bind");
761
762         if(!set_current(this))
763                 return;
764
765         glUseProgram(id);
766 }
767
768 void Program::unbind()
769 {
770         if(!set_current(0))
771                 return;
772
773         glUseProgram(0);
774 }
775
776 void Program::set_debug_name(const string &name)
777 {
778 #ifdef DEBUG
779         debug_name = name;
780         if(KHR_debug)
781         {
782                 glObjectLabel(GL_PROGRAM, id, name.size(), name.c_str());
783                 for(unsigned i=0; i<MAX_STAGES; ++i)
784                         if(stage_ids[i])
785                                 set_stage_debug_name(stage_ids[i], static_cast<Stage>(i));
786         }
787 #else
788         (void)name;
789 #endif
790 }
791
792 void Program::set_stage_debug_name(unsigned stage_id, Stage type)
793 {
794 #ifdef DEBUG
795         static const char *const suffixes[] = { " [VS]", " [GS]", " [FS]" };
796         string name = debug_name+suffixes[type];
797         glObjectLabel(GL_SHADER, stage_id, name.size(), name.c_str());
798 #else
799         (void)stage_id; (void)type;
800 #endif
801 }
802
803
804 Program::UniformInfo::UniformInfo():
805         block(0),
806         location(-1),
807         array_size(0),
808         array_stride(0),
809         matrix_stride(0),
810         type(VOID),
811         binding(-1)
812 { }
813
814
815 Program::UniformBlockInfo::UniformBlockInfo():
816         data_size(0),
817         bind_point(-1),
818         layout_hash(0)
819 { }
820
821
822 Program::AttributeInfo::AttributeInfo():
823         location(-1),
824         array_size(0),
825         type(VOID)
826 { }
827
828
829 Program::Loader::Loader(Program &p, Collection &c):
830         DataFile::CollectionObjectLoader<Program>(p, &c)
831 {
832         add("module",          &Loader::module);
833
834         // Deprecated
835         add("attribute",       &Loader::attribute);
836         add("fragment_shader", &Loader::fragment_shader);
837         add("geometry_shader", &Loader::geometry_shader);
838         add("vertex_shader",   &Loader::vertex_shader);
839 }
840
841 void Program::Loader::finish()
842 {
843         obj.link();
844 }
845
846 void Program::Loader::module(const string &n)
847 {
848         map<string, int> spec_values;
849         SpecializationLoader ldr(spec_values);
850         load_sub_with(ldr);
851         obj.add_stages(get_collection().get<Module>(n), spec_values);
852 }
853
854 #pragma GCC diagnostic push
855 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
856 void Program::Loader::attribute(unsigned i, const string &n)
857 {
858         obj.bind_attribute(i, n);
859 }
860
861 void Program::Loader::fragment_shader(const string &src)
862 {
863         obj.attach_shader_owned(new FragmentShader(src));
864 }
865
866 void Program::Loader::geometry_shader(const string &src)
867 {
868         obj.attach_shader_owned(new GeometryShader(src));
869 }
870
871 void Program::Loader::vertex_shader(const string &src)
872 {
873         obj.attach_shader_owned(new VertexShader(src));
874 }
875 #pragma GCC diagnostic pop
876
877
878 DataFile::Loader::ActionMap Program::SpecializationLoader::shared_actions;
879
880 Program::SpecializationLoader::SpecializationLoader(map<string, int> &sv):
881         spec_values(sv)
882 {
883         set_actions(shared_actions);
884 }
885
886 void Program::SpecializationLoader::init_actions()
887 {
888         add("specialize", &SpecializationLoader::specialize_bool);
889         add("specialize", &SpecializationLoader::specialize_int);
890 }
891
892 void Program::SpecializationLoader::specialize_bool(const string &name, bool value)
893 {
894         spec_values[name] = value;
895 }
896
897 void Program::SpecializationLoader::specialize_int(const string &name, int value)
898 {
899         spec_values[name] = value;
900 }
901
902 } // namespace GL
903 } // namespace Msp