]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/finalize.cpp
Refactor a common part in LocationAllocator into a function
[libs/gl.git] / source / glsl / finalize.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/core/hash.h>
3 #include <msp/core/raii.h>
4 #include <msp/strings/lexicalcast.h>
5 #include "finalize.h"
6 #include "glsl_error.h"
7 #include "reflect.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13 namespace SL {
14
15 void StructOrganizer::visit(StructDeclaration &strct)
16 {
17         SetForScope<int> set_offset(offset, 0);
18         TraversingVisitor::visit(strct);
19 }
20
21 void StructOrganizer::visit(VariableDeclaration &var)
22 {
23         if(offset>=0)
24         {
25                 int *layout_offset = 0;
26                 bool has_matrix_order = false;
27                 if(var.layout)
28                 {
29                         for(Layout::Qualifier &q: var.layout->qualifiers)
30                         {
31                                 if(q.name=="offset" && q.has_value)
32                                 {
33                                         layout_offset = &q.value;
34                                         if(q.value>=offset)
35                                                 offset = q.value;
36                                 }
37                                 else if(q.name=="column_major" || q.name=="row_major")
38                                         has_matrix_order = true;
39                         }
40                 }
41
42                 MemoryRequirementsCalculator::Result mem_reqs = MemoryRequirementsCalculator().apply(var);
43                 offset += mem_reqs.alignment-1;
44                 offset -= offset%mem_reqs.alignment;
45
46                 if(layout_offset)
47                         *layout_offset = offset;
48                 else
49                 {
50                         if(!var.layout)
51                                 var.layout = new Layout;
52
53                         var.layout->qualifiers.push_back(Layout::Qualifier("offset", offset));
54                 }
55
56                 if(!has_matrix_order)
57                 {
58                         const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(var.type_declaration);
59                         while(basic && basic->kind==BasicTypeDeclaration::ARRAY)
60                                 basic = dynamic_cast<const BasicTypeDeclaration *>(basic->base_type);
61                         if(basic && basic->kind==BasicTypeDeclaration::MATRIX)
62                                 var.layout->qualifiers.push_back(Layout::Qualifier("column_major"));
63                 }
64
65                 offset += mem_reqs.size;
66         }
67 }
68
69
70 void LocationAllocator::apply(Module &module, const Features &features)
71 {
72         for(Stage &s: module.stages)
73                 apply(s);
74
75         if(features.target_api!=VULKAN)
76                 allocate_locations("uniform");
77
78         for(InterfaceBlock *b: unbound_blocks)
79                 bind_uniform(b->layout, b->block_name, features.uniform_binding_range);
80         for(VariableDeclaration *t: unbound_textures)
81                 bind_uniform(t->layout, t->name, features.texture_binding_range);
82 }
83
84 void LocationAllocator::apply(Stage &stage)
85 {
86         swap(used_locations["in"], used_locations["out"]);
87         used_locations["out"].clear();
88
89         stage.content.visit(*this);
90
91         allocate_locations("in");
92         allocate_locations("out");
93 }
94
95 void LocationAllocator::allocate_locations(const string &iface)
96 {
97         auto write = unplaced_variables.begin();
98         unsigned next = 0;
99         for(auto i=unplaced_variables.begin(); i!=unplaced_variables.end(); ++i)
100         {
101                 if((*i)->interface!=iface)
102                 {
103                         if(write!=i)
104                                 *write = *i;
105                         ++write;
106                         continue;
107                 }
108
109                 if((*i)->interface=="uniform")
110                 {
111                         auto j = uniforms.find((*i)->name);
112                         if(j!=uniforms.end() && j->second.location>=0)
113                         {
114                                 add_layout_value((*i)->layout, "location", j->second.location);
115                                 continue;
116                         }
117                 }
118
119                 set<unsigned> &used = used_locations[(*i)->interface];
120
121                 unsigned size = LocationCounter().apply(**i);
122                 while(1)
123                 {
124                         int blocking = -1;
125                         for(unsigned j=0; j<size; ++j)
126                                 if(used.count(next+j))
127                                         blocking = next+j;
128                         if(blocking<0)
129                                 break;
130                         next = blocking+1;
131                 }
132
133                 add_layout_value((*i)->layout, "location", next);
134                 if((*i)->interface=="uniform")
135                         uniforms[(*i)->name].location = next;
136
137                 for(unsigned j=0; j<size; ++j)
138                         used.insert(next+j);
139                 next += size;
140         }
141
142         unplaced_variables.erase(write, unplaced_variables.end());
143 }
144
145 void LocationAllocator::bind_uniform(RefPtr<Layout> &layout, const string &name, unsigned range)
146 {
147         auto i = uniforms.find(name);
148         if(i!=uniforms.end() && i->second.bind_point>=0)
149                 add_layout_value(layout, "binding", i->second.bind_point);
150         else
151         {
152                 set<unsigned> &used = used_bindings[0];
153
154                 unsigned bind_point = fold32(hash64(name))%range;
155                 while(used.count(bind_point))
156                         bind_point = (bind_point+1)%range;
157
158                 add_layout_value(layout, "binding", bind_point);
159                 uniforms[name].bind_point = bind_point;
160                 used.insert(bind_point);
161         }
162 }
163
164 void LocationAllocator::add_layout_value(RefPtr<Layout> &layout, const string &name, unsigned value)
165 {
166         if(!layout)
167                 layout = new Layout;
168
169         layout->qualifiers.push_back(Layout::Qualifier(name, value));
170 }
171
172 bool LocationAllocator::visit_uniform(const string &name, RefPtr<Layout> &layout)
173 {
174         int bind_point = (layout ? get_layout_value(*layout, "binding") : -1);
175         if(bind_point>=0)
176         {
177                 used_bindings[0].insert(bind_point);
178                 uniforms[name].bind_point = bind_point;
179         }
180         return bind_point>=0;
181 }
182
183 void LocationAllocator::visit(VariableDeclaration &var)
184 {
185         if(!var.name.compare(0, 3, "gl_"))
186                 return;
187
188         if(!var.interface.empty())
189         {
190                 int location = (var.layout ? get_layout_value(*var.layout, "location") : -1);
191
192                 if(location<0 && var.linked_declaration && var.linked_declaration->layout)
193                 {
194                         location = get_layout_value(*var.linked_declaration->layout, "location");
195                         if(location>=0)
196                                 add_layout_value(var.layout, "location", location);
197                 }
198
199                 if(location>=0)
200                 {
201                         unsigned size = LocationCounter().apply(var);
202                         for(unsigned i=0; i<size; ++i)
203                                 used_locations[var.interface].insert(location+i);
204                         if(var.interface=="uniform")
205                                 uniforms[var.name].location = location;
206                 }
207                 else
208                         unplaced_variables.push_back(&var);
209         }
210
211         if(var.interface=="uniform")
212         {
213                 const TypeDeclaration *type = var.type_declaration;
214                 while(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
215                         type = basic->base_type;
216                 if(dynamic_cast<const ImageTypeDeclaration *>(type) && !visit_uniform(var.name, var.layout))
217                         unbound_textures.push_back(&var);
218         }
219 }
220
221 void LocationAllocator::visit(InterfaceBlock &iface)
222 {
223         if(!iface.instance_name.compare(0, 3, "gl_"))
224                 return;
225
226         if(iface.interface=="uniform")
227         {
228                 bool push_constant = false;
229                 if(iface.layout)
230                 {
231                         auto i = find_member(iface.layout->qualifiers, string("push_constant"), &Layout::Qualifier::name);
232                         push_constant = (i!=iface.layout->qualifiers.end());
233                 }
234
235                 if(!push_constant && !visit_uniform(iface.block_name, iface.layout))
236                         unbound_blocks.push_back(&iface);
237         }
238 }
239
240
241 void PrecisionConverter::apply(Stage &s)
242 {
243         stage = &s;
244         s.content.visit(*this);
245         NodeRemover().apply(s, nodes_to_remove);
246 }
247
248 void PrecisionConverter::visit(Block &block)
249 {
250         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
251         {
252                 if(&block==&stage->content)
253                         insert_point = i;
254                 (*i)->visit(*this);
255         }
256 }
257
258 void PrecisionConverter::visit(Precision &prec)
259 {
260         if(stage->required_features.target_api==OPENGL_ES)
261                 have_default.insert(prec.type);
262         else
263                 nodes_to_remove.insert(&prec);
264 }
265
266 void PrecisionConverter::visit(VariableDeclaration &var)
267 {
268         if(stage->required_features.target_api!=OPENGL_ES)
269         {
270                 var.precision.clear();
271                 return;
272         }
273
274         const char *default_prec = (stage->type==Stage::FRAGMENT ? "mediump" : "highp");
275         const TypeDeclaration *type = var.type_declaration;
276         while(type)
277         {
278                 if(dynamic_cast<const ImageTypeDeclaration *>(type))
279                 {
280                         default_prec = "lowp";
281                         break;
282                 }
283                 else if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
284                 {
285                         if(basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT)
286                                 break;
287                         type = basic->base_type;
288                 }
289                 else
290                         return;
291         }
292         if(!type)
293                 return;
294
295         if(!have_default.count(type->name))
296         {
297                 Precision *prec = new Precision;
298                 prec->precision = default_prec;
299                 prec->type = type->name;
300                 stage->content.body.insert(insert_point, prec);
301
302                 have_default.insert(type->name);
303         }
304 }
305
306
307 void FeatureConverter::apply(Stage &s, const Features &feat)
308 {
309         stage = &s;
310         features = feat;
311
312         if(!stage->required_features.glsl_version)
313                 stage->required_features.glsl_version = Version(1, (stage->required_features.target_api==OPENGL_ES ? 0 : 10));
314
315         apply();
316 }
317
318 void FeatureConverter::unsupported(const string &reason)
319 {
320         Diagnostic diagnostic;
321         diagnostic.severity = Diagnostic::ERR;
322         diagnostic.source = GENERATED_SOURCE;
323         diagnostic.line = 0;
324         diagnostic.message = reason;
325         stage->diagnostics.push_back(diagnostic);
326 }
327
328 bool FeatureConverter::check_version(const Version &feature_version) const
329 {
330         if(features.glsl_version<feature_version)
331                 return false;
332         else if(stage->required_features.glsl_version<feature_version)
333                 stage->required_features.glsl_version = feature_version;
334
335         return true;
336 }
337
338 bool FeatureConverter::check_extension(bool Features::*extension) const
339 {
340         if(!(features.*extension))
341                 return false;
342
343         stage->required_features.*extension = true;
344
345         return true;
346 }
347
348
349 void StructuralFeatureConverter::apply()
350 {
351         if(supports_stage(stage->type))
352         {
353                 stage->content.visit(*this);
354                 NodeRemover().apply(*stage, nodes_to_remove);
355         }
356         else
357                 unsupported(format("Stage %s is not supported", Stage::get_stage_name(stage->type)));
358 }
359
360 void StructuralFeatureConverter::visit(Block &block)
361 {
362         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
363         {
364                 if(&block==&stage->content)
365                         uniform_insert_point = i;
366                 (*i)->visit(*this);
367         }
368 }
369
370 void StructuralFeatureConverter::visit(RefPtr<Expression> &expr)
371 {
372         r_replaced_reference = 0;
373         expr->visit(*this);
374         if(r_replaced_reference)
375                 expr = r_replaced_reference;
376         r_replaced_reference = 0;
377 }
378
379 bool StructuralFeatureConverter::supports_stage(Stage::Type st) const
380 {
381         if(st==Stage::GEOMETRY)
382         {
383                 if(features.target_api==VULKAN)
384                         return true;
385                 else if(features.target_api==OPENGL_ES)
386                         return check_version(Version(3, 20));
387                 else
388                         return check_version(Version(1, 50));
389         }
390         else
391                 return true;
392 }
393
394 bool StructuralFeatureConverter::supports_unified_interface_syntax() const
395 {
396         if(features.target_api==VULKAN)
397                 return true;
398         else if(features.target_api==OPENGL_ES)
399                 return check_version(Version(3, 0));
400         else
401                 return check_version(Version(1, 30));
402 }
403
404 void StructuralFeatureConverter::visit(VariableReference &var)
405 {
406         if(var.declaration==frag_out && !supports_unified_interface_syntax())
407         {
408                 var.name = "gl_FragColor";
409                 var.declaration = 0;
410         }
411 }
412
413 void StructuralFeatureConverter::visit(InterfaceBlockReference &iface)
414 {
415         r_flattened_interface = nodes_to_remove.count(iface.declaration);
416 }
417
418 void StructuralFeatureConverter::visit(MemberAccess &memacc)
419 {
420         r_flattened_interface = false;
421         visit(memacc.left);
422         if(r_flattened_interface)
423         {
424                 VariableReference *var = new VariableReference;
425                 var->name = memacc.member;
426                 r_replaced_reference = var;
427         }
428 }
429
430 void StructuralFeatureConverter::visit(Assignment &assign)
431 {
432         TraversingVisitor::visit(assign);
433         if(assign.target.declaration==frag_out && !supports_unified_interface_syntax())
434                 assign.target.declaration = 0;
435 }
436
437 bool StructuralFeatureConverter::supports_unified_sampling_functions() const
438 {
439         if(features.target_api==VULKAN)
440                 return true;
441         else if(features.target_api==OPENGL_ES)
442                 return check_version(Version(3, 0));
443         else
444                 return check_version(Version(1, 30));
445 }
446
447 void StructuralFeatureConverter::visit(FunctionCall &call)
448 {
449         if(call.declaration && call.declaration->source==BUILTIN_SOURCE)
450         {
451                 if(!call.name.compare(0, 7, "texture") && call.arguments.size()>=1)
452                 {
453                         const ImageTypeDeclaration *arg_image = dynamic_cast<const ImageTypeDeclaration *>(call.arguments.front()->type);
454                         if(arg_image && !supports_unified_sampling_functions())
455                         {
456                                 string suffix = call.name.substr(7);
457                                 call.name = (arg_image->shadow ? "shadow" : "texture");
458
459                                 switch(arg_image->dimensions)
460                                 {
461                                 case ImageTypeDeclaration::ONE: call.name += "1D"; break;
462                                 case ImageTypeDeclaration::TWO: call.name += "2D"; break;
463                                 case ImageTypeDeclaration::THREE: call.name += "3D"; break;
464                                 case ImageTypeDeclaration::CUBE: call.name += "Cube"; break;
465                                 }
466
467                                 if(arg_image->array)
468                                 {
469                                         /* Array textures and the unified sampling function name were
470                                         both introduced in GLSL 1.30. */
471                                         if(arg_image->dimensions==ImageTypeDeclaration::ONE || arg_image->dimensions==ImageTypeDeclaration::TWO)
472                                                 check_extension(&Features::ext_texture_array);
473                                         call.name += "Array";
474                                 }
475
476                                 call.name += suffix;
477                         }
478                 }
479         }
480
481         TraversingVisitor::visit(call);
482 }
483
484 void StructuralFeatureConverter::visit(VariableDeclaration &var)
485 {
486         if((var.interface=="in" || var.interface=="out") && !supports_unified_interface_syntax())
487                 if(stage->type==Stage::FRAGMENT && var.interface=="out")
488                 {
489                         frag_out = &var;
490                         nodes_to_remove.insert(&var);
491                 }
492
493         TraversingVisitor::visit(var);
494 }
495
496 bool StructuralFeatureConverter::supports_interface_blocks(const string &iface) const
497 {
498         if(features.target_api==VULKAN)
499                 return true;
500         else if(features.target_api==OPENGL_ES)
501         {
502                 if(iface=="uniform")
503                         return check_version(Version(3, 0));
504                 else
505                         return check_version(Version(3, 20));
506         }
507         else if(check_version(Version(1, 50)))
508                 return true;
509         else if(iface=="uniform")
510                 return check_extension(&Features::arb_uniform_buffer_object);
511         else
512                 return false;
513 }
514
515 void StructuralFeatureConverter::visit(InterfaceBlock &iface)
516 {
517         bool push_constant = false;
518         if(iface.layout)
519         {
520                 auto i = find_member(iface.layout->qualifiers, string("push_constant"), &Layout::Qualifier::name);
521                 push_constant = (i!=iface.layout->qualifiers.end());
522         }
523
524         if((!supports_interface_blocks(iface.interface) || (push_constant && features.target_api!=VULKAN)) && iface.type_declaration)
525         {
526                 if(!iface.instance_name.empty())
527                         unsupported("ARB_uniform_buffer_object required for interface block instances");
528                 else if(iface.struct_declaration)
529                 {
530                         for(const RefPtr<Statement> &s: iface.struct_declaration->members.body)
531                                 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
532                                         var->interface = iface.interface;
533                         stage->content.body.splice(uniform_insert_point, iface.struct_declaration->members.body);
534                         nodes_to_remove.insert(&iface);
535                         nodes_to_remove.insert(iface.struct_declaration);
536                 }
537                 else
538                         /* If the interface block is an array, it should have an instance
539                         name too, so this should never be reached */
540                         throw logic_error("Unexpected interface block configuration");
541         }
542 }
543
544
545 void QualifierConverter::apply()
546 {
547         stage->content.visit(*this);
548 }
549
550 bool QualifierConverter::supports_interface_layouts() const
551 {
552         if(features.target_api==VULKAN)
553                 return true;
554         else if(features.target_api==OPENGL_ES)
555                 return check_version(Version(3, 0));
556         else if(check_version(Version(3, 30)))
557                 return true;
558         else if(check_version(Version(1, 30)))
559                 return check_extension(&Features::arb_explicit_attrib_location);
560         else
561                 return false;
562 }
563
564 bool QualifierConverter::supports_stage_interface_layouts() const
565 {
566         if(features.target_api==VULKAN)
567                 return true;
568         else if(features.target_api==OPENGL_ES)
569                 return check_version(Version(3, 10));
570         else if(check_version(Version(4, 10)))
571                 return true;
572         else
573                 return check_extension(&Features::arb_separate_shader_objects);
574 }
575
576 bool QualifierConverter::supports_centroid_sampling() const
577 {
578         if(features.target_api==VULKAN)
579                 return true;
580         else if(features.target_api==OPENGL_ES)
581                 return check_version(Version(3, 0));
582         else if(check_version(Version(1, 20)))
583                 return true;
584         else
585                 return check_extension(&Features::ext_gpu_shader4);
586 }
587
588 bool QualifierConverter::supports_sample_sampling() const
589 {
590         if(features.target_api==VULKAN)
591                 return true;
592         else if(features.target_api==OPENGL_ES)
593                 return check_version(Version(3, 20));
594         else if(check_version(Version(4, 0)))
595                 return true;
596         else
597                 return check_extension(&Features::arb_gpu_shader5);
598 }
599
600 bool QualifierConverter::supports_uniform_location() const
601 {
602         if(features.target_api==VULKAN)
603                 return true;
604         else if(features.target_api==OPENGL_ES)
605                 return check_version(Version(3, 10));
606         else if(check_version(Version(4, 30)))
607                 return true;
608         else
609                 return check_extension(&Features::arb_explicit_uniform_location);
610 }
611
612 bool QualifierConverter::supports_binding() const
613 {
614         if(features.target_api==VULKAN)
615                 return true;
616         else if(features.target_api==OPENGL_ES)
617                 return check_version(Version(3, 10));
618         else
619                 return check_version(Version(4, 20));
620 }
621
622 void QualifierConverter::visit(VariableDeclaration &var)
623 {
624         if(var.layout)
625         {
626                 for(auto i=var.layout->qualifiers.begin(); i!=var.layout->qualifiers.end(); )
627                 {
628                         if(i->name=="location")
629                         {
630                                 bool supported = true;
631                                 bool external = false;
632                                 if(var.interface=="in")
633                                 {
634                                         external = (stage->type==Stage::VERTEX);
635                                         supported = (external ? supports_interface_layouts() : supports_stage_interface_layouts());
636                                 }
637                                 else if(var.interface=="out")
638                                 {
639                                         external = (stage->type==Stage::FRAGMENT);
640                                         supported = (external ? supports_interface_layouts() : supports_stage_interface_layouts());
641                                         if(external && !supported && !check_extension(&Features::ext_gpu_shader4))
642                                         {
643                                                 external = false;
644                                                 if(i->value!=0)
645                                                         unsupported("EXT_gpu_shader4 required for multiple fragment shader outputs");
646                                         }
647                                 }
648                                 else if(var.interface=="uniform")
649                                         supported = supports_uniform_location();
650
651                                 if(!supported)
652                                 {
653                                         if(external)
654                                                 stage->locations[var.name] = i->value;
655                                         i = var.layout->qualifiers.erase(i);
656                                 }
657                                 else
658                                         ++i;
659                         }
660                         else if(i->name=="binding" && !supports_binding())
661                         {
662                                 const TypeDeclaration *type = var.type_declaration;
663                                 while(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(type))
664                                         type = basic->base_type;
665                                 if(dynamic_cast<const ImageTypeDeclaration *>(type))
666                                         stage->texture_bindings[var.name] = i->value;
667
668                                 i = var.layout->qualifiers.erase(i);
669                         }
670                         else
671                                 ++i;
672                 }
673
674                 if(var.layout->qualifiers.empty())
675                         var.layout = 0;
676         }
677
678         if(var.sampling=="centroid")
679         {
680                 if(!supports_centroid_sampling())
681                         var.sampling = string();
682         }
683         else if(var.sampling=="sample")
684         {
685                 if(!supports_sample_sampling())
686                         var.sampling = string();
687         }
688
689         if(var.name=="gl_ClipDistance")
690                 if(const Literal *literal_size = dynamic_cast<const Literal *>(var.array_size.get()))
691                         stage->n_clip_distances = literal_size->value.value<int>();
692
693         TraversingVisitor::visit(var);
694 }
695
696 bool QualifierConverter::supports_interface_block_location() const
697 {
698         if(features.target_api==VULKAN)
699                 return true;
700         else if(features.target_api==OPENGL_ES)
701                 return check_version(Version(3, 20));
702         else if(check_version(Version(4, 40)))
703                 return true;
704         else
705                 return check_extension(&Features::arb_enhanced_layouts);
706 }
707
708 void QualifierConverter::visit(InterfaceBlock &iface)
709 {
710         if(iface.layout)
711         {
712                 for(auto i=iface.layout->qualifiers.begin(); i!=iface.layout->qualifiers.end(); )
713                 {
714                         if(i->name=="location" && !supports_interface_block_location())
715                                 i = iface.layout->qualifiers.erase(i);
716                         else if(i->name=="binding" && !supports_binding())
717                         {
718                                 stage->uniform_block_bindings[iface.block_name] = i->value;
719                                 i = iface.layout->qualifiers.erase(i);
720                         }
721                         else
722                                 ++i;
723                 }
724
725                 if(iface.layout->qualifiers.empty())
726                         iface.layout = 0;
727         }
728 }
729
730 } // namespace SL
731 } // namespace GL
732 } // namespace Msp