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