]> git.tdb.fi Git - libs/gl.git/blob - source/programbuilder.cpp
Use uniform blocks in generated shaders if supported
[libs/gl.git] / source / programbuilder.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <set>
4 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
5 #include <msp/strings/format.h>
6 #include <msp/strings/utils.h>
7 #include "extension.h"
8 #include "program.h"
9 #include "programbuilder.h"
10 #include "shader.h"
11 #include "vertexformat.h"
12
13 using namespace std;
14
15 namespace Msp {
16 namespace GL {
17
18 /*
19 Naming conventions:
20   n_*        Normalized vector
21   l_*        Lighting component
22
23   obj_*      Object space
24   eye_*      Eye space
25   tbn_*      Tangent-Binormal-Normal space
26   shd_*      Shadow space
27   env_*      Environment space
28   *_dir      Direction vector
29
30   zzz_*      Wildcard space, resolved by the builder
31              All wildcard spaces within an expression must match
32
33   xxx_yyy_*  Matrix that transforms between yyy to xxx
34              The vector is on the side of its designated space, result will be
35              in the other space
36   *_matrix   A matrix (duh)
37   *_rmatrix  A mat4 that works with a row vector
38
39   rgb_*      Color with rgb components only
40   color_*    Color with rgba components
41 */
42
43 /* The array is stored in reverse order, so that variables always come after
44 anything that might need them. */
45 const ProgramBuilder::VariableDefinition ProgramBuilder::standard_variables[] =
46 {
47         { FRAGMENT, "gl_FragColor", "vec4", "frag_color", "g" },
48         { FRAGMENT, "frag_color", "vec4", "basic_color", "!e!l" },
49         { FRAGMENT, "frag_color", "vec4", "vec4(rgb_surface, surface_alpha)", "!el" },
50         { FRAGMENT, "frag_color", "vec4", "vec4(rgb_surface+rgb_reflection, surface_alpha)", "e" },
51
52         { FRAGMENT, "rgb_reflection", "vec3", "reflect_sample.rgb*reflectivity", 0 },
53         { FRAGMENT, "reflect_sample", "vec4", "textureCube(environment, env_reflect_dir)", 0 },
54         { FRAGMENT, "env_reflect_dir", "vec3", "env_eye_matrix*eye_reflect_dir", 0 },
55         { FRAGMENT, "eye_reflect_dir", "vec3", "eye_tbn_matrix*tbn_reflect_dir", "n" },
56
57         { FRAGMENT, "rgb_surface", "vec3", "rgb_unlit_surface", "!l" },
58         { FRAGMENT, "rgb_surface", "vec3", "rgb_lit_surface", "l" },
59         { FRAGMENT, "rgb_unlit_surface", "vec3", "basic_color.rgb", "!s" },
60         { FRAGMENT, "rgb_unlit_surface", "vec3", "basic_color.rgb*l_shadow", "s" },
61         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_illumination_diffuse", "!m" },
62         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_surface_ambient+rgb_surface_diffuse", "m!p" },
63         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_surface_ambient+rgb_surface_diffuse+rgb_surface_specular", "mp" },
64
65         { FRAGMENT, "surface_alpha", "float", "basic_color.a", "!m" },
66         { FRAGMENT, "surface_alpha", "float", "basic_color.a", "m!l" },
67         { FRAGMENT, "surface_alpha", "float", "material.diffuse.a", "ml!t" },
68         { FRAGMENT, "surface_alpha", "float", "material.diffuse.a*tex_sample.a", "mlt" },
69         { FRAGMENT, "basic_color", "vec4", "vec4(1.0)", "!m!t" },
70         { FRAGMENT, "basic_color", "vec4", "tex_sample", "!mt" },
71         { FRAGMENT, "basic_color", "vec4", "color", "m!t" },
72         { FRAGMENT, "basic_color", "vec4", "color*tex_sample", "mt" },
73
74         { FRAGMENT, "rgb_surface_ambient", "vec3", "rgb_illumination_ambient*material.ambient.rgb", "!t" },
75         { FRAGMENT, "rgb_surface_ambient", "vec3", "rgb_illumination_ambient*material.ambient.rgb*tex_sample.rgb", "t" },
76         { FRAGMENT, "rgb_illumination_ambient", "vec3", "ambient_color.rgb", "!y" },
77         { FRAGMENT, "rgb_illumination_ambient", "vec3", "ambient_color.rgb+l_skylight*sky_color.rgb", "y" },
78         { FRAGMENT, "l_skylight", "float", "dot(n_zzz_normal, zzz_sky_dir)*0.5+0.5", 0 },
79
80         { FRAGMENT, "rgb_surface_specular", "vec3", "rgb_illumination_specular*material.specular.rgb", 0 },
81         { FRAGMENT, "rgb_illumination_specular", "vec3", "rgb_illumination_specular_direct", "!y|e" },
82         { FRAGMENT, "rgb_illumination_specular", "vec3", "rgb_illumination_specular_direct+l_sky_specular*sky_color.rgb", "y!e" },
83         { FRAGMENT, "rgb_illumination_specular_direct", "vec3", "rgb_light_specular", "!s" },
84         { FRAGMENT, "rgb_illumination_specular_direct", "vec3", "rgb_light_specular*l_shadow", "s" },
85         { FRAGMENT, "rgb_light_specular[i]", "vec3", "l_specular[i]*light_sources[i].specular.rgb", 0 },
86         { FRAGMENT, "l_sky_specular", "float", "pow((1.0-pow(clamp(dot(zzz_reflect_dir, zzz_sky_dir)-horizon_limit, -1.0, 0.0), 2.0)), material.shininess/2.0)", 0 },
87         { FRAGMENT, "l_specular[i]", "float", "pow(max(dot(n_zzz_half_vec[i], n_zzz_normal), 0.0), material.shininess)", 0 },
88
89         { FRAGMENT, "rgb_surface_diffuse", "vec3", "rgb_illumination_diffuse*material.diffuse.rgb", "!t" },
90         { FRAGMENT, "rgb_surface_diffuse", "vec3", "rgb_illumination_diffuse*material.diffuse.rgb*tex_sample.rgb", "t" },
91         { FRAGMENT, "rgb_illumination_diffuse", "vec3", "rgb_light_diffuse", "!s" },
92         { FRAGMENT, "rgb_illumination_diffuse", "vec3", "rgb_light_diffuse*l_shadow", "s" },
93         { FRAGMENT, "rgb_light_diffuse[i]", "vec3", "l_diffuse[i]*light_sources[i].diffuse.rgb", 0 },
94         { FRAGMENT, "l_diffuse[i]", "float", "max(dot(n_zzz_normal, n_zzz_light_dir[i]), 0.0)", 0 },
95
96         { FRAGMENT, "l_shadow", "float", "mix(1.0, shadow_sample, shadow_darkness)", 0 },
97         { FRAGMENT, "shadow_sample", "float", "shadow2D(shadow, shd_vertex).r", 0 },
98
99         { FRAGMENT, "zzz_reflect_dir", "vec3", "reflect(zzz_incident_dir, n_zzz_normal)", 0 },
100         { FRAGMENT, "n_zzz_half_vec[i]", "vec3", "normalize(zzz_light_dir[i]-zzz_incident_dir)", 0 },
101         { FRAGMENT, "n_zzz_light_dir[i]", "vec3", "normalize(zzz_light_dir[i])", 0 },
102         { FRAGMENT, "n_tbn_normal", "vec3", "normal_sample*2.0-1.0", "n" },
103         { FRAGMENT, "n_eye_normal", "vec3", "normalize(eye_normal)", "!n" },
104         { FRAGMENT, "normal_sample", "vec3", "texture2D(normalmap, texture_coord).xyz", 0 },
105         { FRAGMENT, "tex_sample", "vec4", "texture2D(texture, texture_coord)", 0 },
106
107         { VERTEX, "gl_Position", "vec4", "projection_matrix*eye_vertex", 0 },
108         { VERTEX, "shd_vertex", "vec3", "vec3(dot(eye_vertex, gl_EyePlaneS[shadow_unit]), dot(eye_vertex, gl_EyePlaneT[shadow_unit]), dot(eye_vertex, gl_EyePlaneR[shadow_unit]))", "g" },
109         { VERTEX, "shd_vertex", "vec3", "(shd_eye_matrix*eye_vertex).xyz", "!g" },
110         { VERTEX, "tbn_sky_dir", "vec3", "eye_sky_dir*eye_tbn_matrix", "n" },
111         { VERTEX, "tbn_light_dir[i]", "vec3", "eye_light_dir[i]*eye_tbn_matrix", 0 },
112         { VERTEX, "eye_light_dir[i]", "vec3", "normalize(eye_light_position[i].xyz-eye_vertex.xyz*eye_light_position[i].w)", 0 },
113         { VERTEX, "eye_light_position[i]", "vec4", "light_sources[i].position", 0 },
114         { VERTEX, "tbn_incident_dir", "vec3", "eye_incident_dir*eye_tbn_matrix", 0 },
115         { VERTEX, "eye_incident_dir", "vec3", "normalize(eye_vertex.xyz)", 0 },
116         { VERTEX, "eye_tbn_matrix", "mat3", "mat3(eye_tangent, eye_binormal, eye_normal)", 0 },
117         { VERTEX, "eye_vertex", "vec4", "eye_obj_matrix*vertex", 0 },
118         { VERTEX, "eye_normal", "vec3", "eye_obj_normal_matrix*normal", 0 },
119         { VERTEX, "eye_tangent", "vec3", "eye_obj_normal_matrix*tangent", 0 },
120         { VERTEX, "eye_binormal", "vec3", "eye_obj_normal_matrix*binormal", 0 },
121         { VERTEX, "texture_coord", "vec2", "texcoord.xy", 0 },
122
123         { ATTRIBUTE, "vertex", "vec4", "gl_Vertex", 0 },
124         { ATTRIBUTE, "texcoord", "vec4", "gl_MultiTexCoord0", 0 },
125         { ATTRIBUTE, "color", "vec4", "gl_Color", 0 },
126         { ATTRIBUTE, "normal", "vec3", "gl_Normal", 0 },
127         { ATTRIBUTE, "tangent", "vec3", 0, 0 },
128         { ATTRIBUTE, "binormal", "vec3", 0, 0 },
129
130         { UNIFORM, "ShadowMap::shadow_unit", "int", 0, 0 },
131         { UNIFORM, "texture", "sampler2D", 0, 0 },
132         { UNIFORM, "shadow", "sampler2DShadow", 0, 0 },
133         { UNIFORM, "ShadowMap::shadow_darkness", "float", 0, 0 },
134         { UNIFORM, "normalmap", "sampler2D", 0, 0 },
135         { UNIFORM, "environment", "samplerCube", 0, 0 },
136         { UNIFORM, "EnvMap::env_eye_matrix", "mat3", 0, 0 },
137         { UNIFORM, "EnvMap::reflectivity", "float", 0, 0 },
138         { UNIFORM, "eye_obj_matrix", "mat4", "gl_ModelViewMatrix", 0 },
139         { UNIFORM, "eye_obj_normal_matrix", "mat3", "gl_NormalMatrix", 0 },
140         { UNIFORM, "projection_matrix", "mat4", "gl_ProjectionMatrix", 0 },
141         { UNIFORM, "ShadowMap::shd_eye_matrix", "mat4", 0, 0 },
142         { UNIFORM, "Lighting::light_sources", "LightSourceParameters[MAX_LIGHTS]", "gl_LightSource[i]", 0 },
143         { UNIFORM, "Lighting::ambient_color", "vec4", 0, 0 },
144         { UNIFORM, "Lighting::sky_color", "vec4", 0, 0 },
145         { UNIFORM, "Lighting::eye_sky_dir", "vec3", 0, 0 },
146         { UNIFORM, "Lighting::horizon_limit", "float", 0, 0 },
147         { UNIFORM, "Material::material", "MaterialParameters", "gl_FrontMaterial", 0 },
148
149         { TYPE, "LightSourceParameters", "struct { vec4 position; vec4 diffuse; vec4 specular; }", "gl_LightSourceParameters", 0 },
150         { TYPE, "MaterialParameters", "struct { vec4 ambient; vec4 diffuse; vec4 specular; float shininess; }", "gl_MaterialParameters", 0 },
151
152         // Terminator entry
153         { NO_SCOPE, 0, 0, 0, 0 }
154 };
155
156 const char ProgramBuilder::interfaces[] = { 0, 0, 0, 0, 'v', 0 };
157
158 ProgramBuilder::ProgramBuilder(const StandardFeatures &f):
159         features(f),
160         feature_flags(features.create_flags()),
161         optimize(true)
162 {
163         if(!features.custom.empty())
164         {
165                 const char *whitespace = " \t\n";
166                 string::size_type start = 0;
167                 while(1)
168                 {
169                         start = features.custom.find_first_not_of(whitespace, start);
170                         if(start==string::npos)
171                                 break;
172
173                         string::size_type semicolon = features.custom.find(';', start);
174                         if(semicolon==start)
175                         {
176                                 ++start;
177                                 continue;
178                         }
179                         else if(semicolon==string::npos)
180                                 throw invalid_variable_definition(features.custom.substr(start));
181
182                         string::size_type equals = features.custom.find('=', start);
183                         if(equals>semicolon)
184                                 equals = string::npos;
185
186                         VariableDefinition var;
187                         string::size_type decl_end = min(equals, semicolon);
188                         for(unsigned i=0;; ++i)
189                         {
190                                 string::size_type word_end = features.custom.find_first_of(whitespace, start);
191                                 word_end = min(word_end, decl_end);
192                                 features.custom[word_end] = 0;
193
194                                 const char *word = &features.custom[start];
195                                 if(i==0)
196                                 {
197                                         if(!strcmp(word, "uniform"))
198                                                 var.scope = UNIFORM;
199                                         else if(!strcmp(word, "attribute"))
200                                                 var.scope = ATTRIBUTE;
201                                         else if(!strcmp(word, "vertex"))
202                                                 var.scope = VERTEX;
203                                         else if(!strcmp(word, "fragment"))
204                                                 var.scope = FRAGMENT;
205                                         else
206                                                 throw invalid_variable_definition(word);
207                                 }
208                                 else if(i==1)
209                                         var.type = word;
210                                 else if(i==2)
211                                         var.name = word;
212
213                                 start = features.custom.find_first_not_of(whitespace, word_end+1);
214                                 if(start>=decl_end)
215                                         break;
216                         }
217
218                         if(equals!=string::npos)
219                         {
220                                 start = features.custom.find_first_not_of(whitespace, equals+1);
221                                 if(start>=semicolon)
222                                         throw invalid_variable_definition("no expression");
223                                 features.custom[semicolon] = 0;
224                                 var.expression = &features.custom[start];
225                         }
226                         else
227                                 var.expression = 0;
228
229                         var.flags = 0;
230                         for(const VariableDefinition *j=standard_variables; j->name; ++j)
231                                 if(!strcmp(var.name, j->name))
232                                         var.flags = "o";
233
234                         custom_variables.push_front(var);
235
236                         start = semicolon+1;
237                 }
238         }
239 }
240
241 void ProgramBuilder::set_optimize(bool o)
242 {
243         optimize = o;
244 }
245
246 Program *ProgramBuilder::create_program() const
247 {
248         Program *prog = new Program;
249         add_shaders(*prog);
250         return prog;
251 }
252
253 void ProgramBuilder::add_shaders(Program &prog) const
254 {
255         list<ShaderVariable> variables;
256         list<ShaderVariable *> resolved_vars;
257
258         variables.push_front(ShaderVariable("gl_Position"));
259         variables.push_front(ShaderVariable(features.legacy ? "gl_FragColor" : "frag_color"));
260
261         list<VariableDefinition>::const_iterator next_custom = custom_variables.begin();
262         for(const VariableDefinition *i=standard_variables; i->name; )
263         {
264                 const VariableDefinition *def = 0;
265                 if(next_custom!=custom_variables.end() && (!strcmp(next_custom->name, i->name) || !next_custom->flags))
266                 {
267                         def = &*next_custom;
268                         ++next_custom;
269                 }
270                 else
271                 {
272                         def = i;
273                         ++i;
274
275                         // Skip over anything that isn't used with the supplied flags
276                         if(def->flags && !evaluate_flags(def->flags))
277                                 continue;
278                 }
279
280                 if(def->scope==TYPE)
281                 {
282                         for(list<ShaderVariable *>::iterator j=resolved_vars.begin(); j!=resolved_vars.end(); ++j)
283                                 if(!(*j)->type && name_match(def->name, (*j)->variable->type))
284                                         (*j)->resolve_type(*def);
285
286                         continue;
287                 }
288
289                 const char *def_uq_name = unqualified_name(def->name);
290
291                 // See if this variable can satisfy any unresolved variables
292                 ShaderVariable *last_resolved = 0;
293                 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
294                 {
295                         if(j->variable)
296                                 continue;
297
298                         if(!name_match(def_uq_name, j->resolved_name.c_str()))
299                                 continue;
300
301                         if(last_resolved)
302                         {
303                                 /* We've already resolved a non-fuzzy variable in this iteration.
304                                 If there are multiple variables that can be resolved, they refer
305                                 to the same variable. */
306                                 j->resolve(*last_resolved);
307                                 continue;
308                         }
309
310                         j->resolve(*def);
311                         resolved_vars.push_front(&*j);
312                         if(!j->fuzzy_space)
313                                 last_resolved = &*j;
314
315                         if(!def->expression)
316                                 continue;
317
318                         vector<string> identifiers = extract_identifiers(def->expression);
319                         for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
320                         {
321                                 // Use an existing variable if possible, but only if it's not fuzzy
322                                 ShaderVariable *var = 0;
323                                 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
324                                         if(!l->fuzzy_space && l->resolved_name==*k)
325                                                 var = &*l;
326
327                                 if(!var)
328                                 {
329                                         variables.push_back(ShaderVariable(*k));
330                                         var = &variables.back();
331                                 }
332                                 j->add_reference(*var);
333                         }
334                 }
335         }
336
337         // Array sizes need to be resolved for inline processing
338         for(list<ShaderVariable>::iterator i=variables.end(); i!=variables.begin(); )
339                 (--i)->resolve_array(features);
340
341         for(list<ShaderVariable *>::const_iterator i=resolved_vars.begin(); i!=resolved_vars.end(); ++i)
342                 (*i)->check_inline(features.legacy, !optimize);
343
344         prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
345         prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
346
347         if(!features.legacy)
348         {
349                 prog.bind_fragment_data(0, "frag_color");
350                 prog.bind_attribute(VERTEX4, "vertex");
351                 if(features.lighting)
352                         prog.bind_attribute(NORMAL3, "normal");
353                 else if(features.material)
354                         prog.bind_attribute(COLOR4_FLOAT, "color");
355                 if(features.texture || features.normalmap)
356                         prog.bind_attribute(TEXCOORD4, "texcoord");
357         }
358         if(features.normalmap)
359         {
360                 prog.bind_attribute(get_component_type(TANGENT3), "tangent");
361                 prog.bind_attribute(get_component_type(BINORMAL3), "binormal");
362         }
363 }
364
365 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
366 {
367         string source;
368
369         bool use_blocks = !features.legacy && ARB_uniform_buffer_object;
370
371         if(!features.legacy)
372         {
373                 source += "#version 130\n";
374                 if(use_blocks)
375                         source += "#extension GL_ARB_uniform_buffer_object: require\n";
376         }
377
378         set<const VariableDefinition *> declared_types;
379         set<string> uniform_blocks;
380         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
381                 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope) && !(*i)->inlined)
382                 {
383                         if((*i)->type && !declared_types.count((*i)->type))
384                         {
385                                 source += format("%s;\n", (*i)->create_type_declaration());
386                                 declared_types.insert((*i)->type);
387                         }
388
389                         if(!(*i)->resolved_block.empty() && use_blocks)
390                                 uniform_blocks.insert((*i)->resolved_block);
391                         else
392                                 source += format("uniform %s;\n", (*i)->create_declaration());
393                 }
394
395         for(set<string>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
396         {
397                 source += format("uniform %s\n{\n", *i);
398                 for(list<ShaderVariable *>::const_iterator j=variables.begin(); j!=variables.end(); ++j)
399                         if((*j)->resolved_block==*i)
400                                 source += format("\t%s;\n", (*j)->create_declaration());
401                 source += "};\n";
402         }
403
404         /* Interface variables need to have global declarations. */
405         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
406         {
407                 if(!(*i)->resolved_name.compare(0, 3, "gl_"))
408                         continue;
409
410                 InterfaceFlags interface = (*i)->get_interface_flags(scope);
411
412                 if(interface&INPUT)
413                 {
414                         const char *qualifier = (features.legacy ? scope==VERTEX ? "attribute" : "varying" : "in");
415                         source += format("%s %s;\n", qualifier, (*i)->create_declaration(interfaces[scope-1]));
416                 }
417
418                 if(interface&OUTPUT)
419                 {
420                         const char *qualifier = (features.legacy ? "varying" : "out");
421                         source += format("%s %s;\n", qualifier, (*i)->create_declaration(interfaces[scope]));
422                 }
423         }
424
425         source += "void main()\n{\n";
426
427         list<ShaderVariable *> loop_vars;
428         unsigned loop_size = 0;
429         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
430         {
431                 if(!loop_vars.empty() && !loop_vars.back()->in_loop && (*i)->array_size!=loop_size)
432                 {
433                         /* Declare all variables that need to be visible outside the loop.
434                         Output variables are already declared. */
435                         for(list<ShaderVariable *>::const_iterator j=loop_vars.begin(); j!=loop_vars.end(); ++j)
436                         {
437                                 InterfaceFlags interface = (*j)->get_interface_flags(scope);
438                                 if(!(*j)->in_loop && !(interface&OUTPUT))
439                                         source += format("\t%s;\n", (*j)->create_declaration());
440                         }
441
442                         source += format("\tfor(int i=0; i<%d; ++i)\n\t{\n", loop_size);
443                         for(list<ShaderVariable *>::const_iterator j=loop_vars.begin(); j!=loop_vars.end(); ++j)
444                         {
445                                 if((*j)->variable->scope==scope && !(*j)->inlined)
446                                 {
447                                         string decl;
448                                         if((*j)->in_loop)
449                                                 decl = (*j)->create_declaration(0, true);
450                                         else
451                                         {
452                                                 decl = (*j)->resolved_name;
453                                                 if(!(*j)->array_sum)
454                                                         decl += "[i]";
455                                         }
456                                         const char *oper = ((*j)->array_sum ? "+=" : "=");
457                                         source += format("\t\t%s %s %s;\n", decl, oper, (*j)->create_expression("i"));
458                                 }
459
460                                 InterfaceFlags interface = (*j)->get_interface_flags(scope);
461                                 if(interface&OUTPUT)
462                                 {
463                                         string expr = ((*j)->inlined ? (*j)->create_expression("i") : (*j)->resolved_name+"[i]");
464                                         source += format("\t\t%c_%s[i] = %s;\n", interfaces[scope], (*j)->resolved_name, expr);
465                                 }
466                         }
467                         source += "\t}\n";
468
469                         loop_vars.clear();
470                 }
471
472                 InterfaceFlags interface = (*i)->get_interface_flags(scope);
473
474                 if((*i)->array_size>1)
475                 {
476                         if((*i)->variable->scope==scope || (interface&OUTPUT))
477                         {
478                                 loop_size = (*i)->array_size;
479                                 loop_vars.push_back(*i);
480                         }
481                         continue;
482                 }
483
484                 if((*i)->variable->scope==scope && !(*i)->inlined)
485                 {
486                         string decl = ((interface&GOAL) ? (*i)->resolved_name : (*i)->create_declaration());
487                         source += format("\t%s = %s;\n", decl, (*i)->create_expression());
488                 }
489
490                 if((interface&(OUTPUT|GOAL))==OUTPUT)
491                 {
492                         string expr = ((*i)->inlined ? (*i)->create_expression() : (*i)->resolved_name);
493                         source += format("\t%c_%s = %s;\n", interfaces[scope], (*i)->resolved_name, expr);
494                 }
495         }
496
497         source += '}';
498
499         return source;
500 }
501
502 bool ProgramBuilder::evaluate_flags(const char *flags) const
503 {
504         if(!flags)
505                 return true;
506
507         bool cond = true;
508         char oper = '&';
509         for(const char *i=flags; *i; ++i)
510         {
511                 if(*i>='a' && *i<='z')
512                 {
513                         bool found = (feature_flags.find(*i)!=string::npos);
514                         if(oper=='|')
515                                 cond = (cond || found);
516                         else if(oper=='!')
517                                 cond = (cond && !found);
518                         else if(oper=='&')
519                                 cond = (cond && found);
520                         oper = '&';
521                 }
522                 else
523                         oper = *i;
524         }
525
526         return cond;
527 }
528
529 const char *ProgramBuilder::unqualified_name(const char *name)
530 {
531         for(const char *p=name; *p; ++p)
532                 if(*p==':' && *++p==':')
533                         name = p+1;
534         return name;
535 }
536
537 ProgramBuilder::MatchType ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
538 {
539         int i = 0;
540         int zzz = -1;
541         int zside = 0;
542         while(*n1 && *n2)
543         {
544                 if(*n1==*n2 || *n1=='z' || *n2=='z')
545                 {
546                         if(*n1!=*n2)
547                         {
548                                 int side = (*n1=='z' ? 1 : 2);
549                                 if(zzz<0)
550                                 {
551                                         zzz = i;
552                                         zside = side;
553                                         if(space)
554                                         {
555                                                 if(*n1=='z')
556                                                         *space = n2;
557                                                 else
558                                                         *space = n1;
559                                         }
560                                 }
561                                 else if(i>=zzz+3 || side!=zside)
562                                         return NO_MATCH;
563                         }
564                 }
565                 else
566                         return NO_MATCH;
567                 ++n1;
568                 ++n2;
569                 ++i;
570         }
571         return (!*n1 && !*n2) ? (zzz>=0 ? FUZZY : EXACT) : ((*n1=='[' || *n2=='[') ? ARRAY : NO_MATCH);
572 }
573
574 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
575 {
576         bool found = false;
577         bool member = false;
578         bool subscript = false;
579         for(const char *i=ptr;; ++i)
580         {
581                 if(!found)
582                 {
583                         if(!*i)
584                                 return false;
585                         if(isalpha(*i) || *i=='_')
586                         {
587                                 if(!member)
588                                 {
589                                         start = i-ptr;
590                                         found = true;
591                                 }
592                         }
593                         else if(*i=='.')
594                                 member = true;
595                         else
596                                 member = false;
597                 }
598                 else
599                 {
600                         if(subscript)
601                         {
602                                 if(*i==']')
603                                 {
604                                         length = i+1-(ptr+start);
605                                         return true;
606                                 }
607                                 else if(!isalpha(*i) || i>ptr+start+length+1)
608                                         return true;
609                         }
610                         else if(!isalnum(*i) && *i!='_')
611                         {
612                                 length = i-(ptr+start);
613                                 if(*i=='[')
614                                         subscript = true;
615                                 else
616                                         return true;
617                         }
618                 }
619         }
620 }
621
622 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
623 {
624         vector<string> result;
625         const char *ptr = expression;
626         unsigned start = 0;
627         unsigned length = 0;
628         while(parse_identifier(ptr, start, length))
629         {
630                 result.push_back(string(ptr+start, length));
631                 ptr += start+length;
632         }
633         return result;
634 }
635
636 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map)
637 {
638         string result;
639         const char *ptr = expression;
640         unsigned start = 0;
641         unsigned length = 0;
642         while(parse_identifier(ptr, start, length))
643         {
644                 result.append(ptr, start);
645                 string identifier(ptr+start, length);
646                 map<string, string>::const_iterator i = replace_map.find(identifier);
647                 if(i!=replace_map.end())
648                         result += i->second;
649                 else
650                         result += identifier;
651                 ptr += start+length;
652         }
653         result += ptr;
654         return result;
655 }
656
657
658 ProgramBuilder::StandardFeatures::StandardFeatures():
659         texture(false),
660         material(false),
661         lighting(false),
662         max_lights(1),
663         skylight(false),
664         specular(false),
665         normalmap(false),
666         shadow(false),
667         reflection(false),
668         legacy(!(get_glsl_version()>=Version(1, 30)))
669 { }
670
671 string ProgramBuilder::StandardFeatures::create_flags() const
672 {
673         string flags;
674         if(texture)
675                 flags += 't';
676         if(material)
677                 flags += 'm';
678         if(lighting)
679         {
680                 flags += 'l';
681                 if(skylight)
682                         flags += 'y';
683                 if(specular)
684                         flags += 'p';
685                 if(normalmap)
686                         flags += 'n';
687         }
688         if(shadow)
689                 flags += 's';
690         if(reflection)
691                 flags += 'e';
692         if(legacy)
693                 flags += 'g';
694
695         return flags;
696 }
697
698
699 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
700         name(n),
701         variable(0),
702         type(0),
703         resolved_name(n),
704         fuzzy_space(name.find("zzz")!=string::npos),
705         array_sum(false),
706         array_size(0),
707         inlined(false),
708         inline_parens(false),
709         in_loop(false)
710 {
711         string::size_type bracket = name.find('[');
712         if(bracket!=string::npos)
713                 array_subscript = name.substr(bracket+1, name.size()-bracket-2);
714 }
715
716 void ProgramBuilder::ShaderVariable::resolve(const VariableDefinition &var)
717 {
718         variable = &var;
719         const char *space = 0;
720         const char *var_uq_name = unqualified_name(variable->name);
721         MatchType match = name_match(var_uq_name, resolved_name.c_str(), &space);
722
723         if(var_uq_name!=variable->name)
724                 resolved_block.assign(variable->name, var_uq_name-2);
725
726         if(match==FUZZY)
727                 resolve_space(string(space, 3));
728         else if(match==ARRAY)
729         {
730                 if(array_subscript.empty())
731                         array_sum = true;
732                 else if(var.scope==UNIFORM)
733                 {
734                         const char *bracket = strrchr(variable->type, '[');
735                         if(bracket)
736                                 array_subscript = string(bracket+1, strlen(bracket)-2);
737                 }
738         }
739 }
740
741 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
742 {
743         for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
744                 (*i)->update_reference(*this, var);
745         var.referenced_by.insert(var.referenced_by.end(), referenced_by.begin(), referenced_by.end());
746 }
747
748 void ProgramBuilder::ShaderVariable::resolve_type(const VariableDefinition &var)
749 {
750         type = &var;
751 }
752
753 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
754 {
755         if(fuzzy_space)
756         {
757                 resolved_space = space;
758
759                 string::size_type zzz = resolved_name.find("zzz");
760                 resolved_name.replace(zzz, 3, resolved_space);
761                 fuzzy_space = false;
762
763                 // Resolving the space could have affected other variables that use this one
764                 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
765                         (*i)->resolve_space(space);
766         }
767
768         for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
769                 if((*i)->fuzzy_space)
770                         (*i)->resolve_space(space);
771 }
772
773 void ProgramBuilder::ShaderVariable::resolve_array(const StandardFeatures &features, unsigned size_hint)
774 {
775         if(array_size)
776                 return;
777         if(!array_sum && array_subscript.empty())
778                 return;
779
780         if(!array_subscript.empty())
781         {
782                 string::size_type bracket = resolved_name.find('[');
783                 if(bracket!=string::npos)
784                         resolved_name = resolved_name.substr(0, bracket);
785         }
786
787         if(variable && variable->scope==UNIFORM)
788         {
789                 if(array_subscript=="MAX_LIGHTS")
790                         array_size = features.max_lights;
791                 else if(isnumrc(array_subscript))
792                         array_size = lexical_cast<unsigned>(array_subscript);
793                 else
794                         throw invalid_variable_definition("invalid array size");
795         }
796
797         if(!array_size)
798         {
799                 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
800                         if((*i)->array_size)
801                         {
802                                 array_size = (*i)->array_size;
803                                 break;
804                         }
805         }
806
807         if(!array_size && size_hint)
808                 array_size = size_hint;
809
810         if(array_size)
811         {
812                 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
813                         if(!(*i)->array_subscript.empty() && !(*i)->array_size)
814                                 (*i)->resolve_array(features, array_size);
815         }
816 }
817
818 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
819 {
820         referenced_vars.push_back(&var);
821         var.referenced_by.push_back(this);
822         if(var.fuzzy_space && !resolved_space.empty())
823                 var.resolve_space(resolved_space);
824 }
825
826 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
827 {
828         replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
829         replace(referenced_by.begin(), referenced_by.end(), &from, &to);
830         if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
831                 resolve_space(to.resolved_space);
832 }
833
834 void ProgramBuilder::ShaderVariable::check_inline(bool allow_legacy, bool trivial_only)
835 {
836         if(variable->expression)
837         {
838                 if(array_sum && array_size>1)
839                         return;
840                 if(!allow_legacy && !strncmp(variable->expression, "gl_", 3))
841                         return;
842
843                 // Never inline goal variables
844                 if(referenced_by.empty())
845                         return;
846
847                 // Inline an expression consisting of a single identifier
848                 unsigned start, length;
849                 if(parse_identifier(variable->expression, start, length))
850                         if(start==0 && variable->expression[length]==0)
851                         {
852                                 inlined = true;
853                                 return;
854                         }
855
856                 if(trivial_only)
857                         return;
858
859                 /* If all references to the variable come from arrays in the same scope
860                 and of the same size, the variable can be embedded in the loop. */
861                 in_loop = (array_size>1 && !array_sum);
862                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
863                         if((*i)->variable->scope!=variable->scope || (*i)->array_size!=array_size)
864                                 in_loop = false;
865                 
866                 /* Count all refs to this variable.  Refs from array variables count once
867                 per loop iteration. */
868                 unsigned total_refs = 0;
869                 unsigned in_scope_refs = 0;
870                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
871                 {
872                         unsigned count = max((*i)->array_size*!in_loop, 1U);
873                         total_refs += count;
874                         if((*i)->variable->scope==variable->scope)
875                                 in_scope_refs += count;
876                 }
877
878                 /* Inline if there's only one ref, or if all refs are in other scopes.
879                 In the latter case, the actual inlining will happen in the interface
880                 variable assignment. */
881                 if(total_refs==1 || in_scope_refs==0)
882                 {
883                         inlined = true;
884                         unsigned level = 0;
885                         for(const char *c=variable->expression; (!inline_parens && *c); ++c)
886                         {
887                                 if(*c=='(')
888                                         ++level;
889                                 else if(*c==')')
890                                         --level;
891                                 else if(level==0 && !isalnum(*c) && *c!='_' && *c!='.')
892                                         inline_parens = true;
893                         }
894                 }
895         }
896 }
897
898 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
899 {
900         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
901                 if((*i)->variable->scope==scope)
902                         return true;
903         return false;
904 }
905
906 ProgramBuilder::InterfaceFlags ProgramBuilder::ShaderVariable::get_interface_flags(VariableScope scope) const
907 {
908         /* Uniforms are available to all stages and are not passed through
909         interfaces */
910         if(variable->scope==UNIFORM)
911                 return NO_INTERFACE;
912
913         int flags = NO_INTERFACE;
914
915         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
916         {
917                 /* Variables used in a later scope than they are declared in need to go
918                 through the interface */
919                 if((*i)->variable->scope>scope && variable->scope<=scope)
920                         flags |= OUTPUT;
921                 if((*i)->variable->scope>=scope && variable->scope<scope)
922                         if(!inlined || variable->scope!=ATTRIBUTE || scope!=VERTEX)
923                                 flags |= INPUT;
924         }
925
926         // Variables without any references are goals and also outputs.
927         if(referenced_by.empty() && variable->scope==scope)
928                 flags |= OUTPUT|GOAL;
929
930         return static_cast<InterfaceFlags>(flags);
931 }
932
933 string ProgramBuilder::ShaderVariable::create_type_declaration() const
934 {
935         if(!type)
936                 throw logic_error("no type");
937
938         if(!strncmp(type->type, "struct", 6))
939         {
940                 const char *brace = strchr(type->type, '{');
941                 if(brace)
942                         return format("struct %s %s", type->name, brace);
943         }
944
945         throw invalid_variable_definition("invalid typedef");
946 }
947
948 string ProgramBuilder::ShaderVariable::create_declaration(char interface, bool loop) const
949 {
950         if(variable->scope==UNIFORM && !array_subscript.empty())
951         {
952                 const char *bracket = strrchr(variable->type, '[');
953                 if(bracket)
954                         return format("%s %s[%d]", string(variable->type, bracket), resolved_name, array_size);
955         }
956
957         string array;
958         if(!array_sum && array_size>1 && !loop)
959                 array = format("[%d]", array_size);
960
961         if(interface)
962                 return format("%s %c_%s%s", variable->type, interface, resolved_name, array);
963         else
964                 return format("%s %s%s", variable->type, resolved_name, array);
965 }
966
967 string ProgramBuilder::ShaderVariable::create_replacement(VariableScope from_scope, const char *loop) const
968 {
969         string replacement = resolved_name;
970         InterfaceFlags interface = NO_INTERFACE;
971         if(variable)
972         {
973                 interface = get_interface_flags(from_scope);
974                 if((interface&INPUT) && interfaces[from_scope-1])
975                         replacement = format("%c_%s", interfaces[from_scope-1], replacement);
976                 else if(inlined)
977                 {
978                         replacement = create_expression(loop);
979                         if(inline_parens)
980                                 replacement = "("+replacement+")";
981                         return replacement;
982                 }
983         }
984
985         // Add an array subscript, unless the variable is embedded in a loop
986         if(!array_subscript.empty() && !in_loop)
987         {
988                 if(loop)
989                         return format("%s[%s]", replacement, loop);
990                 else if(!variable || variable->scope==UNIFORM)
991                         return replacement+"[0]";
992         }
993
994         return replacement;
995 }
996
997 string ProgramBuilder::ShaderVariable::create_expression(const char *loop) const
998 {
999         map<string, string> replace_map;
1000         for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
1001         {
1002                 string replacement = (*i)->create_replacement(variable->scope, loop);
1003                 if(replacement!=(*i)->name)
1004                         replace_map[(*i)->name] = replacement;
1005         }
1006
1007         if(replace_map.empty())
1008                 return variable->expression;
1009         else
1010                 return replace_identifiers(variable->expression, replace_map);
1011 }
1012
1013
1014 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
1015         DataFile::ObjectLoader<StandardFeatures>(f)
1016 {
1017         add("custom",    &StandardFeatures::custom);
1018         add("lighting",  &StandardFeatures::lighting);
1019         add("material",  &StandardFeatures::material);
1020         add("max_lights", &StandardFeatures::max_lights);
1021         add("normalmap", &StandardFeatures::normalmap);
1022         add("reflection", &StandardFeatures::reflection);
1023         add("shadow",    &StandardFeatures::shadow);
1024         add("skylight",  &StandardFeatures::skylight);
1025         add("specular",  &StandardFeatures::specular);
1026         add("texture",   &StandardFeatures::texture);
1027 }
1028
1029 } // namespace GL
1030 } // namespace Msp