]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Don't expose the shader type enum
[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/strings/format.h>
6 #include "arb_shader_objects.h"
7 #include "arb_uniform_buffer_object.h"
8 #include "arb_vertex_shader.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 {
17
18 const char *standard_vertex_src[] =
19 {
20         "s",   "uniform int shadow_unit;\n",
21         "n",   "attribute vec3 tangent;\n",
22         "n",   "attribute vec3 binormal;\n",
23         "t|n", "varying vec2 v_texcoord;\n",
24         "s",   "varying vec3 v_shadowcoord;\n",
25         "!lm", "varying vec4 v_color;\n",
26         "l!n", "varying vec3 v_normal;\n",
27         "l",   "varying vec3 v_light_dir;\n",
28         "p|e", "varying vec3 v_eye_dir;\n",
29         "r",   "vec4 transform_vertex(vec4);\n",
30         "lr",  "vec3 transform_normal(vec3);\n",
31          0,    "void main()\n",
32          0,    "{\n",
33         "r",   "\tvec4 eye_pos = transform_vertex(gl_Vertex);\n",
34         "!r",  "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
35          0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
36         "lr",  "\tvec3 eye_normal = transform_normal(gl_Normal);\n",
37         "l!r", "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
38         "l!n", "\tv_normal = eye_normal;\n",
39         "nr",  "\tvec3 eye_tangent = transform_normal(tangent);\n",
40         "n!r", "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
41         "nr",  "\tvec3 eye_binormal = transform_normal(binormal);\n",
42         "n!r", "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
43         "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
44         "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
45         "l!n", "\tv_light_dir = eye_light_dir;\n",
46         "p|e", "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
47         "p|en",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
48         "p|e!n", "\tv_eye_dir = eye_dir;\n",
49         "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
50         "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[shadow_unit], eye_pos), dot(gl_EyePlaneT[shadow_unit], eye_pos), dot(gl_EyePlaneR[shadow_unit], eye_pos));\n",
51         "!lm", "\tv_color = gl_Color;\n",
52          0,    "}",
53         0, 0
54 };
55
56 const char *standard_fragment_src[] =
57 {
58         "t",   "uniform sampler2D texture;\n",
59         "n",   "uniform sampler2D normalmap;\n",
60         "s",   "uniform sampler2DShadow shadow;\n",
61         "e",   "uniform samplerCube environment;\n",
62         "e",   "uniform float reflectivity;\n",
63         "t|n", "varying vec2 v_texcoord;\n",
64         "s",   "varying vec3 v_shadowcoord;\n",
65         "!lm", "varying vec4 v_color;\n",
66         "l!n", "varying vec3 v_normal;\n",
67         "l",   "varying vec3 v_light_dir;\n",
68         "p|e", "varying vec3 v_eye_dir;\n",
69          0,    "void main()\n",
70          0,    "{\n",
71         "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
72         "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
73         "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
74         "p",   "\tvec3 half_dir = normalize(v_eye_dir+v_light_dir);\n",
75         "p",   "\tfloat l_specular = pow(max(dot(half_dir, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
76         "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
77         /* XXX This is incorrect with normal mapping, since the vectors are in TBN
78         space but environment map is expected to be in eye space */
79         "e",   "\tvec4 reflection = textureCube(environment, n_normal*(dot(n_normal, v_eye_dir)*2.0)-v_eye_dir);\n",
80         "t",   "\tvec4 tex_sample = texture2D(texture, v_texcoord);\n",
81          0,    "\tgl_FragColor.rgb = ",
82         "!t!m",  "vec3(1.0)",
83         "t",     "tex_sample.rgb",
84         "l|mt",  "*",
85         "l!m!t",  "*",
86         "!lm",   "v_color.rgb",
87         "l",     "((l_diffuse",
88         "lm",    "*gl_FrontLightProduct[0].diffuse.rgb",
89         "p",     "+l_specular",
90         "pm",    "*gl_FrontLightProduct[0].specular.rgb",
91         "l",     ")",
92         "s",     "*l_shadow",
93         "lm",    "+gl_FrontLightModelProduct.sceneColor.rgb",
94         "l",     ")",
95         "e",     "+reflection.rgb*reflectivity",
96          0,      ";\n",
97          0,    "\tgl_FragColor.a = ",
98         "!t!m",  "1.0",
99         "t",     "tex_sample.a",
100         "tm",    "*",
101         "!lm",   "v_color.a",
102         "lm",    "gl_FrontMaterial.diffuse.a",
103          0,      ";\n",
104          0,    "}\n",
105         0, 0
106 };
107
108 }
109
110 namespace Msp {
111 namespace GL {
112
113 Program::Program()
114 {
115         init();
116 }
117
118 Program::Program(const StandardFeatures &features)
119 {
120         init();
121
122         add_standard_shaders(features);
123         if(!features.transform)
124                 link();
125 }
126
127 Program::Program(const string &vert, const string &frag)
128 {
129         init();
130
131         attach_shader_owned(new VertexShader(vert));
132         attach_shader_owned(new FragmentShader(frag));
133         link();
134 }
135
136 void Program::init()
137 {
138         static Require _req(ARB_shader_objects);
139
140         linked = false;
141         id = glCreateProgram();
142 }
143
144 Program::~Program()
145 {
146         for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
147                 delete *i;
148         glDeleteProgram(id);
149 }
150
151 void Program::attach_shader(Shader &shader)
152 {
153         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
154         {
155                 glAttachShader(id, shader.get_id());
156                 shaders.push_back(&shader);
157         }
158 }
159
160 void Program::attach_shader_owned(Shader *shader)
161 {
162         attach_shader(*shader);
163         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
164                 owned_data.push_back(shader);
165 }
166
167 void Program::detach_shader(Shader &shader)
168 {
169         ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
170         if(i!=shaders.end())
171         {
172                 shaders.erase(i, shaders.end());
173                 glDetachShader(id, shader.get_id());
174         }
175 }
176
177 void Program::add_standard_shaders(const StandardFeatures &features)
178 {
179         string flags = features.create_flags();
180         string vertex_src = process_standard_source(standard_vertex_src, flags);
181         string fragment_src = process_standard_source(standard_fragment_src, flags);
182         attach_shader_owned(new VertexShader(vertex_src));
183         attach_shader_owned(new FragmentShader(fragment_src));
184 }
185
186 string Program::process_standard_source(const char **source, const string &flags)
187 {
188         string result;
189
190         for(unsigned i=0; source[i+1]; i+=2)
191         {
192                 if(source[i])
193                 {
194                         bool cond = true;
195                         char oper = '&';
196                         for(const char *c=source[i]; *c; ++c)
197                         {
198                                 if(*c>='a' && *c<='z')
199                                 {
200                                         bool found = (flags.find(*c)!=string::npos);
201                                         if(oper=='|')
202                                                 cond = (cond || found);
203                                         else if(oper=='!')
204                                                 cond = (cond && !found);
205                                         else if(oper=='&')
206                                                 cond = (cond && found);
207                                         oper = '&';
208                                 }
209                                 else
210                                         oper = *c;
211                         }
212
213                         if(!cond)
214                                 continue;
215                 }
216
217                 result += source[i+1];
218         }
219
220         return result;
221 }
222
223 void Program::bind_attribute(unsigned index, const string &name)
224 {
225         static Require _req(ARB_vertex_shader);
226         glBindAttribLocation(id, index, name.c_str());
227 }
228
229 void Program::link()
230 {
231         for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
232                 if(!(*i)->is_compiled())
233                         (*i)->compile();
234
235         uniforms.clear();
236
237         glLinkProgram(id);
238         int value;
239         glGetProgramiv(id, GL_LINK_STATUS, &value);
240         if(!(linked = value))
241                 throw compile_error(get_info_log());
242
243         glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &value);
244         unsigned count = value;
245         vector<UniformInfo *> uniforms_by_index(count);
246         for(unsigned i=0; i<count; ++i)
247         {
248                 char name[128];
249                 int len = 0;
250                 int size;
251                 GLenum type;
252                 glGetActiveUniform(id, i, 128, &len, &size, &type, name);
253                 if(len && strncmp(name, "gl_", 3))
254                 {
255                         UniformInfo &info = uniforms[name];
256                         info.block = 0;
257                         info.name = name;
258                         info.size = size;
259                         info.array_stride = 0;
260                         info.matrix_stride = 0;
261                         info.type = type;
262                         uniforms_by_index[i] = &info;
263                 }
264         }
265
266         if(ARB_uniform_buffer_object)
267         {
268                 glGetProgramiv(id, GL_ACTIVE_UNIFORM_BLOCKS, &value);
269                 count = value;
270                 for(unsigned i=0; i<count; ++i)
271                 {
272                         char name[128];
273                         int len;
274                         glGetActiveUniformBlockName(id, i, 128, &len, name);
275                         UniformBlockInfo &info = uniform_blocks[name];
276                         info.name = name;
277
278                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
279                         info.data_size = value;
280
281                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
282                         vector<int> indices(value);
283                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
284                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
285                         {
286                                 if(!uniforms_by_index[*j])
287                                         throw logic_error("Program::link");
288                                 info.uniforms.push_back(uniforms_by_index[*j]);
289                                 uniforms_by_index[*j]->block = &info;
290                         }
291
292                         vector<unsigned> indices2(indices.begin(), indices.end());
293                         vector<int> values(indices.size());
294                         glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
295                         for(unsigned j=0; j<indices.size(); ++j)
296                                 uniforms_by_index[indices[j]]->location = values[j];
297
298                         indices2.clear();
299                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
300                                 if(uniforms_by_index[*j]->size>1)
301                                         indices2.push_back(*j);
302                         if(!indices2.empty())
303                         {
304                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
305                                 for(unsigned j=0; j<indices2.size(); ++j)
306                                         uniforms_by_index[indices[j]]->array_stride = values[j];
307                         }
308
309                         indices2.clear();
310                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
311                         {
312                                 GLenum t = uniforms_by_index[*j]->type;
313                                 if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
314                                         t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
315                                         t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
316                                         indices2.push_back(*j);
317                         }
318                         if(!indices2.empty())
319                         {
320                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
321                                 for(unsigned j=0; j<indices2.size(); ++j)
322                                         uniforms_by_index[indices[j]]->matrix_stride = values[j];
323                         }
324
325                         sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
326                         info.layout_hash = compute_layout_hash(info.uniforms);
327                         info.bind_point = info.layout_hash%BufferRange::get_n_uniform_buffer_bindings();
328                         glUniformBlockBinding(id, i, info.bind_point);
329                 }
330         }
331
332         vector<const UniformInfo *> blockless_uniforms;
333         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
334                 if(!i->second.block)
335                 {
336                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
337                         blockless_uniforms.push_back(&i->second);
338                 }
339
340         uniform_layout_hash = compute_layout_hash(blockless_uniforms);
341 }
342
343 unsigned Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
344 {
345         string layout_descriptor;
346         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
347                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
348         return hash32(layout_descriptor);
349 }
350
351 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
352 {
353         return uni1->location<uni2->location;
354 }
355
356 string Program::get_info_log() const
357 {
358         GLsizei len = 0;
359         glGetProgramiv(id, GL_INFO_LOG_LENGTH, &len);
360         char *buf = new char[len+1];
361         glGetProgramInfoLog(id, len+1, &len, buf);
362         string log(buf, len);
363         delete[] buf;
364         return log;
365 }
366
367 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
368 {
369         return get_item(uniform_blocks, name);
370 }
371
372 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
373 {
374         return get_item(uniforms, name);
375 }
376
377 int Program::get_uniform_location(const string &n) const
378 {
379         UniformMap::const_iterator i = uniforms.find(n);
380         if(i==uniforms.end())
381         {
382                 if(n[n.size()-1]==']')
383                 {
384                         string::size_type open_bracket = n.rfind('[');
385                         if(open_bracket!=string::npos)
386                         {
387                                 /* The requested name looks like an array.  glGetActiveUniform only
388                                 gives us the first element of the array, so try to look that up and
389                                 add an offset. */
390                                 unsigned offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
391                                 i = uniforms.find(n.substr(0, open_bracket)+"[0]");
392                                 if(i!=uniforms.end() && !i->second.block && offset<i->second.size)
393                                         return i->second.location+offset;
394                         }
395                 }
396                 return -1;
397         }
398
399         return i->second.block ? -1 : i->second.location;
400 }
401
402 void Program::bind() const
403 {
404         if(!linked)
405                 throw invalid_operation("Program::bind");
406
407         if(!set_current(this))
408                 return;
409
410         glUseProgram(id);
411 }
412
413 void Program::unbind()
414 {
415         if(!set_current(0))
416                 return;
417
418         glUseProgram(0);
419 }
420
421
422 Program::StandardFeatures::StandardFeatures():
423         texture(false),
424         material(false),
425         lighting(false),
426         specular(false),
427         normalmap(false),
428         shadow(false),
429         reflection(false),
430         transform(false)
431 { }
432
433 string Program::StandardFeatures::create_flags() const
434 {
435         string flags;
436         if(texture)
437                 flags += 't';
438         if(material)
439                 flags += 'm';
440         if(lighting)
441         {
442                 flags += 'l';
443                 if(specular)
444                         flags += 'p';
445                 if(normalmap)
446                         flags += 'n';
447         }
448         if(shadow)
449                 flags += 's';
450         if(reflection)
451                 flags += 'e';
452         if(transform)
453                 flags += 'r';
454
455         return flags;
456 }
457
458
459 Program::Loader::Loader(Program &p):
460         DataFile::ObjectLoader<Program>(p)
461 {
462         add("attribute",       &Loader::attribute);
463         add("fragment_shader", &Loader::fragment_shader);
464         add("standard",        &Loader::standard);
465         add("vertex_shader",   &Loader::vertex_shader);
466 }
467
468 void Program::Loader::finish()
469 {
470         obj.link();
471 }
472
473 void Program::Loader::attribute(unsigned i, const string &n)
474 {
475         obj.bind_attribute(i, n);
476 }
477
478 void Program::Loader::fragment_shader(const string &src)
479 {
480         obj.attach_shader_owned(new FragmentShader(src));
481 }
482
483 void Program::Loader::standard()
484 {
485         StandardFeatures feat;
486         load_sub(feat);
487         obj.add_standard_shaders(feat);
488 }
489
490 void Program::Loader::vertex_shader(const string &src)
491 {
492         obj.attach_shader_owned(new VertexShader(src));
493 }
494
495
496 Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
497         DataFile::ObjectLoader<StandardFeatures>(f)
498 {
499         add("lighting",  &StandardFeatures::lighting);
500         add("material",  &StandardFeatures::material);
501         add("normalmap", &StandardFeatures::normalmap);
502         add("shadow",    &StandardFeatures::shadow);
503         add("specular",  &StandardFeatures::specular);
504         add("texture",   &StandardFeatures::texture);
505         add("transform", &StandardFeatures::transform);
506 }
507
508 } // namespace GL
509 } // namespace Msp