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