]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Integrate ProgramCompiler with Program and Resources
[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 "shader.h"
19
20 using namespace std;
21
22 namespace Msp {
23 namespace GL {
24
25 Program::Program()
26 {
27         init();
28 }
29
30 Program::Program(const ProgramBuilder::StandardFeatures &features)
31 {
32         init();
33
34         ProgramBuilder builder(features);
35         builder.add_shaders(*this);
36         link();
37 }
38
39 Program::Program(const std::string &source)
40 {
41         init();
42
43         ProgramCompiler compiler;
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         legacy_vars = false;
124
125         glLinkProgram(id);
126         linked = get_program_i(id, GL_LINK_STATUS);
127         if(!linked)
128                 throw compile_error(get_info_log());
129
130 #ifdef DEBUG
131         std::string info_log = get_info_log();
132         if(!info_log.empty())
133                 IO::print("Program link info log:\n%s", info_log);
134 #endif
135
136         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
137         vector<UniformInfo *> uniforms_by_index(count);
138         for(unsigned i=0; i<count; ++i)
139         {
140                 char name[128];
141                 int len = 0;
142                 int size;
143                 GLenum type;
144                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
145                 if(len && strncmp(name, "gl_", 3))
146                 {
147                         /* Some implementations report the first element of a uniform array,
148                         others report just the name of the array itself. */
149                         if(len>3 && !strcmp(name+len-3, "[0]"))
150                                 name[len-3] = 0;
151
152                         UniformInfo &info = uniforms[name];
153                         info.block = 0;
154                         info.name = name;
155                         info.size = size;
156                         info.array_stride = 0;
157                         info.matrix_stride = 0;
158                         info.type = type;
159                         uniforms_by_index[i] = &info;
160                 }
161                 else
162                         legacy_vars = true;
163         }
164
165         count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
166         for(unsigned i=0; i<count; ++i)
167         {
168                 char name[128];
169                 int len = 0;
170                 int size;
171                 GLenum type;
172                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
173                 if(len && !strncmp(name, "gl_", 3))
174                         legacy_vars = true;
175         }
176
177         if(ARB_uniform_buffer_object)
178         {
179                 uniform_blocks.clear();
180
181                 std::set<unsigned> used_bind_points;
182                 count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
183                 for(unsigned i=0; i<count; ++i)
184                 {
185                         char name[128];
186                         int len;
187                         glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
188                         UniformBlockInfo &info = uniform_blocks[name];
189                         info.name = name;
190
191                         int value;
192                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
193                         info.data_size = value;
194
195                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
196                         vector<int> indices(value);
197                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
198                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
199                         {
200                                 if(!uniforms_by_index[*j])
201                                         throw logic_error("Program::link");
202                                 info.uniforms.push_back(uniforms_by_index[*j]);
203                                 uniforms_by_index[*j]->block = &info;
204                         }
205
206                         vector<unsigned> indices2(indices.begin(), indices.end());
207                         vector<int> values(indices.size());
208                         glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
209                         for(unsigned j=0; j<indices.size(); ++j)
210                                 uniforms_by_index[indices[j]]->location = values[j];
211
212                         indices2.clear();
213                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
214                                 if(uniforms_by_index[*j]->size>1)
215                                         indices2.push_back(*j);
216                         if(!indices2.empty())
217                         {
218                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
219                                 for(unsigned j=0; j<indices2.size(); ++j)
220                                         uniforms_by_index[indices2[j]]->array_stride = values[j];
221                         }
222
223                         indices2.clear();
224                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
225                         {
226                                 GLenum t = uniforms_by_index[*j]->type;
227                                 if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
228                                         t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
229                                         t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
230                                         indices2.push_back(*j);
231                         }
232                         if(!indices2.empty())
233                         {
234                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
235                                 for(unsigned j=0; j<indices2.size(); ++j)
236                                         uniforms_by_index[indices2[j]]->matrix_stride = values[j];
237                         }
238
239                         sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
240                         info.layout_hash = compute_layout_hash(info.uniforms);
241                         unsigned n_bindings = BufferRange::get_n_uniform_buffer_bindings();
242                         info.bind_point = info.layout_hash%n_bindings;
243                         while(used_bind_points.count(info.bind_point))
244                                 info.bind_point = (info.bind_point+1)%n_bindings;
245                         glUniformBlockBinding(id, i, info.bind_point);
246                         used_bind_points.insert(info.bind_point);
247                 }
248         }
249
250         UniformBlockInfo &default_block = uniform_blocks[string()];
251         default_block.data_size = 0;
252         default_block.bind_point = -1;
253
254         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
255                 if(!i->second.block)
256                 {
257                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
258                         i->second.block = &default_block;
259                         default_block.uniforms.push_back(&i->second);
260                 }
261
262         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
263
264         string layout_descriptor;
265         for(UniformBlockMap::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
266                 layout_descriptor += format("%d:%x\n", i->second.bind_point, i->second.layout_hash);
267         uniform_layout_hash = hash32(layout_descriptor);
268 }
269
270 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
271 {
272         string layout_descriptor;
273         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
274                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
275         return hash32(layout_descriptor);
276 }
277
278 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
279 {
280         return uni1->location<uni2->location;
281 }
282
283 string Program::get_info_log() const
284 {
285         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
286         char *buf = new char[len+1];
287         glGetProgramInfoLog(id, len+1, &len, buf);
288         string log(buf, len);
289         delete[] buf;
290         return log;
291 }
292
293 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
294 {
295         return get_item(uniform_blocks, name);
296 }
297
298 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
299 {
300         return get_item(uniforms, name);
301 }
302
303 int Program::get_uniform_location(const string &n) const
304 {
305         if(n[n.size()-1]==']')
306                 throw invalid_argument("Program::get_uniform_location");
307
308         UniformMap::const_iterator i = uniforms.find(n);
309         if(i==uniforms.end())
310                 return -1;
311
312         return i->second.block->bind_point<0 ? i->second.location : -1;
313 }
314
315 void Program::bind() const
316 {
317         if(!linked)
318                 throw invalid_operation("Program::bind");
319
320         if(!set_current(this))
321                 return;
322
323         glUseProgram(id);
324 }
325
326 void Program::unbind()
327 {
328         if(!set_current(0))
329                 return;
330
331         glUseProgram(0);
332 }
333
334
335 Program::Loader::Loader(Program &p):
336         DataFile::ObjectLoader<Program>(p)
337 {
338         add("attribute",       &Loader::attribute);
339         add("fragment_shader", &Loader::fragment_shader);
340         add("geometry_shader", &Loader::geometry_shader);
341         add("standard",        &Loader::standard);
342         add("vertex_shader",   &Loader::vertex_shader);
343 }
344
345 void Program::Loader::finish()
346 {
347         obj.link();
348 }
349
350 void Program::Loader::attribute(unsigned i, const string &n)
351 {
352         obj.bind_attribute(i, n);
353 }
354
355 void Program::Loader::fragment_shader(const string &src)
356 {
357         obj.attach_shader_owned(new FragmentShader(src));
358 }
359
360 void Program::Loader::geometry_shader(const string &src)
361 {
362         obj.attach_shader_owned(new GeometryShader(src));
363 }
364
365 void Program::Loader::standard()
366 {
367         ProgramBuilder::StandardFeatures feat;
368         load_sub(feat);
369         ProgramBuilder builder(feat);
370         builder.add_shaders(obj);
371 }
372
373 void Program::Loader::vertex_shader(const string &src)
374 {
375         obj.attach_shader_owned(new VertexShader(src));
376 }
377
378 } // namespace GL
379 } // namespace Msp