]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
More options for exporting techniques
[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/gl/extensions/arb_shader_objects.h>
6 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
7 #include <msp/gl/extensions/arb_vertex_shader.h>
8 #include <msp/gl/extensions/ext_gpu_shader4.h>
9 #include <msp/strings/format.h>
10 #include "buffer.h"
11 #include "error.h"
12 #include "misc.h"
13 #include "program.h"
14 #include "shader.h"
15
16 using namespace std;
17
18 namespace Msp {
19 namespace GL {
20
21 Program::Program()
22 {
23         init();
24 }
25
26 Program::Program(const ProgramBuilder::StandardFeatures &features)
27 {
28         init();
29
30         ProgramBuilder builder(features);
31         builder.add_shaders(*this);
32         link();
33 }
34
35 Program::Program(const string &vert, const string &frag)
36 {
37         init();
38
39         attach_shader_owned(new VertexShader(vert));
40         attach_shader_owned(new FragmentShader(frag));
41         link();
42 }
43
44 void Program::init()
45 {
46         static Require _req(ARB_shader_objects);
47
48         linked = false;
49         id = glCreateProgram();
50 }
51
52 Program::~Program()
53 {
54         for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
55                 delete *i;
56         glDeleteProgram(id);
57 }
58
59 void Program::attach_shader(Shader &shader)
60 {
61         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
62         {
63                 glAttachShader(id, shader.get_id());
64                 shaders.push_back(&shader);
65         }
66 }
67
68 void Program::attach_shader_owned(Shader *shader)
69 {
70         attach_shader(*shader);
71         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
72                 owned_data.push_back(shader);
73 }
74
75 void Program::detach_shader(Shader &shader)
76 {
77         ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
78         if(i!=shaders.end())
79         {
80                 shaders.erase(i, shaders.end());
81                 glDetachShader(id, shader.get_id());
82         }
83 }
84
85 void Program::bind_attribute(unsigned index, const string &name)
86 {
87         static Require _req(ARB_vertex_shader);
88         glBindAttribLocation(id, index, name.c_str());
89 }
90
91 void Program::bind_attribute(VertexComponent comp, const string &name)
92 {
93         bind_attribute(get_component_type(comp), name);
94 }
95
96 void Program::bind_fragment_data(unsigned index, const string &name)
97 {
98         static Require _req(EXT_gpu_shader4);
99         glBindFragDataLocation(id, index, name.c_str());
100 }
101
102 void Program::link()
103 {
104         for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
105                 if(!(*i)->is_compiled())
106                         (*i)->compile();
107
108         uniforms.clear();
109         legacy_vars = false;
110
111         glLinkProgram(id);
112         linked = get_program_i(id, GL_LINK_STATUS);
113         if(!linked)
114                 throw compile_error(get_info_log());
115
116         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
117         vector<UniformInfo *> uniforms_by_index(count);
118         for(unsigned i=0; i<count; ++i)
119         {
120                 char name[128];
121                 int len = 0;
122                 int size;
123                 GLenum type;
124                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
125                 if(len && strncmp(name, "gl_", 3))
126                 {
127                         /* Some implementations report the first element of a uniform array,
128                         others report just the name of an array. */
129                         if(len>3 && !strcmp(name+len-3, "[0]"))
130                                 name[len-3] = 0;
131
132                         UniformInfo &info = uniforms[name];
133                         info.block = 0;
134                         info.name = name;
135                         info.size = size;
136                         info.array_stride = 0;
137                         info.matrix_stride = 0;
138                         info.type = type;
139                         uniforms_by_index[i] = &info;
140                 }
141                 else
142                         legacy_vars = true;
143         }
144
145         count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
146         for(unsigned i=0; i<count; ++i)
147         {
148                 char name[128];
149                 int len = 0;
150                 int size;
151                 GLenum type;
152                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
153                 if(len && !strncmp(name, "gl_", 3))
154                         legacy_vars = true;
155         }
156
157         if(ARB_uniform_buffer_object)
158         {
159                 count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
160                 for(unsigned i=0; i<count; ++i)
161                 {
162                         char name[128];
163                         int len;
164                         glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
165                         UniformBlockInfo &info = uniform_blocks[name];
166                         info.name = name;
167
168                         int value;
169                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
170                         info.data_size = value;
171
172                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
173                         vector<int> indices(value);
174                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
175                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
176                         {
177                                 if(!uniforms_by_index[*j])
178                                         throw logic_error("Program::link");
179                                 info.uniforms.push_back(uniforms_by_index[*j]);
180                                 uniforms_by_index[*j]->block = &info;
181                         }
182
183                         vector<unsigned> indices2(indices.begin(), indices.end());
184                         vector<int> values(indices.size());
185                         glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
186                         for(unsigned j=0; j<indices.size(); ++j)
187                                 uniforms_by_index[indices[j]]->location = values[j];
188
189                         indices2.clear();
190                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
191                                 if(uniforms_by_index[*j]->size>1)
192                                         indices2.push_back(*j);
193                         if(!indices2.empty())
194                         {
195                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
196                                 for(unsigned j=0; j<indices2.size(); ++j)
197                                         uniforms_by_index[indices[j]]->array_stride = values[j];
198                         }
199
200                         indices2.clear();
201                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
202                         {
203                                 GLenum t = uniforms_by_index[*j]->type;
204                                 if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
205                                         t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
206                                         t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
207                                         indices2.push_back(*j);
208                         }
209                         if(!indices2.empty())
210                         {
211                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
212                                 for(unsigned j=0; j<indices2.size(); ++j)
213                                         uniforms_by_index[indices[j]]->matrix_stride = values[j];
214                         }
215
216                         sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
217                         info.layout_hash = compute_layout_hash(info.uniforms);
218                         info.bind_point = info.layout_hash%BufferRange::get_n_uniform_buffer_bindings();
219                         glUniformBlockBinding(id, i, info.bind_point);
220                 }
221         }
222
223         vector<const UniformInfo *> blockless_uniforms;
224         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
225                 if(!i->second.block)
226                 {
227                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
228                         blockless_uniforms.push_back(&i->second);
229                 }
230
231         uniform_layout_hash = compute_layout_hash(blockless_uniforms);
232 }
233
234 unsigned Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
235 {
236         string layout_descriptor;
237         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
238                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
239         return hash32(layout_descriptor);
240 }
241
242 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
243 {
244         return uni1->location<uni2->location;
245 }
246
247 string Program::get_info_log() const
248 {
249         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
250         char *buf = new char[len+1];
251         glGetProgramInfoLog(id, len+1, &len, buf);
252         string log(buf, len);
253         delete[] buf;
254         return log;
255 }
256
257 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
258 {
259         return get_item(uniform_blocks, name);
260 }
261
262 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
263 {
264         return get_item(uniforms, name);
265 }
266
267 int Program::get_uniform_location(const string &n) const
268 {
269         UniformMap::const_iterator i = uniforms.find(n);
270         if(i==uniforms.end())
271         {
272                 if(n[n.size()-1]==']')
273                 {
274                         string::size_type open_bracket = n.rfind('[');
275                         if(open_bracket!=string::npos)
276                         {
277                                 /* The requested name looks like an array.  glGetActiveUniform only
278                                 gives us the first element of the array, so try to look that up and
279                                 add an offset. */
280                                 unsigned offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
281                                 i = uniforms.find(n.substr(0, open_bracket));
282                                 if(i!=uniforms.end() && !i->second.block && offset<i->second.size)
283                                         return i->second.location+offset;
284                         }
285                 }
286                 return -1;
287         }
288
289         return i->second.block ? -1 : i->second.location;
290 }
291
292 void Program::bind() const
293 {
294         if(!linked)
295                 throw invalid_operation("Program::bind");
296
297         if(!set_current(this))
298                 return;
299
300         glUseProgram(id);
301 }
302
303 void Program::unbind()
304 {
305         if(!set_current(0))
306                 return;
307
308         glUseProgram(0);
309 }
310
311
312 Program::Loader::Loader(Program &p):
313         DataFile::ObjectLoader<Program>(p)
314 {
315         add("attribute",       &Loader::attribute);
316         add("fragment_shader", &Loader::fragment_shader);
317         add("standard",        &Loader::standard);
318         add("vertex_shader",   &Loader::vertex_shader);
319 }
320
321 void Program::Loader::finish()
322 {
323         obj.link();
324 }
325
326 void Program::Loader::attribute(unsigned i, const string &n)
327 {
328         obj.bind_attribute(i, n);
329 }
330
331 void Program::Loader::fragment_shader(const string &src)
332 {
333         obj.attach_shader_owned(new FragmentShader(src));
334 }
335
336 void Program::Loader::standard()
337 {
338         ProgramBuilder::StandardFeatures feat;
339         load_sub(feat);
340         ProgramBuilder builder(feat);
341         builder.add_shaders(obj);
342 }
343
344 void Program::Loader::vertex_shader(const string &src)
345 {
346         obj.attach_shader_owned(new VertexShader(src));
347 }
348
349 } // namespace GL
350 } // namespace Msp