3 #include <msp/strings/format.h>
5 #include "programbuilder.h"
7 #include "vertexformat.h"
17 l_* Lighting component
21 tbn_* Tangent-Binormal-Normal space
23 env_* Environment space
24 *_dir Direction vector
26 zzz_* Wildcard space, resolved by the builder
27 All wildcard spaces within an expression must match
29 xxx_yyy_* Matrix that transforms between yyy to xxx
30 The vector is on the side of its designated space, result will be
32 *_matrix A matrix (duh)
33 *_rmatrix A mat4 that works with a row vector
35 rgb_* Color with rgb components only
36 color_* Color with rgba components
39 /* The array are stored in reverse order, so that variables always come after
40 anything that might need them. */
41 const ProgramBuilder::StandardVariable ProgramBuilder::standard_variables[] =
43 { FRAGMENT, "gl_FragColor", 0, "frag_color", "g" },
44 { FRAGMENT, "frag_color", 0, "color_base", "!t" },
45 { FRAGMENT, "frag_color", 0, "tex_sample", "!l!s!mt" },
46 { FRAGMENT, "frag_color", 0, "tex_sample*color_base", "l|s|mt" },
47 { FRAGMENT, "color_base", "vec4", "vec4(1.0)", "!l!s!m" },
48 { FRAGMENT, "color_base", "vec4", "color", "!l!sm" },
49 { FRAGMENT, "color_base", "vec4", "vec4(vec3(l_shadow), 1.0)", "!ls!m" },
50 { FRAGMENT, "color_base", "vec4", "color*vec4(vec3(l_shadow), 1.0)", "!lsm" },
51 { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_env, 1.0)", "l!m" },
52 { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_env, material.diffuse.a)", "lm" },
53 { FRAGMENT, "rgb_light_env", "vec3", "rgb_light_full+reflect_sample.rgb*reflectivity", "e" },
54 { FRAGMENT, "rgb_light_env", "vec3", "rgb_light_full", "!e" },
55 { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow+ambient_product_diffuse.rgb", "m" },
56 { FRAGMENT, "ambient_product_diffuse", "vec4", "gl_FrontLightModelProduct.sceneColor", "g" },
57 { FRAGMENT, "ambient_product_diffuse", "vec4", "ambient_color*material.diffuse", "!g" },
58 { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow", "!m" },
59 { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light*l_shadow", "s" },
60 { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light", "!s" },
61 { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse)", "!m!p" },
62 { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse+l_specular)", "!mp" },
63 { FRAGMENT, "rgb_light", "vec3", "l_diffuse*light_product_diffuse.rgb", "m!p" },
64 { FRAGMENT, "rgb_light", "vec3", "l_diffuse*light_product_diffuse.rgb+l_specular*light_product_specular.rgb", "mp" },
65 { FRAGMENT, "light_product_diffuse", "vec4", "gl_FrontLightProduct[0].diffuse", "g" },
66 { FRAGMENT, "light_product_diffuse", "vec4", "light_sources[0].diffuse*material.diffuse", "!g" },
67 { FRAGMENT, "light_product_specular", "vec4", "gl_FrontLightProduct[0].specular", "g" },
68 { FRAGMENT, "light_product_specular", "vec4", "light_sources[0].specular*material.specular", "!g" },
69 { FRAGMENT, "reflect_sample", "vec4", "textureCube(environment, env_reflect_dir)", 0 },
70 { FRAGMENT, "env_reflect_dir", "vec3", "env_eye_matrix*eye_reflect_dir", 0 },
71 { FRAGMENT, "eye_reflect_dir", "vec3", "eye_tbn_matrix*tbn_reflect_dir", "n" },
72 { FRAGMENT, "zzz_reflect_dir", "vec3", "reflect(zzz_incident_dir, n_zzz_normal)", 0 },
73 { FRAGMENT, "l_shadow", "float", "mix(1.0, shadow_sample, shadow_darkness)", 0 },
74 { FRAGMENT, "shadow_sample", "float", "shadow2D(shadow, shd_vertex).r", 0 },
75 { FRAGMENT, "l_diffuse", "float", "max(dot(n_zzz_normal, n_zzz_light_dir), 0.0)", 0 },
76 { FRAGMENT, "l_specular", "float", "pow(max(dot(n_zzz_half_vec, n_zzz_normal), 0.0), material.shininess)", 0 },
77 { FRAGMENT, "n_zzz_half_vec", "vec3", "normalize(zzz_light_dir-zzz_incident_dir)", 0 },
78 { FRAGMENT, "n_zzz_light_dir", "vec3", "normalize(zzz_light_dir)", 0 },
79 { FRAGMENT, "n_tbn_normal", "vec3", "normal_sample*2.0-1.0", "n" },
80 { FRAGMENT, "n_eye_normal", "vec3", "normalize(eye_normal)", "!n" },
81 { FRAGMENT, "normal_sample", "vec3", "texture2D(normalmap, texture_coord).xyz", "!c" },
82 { FRAGMENT, "normal_sample", "vec3", "sample_normalmap(texture_coord)", "c" },
83 { FRAGMENT, "tex_sample", "vec4", "texture2D(texture, texture_coord)", "!c" },
84 { FRAGMENT, "tex_sample", "vec4", "sample_texture(texture_coord)", "c" },
86 { VERTEX, "gl_Position", 0, "projection_matrix*eye_vertex", 0 },
87 { 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" },
88 { VERTEX, "shd_vertex", "vec3", "(shd_eye_matrix*eye_vertex).xyz", "!g" },
89 { VERTEX, "tbn_light_dir", "vec3", "eye_light_dir*eye_tbn_matrix", 0 },
90 { VERTEX, "eye_light_dir", "vec3", "normalize(eye_light_position.xyz-eye_vertex.xyz*eye_light_position.w)", 0 },
91 { VERTEX, "eye_light_position", "vec4", "light_sources[0].position", 0 },
92 { VERTEX, "tbn_incident_dir", "vec3", "eye_incident_dir*eye_tbn_matrix", 0 },
93 { VERTEX, "eye_incident_dir", "vec3", "normalize(eye_vertex.xyz)", 0 },
94 { VERTEX, "eye_tbn_matrix", "mat3", "mat3(eye_tangent, eye_binormal, eye_normal)", 0 },
95 { VERTEX, "eye_vertex", "vec4", "eye_obj_matrix*vertex", "!r" },
96 { VERTEX, "eye_vertex", "vec4", "transform_vertex(vertex)", "r" },
97 { VERTEX, "eye_normal", "vec3", "eye_obj_normal_matrix*normal", "!r" },
98 { VERTEX, "eye_normal", "vec3", "transform_normal(normal)", "r" },
99 { VERTEX, "eye_tangent", "vec3", "eye_obj_normal_matrix*tangent", "!r" },
100 { VERTEX, "eye_tangent", "vec3", "transform_normal(tangent)", "r" },
101 { VERTEX, "eye_binormal", "vec3", "eye_obj_normal_matrix*binormal", "!r" },
102 { VERTEX, "eye_binormal", "vec3", "transform_normal(binormal)", "r" },
103 { VERTEX, "texture_coord", "vec2", "texcoord.xy", 0 },
105 { ATTRIBUTE, "vertex", "vec4", "gl_Vertex", 0 },
106 { ATTRIBUTE, "texcoord", "vec4", "gl_MultiTexCoord0", 0 },
107 { ATTRIBUTE, "color", "vec4", "gl_Color", 0 },
108 { ATTRIBUTE, "normal", "vec3", "gl_Normal", 0 },
109 { ATTRIBUTE, "tangent", "vec3", 0, 0 },
110 { ATTRIBUTE, "binormal", "vec3", 0, 0 },
112 { UNIFORM, "shadow_unit", "int", 0, 0 },
113 { UNIFORM, "texture", "sampler2D", 0, 0 },
114 { UNIFORM, "shadow", "sampler2DShadow", 0, 0 },
115 { UNIFORM, "shadow_darkness", "float", 0, 0 },
116 { UNIFORM, "normalmap", "sampler2D", 0, 0 },
117 { UNIFORM, "environment", "samplerCube", 0, 0 },
118 { UNIFORM, "env_eye_matrix", "mat3", 0, 0 },
119 { UNIFORM, "reflectivity", "float", 0, 0 },
120 { UNIFORM, "eye_obj_matrix", "mat4", "gl_ModelViewMatrix", 0 },
121 { UNIFORM, "eye_obj_normal_matrix", "mat3", "gl_NormalMatrix", 0 },
122 { UNIFORM, "projection_matrix", "mat4", "gl_ProjectionMatrix", 0 },
123 { UNIFORM, "shd_eye_matrix", "mat4", 0, "!g" },
124 { UNIFORM, "light_sources", "struct { vec4 position; vec4 diffuse; vec4 specular; } %s[2]", "gl_LightSource", 0 },
125 { UNIFORM, "ambient_color", "vec4", 0, 0 },
126 { UNIFORM, "material", "struct { vec4 ambient; vec4 diffuse; vec4 specular; float shininess; }", "gl_FrontMaterial", 0 },
129 { NO_SCOPE, 0, 0, 0, 0 }
132 ProgramBuilder::ProgramBuilder(const StandardFeatures &f):
134 feature_flags(features.create_flags()),
138 void ProgramBuilder::set_optimize(bool o)
143 Program *ProgramBuilder::create_program() const
145 Program *prog = new Program;
150 void ProgramBuilder::add_shaders(Program &prog) const
152 list<ShaderVariable> variables;
153 list<ShaderVariable *> resolved_vars;
155 variables.push_front(ShaderVariable("gl_Position"));
156 variables.push_front(ShaderVariable(features.legacy ? "gl_FragColor" : "frag_color"));
158 for(const StandardVariable *i=standard_variables; i->name; ++i)
160 // Skip over anything that isn't used with the supplied flags
161 if(i->flags && !evaluate_flags(i->flags))
164 // See if this variable can satisfy any unresolved variables
165 ShaderVariable *last_resolved = 0;
166 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
171 if(!name_match(i->name, j->resolved_name.c_str()))
176 /* We've already resolved a non-fuzzy variable in this iteration.
177 If there are multiple variables that can be resolved, they refer
178 to the same variable. */
179 j->resolve(*last_resolved);
184 resolved_vars.push_front(&*j);
191 vector<string> identifiers = extract_identifiers(i->expression);
192 for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
194 // Use an existing variable if possible, but only if it's not fuzzy
195 ShaderVariable *var = 0;
196 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
197 if(!l->fuzzy_space && l->resolved_name==*k)
202 variables.push_back(ShaderVariable(*k));
203 var = &variables.back();
205 j->add_reference(*var);
212 for(list<ShaderVariable *>::const_iterator i=resolved_vars.begin(); i!=resolved_vars.end(); ++i)
213 (*i)->check_inline(features.legacy);
216 prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
217 prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
221 prog.bind_fragment_data(0, "frag_color");
222 prog.bind_attribute(get_component_type(VERTEX4), "vertex");
223 if(features.lighting)
224 prog.bind_attribute(get_component_type(NORMAL3), "normal");
225 else if(features.material)
226 prog.bind_attribute(get_component_type(COLOR4_FLOAT), "color");
227 if(features.texture || features.normalmap)
228 prog.bind_attribute(get_component_type(TEXCOORD4), "texcoord");
230 if(features.normalmap)
232 prog.bind_attribute(get_component_type(TANGENT3), "tangent");
233 prog.bind_attribute(get_component_type(BINORMAL3), "binormal");
237 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
242 source += "#version 130\n";
244 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
245 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope) && !(*i)->inlined)
247 if(strchr((*i)->variable->type, '%'))
248 source += format("uniform %s;\n", format((*i)->variable->type, (*i)->resolved_name));
250 source += format("uniform %s %s;\n", (*i)->variable->type, (*i)->resolved_name);
255 const char *qualifier = (features.legacy ? "attribute" : "in");
256 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
257 if((*i)->variable->scope==ATTRIBUTE && !(*i)->inlined)
258 source += format("%s %s %s;\n", qualifier, (*i)->variable->type, (*i)->resolved_name);
261 /* Any variables defined in vertex scope but referenced from fragment scope
262 should be exported as varyings over the interface. */
263 list<ShaderVariable *> varyings;
264 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
265 if(((*i)->variable->scope==VERTEX || (*i)->variable->scope==ATTRIBUTE) && (*i)->is_referenced_from(FRAGMENT))
267 varyings.push_back(*i);
268 const char *qualifier;
270 qualifier = (scope==VERTEX ? "out" : "in");
272 qualifier = "varying";
273 source += format("%s %s v_%s;\n", qualifier, (*i)->variable->type, (*i)->resolved_name);
276 if(scope==FRAGMENT && !features.legacy)
277 source += "out vec4 frag_color;\n";
279 if(scope==VERTEX && features.transform)
281 // Add the prototypes here, until I come up with something better
282 source += "vec4 transform_vertex(vec4);\n";
283 source += "vec3 transform_normal(vec3);\n";
285 else if(scope==FRAGMENT && features.colorify)
288 source += "vec4 sample_texture(vec2);\n";
289 if(features.normalmap)
290 source += "vec3 sample_normalmap(vec2);\n";
293 source += "void main()\n{\n";
295 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
296 if((*i)->variable->scope==scope && !(*i)->inlined)
299 if((*i)->variable->type)
301 source += (*i)->variable->type;
304 source += format("%s = %s;\n", (*i)->resolved_name, (*i)->get_expression());
309 for(list<ShaderVariable *>::const_iterator i=varyings.begin(); i!=varyings.end(); ++i)
312 source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->get_expression());
314 source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->resolved_name);
323 bool ProgramBuilder::evaluate_flags(const char *flags) const
330 for(const char *i=flags; *i; ++i)
332 if(*i>='a' && *i<='z')
334 bool found = (feature_flags.find(*i)!=string::npos);
336 cond = (cond || found);
338 cond = (cond && !found);
340 cond = (cond && found);
350 ProgramBuilder::MatchLevel ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
357 if(*n1==*n2 || *n1=='z' || *n2=='z')
361 int side = (*n1=='z' ? 1 : 2);
374 else if(i>=zzz+3 || side!=zside)
384 return (!*n1 && !*n2) ? zzz>=0 ? FUZZY : EXACT : NO_MATCH;
387 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
391 for(const char *i=ptr;; ++i)
397 if(isalpha(*i) || *i=='_')
412 if(!isalnum(*i) && *i!='_')
414 length = i-(ptr+start);
421 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
423 vector<string> result;
424 const char *ptr = expression;
427 while(parse_identifier(ptr, start, length))
429 result.push_back(string(ptr+start, length));
435 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map)
438 const char *ptr = expression;
441 while(parse_identifier(ptr, start, length))
443 result.append(ptr, start);
444 string identifier(ptr+start, length);
445 map<string, string>::const_iterator i = replace_map.find(identifier);
446 if(i!=replace_map.end())
449 result += identifier;
457 ProgramBuilder::StandardFeatures::StandardFeatures():
467 legacy(!(get_glsl_version()>=Version(1, 30)))
470 string ProgramBuilder::StandardFeatures::create_flags() const
500 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
504 fuzzy_space(name.find("zzz")!=string::npos),
509 void ProgramBuilder::ShaderVariable::resolve(const StandardVariable &var)
512 const char *space = 0;
513 if(name_match(var.name, resolved_name.c_str(), &space)==FUZZY)
514 resolve_space(string(space, 3));
517 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
519 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
520 (*i)->update_reference(*this, var);
521 var.referenced_by.insert(var.referenced_by.end(), referenced_by.begin(), referenced_by.end());
524 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
528 resolved_space = space;
530 string::size_type zzz = resolved_name.find("zzz");
531 resolved_name.replace(zzz, 3, resolved_space);
534 // Resolving the space could have affected other variables that use this one
535 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
536 (*i)->resolve_space(space);
539 for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
540 if((*i)->fuzzy_space)
541 (*i)->resolve_space(space);
544 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
546 referenced_vars.push_back(&var);
547 var.referenced_by.push_back(this);
548 if(var.fuzzy_space && !resolved_space.empty())
549 var.resolve_space(resolved_space);
552 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
554 replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
555 replace(referenced_by.begin(), referenced_by.end(), &from, &to);
556 if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
557 resolve_space(to.resolved_space);
560 void ProgramBuilder::ShaderVariable::check_inline(bool allow_legacy)
562 if(variable->expression)
564 if(!allow_legacy && !strncmp(variable->expression, "gl_", 3))
567 unsigned total_refs = referenced_by.size();
568 unsigned in_scope_refs = 0;
569 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
570 if((*i)->variable->scope==variable->scope)
572 if(total_refs==1 || (total_refs>0 && in_scope_refs==0))
576 for(const char *c=variable->expression; (!inline_parens && *c); ++c)
582 else if(level==0 && !isalnum(*c) && *c!='_' && *c!='.')
583 inline_parens = true;
589 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
591 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
592 if((*i)->variable->scope==scope)
597 string ProgramBuilder::ShaderVariable::get_expression() const
599 map<string, string> replace_map;
600 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
603 string replacement = (*i)->resolved_name;
604 if(variable->scope==FRAGMENT && ((*i)->variable->scope==VERTEX || (*i)->variable->scope==ATTRIBUTE))
605 replacement = "v_"+replacement;
606 else if((*i)->inlined)
608 replacement = (*i)->get_expression();
609 if((*i)->inline_parens)
610 replacement = "("+replacement+")";
612 if(replacement!=(*i)->name)
613 replace_map[(*i)->name] = replacement;
616 if(replace_map.empty())
617 return variable->expression;
619 return replace_identifiers(variable->expression, replace_map);
623 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
624 DataFile::ObjectLoader<StandardFeatures>(f)
626 add("colorify", &StandardFeatures::colorify);
627 add("lighting", &StandardFeatures::lighting);
628 add("material", &StandardFeatures::material);
629 add("normalmap", &StandardFeatures::normalmap);
630 add("reflection", &StandardFeatures::reflection);
631 add("shadow", &StandardFeatures::shadow);
632 add("specular", &StandardFeatures::specular);
633 add("texture", &StandardFeatures::texture);
634 add("transform", &StandardFeatures::transform);