]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/compiler.cpp
Refactor the interface of SL::Compiler
[libs/gl.git] / source / glsl / compiler.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/gl/extensions/ext_gpu_shader4.h>
3 #include <msp/strings/format.h>
4 #include <msp/strings/regex.h>
5 #include <msp/strings/utils.h>
6 #include "compatibility.h"
7 #include "compiler.h"
8 #include "error.h"
9 #include "generate.h"
10 #include "optimize.h"
11 #include "output.h"
12 #include "resources.h"
13 #include "shader.h"
14
15 #undef interface
16
17 using namespace std;
18
19 namespace Msp {
20 namespace GL {
21 namespace SL {
22
23 Compiler::Compiler():
24         module(0)
25 { }
26
27 Compiler::~Compiler()
28 {
29         delete module;
30 }
31
32 void Compiler::clear()
33 {
34         delete module;
35         module = new Module();
36         imported_names.clear();
37 }
38
39 void Compiler::set_source(const string &source, const string &src_name)
40 {
41         clear();
42         Parser parser;
43         imported_names.push_back(src_name);
44         append_module(parser.parse(source, src_name, 1), 0);
45 }
46
47 void Compiler::load_source(IO::Base &io, DataFile::Collection *res, const string &src_name)
48 {
49         clear();
50         Parser parser;
51         imported_names.push_back(src_name);
52         append_module(parser.parse(io, src_name, 1), res);
53 }
54
55 void Compiler::load_source(IO::Base &io, const string &src_name)
56 {
57         load_source(io, 0, src_name);
58 }
59
60 void Compiler::compile()
61 {
62         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
63                 generate(*i);
64         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); )
65         {
66                 if(optimize(*i))
67                         i = module->stages.begin();
68                 else
69                         ++i;
70         }
71         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
72                 finalize(*i);
73 }
74
75 void Compiler::add_shaders(Program &program)
76 {
77         if(!module)
78                 throw invalid_operation("Compiler::add_shaders");
79
80         try
81         {
82                 for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
83                 {
84                         string stage_src = Formatter().apply(*i);
85
86                         if(i->type==Stage::VERTEX)
87                         {
88                                 program.attach_shader_owned(new VertexShader(stage_src));
89                                 for(map<string, unsigned>::iterator j=i->locations.begin(); j!=i->locations.end(); ++j)
90                                         program.bind_attribute(j->second, j->first);
91                         }
92                         else if(i->type==Stage::GEOMETRY)
93                                 program.attach_shader_owned(new GeometryShader(stage_src));
94                         else if(i->type==Stage::FRAGMENT)
95                         {
96                                 program.attach_shader_owned(new FragmentShader(stage_src));
97                                 if(EXT_gpu_shader4)
98                                 {
99                                         for(map<string, unsigned>::iterator j=i->locations.begin(); j!=i->locations.end(); ++j)
100                                                 program.bind_fragment_data(j->second, j->first);
101                                 }
102                         }
103                 }
104         }
105         catch(const compile_error &e)
106         {
107                 static const Regex r_message("^(([0-9]+)\\(([0-9]+)\\) :|ERROR: ([0-9]+):([0-9]+):) (.*)$");
108                 vector<string> lines = split(e.what(), '\n');
109                 string translated;
110                 for(vector<string>::const_iterator i=lines.begin(); i!=lines.end(); ++i)
111                 {
112                         RegMatch m = r_message.match(*i);
113                         if(m)
114                         {
115                                 unsigned index = 0;
116                                 unsigned line = 0;
117                                 if(m[2])
118                                 {
119                                         index = lexical_cast<unsigned>(m[2].str);
120                                         line = lexical_cast<unsigned>(m[3].str);
121                                 }
122                                 else if(m[4])
123                                 {
124                                         index = lexical_cast<unsigned>(m[4].str);
125                                         line = lexical_cast<unsigned>(m[5].str);
126                                 }
127                                 const char *src = "<unknown>";
128                                 if(index==0)
129                                         src = "<generated>";
130                                 else if(index-1<imported_names.size())
131                                         src = imported_names[index-1].c_str();
132                                 translated += format("%s:%d: %s", src, line, m[6].str);
133                         }
134                         else
135                                 translated += *i;
136                         translated += '\n';
137                 }
138
139                 throw compile_error(translated);
140         }
141 }
142
143 void Compiler::append_module(Module &mod, DataFile::Collection *res)
144 {
145         vector<Import *> imports = NodeGatherer<Import>().apply(mod.shared);
146         for(vector<Import *>::iterator i=imports.begin(); i!=imports.end(); ++i)
147                 import(res, (*i)->module);
148         NodeRemover(set<Node *>(imports.begin(), imports.end())).apply(mod.shared);
149
150         append_stage(mod.shared);
151         for(list<Stage>::iterator i=mod.stages.begin(); i!=mod.stages.end(); ++i)
152                 append_stage(*i);
153 }
154
155 void Compiler::append_stage(Stage &stage)
156 {
157         Stage *target = 0;
158         if(stage.type==Stage::SHARED)
159                 target = &module->shared;
160         else
161         {
162                 list<Stage>::iterator i;
163                 for(i=module->stages.begin(); (i!=module->stages.end() && i->type<stage.type); ++i) ;
164                 if(i==module->stages.end() || i->type>stage.type)
165                 {
166                         list<Stage>::iterator j = module->stages.insert(i, stage.type);
167                         if(i!=module->stages.end())
168                                 i->previous = &*j;
169                         i = j;
170                         if(i!=module->stages.begin())
171                                 i->previous = &*--j;
172                 }
173
174                 target = &*i;
175         }
176
177         if(stage.required_version>target->required_version)
178                 target->required_version = stage.required_version;
179         for(NodeList<Statement>::iterator i=stage.content.body.begin(); i!=stage.content.body.end(); ++i)
180                 target->content.body.push_back(*i);
181         DeclarationCombiner().apply(*target);
182 }
183
184 void Compiler::import(DataFile::Collection *resources, const string &name)
185 {
186         string fn = name+".glsl";
187         if(find(imported_names, fn)!=imported_names.end())
188                 return;
189         imported_names.push_back(fn);
190
191         RefPtr<IO::Seekable> io = (resources ? resources->open_raw(fn) : Resources::get_builtins().open(fn));
192         if(!io)
193                 throw runtime_error(format("module %s not found", name));
194         Parser import_parser;
195         append_module(import_parser.parse(*io, fn, imported_names.size()), resources);
196 }
197
198 void Compiler::generate(Stage &stage)
199 {
200         if(module->shared.required_version>stage.required_version)
201                 stage.required_version = module->shared.required_version;
202         inject_block(stage.content, module->shared.content);
203
204         DeclarationReorderer().apply(stage);
205         FunctionResolver().apply(stage);
206         VariableResolver().apply(stage);
207         InterfaceGenerator().apply(stage);
208         VariableResolver().apply(stage);
209         DeclarationReorderer().apply(stage);
210         FunctionResolver().apply(stage);
211         LegacyConverter().apply(stage);
212 }
213
214 bool Compiler::optimize(Stage &stage)
215 {
216         ConstantConditionEliminator().apply(stage);
217
218         set<FunctionDeclaration *> inlineable = InlineableFunctionLocator().apply(stage);
219         FunctionInliner(inlineable).apply(stage);
220
221         set<Node *> unused = UnusedVariableLocator().apply(stage);
222         set<Node *> unused2 = UnusedFunctionLocator().apply(stage);
223         unused.insert(unused2.begin(), unused2.end());
224         NodeRemover(unused).apply(stage);
225
226         return !unused.empty();
227 }
228
229 void Compiler::finalize(Stage &stage)
230 {
231         if(get_gl_api()==OPENGL_ES2)
232                 DefaultPrecisionGenerator().apply(stage);
233         else
234                 PrecisionRemover().apply(stage);
235 }
236
237 void Compiler::inject_block(Block &target, const Block &source)
238 {
239         NodeList<Statement>::iterator insert_point = target.body.begin();
240         for(NodeList<Statement>::const_iterator i=source.body.begin(); i!=source.body.end(); ++i)
241                 target.body.insert(insert_point, (*i)->clone());
242 }
243
244 } // namespace SL
245 } // namespace GL
246 } // namespace Msp