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