1 #include <msp/core/application.h>
2 #include <msp/core/getopt.h>
3 #include <msp/gl/glsl/compiler.h>
4 #include <msp/gl/glsl/glsl_error.h>
5 #include <msp/io/print.h>
6 #include <msp/strings/utils.h>
8 class GlslCompiler: public Msp::RegisteredApplication<GlslCompiler>
11 std::string source_fn;
12 std::map<std::string, int> spec_values;
15 Msp::GL::SL::Stage::Type stage;
19 GlslCompiler(int, char **);
27 GlslCompiler::GlslCompiler(int argc, char **argv):
30 stage(GL::SL::Stage::SHARED),
34 vector<string> spec_values_in;
37 getopt.add_option('c', "combined", combined, GetOpt::NO_ARG).set_help("Output combined GLSL");
38 getopt.add_option('a', "dump-ast", dump_ast, GetOpt::NO_ARG).set_help("Dump AST for debugging");
39 getopt.add_option('p', "parse_only", parse_only, GetOpt::NO_ARG).set_help("Only parse the loaded source, don't compile");
40 getopt.add_option('e', "specialize", spec_values_in, GetOpt::REQUIRED_ARG).set_help("Set specialization constant", "NAME:VALUE");
41 getopt.add_option('s', "stage", stage_str, GetOpt::REQUIRED_ARG).set_help("Output GLSL for STAGE", "STAGE");
42 getopt.add_argument("source", source_fn, GetOpt::REQUIRED_ARG).set_help("GLSL file to compile");
45 if(stage_str=="vertex")
46 stage = GL::SL::Stage::VERTEX;
47 else if(stage_str=="geometry")
48 stage = GL::SL::Stage::GEOMETRY;
49 else if(stage_str=="fragment")
50 stage = GL::SL::Stage::FRAGMENT;
54 for(vector<string>::const_iterator i=spec_values_in.begin(); i!=spec_values_in.end(); ++i)
56 unsigned colon = i->find(':');
57 if(colon==string::npos || colon==0 || colon+1>=i->size())
58 throw usage_error("Invalid specialization value");
60 string value_str = i->substr(colon+1);
62 if(isnumrc(value_str))
63 value = lexical_cast<int>(value_str);
65 value = lexical_cast<bool>(value_str);
66 spec_values[i->substr(0, colon)] = value;
70 int GlslCompiler::main()
72 GL::SL::Compiler compiler(GL::SL::Features::all());
73 IO::File file(source_fn);
74 compiler.load_source(file, source_fn);
75 compiler.specialize(spec_values);
80 compiler.compile(GL::SL::Compiler::PROGRAM);
82 catch(const GL::SL::invalid_shader_source &exc)
87 IO::print("Compilation resulted in errors:\n%s\n", exc.what());
89 stage = GL::SL::Stage::SHARED;
95 vector<GL::SL::Stage::Type> stages = compiler.get_stages();
96 for(vector<GL::SL::Stage::Type>::const_iterator i=stages.begin(); i!=stages.end(); ++i)
97 IO::print("%s\n", compiler.get_stage_debug(*i));
101 IO::print("%s\n", compiler.get_combined_glsl());
102 else if(stage!=GL::SL::Stage::SHARED)
103 IO::print("%s\n", compiler.get_stage_glsl(stage));