]> git.tdb.fi Git - libs/gl.git/blob - source/programbuilder.cpp
Refactor certain variable operations into functions
[libs/gl.git] / source / programbuilder.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <msp/strings/format.h>
4 #include "extension.h"
5 #include "program.h"
6 #include "programbuilder.h"
7 #include "shader.h"
8 #include "vertexformat.h"
9
10 using namespace std;
11
12 namespace Msp {
13 namespace GL {
14
15 /*
16 Naming conventions:
17   n_*        Normalized vector
18   l_*        Lighting component
19
20   obj_*      Object space
21   eye_*      Eye space
22   tbn_*      Tangent-Binormal-Normal space
23   shd_*      Shadow space
24   env_*      Environment space
25   *_dir      Direction vector
26
27   zzz_*      Wildcard space, resolved by the builder
28              All wildcard spaces within an expression must match
29
30   xxx_yyy_*  Matrix that transforms between yyy to xxx
31              The vector is on the side of its designated space, result will be
32              in the other space
33   *_matrix   A matrix (duh)
34   *_rmatrix  A mat4 that works with a row vector
35
36   rgb_*      Color with rgb components only
37   color_*    Color with rgba components
38 */
39
40 /* The array are stored in reverse order, so that variables always come after
41 anything that might need them. */
42 const ProgramBuilder::VariableDefinition ProgramBuilder::standard_variables[] =
43 {
44         { FRAGMENT, "gl_FragColor", "vec4", "frag_color", "g" },
45         { FRAGMENT, "frag_color", "vec4", "color_base", "!t" },
46         { FRAGMENT, "frag_color", "vec4", "tex_sample", "!l!s!mt" },
47         { FRAGMENT, "frag_color", "vec4", "tex_sample*color_base", "l|s|mt" },
48         { FRAGMENT, "color_base", "vec4", "vec4(1.0)", "!l!s!m" },
49         { FRAGMENT, "color_base", "vec4", "color", "!l!sm" },
50         { FRAGMENT, "color_base", "vec4", "vec4(vec3(l_shadow), 1.0)", "!ls!m" },
51         { FRAGMENT, "color_base", "vec4", "color*vec4(vec3(l_shadow), 1.0)", "!lsm" },
52         { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_env, 1.0)", "l!m" },
53         { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_env, material.diffuse.a)", "lm" },
54         { FRAGMENT, "rgb_light_env", "vec3", "rgb_light_full+reflect_sample.rgb*reflectivity", "e" },
55         { FRAGMENT, "rgb_light_env", "vec3", "rgb_light_full", "!e" },
56         { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow+ambient_product_diffuse.rgb", "m" },
57         { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow", "!m" },
58         { FRAGMENT, "ambient_product_diffuse", "vec4", "gl_FrontLightModelProduct.sceneColor", "g" },
59         { FRAGMENT, "ambient_product_diffuse", "vec4", "ambient_color*material.diffuse", "!g" },
60         { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light*l_shadow", "s" },
61         { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light", "!s" },
62         { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse)", "!m!p" },
63         { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse+l_specular)", "!mp" },
64         { FRAGMENT, "rgb_light", "vec3", "l_diffuse*light_product_diffuse.rgb", "m!p" },
65         { FRAGMENT, "rgb_light", "vec3", "l_diffuse*light_product_diffuse.rgb+l_specular*light_product_specular.rgb", "mp" },
66         { FRAGMENT, "light_product_diffuse", "vec4", "gl_FrontLightProduct[0].diffuse", "g" },
67         { FRAGMENT, "light_product_diffuse", "vec4", "light_sources[0].diffuse*material.diffuse", "!g" },
68         { FRAGMENT, "light_product_specular", "vec4", "gl_FrontLightProduct[0].specular", "g" },
69         { FRAGMENT, "light_product_specular", "vec4", "light_sources[0].specular*material.specular", "!g" },
70         { FRAGMENT, "reflect_sample", "vec4", "textureCube(environment, env_reflect_dir)", 0 },
71         { FRAGMENT, "env_reflect_dir", "vec3", "env_eye_matrix*eye_reflect_dir", 0 },
72         { FRAGMENT, "eye_reflect_dir", "vec3", "eye_tbn_matrix*tbn_reflect_dir", "n" },
73         { FRAGMENT, "zzz_reflect_dir", "vec3", "reflect(zzz_incident_dir, n_zzz_normal)", 0 },
74         { FRAGMENT, "l_shadow", "float", "mix(1.0, shadow_sample, shadow_darkness)", 0 },
75         { FRAGMENT, "shadow_sample", "float", "shadow2D(shadow, shd_vertex).r", 0 },
76         { FRAGMENT, "l_diffuse", "float", "max(dot(n_zzz_normal, n_zzz_light_dir), 0.0)", 0 },
77         { FRAGMENT, "l_specular", "float", "pow(max(dot(n_zzz_half_vec, n_zzz_normal), 0.0), material.shininess)", 0 },
78         { FRAGMENT, "n_zzz_half_vec", "vec3", "normalize(zzz_light_dir-zzz_incident_dir)", 0 },
79         { FRAGMENT, "n_zzz_light_dir", "vec3", "normalize(zzz_light_dir)", 0 },
80         { FRAGMENT, "n_tbn_normal", "vec3", "normal_sample*2.0-1.0", "n" },
81         { FRAGMENT, "n_eye_normal", "vec3", "normalize(eye_normal)", "!n" },
82         { FRAGMENT, "normal_sample", "vec3", "texture2D(normalmap, texture_coord).xyz", 0 },
83         { FRAGMENT, "tex_sample", "vec4", "texture2D(texture, texture_coord)", 0 },
84
85         { VERTEX, "gl_Position", "vec4", "projection_matrix*eye_vertex", 0 },
86         { 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" },
87         { VERTEX, "shd_vertex", "vec3", "(shd_eye_matrix*eye_vertex).xyz", "!g" },
88         { VERTEX, "tbn_light_dir", "vec3", "eye_light_dir*eye_tbn_matrix", 0 },
89         { VERTEX, "eye_light_dir", "vec3", "normalize(eye_light_position.xyz-eye_vertex.xyz*eye_light_position.w)", 0 },
90         { VERTEX, "eye_light_position", "vec4", "light_sources[0].position", 0 },
91         { VERTEX, "tbn_incident_dir", "vec3", "eye_incident_dir*eye_tbn_matrix", 0 },
92         { VERTEX, "eye_incident_dir", "vec3", "normalize(eye_vertex.xyz)", 0 },
93         { VERTEX, "eye_tbn_matrix", "mat3", "mat3(eye_tangent, eye_binormal, eye_normal)", 0 },
94         { VERTEX, "eye_vertex", "vec4", "eye_obj_matrix*vertex", 0 },
95         { VERTEX, "eye_normal", "vec3", "eye_obj_normal_matrix*normal", 0 },
96         { VERTEX, "eye_tangent", "vec3", "eye_obj_normal_matrix*tangent", 0 },
97         { VERTEX, "eye_binormal", "vec3", "eye_obj_normal_matrix*binormal", 0 },
98         { VERTEX, "texture_coord", "vec2", "texcoord.xy", 0 },
99
100         { ATTRIBUTE, "vertex", "vec4", "gl_Vertex", 0 },
101         { ATTRIBUTE, "texcoord", "vec4", "gl_MultiTexCoord0", 0 },
102         { ATTRIBUTE, "color", "vec4", "gl_Color", 0 },
103         { ATTRIBUTE, "normal", "vec3", "gl_Normal", 0 },
104         { ATTRIBUTE, "tangent", "vec3", 0, 0 },
105         { ATTRIBUTE, "binormal", "vec3", 0, 0 },
106
107         { UNIFORM, "shadow_unit", "int", 0, 0 },
108         { UNIFORM, "texture", "sampler2D", 0, 0 },
109         { UNIFORM, "shadow", "sampler2DShadow", 0, 0 },
110         { UNIFORM, "shadow_darkness", "float", 0, 0 },
111         { UNIFORM, "normalmap", "sampler2D", 0, 0 },
112         { UNIFORM, "environment", "samplerCube", 0, 0 },
113         { UNIFORM, "env_eye_matrix", "mat3", 0, 0 },
114         { UNIFORM, "reflectivity", "float", 0, 0 },
115         { UNIFORM, "eye_obj_matrix", "mat4", "gl_ModelViewMatrix", 0 },
116         { UNIFORM, "eye_obj_normal_matrix", "mat3", "gl_NormalMatrix", 0 },
117         { UNIFORM, "projection_matrix", "mat4", "gl_ProjectionMatrix", 0 },
118         { UNIFORM, "shd_eye_matrix", "mat4", 0, 0 },
119         { UNIFORM, "light_sources", "struct { vec4 position; vec4 diffuse; vec4 specular; }[2]", "gl_LightSource", 0 },
120         { UNIFORM, "ambient_color", "vec4", 0, 0 },
121         { UNIFORM, "material", "struct { vec4 ambient; vec4 diffuse; vec4 specular; float shininess; }", "gl_FrontMaterial", 0 },
122
123         // Terminator entry
124         { NO_SCOPE, 0, 0, 0, 0 }
125 };
126
127 ProgramBuilder::ProgramBuilder(const StandardFeatures &f):
128         features(f),
129         feature_flags(features.create_flags()),
130         optimize(true)
131 {
132         if(!features.custom.empty())
133         {
134                 const char *whitespace = " \t\n";
135                 string::size_type start = 0;
136                 while(1)
137                 {
138                         start = features.custom.find_first_not_of(whitespace, start);
139                         if(start==string::npos)
140                                 break;
141
142                         string::size_type semicolon = features.custom.find(';', start);
143                         if(semicolon==start)
144                         {
145                                 ++start;
146                                 continue;
147                         }
148                         else if(semicolon==string::npos)
149                                 throw invalid_variable_definition(features.custom.substr(start));
150
151                         string::size_type equals = features.custom.find('=', start);
152                         if(equals>semicolon)
153                                 equals = string::npos;
154
155                         VariableDefinition var;
156                         string::size_type decl_end = min(equals, semicolon);
157                         for(unsigned i=0;; ++i)
158                         {
159                                 string::size_type word_end = features.custom.find_first_of(whitespace, start);
160                                 word_end = min(word_end, decl_end);
161                                 features.custom[word_end] = 0;
162
163                                 const char *word = &features.custom[start];
164                                 if(i==0)
165                                 {
166                                         if(!strcmp(word, "uniform"))
167                                                 var.scope = UNIFORM;
168                                         else if(!strcmp(word, "attribute"))
169                                                 var.scope = ATTRIBUTE;
170                                         else if(!strcmp(word, "vertex"))
171                                                 var.scope = VERTEX;
172                                         else if(!strcmp(word, "fragment"))
173                                                 var.scope = FRAGMENT;
174                                         else
175                                                 throw invalid_variable_definition(word);
176                                 }
177                                 else if(i==1)
178                                         var.type = word;
179                                 else if(i==2)
180                                         var.name = word;
181
182                                 start = features.custom.find_first_not_of(whitespace, word_end+1);
183                                 if(start>=decl_end)
184                                         break;
185                         }
186
187                         if(equals!=string::npos)
188                         {
189                                 start = features.custom.find_first_not_of(whitespace, equals+1);
190                                 if(start>=semicolon)
191                                         throw invalid_variable_definition("no expression");
192                                 features.custom[semicolon] = 0;
193                                 var.expression = &features.custom[start];
194                         }
195                         else
196                                 var.expression = 0;
197
198                         var.flags = 0;
199                         for(const VariableDefinition *j=standard_variables; j->name; ++j)
200                                 if(!strcmp(var.name, j->name))
201                                         var.flags = "o";
202
203                         custom_variables.push_front(var);
204
205                         start = semicolon+1;
206                 }
207         }
208 }
209
210 void ProgramBuilder::set_optimize(bool o)
211 {
212         optimize = o;
213 }
214
215 Program *ProgramBuilder::create_program() const
216 {
217         Program *prog = new Program;
218         add_shaders(*prog);
219         return prog;
220 }
221
222 void ProgramBuilder::add_shaders(Program &prog) const
223 {
224         list<ShaderVariable> variables;
225         list<ShaderVariable *> resolved_vars;
226
227         variables.push_front(ShaderVariable("gl_Position"));
228         variables.push_front(ShaderVariable(features.legacy ? "gl_FragColor" : "frag_color"));
229
230         list<VariableDefinition>::const_iterator next_custom = custom_variables.begin();
231         for(const VariableDefinition *i=standard_variables; i->name; )
232         {
233                 const VariableDefinition *def = 0;
234                 if(next_custom!=custom_variables.end() && (!strcmp(next_custom->name, i->name) || !next_custom->flags))
235                 {
236                         def = &*next_custom;
237                         ++next_custom;
238                 }
239                 else
240                 {
241                         def = i;
242                         ++i;
243
244                         // Skip over anything that isn't used with the supplied flags
245                         if(def->flags && !evaluate_flags(def->flags))
246                                 continue;
247                 }
248
249                 // See if this variable can satisfy any unresolved variables
250                 ShaderVariable *last_resolved = 0;
251                 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
252                 {
253                         if(j->variable)
254                                 continue;
255
256                         if(!name_match(def->name, j->resolved_name.c_str()))
257                                 continue;
258
259                         if(last_resolved)
260                         {
261                                 /* We've already resolved a non-fuzzy variable in this iteration.
262                                 If there are multiple variables that can be resolved, they refer
263                                 to the same variable. */
264                                 j->resolve(*last_resolved);
265                                 continue;
266                         }
267
268                         j->resolve(*def);
269                         resolved_vars.push_front(&*j);
270                         if(!j->fuzzy_space)
271                                 last_resolved = &*j;
272
273                         if(!def->expression)
274                                 continue;
275
276                         vector<string> identifiers = extract_identifiers(def->expression);
277                         for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
278                         {
279                                 // Use an existing variable if possible, but only if it's not fuzzy
280                                 ShaderVariable *var = 0;
281                                 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
282                                         if(!l->fuzzy_space && l->resolved_name==*k)
283                                                 var = &*l;
284
285                                 if(!var)
286                                 {
287                                         variables.push_back(ShaderVariable(*k));
288                                         var = &variables.back();
289                                 }
290                                 j->add_reference(*var);
291                         }
292                 }
293         }
294
295         for(list<ShaderVariable *>::const_iterator i=resolved_vars.begin(); i!=resolved_vars.end(); ++i)
296                 (*i)->check_inline(features.legacy, !optimize);
297
298         prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
299         prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
300
301         if(!features.legacy)
302         {
303                 prog.bind_fragment_data(0, "frag_color");
304                 prog.bind_attribute(VERTEX4, "vertex");
305                 if(features.lighting)
306                         prog.bind_attribute(NORMAL3, "normal");
307                 else if(features.material)
308                         prog.bind_attribute(COLOR4_FLOAT, "color");
309                 if(features.texture || features.normalmap)
310                         prog.bind_attribute(TEXCOORD4, "texcoord");
311         }
312         if(features.normalmap)
313         {
314                 prog.bind_attribute(get_component_type(TANGENT3), "tangent");
315                 prog.bind_attribute(get_component_type(BINORMAL3), "binormal");
316         }
317 }
318
319 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
320 {
321         string source;
322
323         if(!features.legacy)
324                 source += "#version 130\n";
325
326         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
327                 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope) && !(*i)->inlined)
328                         source += format("uniform %s;\n", (*i)->create_declaration());
329
330         if(scope==VERTEX)
331         {
332                 const char *qualifier = (features.legacy ? "attribute" : "in");
333                 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
334                         if((*i)->variable->scope==ATTRIBUTE && !(*i)->inlined)
335                                 source += format("%s %s;\n", qualifier, (*i)->create_declaration());
336         }
337
338         /* Any variables defined in vertex scope but referenced from fragment scope
339         should be exported as varyings over the interface. */
340         list<ShaderVariable *> varyings;
341         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
342                 if(((*i)->variable->scope==VERTEX || (*i)->variable->scope==ATTRIBUTE) && (*i)->is_referenced_from(FRAGMENT))
343                 {
344                         varyings.push_back(*i);
345                         const char *qualifier;
346                         if(!features.legacy)
347                                 qualifier = (scope==VERTEX ? "out" : "in");
348                         else
349                                 qualifier = "varying";
350                         source += format("%s %s;\n", qualifier, (*i)->create_declaration('v'));
351                 }
352
353         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
354                 if((*i)->referenced_by.empty() && (*i)->resolved_name.compare(0, 3, "gl_"))
355                         source += format("out %s;\n", (*i)->create_declaration());
356
357         source += "void main()\n{\n";
358
359         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
360                 if((*i)->variable->scope==scope && !(*i)->inlined)
361                 {
362                         source += '\t';
363                         if((*i)->referenced_by.empty())
364                                 source += (*i)->resolved_name;
365                         else
366                                 source += (*i)->create_declaration();
367                         source += format(" = %s;\n", (*i)->create_expression());
368                 }
369
370         if(scope==VERTEX)
371         {
372                 for(list<ShaderVariable *>::const_iterator i=varyings.begin(); i!=varyings.end(); ++i)
373                 {
374                         if((*i)->inlined)
375                                 source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->create_expression());
376                         else
377                                 source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->resolved_name);
378                 }
379         }
380
381         source += '}';
382
383         return source;
384 }
385
386 bool ProgramBuilder::evaluate_flags(const char *flags) const
387 {
388         if(!flags)
389                 return true;
390
391         bool cond = true;
392         char oper = '&';
393         for(const char *i=flags; *i; ++i)
394         {
395                 if(*i>='a' && *i<='z')
396                 {
397                         bool found = (feature_flags.find(*i)!=string::npos);
398                         if(oper=='|')
399                                 cond = (cond || found);
400                         else if(oper=='!')
401                                 cond = (cond && !found);
402                         else if(oper=='&')
403                                 cond = (cond && found);
404                         oper = '&';
405                 }
406                 else
407                         oper = *i;
408         }
409
410         return cond;
411 }
412
413 ProgramBuilder::MatchLevel ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
414 {
415         int i = 0;
416         int zzz = -1;
417         int zside = 0;
418         while(*n1 && *n2)
419         {
420                 if(*n1==*n2 || *n1=='z' || *n2=='z')
421                 {
422                         if(*n1!=*n2)
423                         {
424                                 int side = (*n1=='z' ? 1 : 2);
425                                 if(zzz<0)
426                                 {
427                                         zzz = i;
428                                         zside = side;
429                                         if(space)
430                                         {
431                                                 if(*n1=='z')
432                                                         *space = n2;
433                                                 else
434                                                         *space = n1;
435                                         }
436                                 }
437                                 else if(i>=zzz+3 || side!=zside)
438                                         return NO_MATCH;
439                         }
440                 }
441                 else
442                         return NO_MATCH;
443                 ++n1;
444                 ++n2;
445                 ++i;
446         }
447         return (!*n1 && !*n2) ? zzz>=0 ? FUZZY : EXACT : NO_MATCH;
448 }
449
450 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
451 {
452         bool found = false;
453         bool member = false;
454         for(const char *i=ptr;; ++i)
455         {
456                 if(!found)
457                 {
458                         if(!*i)
459                                 return false;
460                         if(isalpha(*i) || *i=='_')
461                         {
462                                 if(!member)
463                                 {
464                                         start = i-ptr;
465                                         found = true;
466                                 }
467                         }
468                         else if(*i=='.')
469                                 member = true;
470                         else
471                                 member = false;
472                 }
473                 else
474                 {
475                         if(!isalnum(*i) && *i!='_')
476                         {
477                                 length = i-(ptr+start);
478                                 return true;
479                         }
480                 }
481         }
482 }
483
484 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
485 {
486         vector<string> result;
487         const char *ptr = expression;
488         unsigned start = 0;
489         unsigned length = 0;
490         while(parse_identifier(ptr, start, length))
491         {
492                 result.push_back(string(ptr+start, length));
493                 ptr += start+length;
494         }
495         return result;
496 }
497
498 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map)
499 {
500         string result;
501         const char *ptr = expression;
502         unsigned start = 0;
503         unsigned length = 0;
504         while(parse_identifier(ptr, start, length))
505         {
506                 result.append(ptr, start);
507                 string identifier(ptr+start, length);
508                 map<string, string>::const_iterator i = replace_map.find(identifier);
509                 if(i!=replace_map.end())
510                         result += i->second;
511                 else
512                         result += identifier;
513                 ptr += start+length;
514         }
515         result += ptr;
516         return result;
517 }
518
519
520 ProgramBuilder::StandardFeatures::StandardFeatures():
521         texture(false),
522         material(false),
523         lighting(false),
524         specular(false),
525         normalmap(false),
526         shadow(false),
527         reflection(false),
528         legacy(!(get_glsl_version()>=Version(1, 30)))
529 { }
530
531 string ProgramBuilder::StandardFeatures::create_flags() const
532 {
533         string flags;
534         if(texture)
535                 flags += 't';
536         if(material)
537                 flags += 'm';
538         if(lighting)
539         {
540                 flags += 'l';
541                 if(specular)
542                         flags += 'p';
543                 if(normalmap)
544                         flags += 'n';
545         }
546         if(shadow)
547                 flags += 's';
548         if(reflection)
549                 flags += 'e';
550         if(legacy)
551                 flags += 'g';
552
553         return flags;
554 }
555
556
557 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
558         name(n),
559         variable(0),
560         resolved_name(n),
561         fuzzy_space(name.find("zzz")!=string::npos),
562         inlined(false),
563         inline_parens(false)
564 { }
565
566 void ProgramBuilder::ShaderVariable::resolve(const VariableDefinition &var)
567 {
568         variable = &var;
569         const char *space = 0;
570         if(name_match(var.name, resolved_name.c_str(), &space)==FUZZY)
571                 resolve_space(string(space, 3));
572
573 }
574
575 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
576 {
577         for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
578                 (*i)->update_reference(*this, var);
579         var.referenced_by.insert(var.referenced_by.end(), referenced_by.begin(), referenced_by.end());
580 }
581
582 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
583 {
584         if(fuzzy_space)
585         {
586                 resolved_space = space;
587
588                 string::size_type zzz = resolved_name.find("zzz");
589                 resolved_name.replace(zzz, 3, resolved_space);
590                 fuzzy_space = false;
591
592                 // Resolving the space could have affected other variables that use this one
593                 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
594                         (*i)->resolve_space(space);
595         }
596
597         for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
598                 if((*i)->fuzzy_space)
599                         (*i)->resolve_space(space);
600 }
601
602 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
603 {
604         referenced_vars.push_back(&var);
605         var.referenced_by.push_back(this);
606         if(var.fuzzy_space && !resolved_space.empty())
607                 var.resolve_space(resolved_space);
608 }
609
610 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
611 {
612         replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
613         replace(referenced_by.begin(), referenced_by.end(), &from, &to);
614         if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
615                 resolve_space(to.resolved_space);
616 }
617
618 void ProgramBuilder::ShaderVariable::check_inline(bool allow_legacy, bool trivial_only)
619 {
620         if(variable->expression)
621         {
622                 if(!allow_legacy && !strncmp(variable->expression, "gl_", 3))
623                         return;
624
625                 // Never inline goal variables
626                 unsigned total_refs = referenced_by.size();
627                 if(!total_refs)
628                         return;
629
630                 // Inline an expression consisting of a single identifier
631                 unsigned start, length;
632                 if(parse_identifier(variable->expression, start, length))
633                         if(start==0 && variable->expression[length]==0)
634                         {
635                                 inlined = true;
636                                 return;
637                         }
638
639                 if(trivial_only)
640                         return;
641
642                 unsigned in_scope_refs = 0;
643                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
644                         if((*i)->variable->scope==variable->scope)
645                                 ++in_scope_refs;
646
647                 /* Inline if there's only one ref, or if all refs are in other scopes.
648                 In the latter case, the actual inlining will happen in the interface
649                 variable assignment. */
650                 if(total_refs==1 || in_scope_refs==0)
651                 {
652                         inlined = true;
653                         unsigned level = 0;
654                         for(const char *c=variable->expression; (!inline_parens && *c); ++c)
655                         {
656                                 if(*c=='(')
657                                         ++level;
658                                 else if(*c==')')
659                                         --level;
660                                 else if(level==0 && !isalnum(*c) && *c!='_' && *c!='.')
661                                         inline_parens = true;
662                         }
663                 }
664         }
665 }
666
667 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
668 {
669         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
670                 if((*i)->variable->scope==scope)
671                         return true;
672         return false;
673 }
674
675 string ProgramBuilder::ShaderVariable::create_declaration(char interface) const
676 {
677         if(variable->scope==UNIFORM)
678         {
679                 const char *bracket = strrchr(variable->type, '[');
680                 if(bracket)
681                         return format("%s %s%s", string(variable->type, bracket), resolved_name, bracket);
682         }
683
684         if(interface)
685                 return format("%s %c_%s", variable->type, interface, resolved_name);
686         else
687                 return format("%s %s", variable->type, resolved_name);
688 }
689
690 string ProgramBuilder::ShaderVariable::create_replacement(VariableScope from_scope) const
691 {
692         string replacement = resolved_name;
693         if(variable)
694         {
695                 if(from_scope==FRAGMENT && (variable->scope==VERTEX || variable->scope==ATTRIBUTE))
696                         replacement = "v_"+replacement;
697                 else if(inlined)
698                 {
699                         replacement = create_expression();
700                         if(inline_parens)
701                                 replacement = "("+replacement+")";
702                 }
703         }
704
705         return replacement;
706 }
707
708 string ProgramBuilder::ShaderVariable::create_expression() const
709 {
710         map<string, string> replace_map;
711         for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
712         {
713                 string replacement = (*i)->create_replacement(variable->scope);
714                 if(replacement!=(*i)->name)
715                         replace_map[(*i)->name] = replacement;
716         }
717
718         if(replace_map.empty())
719                 return variable->expression;
720         else
721                 return replace_identifiers(variable->expression, replace_map);
722 }
723
724
725 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
726         DataFile::ObjectLoader<StandardFeatures>(f)
727 {
728         add("custom",    &StandardFeatures::custom);
729         add("lighting",  &StandardFeatures::lighting);
730         add("material",  &StandardFeatures::material);
731         add("normalmap", &StandardFeatures::normalmap);
732         add("reflection", &StandardFeatures::reflection);
733         add("shadow",    &StandardFeatures::shadow);
734         add("specular",  &StandardFeatures::specular);
735         add("texture",   &StandardFeatures::texture);
736 }
737
738 } // namespace GL
739 } // namespace Msp