]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
Clear load ID when assigning to a component
[libs/gl.git] / source / glsl / generate.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/core/hash.h>
3 #include <msp/core/raii.h>
4 #include "generate.h"
5
6 using namespace std;
7
8 namespace Msp {
9 namespace GL {
10 namespace SL {
11
12 void ConstantIdAssigner::apply(Module &module, const Features &features)
13 {
14         for(Stage &s: module.stages)
15                 s.content.visit(*this);
16
17         for(VariableDeclaration *v: auto_constants)
18         {
19                 unsigned id;
20                 auto j = existing_constants.find(v->name);
21                 if(j!=existing_constants.end())
22                         id = j->second;
23                 else
24                 {
25                         id = hash<32>(v->name)%features.constant_id_range;
26                         while(used_ids.count(id))
27                                 id = (id+1)%features.constant_id_range;
28                 }
29
30                 auto i = find_member(v->layout->qualifiers, string("constant_id"), &Layout::Qualifier::name);
31                 if(i!=v->layout->qualifiers.end())
32                         i->value = id;
33
34                 used_ids.insert(id);
35                 existing_constants[v->name] = id;
36         }
37 }
38
39 void ConstantIdAssigner::visit(VariableDeclaration &var)
40 {
41         if(var.layout)
42         {
43                 auto i = find_member(var.layout->qualifiers, string("constant_id"), &Layout::Qualifier::name);
44                 if(i!=var.layout->qualifiers.end() && i->has_value)
45                 {
46                         if(i->value==-1)
47                                 auto_constants.push_back(&var);
48                         else
49                         {
50                                 existing_constants[var.name] = i->value;
51                                 used_ids.insert(i->value);
52                         }
53                 }
54         }
55 }
56
57
58 string InterfaceGenerator::get_out_prefix(Stage::Type type)
59 {
60         if(type==Stage::VERTEX)
61                 return "_vs_out_";
62         else if(type==Stage::GEOMETRY)
63                 return "_gs_out_";
64         else
65                 return string();
66 }
67
68 void InterfaceGenerator::apply(Stage &s)
69 {
70         stage = &s;
71         iface_target_block = &stage->content;
72         if(stage->previous)
73                 in_prefix = get_out_prefix(stage->previous->type);
74         out_prefix = get_out_prefix(stage->type);
75         s.content.visit(*this);
76         NodeRemover().apply(s, nodes_to_remove);
77 }
78
79 void InterfaceGenerator::visit(Block &block)
80 {
81         SetForScope<Block *> set_block(current_block, &block);
82         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
83         {
84                 assignment_insert_point = i;
85                 if(&block==&stage->content)
86                         iface_insert_point = i;
87
88                 (*i)->visit(*this);
89         }
90 }
91
92 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
93 {
94         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
95         return prefix+name.substr(offset);
96 }
97
98 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
99 {
100         if(stage->content.variables.count(name))
101                 return 0;
102
103         if(stage->type==Stage::GEOMETRY && var.interface=="out" && var.array)
104                 return 0;
105
106         VariableDeclaration* iface_var = new VariableDeclaration;
107         iface_var->sampling = var.sampling;
108         iface_var->interface = iface;
109         iface_var->type = var.type;
110         iface_var->name = name;
111         // Tessellation and geometry inputs may be arrayed.
112         if(stage->type==Stage::TESS_CONTROL)
113                 // VS out -> TCS in: add | TCS in -> TCS out: unchanged | VS out -> TCS out: add
114                 iface_var->array = (var.array || var.interface!="in");
115         else if(stage->type==Stage::TESS_EVAL)
116                 // TCS out -> TES in: unchanged | TES in -> TES out: remove | TCS out -> TES out: remove
117                 iface_var->array = (var.array && iface=="in");
118         else if(stage->type==Stage::GEOMETRY)
119                 // VS/TES out -> GS in: add | GS in -> GS out: remove | VS/TES out -> GS out: unchanged
120                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
121         else
122                 iface_var->array = var.array;
123         if(iface_var->array)
124                 iface_var->array_size = var.array_size;
125         if(iface=="in")
126         {
127                 iface_var->layout = var.layout;
128                 iface_var->linked_declaration = &var;
129                 var.linked_declaration = iface_var;
130         }
131
132         if(var.block_declaration)
133         {
134                 StructDeclaration *iface_type = var.block_declaration->clone();
135                 iface_type->name = format("_%s_%s", iface, var.block_declaration->block_name);
136                 iface_target_block->body.insert(iface_insert_point, iface_type);
137
138                 iface_var->type = iface_type->name;
139                 if(name.empty())
140                         iface_var->name = format("%s %s", iface, var.block_declaration->block_name);
141
142                 stage->interface_blocks.insert(make_pair("in "+var.block_declaration->block_name, iface_var));
143                 if(!name.empty())
144                         stage->interface_blocks.insert(make_pair(name, iface_var));
145         }
146
147         iface_target_block->body.insert(iface_insert_point, iface_var);
148         iface_target_block->variables.insert(make_pair(name, iface_var));
149         if(iface_target_block==&stage->content && iface=="in")
150                 declared_inputs.push_back(iface_var);
151
152         return iface_var;
153 }
154
155 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
156 {
157         Assignment *assign = new Assignment;
158
159         string::size_type dot = left.find('.');
160         VariableReference *ref = new VariableReference;
161         ref->name = left.substr(0, dot);
162         assign->left = ref;
163
164         while(dot!=string::npos)
165         {
166                 string::size_type start = dot+1;
167                 dot = left.find('.', start);
168
169                 MemberAccess *memacc = new MemberAccess;
170                 memacc->left = assign->left;
171                 memacc->member = left.substr(start, dot-start);
172                 assign->left = memacc;
173         }
174
175         assign->oper = &Operator::get_operator("=", Operator::BINARY);
176         assign->right = right;
177
178         ExpressionStatement *stmt = new ExpressionStatement;
179         stmt->expression = assign;
180         current_block->body.insert(assignment_insert_point, stmt);
181         stmt->visit(*this);
182
183         return *stmt;
184 }
185
186 void InterfaceGenerator::visit(VariableReference &var)
187 {
188         if(var.declaration || !stage->previous)
189                 return;
190         /* Don't pull a variable from previous stage if we just generated an output
191         interface in this stage */
192         if(stage->content.variables.count(var.name))
193                 return;
194
195         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
196         auto i = prev_vars.find(var.name);
197         if(i==prev_vars.end() || i->second->interface!="out")
198                 i = prev_vars.find(in_prefix+var.name);
199         if(i!=prev_vars.end() && i->second->interface=="out")
200         {
201                 if(stage->type==Stage::GEOMETRY && i->second->array)
202                         stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
203                                 format("Can't access '%s' through automatic interface because it's an array", var.name)));
204                 else
205                 {
206                         generate_interface(*i->second, "in", i->second->name);
207                         var.name = i->second->name;
208                 }
209                 return;
210         }
211
212         for(const auto &kvp: stage->previous->interface_blocks)
213                 if(kvp.second->name.find(' ')!=string::npos)
214                 {
215                         const map<string, VariableDeclaration *> &iface_vars = kvp.second->block_declaration->members.variables;
216                         i = iface_vars.find(var.name);
217                         if(i!=iface_vars.end())
218                         {
219                                 generate_interface(*kvp.second, "in", string());
220                                 return;
221                         }
222                 }
223 }
224
225 void InterfaceGenerator::visit(VariableDeclaration &var)
226 {
227         if(var.interface=="out")
228         {
229                 /* For output variables in function scope, generate a global interface
230                 and replace the local declaration with an assignment. */
231                 VariableDeclaration *out_var = 0;
232                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
233                 {
234                         out_var->source = var.source;
235                         out_var->line = var.line;
236                         nodes_to_remove.insert(&var);
237                         if(var.init_expression)
238                         {
239                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
240                                 stmt.source = var.source;
241                                 stmt.line = var.line;
242                                 return;
243                         }
244                 }
245         }
246         else if(var.interface=="in" && current_block==&stage->content)
247         {
248                 if(var.name.compare(0, 3, "gl_"))
249                         declared_inputs.push_back(&var);
250
251                 /* Try to link input variables in global scope with output variables from
252                 previous stage. */
253                 if(!var.linked_declaration && stage->previous)
254                 {
255                         const map<string, VariableDeclaration *> *prev_vars;
256                         string name;
257                         // Blocks are linked by their block name, not instance name
258                         if(var.block_declaration)
259                         {
260                                 prev_vars = &stage->previous->interface_blocks;
261                                 name = "out "+var.block_declaration->block_name;
262                         }
263                         else
264                         {
265                                 prev_vars = &stage->previous->content.variables;
266                                 name = var.name;
267                         }
268
269                         auto i = prev_vars->find(name);
270                         if(i!=prev_vars->end() && i->second->interface=="out")
271                         {
272                                 var.linked_declaration = i->second;
273                                 i->second->linked_declaration = &var;
274                         }
275                 }
276         }
277
278         TraversingVisitor::visit(var);
279 }
280
281 void InterfaceGenerator::visit(FunctionDeclaration &func)
282 {
283         SetFlag set_scope(function_scope, true);
284         // Skip parameters because they're not useful here
285         func.body.visit(*this);
286 }
287
288 void InterfaceGenerator::visit(Passthrough &pass)
289 {
290         // Pass through all input variables declared so far.
291         vector<VariableDeclaration *> pass_vars = declared_inputs;
292
293         if(stage->previous)
294         {
295                 for(const auto &kvp: stage->previous->content.variables)
296                 {
297                         if(kvp.second->interface!="out")
298                                 continue;
299
300                         /* Pass through output variables from the previous stage, but only
301                         those which are not already linked to an input here. */
302                         if(!kvp.second->linked_declaration && generate_interface(*kvp.second, "in", kvp.second->name))
303                                 pass_vars.push_back(kvp.second);
304                 }
305         }
306
307         if(stage->type==Stage::GEOMETRY)
308         {
309                 /* Special case for geometry shader: copy gl_Position from input to
310                 output. */
311                 VariableReference *ref = new VariableReference;
312                 ref->name = "gl_in";
313
314                 BinaryExpression *subscript = new BinaryExpression;
315                 subscript->left = ref;
316                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
317                 subscript->right = pass.subscript;
318
319                 MemberAccess *memacc = new MemberAccess;
320                 memacc->left = subscript;
321                 memacc->member = "gl_Position";
322
323                 insert_assignment("out gl_PerVertex.gl_Position", memacc);
324         }
325
326         for(VariableDeclaration *v: pass_vars)
327         {
328                 string out_name = change_prefix(v->name, out_prefix);
329                 generate_interface(*v, "out", out_name);
330
331                 VariableReference *ref = new VariableReference;
332                 ref->name = v->name;
333                 if(pass.subscript)
334                 {
335                         BinaryExpression *subscript = new BinaryExpression;
336                         subscript->left = ref;
337                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
338                         subscript->right = pass.subscript;
339                         insert_assignment(out_name, subscript);
340                 }
341                 else
342                         insert_assignment(out_name, ref);
343         }
344
345         nodes_to_remove.insert(&pass);
346 }
347
348
349 void LayoutDefaulter::apply(Stage &stage)
350 {
351         if(stage.type==Stage::TESS_EVAL)
352         {
353                 stage.content.visit(*this);
354                 if((need_winding || need_spacing) && in_iface)
355                 {
356                         if(need_winding)
357                                 in_iface->layout.qualifiers.emplace_back("ccw");
358                         if(need_spacing)
359                                 in_iface->layout.qualifiers.emplace_back("equal_spacing");
360                 }
361         }
362 }
363
364 void LayoutDefaulter::visit(InterfaceLayout &iface)
365 {
366         if(iface.interface=="in")
367         {
368                 if(!in_iface)
369                         in_iface = &iface;
370                 for(const Layout::Qualifier &q: iface.layout.qualifiers)
371                 {
372                         if(q.name=="cw" || q.name=="ccw")
373                                 need_winding = false;
374                         else if(q.name=="equal_spacing" || q.name=="fractional_even_spacing" || q.name=="fractional_odd_spacing")
375                                 need_spacing = false;
376                 }
377         }
378 }
379
380
381 void ArraySizer::apply(Stage &stage)
382 {
383         stage.content.visit(*this);
384         for(const auto &kvp: max_indices)
385                 if(kvp.first->array && !kvp.first->array_size)
386                 {
387                         int size = 0;
388                         if(stage.type==Stage::GEOMETRY && kvp.first->interface=="in")
389                                 size = input_size;
390                         else if(kvp.second>=0)
391                                 size = kvp.second+1;
392                         if(!size && !kvp.first->name.compare(0, 3, "gl_"))
393                                 size = 1;
394
395                         if(size>0)
396                         {
397                                 Literal *literal_size = new Literal;
398                                 literal_size->token = lexical_cast<string>(size);
399                                 literal_size->value = size;
400                                 kvp.first->array_size = literal_size;
401                         }
402                 }
403 }
404
405 void ArraySizer::visit(VariableReference &var)
406 {
407         r_declaration = var.declaration;
408 }
409
410 void ArraySizer::visit(MemberAccess &memacc)
411 {
412         r_declaration = 0;
413         TraversingVisitor::visit(memacc);
414         VariableDeclaration *member_declaration = 0;
415         if(r_declaration)
416                 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(r_declaration->type_declaration))
417                 {
418                         auto i = strct->members.variables.find(memacc.member);
419                         if(i!=strct->members.variables.end())
420                                 member_declaration = i->second;
421                 }
422         r_declaration = member_declaration;
423 }
424
425 void ArraySizer::visit(Swizzle &swizzle)
426 {
427         TraversingVisitor::visit(swizzle);
428         r_declaration = 0;
429 }
430
431 void ArraySizer::visit(UnaryExpression &unary)
432 {
433         TraversingVisitor::visit(unary);
434         r_declaration = 0;
435 }
436
437 void ArraySizer::visit(BinaryExpression &binary)
438 {
439         if(binary.oper->token[0]=='[')
440                 if(const Literal *literal_index = dynamic_cast<const Literal *>(binary.right.get()))
441                         if(literal_index->value.check_type<int>())
442                         {
443                                 r_declaration = 0;
444                                 binary.left->visit(*this);
445                                 if(r_declaration)
446                                 {
447                                         max_indices[r_declaration] = literal_index->value.value<int>();
448                                         return;
449                                 }
450                         }
451
452         TraversingVisitor::visit(binary);
453 }
454
455 void ArraySizer::visit(TernaryExpression &ternary)
456 {
457         TraversingVisitor::visit(ternary);
458         r_declaration = 0;
459 }
460
461 void ArraySizer::visit(FunctionCall &call)
462 {
463         TraversingVisitor::visit(call);
464         r_declaration = 0;
465 }
466
467 void ArraySizer::visit(InterfaceLayout &layout)
468 {
469         if(layout.interface=="in")
470         {
471                 for(const Layout::Qualifier &q: layout.layout.qualifiers)
472                 {
473                         if(q.name=="points")
474                                 input_size = 1;
475                         else if(q.name=="lines")
476                                 input_size = 2;
477                         else if(q.name=="triangles")
478                                 input_size = 3;
479                         else if(q.name=="lines_adjacency")
480                                 input_size = 4;
481                         else if(q.name=="triangles_adjacency")
482                                 input_size = 6;
483                 }
484         }
485 }
486
487 void ArraySizer::visit(VariableDeclaration &var)
488 {
489         if(var.array && !var.array_size)
490                 max_indices[&var] = 0;
491 }
492
493 } // namespace SL
494 } // namespace GL
495 } // namespace Msp