]> git.tdb.fi Git - libs/gl.git/blob - source/programbuilder.cpp
Entirely new system for building standard shaders
[libs/gl.git] / source / programbuilder.cpp
1 #include <algorithm>
2 #include <msp/strings/format.h>
3 #include "program.h"
4 #include "programbuilder.h"
5 #include "shader.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11
12 /*
13 Naming conventions:
14   n_*        Normalized vector
15   l_*        Lighting component
16
17   obj_*      Object space
18   eye_*      Eye space
19   tbn_*      Tangent-Binormal-Normal space
20   shd_*      Shadow space
21   *_dir      Direction vector
22
23   zzz_*      Wildcard space, resolved by the builder
24              All wildcard spaces within an expression must match
25
26   xxx_yyy_*  Matrix that transforms between yyy to xxx
27              The vector is on the side of its designated space, result will be
28              in the other space
29   *_matrix   A matrix (duh)
30   *_rmatrix  A mat4 that works with a row vector
31
32   rgb_*      Color with rgb components only
33   color_*    Color with rgba components
34 */
35
36 /* The array are stored in reverse order, so that variables always come after
37 anything that might need them. */
38 const ProgramBuilder::StandardVariable ProgramBuilder::standard_variables[] =
39 {
40         { FRAGMENT, "gl_FragColor", 0, "color_base", "!t" },
41         { FRAGMENT, "gl_FragColor", 0, "tex_sample*color_base", "t" },
42         { FRAGMENT, "color_base", "vec4", "color_unlit", "!l!s" },
43         { FRAGMENT, "color_base", "vec4", "color_unlit*vec4(vec3(l_shadow), 1.0)", "!ls" },
44         { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_full, 1.0)", "l!m" },
45         { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_full, gl_FrontMaterial.diffuse.a)", "lm" },
46         { FRAGMENT, "color_unlit", "vec4", "vec4(1.0)", "!m" },
47         { FRAGMENT, "color_unlit", "vec4", "color", "m" },
48         { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow+gl_FrontLightModelProduct.sceneColor.rgb", "m" },
49         { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow", "!m" },
50         { FRAGMENT, "rgb_light_shadow", "vec3", "(rgb_light)*l_shadow", "s" },
51         { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light", "!s" },
52         { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse)", "!m!p" },
53         { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse+l_specular)", "!mp" },
54         { FRAGMENT, "rgb_light", "vec3", "l_diffuse*gl_FrontLightProduct[0].diffuse.rgb", "m!p" },
55         { FRAGMENT, "rgb_light", "vec3", "l_diffuse*gl_FrontLightProduct[0].diffuse.rgb+l_specular*gl_FrontLightProduct[0].specular.rgb", "mp" },
56         { FRAGMENT, "l_shadow", "float", "shadow2D(shadow, shd_vertex).r", 0 },
57         { FRAGMENT, "l_diffuse", "float", "max(dot(n_zzz_normal, n_zzz_light_dir), 0.0)", 0 },
58         { FRAGMENT, "l_specular", "float", "pow(max(dot(n_zzz_half_vec, n_zzz_normal), 0.0), gl_FrontMaterial.shininess)", 0 },
59         { FRAGMENT, "n_zzz_half_vec", "vec3", "normalize(zzz_light_dir-zzz_incident_dir)", 0 },
60         { FRAGMENT, "n_zzz_light_dir", "vec3", "normalize(zzz_light_dir)", 0 },
61         { FRAGMENT, "n_tbn_normal", "vec3", "texture2D(normalmap, texture_coord).xyz*2.0-1.0", "n" },
62         { FRAGMENT, "n_eye_normal", "vec3", "normalize(eye_normal)", "!n" },
63         { FRAGMENT, "tex_sample", "vec4", "texture2D(texture, texture_coord)", 0 },
64
65         { VERTEX, "gl_Position", 0, "gl_ProjectionMatrix*eye_vertex", 0 },
66         { VERTEX, "shd_vertex", "vec3", "eye_vertex*eye_shd_rmatrix", 0 },
67         { VERTEX, "eye_shd_rmatrix", "mat4", "mat4(gl_EyePlaneS[shadow_unit], gl_EyePlaneT[shadow_unit], gl_EyePlaneR[shadow_unit], vec4(0.0, 0.0, 0.0, 1.0))", 0 },
68         { VERTEX, "tbn_light_dir", "vec3", "eye_light_dir*eye_tbn_matrix", 0 },
69         { VERTEX, "eye_light_dir", "vec3", "normalize(gl_LightSource[0].position.xyz-eye_vertex.xyz*gl_LightSource[0].position.w)", 0 },
70         { VERTEX, "tbn_incident_dir", "vec3", "eye_incident_dir*eye_tbn_matrix", 0 },
71         { VERTEX, "eye_incident_dir", "vec3", "normalize(eye_vertex.xyz)", 0 },
72         { VERTEX, "eye_tbn_matrix", "mat3", "mat3(eye_tangent, eye_binormal, eye_normal)", 0 },
73         { VERTEX, "eye_vertex", "vec4", "gl_ModelViewMatrix*gl_Vertex", "!r" },
74         { VERTEX, "eye_vertex", "vec4", "transform_vertex(gl_Vertex)", "r" },
75         { VERTEX, "eye_normal", "vec3", "gl_NormalMatrix*gl_Normal", "!r" },
76         { VERTEX, "eye_normal", "vec3", "transform_normal(gl_Normal)", "r" },
77         { VERTEX, "eye_tangent", "vec3", "gl_NormalMatrix*tangent", "!r" },
78         { VERTEX, "eye_tangent", "vec3", "transform_normal(tangent)", "r" },
79         { VERTEX, "eye_binormal", "vec3", "gl_NormalMatrix*binormal", "!r" },
80         { VERTEX, "eye_binormal", "vec3", "transform_normal(binormal)", "r" },
81         { VERTEX, "color", "vec4", "gl_Color", 0 },
82         { VERTEX, "texture_coord", "vec2", "gl_MultiTexCoord0", 0 },
83
84         { ATTRIBUTE, "tangent", "vec3", 0, 0 },
85         { ATTRIBUTE, "binormal", "vec3", 0, 0 },
86
87         { UNIFORM, "shadow_unit", "int", 0, 0 },
88         { UNIFORM, "texture", "sampler2D", 0, 0 },
89         { UNIFORM, "shadow", "sampler2DShadow", 0, 0 },
90         { UNIFORM, "normalmap", "sampler2D", 0, 0 },
91
92         // Terminator entry
93         { NO_SCOPE,  0, 0, 0, 0 }
94 };
95
96 ProgramBuilder::ProgramBuilder(const StandardFeatures &f):
97         features(f),
98         feature_flags(features.create_flags())
99 { }
100
101 Program *ProgramBuilder::create_program() const
102 {
103         Program *prog = new Program;
104         add_shaders(*prog);
105         return prog;
106 }
107
108 void ProgramBuilder::add_shaders(Program &prog) const
109 {
110         list<ShaderVariable> variables;
111         list<ShaderVariable *> resolved_vars;
112
113         variables.push_front(ShaderVariable("gl_Position"));
114         variables.push_front(ShaderVariable("gl_FragColor"));
115
116         for(const StandardVariable *i=standard_variables; i->name; ++i)
117         {
118                 // Skip over anything that isn't used with the supplied flags
119                 if(i->flags && !evaluate_flags(i->flags))
120                         continue;
121
122                 // See if this variable can satisfy any unresolved variables
123                 ShaderVariable *last_resolved = 0;
124                 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
125                 {
126                         if(j->variable)
127                                 continue;
128
129                         if(!name_match(i->name, j->resolved_name.c_str()))
130                                 continue;
131
132                         if(last_resolved)
133                         {
134                                 /* We've already resolved a non-fuzzy variable in this iteration.
135                                 If there are multiple variables that can be resolved, they refer
136                                 to the same variable. */
137                                 j->resolve(*last_resolved);
138                                 continue;
139                         }
140
141                         j->resolve(*i);
142                         resolved_vars.push_front(&*j);
143                         if(!j->fuzzy_space)
144                                 last_resolved = &*j;
145
146                         if(!i->expression)
147                                 continue;
148
149                         vector<string> identifiers = extract_identifiers(i->expression);
150                         for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
151                         {
152                                 // Use an existing variable if possible, but only if it's not fuzzy
153                                 ShaderVariable *var = 0;
154                                 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
155                                         if(!l->fuzzy_space && l->resolved_name==*k)
156                                                 var = &*l;
157
158                                 if(!var)
159                                 {
160                                         variables.push_back(ShaderVariable(*k));
161                                         var = &variables.back();
162                                 }
163                                 j->add_reference(*var);
164                         }
165                 }
166         }
167
168         prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
169         prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
170 }
171
172 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
173 {
174         string source;
175
176         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
177                 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope))
178                         source += format("uniform %s %s;\n", (*i)->variable->type, (*i)->resolved_name);
179
180         if(scope==VERTEX)
181         {
182                 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
183                         if((*i)->variable->scope==ATTRIBUTE)
184                                 source += format("attribute %s %s;\n", (*i)->variable->type, (*i)->resolved_name);
185         }
186
187         /* Any variables defined in vertex scope but referenced from fragment scope
188         should be exported as varyings over the interface. */
189         list<ShaderVariable *> varyings;
190         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
191                 if((*i)->variable->scope==VERTEX && (*i)->is_referenced_from(FRAGMENT))
192                 {
193                         varyings.push_back(*i);
194                         source += format("varying %s v_%s;\n", (*i)->variable->type, (*i)->resolved_name);
195                 }
196
197         if(scope==VERTEX && features.transform)
198         {
199                 // Add the prototypes here, until I come up with something better
200                 source += "vec4 transform_vertex(vec4);\n";
201                 source += "vec3 transform_normal(vec3);\n";
202         }
203
204         source += "void main()\n{\n";
205
206         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
207                 if((*i)->variable->scope==scope)
208                 {
209                         source += '\t';
210                         if((*i)->variable->type)
211                         {
212                                 source += (*i)->variable->type;
213                                 source += ' ';
214                         }
215                         source += format("%s = %s;\n", (*i)->resolved_name, (*i)->get_expression());
216                 }
217
218         if(scope==VERTEX)
219         {
220                 for(list<ShaderVariable *>::const_iterator i=varyings.begin(); i!=varyings.end(); ++i)
221                         source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->resolved_name);
222         }
223
224         source += '}';
225
226         return source;
227 }
228
229 bool ProgramBuilder::evaluate_flags(const char *flags) const
230 {
231         if(!flags)
232                 return true;
233
234         bool cond = true;
235         char oper = '&';
236         for(const char *i=flags; *i; ++i)
237         {
238                 if(*i>='a' && *i<='z')
239                 {
240                         bool found = (feature_flags.find(*i)!=string::npos);
241                         if(oper=='|')
242                                 cond = (cond || found);
243                         else if(oper=='!')
244                                 cond = (cond && !found);
245                         else if(oper=='&')
246                                 cond = (cond && found);
247                         oper = '&';
248                 }
249                 else
250                         oper = *i;
251         }
252
253         return cond;
254 }
255
256 ProgramBuilder::MatchLevel ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
257 {
258         int i = 0;
259         int zzz = -1;
260         int zside = 0;
261         while(*n1 && *n2)
262         {
263                 if(*n1==*n2 || *n1=='z' || *n2=='z')
264                 {
265                         if(*n1!=*n2)
266                         {
267                                 int side = (*n1=='z' ? 1 : 2);
268                                 if(zzz<0)
269                                 {
270                                         zzz = i;
271                                         zside = side;
272                                         if(space)
273                                         {
274                                                 if(*n1=='z')
275                                                         *space = n2;
276                                                 else
277                                                         *space = n1;
278                                         }
279                                 }
280                                 else if(i>=zzz+3 || side!=zside)
281                                         return NO_MATCH;
282                         }
283                 }
284                 else
285                         return NO_MATCH;
286                 ++n1;
287                 ++n2;
288                 ++i;
289         }
290         return (!*n1 && !*n2) ? zzz>=0 ? FUZZY : EXACT : NO_MATCH;
291 }
292
293 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
294 {
295         bool found = false;
296         bool member = false;
297         for(const char *i=ptr;; ++i)
298         {
299                 if(!found)
300                 {
301                         if(!*i)
302                                 return false;
303                         if(isalpha(*i) || *i=='_')
304                         {
305                                 if(!member)
306                                 {
307                                         start = i-ptr;
308                                         found = true;
309                                 }
310                         }
311                         else if(*i=='.')
312                                 member = true;
313                         else
314                                 member = false;
315                 }
316                 else
317                 {
318                         if(!isalnum(*i) && *i!='_')
319                         {
320                                 length = i-(ptr+start);
321                                 return true;
322                         }
323                 }
324         }
325 }
326
327 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
328 {
329         vector<string> result;
330         const char *ptr = expression;
331         unsigned start, length;
332         while(parse_identifier(ptr, start, length))
333         {
334                 result.push_back(string(ptr+start, length));
335                 ptr += start+length;
336         }
337         return result;
338 }
339
340 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map)
341 {
342         string result;
343         const char *ptr = expression;
344         unsigned start, length;
345         while(parse_identifier(ptr, start, length))
346         {
347                 result.append(ptr, start);
348                 string identifier(ptr+start, length);
349                 map<string, string>::const_iterator i = replace_map.find(identifier);
350                 if(i!=replace_map.end())
351                         result += i->second;
352                 else
353                         result += identifier;
354                 ptr += start+length;
355         }
356         result += ptr;
357         return result;
358 }
359
360
361 ProgramBuilder::StandardFeatures::StandardFeatures():
362         texture(false),
363         material(false),
364         lighting(false),
365         specular(false),
366         normalmap(false),
367         shadow(false),
368         reflection(false),
369         transform(false)
370 { }
371
372 string ProgramBuilder::StandardFeatures::create_flags() const
373 {
374         string flags;
375         if(texture)
376                 flags += 't';
377         if(material)
378                 flags += 'm';
379         if(lighting)
380         {
381                 flags += 'l';
382                 if(specular)
383                         flags += 'p';
384                 if(normalmap)
385                         flags += 'n';
386         }
387         if(shadow)
388                 flags += 's';
389         if(reflection)
390                 flags += 'e';
391         if(transform)
392                 flags += 'r';
393
394         return flags;
395 }
396
397
398 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
399         name(n),
400         variable(0),
401         resolved_name(n),
402         fuzzy_space(name.find("zzz")!=string::npos)
403 { }
404
405 void ProgramBuilder::ShaderVariable::resolve(const StandardVariable &var)
406 {
407         variable = &var;
408         const char *space = 0;
409         if(name_match(var.name, resolved_name.c_str(), &space)==FUZZY)
410                 resolve_space(string(space, 3));
411 }
412
413 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
414 {
415         for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
416                 (*i)->update_reference(*this, var);
417 }
418
419 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
420 {
421         if(fuzzy_space)
422         {
423                 resolved_space = space;
424
425                 string::size_type zzz = resolved_name.find("zzz");
426                 resolved_name.replace(zzz, 3, resolved_space);
427                 fuzzy_space = false;
428
429                 // Resolving the space could have affected other variables that use this one
430                 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
431                         (*i)->resolve_space(space);
432         }
433
434         for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
435                 if((*i)->fuzzy_space)
436                         (*i)->resolve_space(space);
437 }
438
439 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
440 {
441         referenced_vars.push_back(&var);
442         var.referenced_by.push_back(this);
443         if(var.fuzzy_space && !resolved_space.empty())
444                 var.resolve_space(resolved_space);
445 }
446
447 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
448 {
449         replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
450         replace(referenced_by.begin(), referenced_by.end(), &from, &to);
451         if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
452                 resolve_space(to.resolved_space);
453 }
454
455 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
456 {
457         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
458                 if((*i)->variable->scope==scope)
459                         return true;
460         return false;
461 }
462
463 string ProgramBuilder::ShaderVariable::get_expression() const
464 {
465         map<string, string> replace_map;
466         for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
467                 if((*i)->variable)
468                 {
469                         string var_name = (*i)->resolved_name;
470                         if(variable->scope==FRAGMENT && (*i)->variable->scope==VERTEX)
471                                 var_name = "v_"+var_name;
472                         if(var_name!=(*i)->name)
473                                 replace_map[(*i)->name] = var_name;
474                 }
475
476         if(replace_map.empty())
477                 return variable->expression;
478         else
479                 return replace_identifiers(variable->expression, replace_map);
480 }
481
482
483 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
484         DataFile::ObjectLoader<StandardFeatures>(f)
485 {
486         add("lighting",  &StandardFeatures::lighting);
487         add("material",  &StandardFeatures::material);
488         add("normalmap", &StandardFeatures::normalmap);
489         add("reflection", &StandardFeatures::reflection);
490         add("shadow",    &StandardFeatures::shadow);
491         add("specular",  &StandardFeatures::specular);
492         add("texture",   &StandardFeatures::texture);
493         add("transform", &StandardFeatures::transform);
494 }
495
496 } // namespace GL
497 } // namespace Msp