Repository navigation
Expand file tree
/
Copy pathPipeline.cpp
More file actions
1411 lines (1352 loc) · 89.2 KB
/
Copy pathPipeline.cpp
File metadata and controls
1411 lines (1352 loc) · 89.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceOverlay.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp"
#include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <list>
#include <mutex>
#include <spirv/unified1/spirv.hpp>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <vector>
namespace AgcDriver::Graphics {
namespace {
bool LogicOpFormat(VkFormat format) {
switch (format) {
case VK_FORMAT_R8_UNORM:
case VK_FORMAT_R8G8_UNORM:
case VK_FORMAT_R8G8B8A8_UNORM:
case VK_FORMAT_B8G8R8A8_UNORM:
case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
case VK_FORMAT_A2R10G10B10_UNORM_PACK32:
case VK_FORMAT_R16_UNORM:
case VK_FORMAT_R16G16_UNORM:
case VK_FORMAT_R16G16B16A16_UNORM:
case VK_FORMAT_R8_UINT:
case VK_FORMAT_R8G8_UINT:
case VK_FORMAT_R8G8B8A8_UINT:
case VK_FORMAT_R16_UINT:
case VK_FORMAT_R16G16_UINT:
case VK_FORMAT_R16G16B16A16_UINT:
case VK_FORMAT_R32_UINT:
case VK_FORMAT_R32G32_UINT:
case VK_FORMAT_R32G32B32A32_UINT: return true;
default: return false;
}
}
}
void LogPipelineStatistics_nid_no_patch(const Context& context, VkPipeline pipeline) {
if (!context.pipelineExecutableInfo) return;
const auto getProperties = context.Function<PFN_vkGetPipelineExecutablePropertiesKHR>("vkGetPipelineExecutablePropertiesKHR");
const auto getStatistics = context.Function<PFN_vkGetPipelineExecutableStatisticsKHR>("vkGetPipelineExecutableStatisticsKHR");
VkPipelineInfoKHR pipelineInfo{VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR};
pipelineInfo.pipeline = pipeline;
std::uint32_t count = 0;
Check(getProperties(context.device, &pipelineInfo, &count, nullptr), "vkGetPipelineExecutablePropertiesKHR count");
std::vector<VkPipelineExecutablePropertiesKHR> properties(count, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_PROPERTIES_KHR});
Check(getProperties(context.device, &pipelineInfo, &count, properties.data()), "vkGetPipelineExecutablePropertiesKHR");
properties.resize(count);
std::string report;
const auto append = [&report](const char* format, auto... values) {
std::array<char, 1024> line{};
std::snprintf(line.data(), line.size(), format, values...);
report += line.data();
};
for (std::uint32_t index = 0; index < properties.size(); ++index) {
VkPipelineExecutableInfoKHR executable{VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_INFO_KHR};
executable.pipeline = pipeline;
executable.executableIndex = index;
count = 0;
Check(getStatistics(context.device, &executable, &count, nullptr), "vkGetPipelineExecutableStatisticsKHR count");
std::vector<VkPipelineExecutableStatisticKHR> statistics(count, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_STATISTIC_KHR});
Check(getStatistics(context.device, &executable, &count, statistics.data()), "vkGetPipelineExecutableStatisticsKHR");
statistics.resize(count);
const auto& property = properties[index];
append("[pipeline-stats] executable=%u stages=0x%x subgroup=%u name=%s\n", index, property.stages, property.subgroupSize, property.name);
for (const auto& statistic : statistics) {
switch (statistic.format) {
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR:
append("[pipeline-stats] executable=%u %s=%s (%s)\n", index, statistic.name, statistic.value.b32 ? "true" : "false", statistic.description);
break;
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR:
append("[pipeline-stats] executable=%u %s=%lld (%s)\n", index, statistic.name, static_cast<long long>(statistic.value.i64), statistic.description);
break;
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR:
append("[pipeline-stats] executable=%u %s=%llu (%s)\n", index, statistic.name, static_cast<unsigned long long>(statistic.value.u64), statistic.description);
break;
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_FLOAT64_KHR:
append("[pipeline-stats] executable=%u %s=%.17g (%s)\n", index, statistic.name, statistic.value.f64, statistic.description);
break;
default:
throw std::runtime_error("unsupported pipeline statistic format");
}
}
}
std::fputs(report.c_str(), stderr);
}
bool HasStencil(VkFormat format) {
return format == VK_FORMAT_D16_UNORM_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_S8_UINT;
}
Framebuffer::Framebuffer(const Context& context, VkRenderPass renderPass, std::span<const VkImageView> targets, VkExtent2D extent, std::uint32_t layers) : context(context) {
// Cached objects outlive their device's teardown; they must not keep its buffer pool alive past it.
this->context.bufferPool.reset();
Require(extent.width != 0 && extent.height != 0 && extent.width <= context.limits.maxFramebufferWidth && extent.height <= context.limits.maxFramebufferHeight, "framebuffer extent exceeds device limits");
Require(layers != 0 && layers <= context.limits.maxFramebufferLayers, "framebuffer layers exceed device limits");
views.assign(targets.begin(), targets.end());
if (renderPass == VK_NULL_HANDLE) return;
VkFramebufferCreateInfo framebufferInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = static_cast<std::uint32_t>(targets.size());
framebufferInfo.pAttachments = targets.empty() ? nullptr : targets.data();
framebufferInfo.width = extent.width;
framebufferInfo.height = extent.height;
framebufferInfo.layers = layers;
Check(context.Function<PFN_vkCreateFramebuffer>("vkCreateFramebuffer")(context.device, &framebufferInfo, nullptr, &framebuffer), "vkCreateFramebuffer");
}
Framebuffer::~Framebuffer() {
if (framebuffer) context.Function<PFN_vkDestroyFramebuffer>("vkDestroyFramebuffer")(context.device, framebuffer, nullptr);
}
void ValidateDepthBounds(const Context& context, const State& state) {
Require(!state.depthBoundsTest || context.depthRangeUnrestricted || (state.minDepthBounds >= 0.0f && state.minDepthBounds <= 1.0f && state.maxDepthBounds >= 0.0f && state.maxDepthBounds <= 1.0f), "depth bounds outside [0, 1] require VK_EXT_depth_range_unrestricted");
}
bool BarycentricPatches(const State& state, std::span<const CompiledShader> shaders) {
return !state.rectList && state.stages.path == ShaderPath::Vertex && std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::TessellationControl; });
}
bool FragmentInterlock(std::span<const CompiledShader> shaders) {
return std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) return false;
const auto words = shader.program->spirv.Words();
for (std::size_t cursor = 5; cursor + 1 < words.size() && (words[cursor] & 0xffffu) == spv::OpCapability && (words[cursor] >> 16u) == 2u; cursor += 2) {
const auto capability = words[cursor + 1];
if (capability == spv::CapabilityFragmentShaderPixelInterlockEXT || capability == spv::CapabilityFragmentShaderSampleInterlockEXT || capability == spv::CapabilityFragmentShaderShadingRateInterlockEXT) return true;
}
return false;
});
}
void ValidateProvokingVertex(const Context& context, const State& state, std::span<const CompiledShader> shaders) {
Require(state.provokingVertexMode == VK_PROVOKING_VERTEX_MODE_FIRST_VERTEX_EXT || state.provokingVertexMode == VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT, "invalid provoking vertex mode");
if (state.provokingVertexMode == VK_PROVOKING_VERTEX_MODE_FIRST_VERTEX_EXT) {
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) continue;
Require(std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flatP10; }), "v_interp_mov p10 of a flat input with the first provoking vertex is not measured");
}
return;
}
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) continue;
Require(std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flatP20; }), "v_interp_mov p20 of a flat input with the last provoking vertex is not measured");
}
if (BarycentricPatches(state, shaders)) {
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) continue;
Require(std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flat && parameter.perVertex; }), "last provoking vertex with explicit per-vertex flat interpolation is unsupported");
}
return;
}
struct Decorations {
std::unordered_map<std::uint64_t, std::uint32_t> builtIns;
std::vector<std::uint64_t> perVertexValues;
std::vector<std::uint64_t> perPrimitiveValues;
};
const auto readDecorations = [](const ShaderRecompiler::RecompileResult& program, Decorations& decorations) {
const auto words = program.spirv.Words();
if (words.size() < 5) return false;
constexpr std::uint32_t NoMember = 0xffffffffu;
const auto key = [](std::uint32_t target, std::uint32_t member) { return (static_cast<std::uint64_t>(target) << 32u) | member; };
for (std::size_t cursor = 5; cursor < words.size();) {
const auto count = words[cursor] >> 16u;
if (count == 0 || count > words.size() - cursor) return false;
const auto op = static_cast<spv::Op>(words[cursor] & 0xffffu);
const std::size_t decoration = op == spv::OpDecorate ? 2 : op == spv::OpMemberDecorate ? 3 : 0;
if (decoration != 0 && count > decoration) {
const auto target = key(words[cursor + 1], op == spv::OpMemberDecorate ? words[cursor + 2] : NoMember);
if (words[cursor + decoration] == spv::DecorationFlat || words[cursor + decoration] == spv::DecorationPerVertexKHR) decorations.perVertexValues.push_back(target);
if (words[cursor + decoration] == spv::DecorationPerPrimitiveEXT) decorations.perPrimitiveValues.push_back(target);
if (words[cursor + decoration] == spv::DecorationBuiltIn && count > decoration + 1) decorations.builtIns[target] = words[cursor + decoration + 1];
}
cursor += count;
}
return true;
};
const auto readsProvokingVertex = [&](const ShaderRecompiler::RecompileResult& program) {
if (std::any_of(program.fragmentParameters.begin(), program.fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) {
return parameter.flat || parameter.perVertex || parameter.custom || parameter.flatP10;
})) return true;
Decorations decorations;
if (!readDecorations(program, decorations)) return true;
const auto& builtIns = decorations.builtIns;
return std::any_of(decorations.perVertexValues.begin(), decorations.perVertexValues.end(), [&](std::uint64_t target) {
const auto builtIn = builtIns.find(target);
if (builtIn == builtIns.end()) return true;
switch (builtIn->second) {
case spv::BuiltInFragCoord:
case spv::BuiltInPointCoord:
case spv::BuiltInFrontFacing:
case spv::BuiltInSampleId:
case spv::BuiltInSamplePosition:
case spv::BuiltInSampleMask:
case spv::BuiltInHelperInvocation:
case spv::BuiltInSubgroupSize:
case spv::BuiltInSubgroupLocalInvocationId:
return false;
default:
return true;
}
});
};
const auto writesProvokingVertexBuiltIn = [&](const ShaderRecompiler::RecompileResult& program) {
Decorations decorations;
if (!readDecorations(program, decorations)) return true;
return std::any_of(decorations.builtIns.begin(), decorations.builtIns.end(), [&](const auto& builtIn) {
return (builtIn.second == spv::BuiltInLayer || builtIn.second == spv::BuiltInViewportIndex) &&
std::find(decorations.perPrimitiveValues.begin(), decorations.perPrimitiveValues.end(), builtIn.first) == decorations.perPrimitiveValues.end();
});
};
const bool observed = std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) {
if (shader.stage == ShaderRecompiler::ShaderStage::Fragment) return shader.program == nullptr || readsProvokingVertex(*shader.program);
return shader.program != nullptr && writesProvokingVertexBuiltIn(*shader.program);
});
if (!context.provokingVertexLast && !observed) return;
Require(context.provokingVertexLast, "last provoking vertex requires VK_EXT_provoking_vertex with provokingVertexLast enabled");
const bool meshPrimitives = state.stages.path == ShaderPath::Geometry && state.stages.mesh;
Require(!state.stages.tessellation && (meshPrimitives || (state.stages.path == ShaderPath::Vertex && !state.stages.mesh)), "last provoking vertex is unsupported for generated primitive pipelines");
Require(state.rectList || state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, "last provoking vertex is unsupported for this primitive topology");
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment) continue;
Require(shader.program != nullptr, "missing compiled fragment shader");
Require(std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flat && parameter.perVertex; }), "last provoking vertex with explicit per-vertex flat interpolation is unsupported");
Require(state.topology != VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.vertexOrder; }), "last provoking vertex with explicit per-vertex triangle-strip interpolation is unsupported");
}
}
bool ValidateSampleLocations(const Context& context, const State& state) {
const bool extensionSupportsSamples = (context.sampleLocationSampleCounts & state.samples) != 0;
Require(!state.customSampleLocations || extensionSupportsSamples, "custom sample locations require VK_EXT_sample_locations support for the draw's sample count");
const bool enabled = extensionSupportsSamples && (state.samples > 1 || state.customSampleLocations) && (!state.depth || SampleLocationsCompatibleDepth(context, HostDepthFormat(context, state.depth->format), state.depth->samples));
Require(!state.customSampleLocations || enabled, "custom sample locations require a compatible depth format and sample count");
return enabled;
}
void ValidateMeshLimits(const Context& context, const ShaderRecompiler::MeshConfiguration& mesh, std::uint32_t invocations) {
const auto& limits = context.meshLimits;
Require(invocations <= limits.maxMeshWorkGroupInvocations && invocations <= limits.maxMeshWorkGroupSize[0], "mesh workgroup of " + std::to_string(invocations) + " invocations exceeds device limits (" + std::to_string(limits.maxMeshWorkGroupInvocations) + " invocations, " + std::to_string(limits.maxMeshWorkGroupSize[0]) + " wide)");
Require(mesh.maxVertices <= limits.maxMeshOutputVertices, "mesh output vertices " + std::to_string(mesh.maxVertices) + " exceed the device limit " + std::to_string(limits.maxMeshOutputVertices));
Require(mesh.maxPrimitives <= limits.maxMeshOutputPrimitives, "mesh output primitives " + std::to_string(mesh.maxPrimitives) + " exceed the device limit " + std::to_string(limits.maxMeshOutputPrimitives));
const auto sharedBytes = static_cast<std::uint64_t>(mesh.ldsSizeDwords) * 4;
Require(sharedBytes <= limits.maxMeshSharedMemorySize, "mesh LDS " + std::to_string(sharedBytes) + " bytes exceeds the device shared memory limit " + std::to_string(limits.maxMeshSharedMemorySize));
}
void ValidateViewport(const Context& context, const VkViewport& viewport) {
Require(std::isfinite(viewport.minDepth) && std::isfinite(viewport.maxDepth), "non-finite viewport depth range");
Require(context.depthRangeUnrestricted || (viewport.minDepth >= 0 && viewport.minDepth <= 1 && viewport.maxDepth >= 0 && viewport.maxDepth <= 1), "viewport depth outside [0, 1] requires VK_EXT_depth_range_unrestricted");
Require(std::isfinite(viewport.x) && std::isfinite(viewport.y) && std::isfinite(viewport.width) && std::isfinite(viewport.height), "viewport arithmetic overflow");
Require(viewport.width <= context.limits.maxViewportDimensions[0] && std::abs(viewport.height) <= context.limits.maxViewportDimensions[1], "viewport dimensions exceed device limits");
Require(viewport.x >= context.limits.viewportBoundsRange[0] && viewport.x + viewport.width <= context.limits.viewportBoundsRange[1], "viewport X exceeds device bounds");
Require(std::min(viewport.y, viewport.y + viewport.height) >= context.limits.viewportBoundsRange[0] && std::max(viewport.y, viewport.y + viewport.height) <= context.limits.viewportBoundsRange[1], "viewport Y exceeds device bounds");
}
bool ShadersWriteMemory(std::span<const CompiledShader> shaders) {
const auto any = [](const std::vector<bool>& written, std::uint32_t count) { return written.size() < count || std::ranges::any_of(written, [](bool element) { return element; }); };
for (const auto& shader : shaders) {
if (shader.program == nullptr) continue;
for (const auto& binding : shader.program->bindings) {
switch (binding.role) {
case ShaderRecompiler::DescriptorRole::GuestBuffers:
if (binding.kind != ShaderRecompiler::DescriptorKind::UniformBuffer && binding.kind != ShaderRecompiler::DescriptorKind::UniformTexelBuffer && any(binding.bufferWritten, binding.count)) return true;
break;
case ShaderRecompiler::DescriptorRole::GuestImages:
if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage && any(binding.imageWritten, binding.count)) return true;
break;
case ShaderRecompiler::DescriptorRole::Gds:
return true;
case ShaderRecompiler::DescriptorRole::BdaPagetable:
if (shader.program->bdaWrites) return true;
break;
case ShaderRecompiler::DescriptorRole::GuestSamplers:
case ShaderRecompiler::DescriptorRole::FaultBuffer:
case ShaderRecompiler::DescriptorRole::FlattenedSrt:
case ShaderRecompiler::DescriptorRole::ShaderData:
break;
}
}
}
return false;
}
void ValidateSampleMask(const Context& context, const State& state, std::span<const CompiledShader> shaders) {
if (!PartialSampleMask(state)) return;
const bool uniform = UniformSampleMask(state) && !SampleMaskFollowsOrder(state, HostSampleLocationsFor(context, state).order);
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment) continue;
Require(shader.program != nullptr, "missing compiled fragment shader");
if (uniform) {
Require(context.earlyFragmentSampleMaskTestBeforeSampleCounting || !DeclaresEarlyFragmentTests(*shader.program), "a sample mask with early fragment tests needs VkPhysicalDeviceMaintenance5Properties::earlyFragmentSampleMaskTestBeforeSampleCounting, which the device lacks");
continue;
}
const bool tested = state.depth.has_value() && (state.depthTest || state.stencilTest || state.depthBoundsTest);
Require(!state.pixelEarlyZ || !tested || !ShadersWriteMemory(std::span(&shader, 1)), "a sample mask that differs between the pixels of a quad, from a pixel program with early depth or stencil tests that writes memory, is unsupported: the masked pixels are removed in the shader, after the tests");
}
}
namespace {
thread_local bool prebuilding = false;
thread_local bool prebuilt = false;
VkShaderStageFlags pushStagesOf(const Context& context) {
return PreRasterizationPushStages(context.meshShader, context.tessellationShader, context.geometryShader);
}
template<typename TValue>
void appendKey(std::vector<std::byte>& key, const TValue& value) {
static_assert(std::is_trivially_copyable_v<TValue>);
const auto bytes = std::as_bytes(std::span(&value, 1));
key.insert(key.end(), bytes.begin(), bytes.end());
}
bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders) {
using Stage = ShaderRecompiler::ShaderStage;
if (!context.graphicsPipelineLibrary || context.pipelineExecutableInfo || (state.stages.tessellation && !context.tessellationPipelineCache) || state.depthBiasPerFace || state.rectList || BarycentricPatches(state, shaders) || SplitsAlternateAlpha(state) || std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; }) || UsesMeshWindow(shaders) || FragmentInterlock(shaders)) return false;
keys = {};
for (const auto& shader : shaders) {
const auto identity = shader.program->Identity();
if (shader.stage == Stage::Geometry || identity.Empty()) return false;
auto& key = shader.stage == Stage::Fragment ? keys.fragmentShader : keys.preRasterization;
appendKey(key, shader.stage);
appendKey(key, identity.low);
appendKey(key, identity.high);
appendKey(key, shader.pushConstantOffset);
appendKey(key, state.meshLayerBase);
appendKey(key, state.meshLayerCount);
if (resources.split) {
auto& sets = shader.stage == Stage::Fragment ? keys.fragmentSets : keys.preRasterizationSets;
for (const auto& binding : shader.program->bindings) {
Require(binding.descriptorSet < 2u, "split pipeline library descriptor set exceeds two slots");
sets |= 1u << binding.descriptorSet;
}
}
}
if (resources.split) {
const auto unused = 3u & ~(keys.preRasterizationSets | keys.fragmentSets);
keys.preRasterizationSets |= unused & 1u;
keys.fragmentSets |= unused & 2u;
}
for (const auto& binding : input.bindings) {
appendKey(keys.vertexInput, binding.binding);
appendKey(keys.vertexInput, binding.stride);
appendKey(keys.vertexInput, binding.inputRate);
}
appendKey(keys.vertexInput, input.attributes.size());
for (const auto& attribute : input.attributes) {
appendKey(keys.vertexInput, attribute.location);
appendKey(keys.vertexInput, attribute.binding);
appendKey(keys.vertexInput, attribute.format);
appendKey(keys.vertexInput, attribute.offset);
}
appendKey(keys.vertexInput, state.topology);
appendKey(keys.vertexInput, state.primitiveRestart);
appendKey(keys.preRasterization, state.provokingVertexMode);
appendKey(keys.preRasterization, state.polygonMode);
appendKey(keys.preRasterization, state.negativeOneToOne);
appendKey(keys.preRasterization, state.depthClamp && context.depthClamp);
appendKey(keys.preRasterization, state.conservativeRasterization);
appendKey(keys.preRasterization, state.depth.has_value() && state.depthBias);
appendKey(keys.preRasterization, state.stages.tessellation.has_value());
if (state.stages.tessellation) appendKey(keys.preRasterization, state.stages.tessellation->inputControlPoints);
appendKey(keys.fragmentShader, state.samples);
appendKey(keys.fragmentOutput, state.samples);
appendKey(keys.fragmentShader, state.perSampleShading);
appendKey(keys.fragmentOutput, state.perSampleShading);
appendKey(keys.fragmentShader, state.mergedCoverage);
appendKey(keys.fragmentOutput, state.mergedCoverage);
appendKey(keys.fragmentShader, state.truncatedCoverage);
appendKey(keys.fragmentOutput, state.truncatedCoverage);
const auto sampleLocationsEnabled = ValidateSampleLocations(context, state);
appendKey(keys.fragmentShader, sampleLocationsEnabled);
appendKey(keys.fragmentOutput, sampleLocationsEnabled);
appendKey(keys.fragmentShader, state.customSampleLocations);
appendKey(keys.fragmentOutput, state.customSampleLocations);
if (state.customSampleLocations) {
appendKey(keys.fragmentShader, state.sampleLocationGrid);
appendKey(keys.fragmentOutput, state.sampleLocationGrid);
const auto grid = SampleLocationGrid(state);
for (std::uint32_t pixel = 0; pixel < grid.width * grid.height; ++pixel) {
for (std::uint32_t sample = 0; sample < state.samples; ++sample) {
appendKey(keys.fragmentShader, state.sampleLocations[pixel * 8u + sample]);
appendKey(keys.fragmentOutput, state.sampleLocations[pixel * 8u + sample]);
}
}
}
for (const auto& blend : state.blends) appendKey(keys.fragmentOutput, blend);
appendKey(keys.fragmentOutput, state.colorRop);
for (const auto value : state.blendConstants) appendKey(keys.fragmentOutput, value);
appendKey(keys.renderPass, state.blends.size());
for (const auto& color : state.colors) {
appendKey(keys.renderPass, color.format);
appendKey(keys.renderPass, color.exportIndex);
appendKey(keys.renderPass, color.partialWriteMask != 0u);
}
appendKey(keys.renderPass, state.depth.has_value());
if (state.depth) appendKey(keys.renderPass, state.depth->format);
appendKey(keys.fragmentShader, HostSampleMask(state));
appendKey(keys.fragmentOutput, HostSampleMask(state));
for (auto* key : {&keys.fragmentShader, &keys.fragmentOutput}) {
appendKey(*key, context.sampleLocationSampleCounts);
appendKey(*key, context.sampleLocationGridSampleCounts);
appendKey(*key, context.storageImageMultisample);
appendKey(*key, context.shaderStencilExport);
}
if (!resources.split) {
appendKey(keys.layout, pushStagesOf(context));
for (const auto word : resources.mainKey) appendKey(keys.layout, word);
keys.preRasterizationLayout = keys.fragmentLayout = keys.layout;
return true;
}
const auto splitKey = [&](std::vector<std::byte>& key, std::uint32_t sets) {
appendKey(key, ~0u);
appendKey(key, sets);
appendKey(key, pushStagesOf(context));
if ((sets & 1u) != 0u) {
appendKey(key, resources.mainKey.size());
for (const auto word : resources.mainKey) appendKey(key, word);
}
if ((sets & 2u) != 0u) {
appendKey(key, resources.fragmentKey.size());
for (const auto word : resources.fragmentKey) appendKey(key, word);
}
};
splitKey(keys.layout, 3u);
splitKey(keys.preRasterizationLayout, keys.preRasterizationSets);
splitKey(keys.fragmentLayout, keys.fragmentSets);
return true;
}
}
Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const ShaderResources& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) : Pipeline(context, state, vertexInput, resources.SetLayouts(), shaders, attachmentLayout) {}
Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicRendering(context.graphicsPipelineLibrary) {
PerformanceTimer timing("Vulkan.GraphicsPipeline");
for (const auto& color : state.colors) boundAttachments.push_back(color.partialWriteMask == 0u);
if (state.depth) boundAttachments.push_back(true);
sampleLocationsEnabled = ValidateSampleLocations(context, state);
const auto host = HostSampleLocationsFor(context, state);
sampleLocationGrid = host.grid;
sampleOrder = host.order;
// A cached pipeline may outlive its device's teardown (see ClearCachedPipelines); it must not keep
// the buffer pool, which is reset with the device, alive past it.
this->context.bufferPool.reset();
Require(state.blends.size() == (state.colors.empty() ? 0u : state.colors.back().exportIndex + 1u) && state.colors.size() <= state.blends.size(), "blend states do not match decoded color state");
Require(state.blends.size() <= context.limits.maxColorAttachments, "color targets exceed device attachment limits");
const bool boundColor = std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask == 0u; });
Require((state.hasColorTarget && (boundColor || state.colors.empty() || state.depth.has_value())) || (context.limits.framebufferNoAttachmentsSampleCounts & static_cast<VkSampleCountFlagBits>(state.samples)) != 0, "device does not support rendering without attachments at the draw's sample count");
Require(state.samples == 1 || !state.depth.has_value() || (context.limits.framebufferDepthSampleCounts & static_cast<VkSampleCountFlagBits>(state.samples)) != 0, "device does not support depth targets with the draw's sample count");
Require(!depthBounds || context.depthBounds, "device does not support the depth bounds test");
Require(!depthBias || state.depthBiasClamp == 0.0f || context.depthBiasClamp, "device does not support depth bias clamping");
Require(!state.dualSourceBlend || (context.dualSrcBlend && state.blends.size() <= context.limits.maxFragmentDualSrcAttachments), "device does not support dual-source blending into this many attachments");
Require(state.reversedBlend == 0 || (context.dualSrcBlend && state.blends.size() <= context.limits.maxFragmentDualSrcAttachments), "blending into a color target with a reversed component order through a second source color needs dual-source blending, which the device does not support");
Require(LogicOpFromRop(state.colorRop) == VK_LOGIC_OP_COPY || context.logicOp, "device does not support color logic operations");
Require(LogicOpFromRop(state.colorRop) == VK_LOGIC_OP_COPY || std::ranges::all_of(state.colors, [](const ColorTarget& color) { return LogicOpFormat(color.format); }), "color logic operations on a color target that is not a normalized or integer format are not implemented");
Require(!state.negativeOneToOne || context.depthClipControl, "negative-one-to-one depth clipping requires VK_EXT_depth_clip_control with depthClipControl enabled");
Require(!state.perSampleShading || context.sampleRateShading, "per-sample pixel shading requires the sampleRateShading device feature");
Require(!state.mergedCoverage || (context.mergedCoverageSampleCounts & state.samples) != 0, "an overrasterized draw (a multisampled rasterizer into one-sample color targets) requires VK_NV_framebuffer_mixed_samples with merged coverage reduction");
Require(!(state.vertexPoints || (state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 1u)) || context.largePoints || (state.pointSize == 1.0f && ((state.paClVsOutCntl & (1u << 16u)) == 0 || (state.pointSizeMin == 1.0f && state.pointSizeMax == 1.0f))), "points of a size other than one pixel require the largePoints device feature");
Require(!state.truncatedCoverage || (context.truncatedCoverageSampleCounts & state.samples) != 0, "one-sample color targets beside a multisampled depth target require VK_AMD_mixed_attachment_samples or VK_NV_framebuffer_mixed_samples with truncated coverage reduction");
Require(state.conservativeRasterization == VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT || context.conservativeRasterization, "conservative rasterization requires VK_EXT_conservative_rasterization with at most 1/256 pixel of overestimation and degenerate triangles rasterized");
ValidateProvokingVertex(context, state, shaders);
if (state.rectList) Require(context.tessellationShader && context.limits.maxTessellationPatchSize >= 4, "rect-list requires tessellation with four output control points");
const bool barycentricPatches = BarycentricPatches(state, shaders);
if (barycentricPatches) Require(context.tessellationShader && ((state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST && (!state.primitiveRestart || !context.primitiveListRestart)) || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP), "emulated barycentrics through tessellation require a triangle list or strip, with primitive restart in a list only on a device without VK_EXT_primitive_topology_list_restart");
if (std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Geometry; })) Require(context.geometryShader, "device does not support geometry shaders");
if (state.stages.tessellation) {
Require(context.tessellationShader, "device does not support tessellation shaders");
Require(state.stages.tessellation->inputControlPoints <= context.limits.maxTessellationPatchSize && state.stages.tessellation->outputControlPoints <= context.limits.maxTessellationPatchSize, "tessellation patch exceeds device limits");
}
if (state.stages.mesh) {
Require(context.meshShader, "device does not support VK_EXT_mesh_shader");
const auto& mesh = *state.stages.mesh;
const auto invocations = state.stages.vertexWaveSize == 64u && context.subgroup.subgroupSize == 32u ? mesh.threadsPerGroup / 2u : mesh.threadsPerGroup;
ValidateMeshLimits(context, mesh, invocations);
}
const auto pushStages = PushConstantStages(shaders);
Require(pushStages == 0 || context.limits.maxPushConstantsSize >= PushBlockBytes(dynamicRendering), "graphics push constant range exceeds device limit");
if (dynamicRendering) {
for (const auto& shader : shaders) Require(shader.program->pushConstants.empty() || (shader.pushConstantOffset >= PipelinePushSlotBytes) == (shader.stage == ShaderRecompiler::ShaderStage::Fragment), "a stage's push constants lie outside its push constant slot");
}
try {
std::vector<VkPipelineShaderStageCreateInfo> stages(shaders.size());
std::vector<PipelineSpecialization> specializations;
specializations.reserve(shaders.size());
const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT meshSubgroup{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT, nullptr, 32u};
for (std::uint32_t i = 0; i < shaders.size(); ++i) {
const auto& shader = *shaders[i].program;
_modules[i] = CreateShaderModule(context, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule graphics");
const auto stage = VulkanStage(shaders[i].stage);
stages[i].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stages[i].stage = stage;
stages[i].module = _modules[i];
stages[i].pName = "main";
if (shaders[i].stage == ShaderRecompiler::ShaderStage::Mesh && context.meshWave32 && shader.hostSubgroupSize == 32u) stages[i].pNext = &meshSubgroup;
specializations.emplace_back(shader, state.meshLayerBase, state.meshLayerCount);
stages[i].pSpecializationInfo = specializations.back().Info();
}
if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && !shader.program->stencilReferences.empty(); })) {
for (std::size_t i = 0; i < shaders.size(); ++i) {
if (shaders[i].stage != ShaderRecompiler::ShaderStage::Vertex) continue;
Require(stages[i].flags == 0u && stages[i].pNext == nullptr, "stencil replay vertex stage allows varying subgroup size");
}
}
// A descriptor set layout with the same bindings as this one is compatible with the pipeline
// layout, so later draws bind their own ShaderResources' set under it.
const bool pixelLds = std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; });
const bool meshWindow = UsesMeshWindow(shaders);
const auto pixelLdsLayouts = pixelLds || meshWindow ? PixelFunctionLdsSetLayouts(context) : PixelFunctionLdsLayouts{};
const std::array<VkDescriptorSetLayout, 4> setLayouts{resources.main, (pixelLds || meshWindow) && !resources.split ? pixelLdsLayouts.empty : resources.fragment, pixelLds ? pixelLdsLayouts.buffer : pixelLdsLayouts.empty, meshWindow ? MeshWindowSetLayout(context) : VK_NULL_HANDLE};
const VkPushConstantRange push{pushStages, 0, PipelinePushSlotBytes};
const std::array<VkPushConstantRange, 2> slots{{{pushStagesOf(context), 0, PipelinePushSlotBytes}, {VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes}}};
VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
layoutInfo.flags = pixelLds || meshWindow || !resources.split ? 0 : VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT;
layoutInfo.setLayoutCount = meshWindow ? 4u : pixelLds ? 3u : resources.split ? 2u : 1u;
layoutInfo.pSetLayouts = setLayouts.data();
layoutInfo.pushConstantRangeCount = dynamicRendering ? static_cast<std::uint32_t>(slots.size()) : pushStages != 0 ? 1 : 0;
layoutInfo.pPushConstantRanges = dynamicRendering ? slots.data() : pushStages != 0 ? &push : nullptr;
Check(context.Function<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &layout), "vkCreatePipelineLayout graphics");
std::vector<VkAttachmentDescription> colors;
std::vector<VkAttachmentReference> references(state.blends.size(), VkAttachmentReference{VK_ATTACHMENT_UNUSED, attachmentLayout});
for (std::uint32_t index = 0; index < state.colors.size(); ++index) {
if (state.colors[index].partialWriteMask != 0u) continue;
VkAttachmentDescription color{};
color.format = state.colors[index].format;
color.samples = state.mergedCoverage || state.truncatedCoverage ? VK_SAMPLE_COUNT_1_BIT : static_cast<VkSampleCountFlagBits>(state.samples);
color.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
color.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color.initialLayout = attachmentLayout;
color.finalLayout = attachmentLayout;
references.at(state.colors[index].exportIndex) = {static_cast<std::uint32_t>(colors.size()), attachmentLayout};
colors.push_back(color);
}
boundColorAttachments = static_cast<std::uint32_t>(colors.size());
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = static_cast<std::uint32_t>(references.size());
subpass.pColorAttachments = references.empty() ? nullptr : references.data();
const VkAttachmentReference depthReference{static_cast<std::uint32_t>(colors.size()), VK_IMAGE_LAYOUT_GENERAL};
if (state.depth) {
VkAttachmentDescription depth{};
depth.format = HostDepthFormat(context, state.depth->format);
depth.samples = static_cast<VkSampleCountFlagBits>(state.samples);
depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depth.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
depth.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
depth.initialLayout = VK_IMAGE_LAYOUT_GENERAL;
depth.finalLayout = VK_IMAGE_LAYOUT_GENERAL;
colors.push_back(depth);
subpass.pDepthStencilAttachment = &depthReference;
}
std::vector<VkFormat> renderingColors(state.blends.size(), VK_FORMAT_UNDEFINED);
for (const auto& color : state.colors) {
if (color.partialWriteMask == 0u) renderingColors.at(color.exportIndex) = color.format;
}
VkPipelineRenderingCreateInfoKHR rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR};
rendering.colorAttachmentCount = static_cast<std::uint32_t>(renderingColors.size());
rendering.pColorAttachmentFormats = renderingColors.empty() ? nullptr : renderingColors.data();
const std::vector<VkSampleCountFlagBits> mergedColorSamples(renderingColors.size(), VK_SAMPLE_COUNT_1_BIT);
VkAttachmentSampleCountInfoNV attachmentSamples{VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV};
attachmentSamples.colorAttachmentCount = static_cast<std::uint32_t>(mergedColorSamples.size());
attachmentSamples.pColorAttachmentSamples = mergedColorSamples.empty() ? nullptr : mergedColorSamples.data();
if (state.truncatedCoverage) attachmentSamples.depthStencilAttachmentSamples = static_cast<VkSampleCountFlagBits>(state.samples);
if (state.mergedCoverage || state.truncatedCoverage) rendering.pNext = &attachmentSamples;
if (state.depth) {
rendering.depthAttachmentFormat = HostDepthFormat(context, state.depth->format);
if (HasStencil(state.depth->format)) rendering.stencilAttachmentFormat = rendering.depthAttachmentFormat;
}
if (dynamicRendering) {
depthFormat = state.depth ? HostDepthFormat(context, state.depth->format) : VK_FORMAT_UNDEFINED;
colorSlots.assign(state.blends.size(), ~0u);
for (std::uint32_t index = 0; index < state.colors.size(); ++index) {
if (state.colors[index].partialWriteMask == 0u) colorSlots.at(state.colors[index].exportIndex) = index;
}
this->attachmentLayout = attachmentLayout;
}
VkRenderPassCreateInfo passInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
passInfo.attachmentCount = static_cast<std::uint32_t>(colors.size());
passInfo.pAttachments = colors.empty() ? nullptr : colors.data();
passInfo.subpassCount = 1;
passInfo.pSubpasses = &subpass;
if (!dynamicRendering) Check(context.Function<PFN_vkCreateRenderPass>("vkCreateRenderPass")(context.device, &passInfo, nullptr, &renderPass), "vkCreateRenderPass");
VkPipelineVertexInputStateCreateInfo input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
input.vertexBindingDescriptionCount = static_cast<std::uint32_t>(vertexInput.bindings.size());
input.pVertexBindingDescriptions = vertexInput.bindings.data();
input.vertexAttributeDescriptionCount = static_cast<std::uint32_t>(vertexInput.attributes.size());
input.pVertexAttributeDescriptions = vertexInput.attributes.data();
VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
const bool patches = BarycentricPatches(state, shaders);
assembly.topology = patches ? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST : state.topology;
const bool listTopology = state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
assembly.primitiveRestartEnable = !patches && state.primitiveRestart && (!listTopology || context.primitiveListRestart) ? VK_TRUE : VK_FALSE;
// Viewport and scissor are set per draw (Begin), so they do not multiply pipelines; the depth
// clip control stays baked in.
VkPipelineViewportStateCreateInfo viewports{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
VkPipelineViewportDepthClipControlCreateInfoEXT depthClip{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_DEPTH_CLIP_CONTROL_CREATE_INFO_EXT};
depthClip.negativeOneToOne = state.negativeOneToOne;
if (state.negativeOneToOne) viewports.pNext = &depthClip;
viewports.viewportCount = 1;
viewports.scissorCount = 1;
PipelineLibraryKeys keys;
libraries = libraryKeys(keys, context, state, vertexInput, resources, shaders);
std::vector<VkDynamicState> dynamicStates{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
if (state.stencilReplayReference) dynamicStates.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
if (depthBounds) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
if (depthBias) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
if (libraries) dynamicStates.assign(PipelineLibraryDynamicStates().begin(), PipelineLibraryDynamicStates().end());
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = static_cast<std::uint32_t>(dynamicStates.size());
dynamic.pDynamicStates = dynamicStates.data();
VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
Require(state.polygonMode == VK_POLYGON_MODE_FILL || context.fillModeNonSolid, "a point or line polygon mode needs the fillModeNonSolid feature");
Require(state.polygonMode != VK_POLYGON_MODE_POINT || context.maintenance5, "a point polygon mode needs VK_KHR_maintenance5 for its one-pixel point size");
raster.polygonMode = state.polygonMode;
raster.rasterizerDiscardEnable = state.rasterizerDiscard ? VK_TRUE : VK_FALSE;
raster.depthClampEnable = state.depthClamp && context.depthClamp ? VK_TRUE : VK_FALSE;
Require(!state.depthBiasPerFace || (depthBias && state.cullMode == VK_CULL_MODE_NONE), "per-face depth bias needs both faces rasterized");
raster.cullMode = state.depthBiasPerFace ? VK_CULL_MODE_BACK_BIT : state.cullMode;
raster.frontFace = state.frontFace;
raster.depthBiasEnable = depthBias;
raster.lineWidth = 1;
VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT};
conservative.conservativeRasterizationMode = state.conservativeRasterization;
if (state.conservativeRasterization != VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT) raster.pNext = &conservative;
VkPipelineRasterizationProvokingVertexStateCreateInfoEXT provoking{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT};
provoking.provokingVertexMode = state.provokingVertexMode;
if (context.provokingVertexLast) {
provoking.pNext = raster.pNext;
raster.pNext = &provoking;
}
VkPipelineMultisampleStateCreateInfo samples{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
samples.rasterizationSamples = static_cast<VkSampleCountFlagBits>(state.samples);
samples.sampleShadingEnable = state.perSampleShading ? VK_TRUE : VK_FALSE;
samples.minSampleShading = state.perSampleShading ? 1.0f : 0.0f;
const auto locations = SampleLocations(state);
VkPipelineSampleLocationsStateCreateInfoEXT sampleLocations{VK_STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT};
sampleLocations.sampleLocationsEnable = VK_TRUE;
const auto grid = sampleLocationGrid;
sampleLocations.sampleLocationsInfo = {VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, samples.rasterizationSamples, grid, state.samples * grid.width * grid.height, locations.data()};
if (sampleLocationsEnabled) samples.pNext = &sampleLocations;
VkPipelineCoverageReductionStateCreateInfoNV coverageReduction{VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV};
coverageReduction.coverageReductionMode = state.truncatedCoverage ? VK_COVERAGE_REDUCTION_MODE_TRUNCATE_NV : VK_COVERAGE_REDUCTION_MODE_MERGE_NV;
if (state.mergedCoverage || (state.truncatedCoverage && !context.mixedAttachmentSamples)) {
coverageReduction.pNext = samples.pNext;
samples.pNext = &coverageReduction;
}
VkPipelineDepthStencilStateCreateInfo depthStencil{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
depthStencil.depthTestEnable = state.depthTest;
depthStencil.depthWriteEnable = state.depthWrite;
depthStencil.depthCompareOp = state.depthCompare;
depthStencil.depthBoundsTestEnable = depthBounds;
depthStencil.stencilTestEnable = state.stencilTest;
depthStencil.front = state.stencilFront;
depthStencil.back = state.stencilBack;
const VkSampleMask sampleMask = HostSampleMask(state);
if (PartialSampleMask(state) && UniformSampleMask(state) && !SampleMaskFollowsOrder(state, sampleOrder)) samples.pSampleMask = &sampleMask;
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
const bool alternateAlpha = SplitsAlternateAlpha(state);
std::vector<VkPipelineColorBlendAttachmentState> firstChannels(state.blends.begin(), state.blends.end());
std::vector<VkPipelineColorBlendAttachmentState> secondChannels(state.blends.begin(), state.blends.end());
for (const auto& merged : state.colors) {
if (merged.partialWriteMask != UnclampedBlendMask) continue;
for (auto* channels : {&firstChannels, &secondChannels}) channels->at(merged.exportIndex) = {};
}
if (alternateAlpha) {
const auto keepsStencil = [](const VkStencilOpState& face) { return face.writeMask == 0 || (face.failOp == VK_STENCIL_OP_KEEP && face.passOp == VK_STENCIL_OP_KEEP && face.depthFailOp == VK_STENCIL_OP_KEEP); };
Require(!(state.depth && (state.depthWrite || (state.stencilTest && (!keepsStencil(state.stencilFront) || !keepsStencil(state.stencilBack))))) && !state.depthBiasPerFace, "blending into an 8_8 color target with the alternate component order and a separate alpha blend from a draw that writes depth or stencil is not implemented");
Require(!ShadersWriteMemory(shaders), "blending into an 8_8 color target with the alternate component order and a separate alpha blend from a draw whose shaders write memory is not implemented");
for (std::size_t index = 0; index < secondChannels.size(); ++index) {
const bool split = index < state.colors.size() && state.colors[index].componentMapping == 0xecu && state.blends[index].blendEnable;
if (!split) {
secondChannels[index].colorWriteMask = 0;
continue;
}
firstChannels[index].colorWriteMask &= ~VK_COLOR_COMPONENT_G_BIT;
secondChannels[index].colorWriteMask &= VK_COLOR_COMPONENT_G_BIT;
secondChannels[index].srcColorBlendFactor = state.blends[index].srcAlphaBlendFactor;
secondChannels[index].dstColorBlendFactor = state.blends[index].dstAlphaBlendFactor;
secondChannels[index].colorBlendOp = state.blends[index].alphaBlendOp;
}
}
if (const auto logicOp = LogicOpFromRop(state.colorRop); logicOp != VK_LOGIC_OP_COPY) {
blend.logicOpEnable = VK_TRUE;
blend.logicOp = logicOp;
}
blend.attachmentCount = static_cast<std::uint32_t>(firstChannels.size());
blend.pAttachments = firstChannels.empty() ? nullptr : firstChannels.data();
std::copy(state.blendConstants.begin(), state.blendConstants.end(), blend.blendConstants);
VkGraphicsPipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
pipelineInfo.flags = context.pipelineExecutableInfo ? VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR : 0;
pipelineInfo.stageCount = static_cast<std::uint32_t>(stages.size());
pipelineInfo.pStages = stages.data();
VkPipelineTessellationStateCreateInfo tessellation{VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO};
if (state.rectList || state.stages.tessellation || barycentricPatches) {
tessellation.patchControlPoints = state.stages.tessellation ? state.stages.tessellation->inputControlPoints : 3u;
pipelineInfo.pTessellationState = &tessellation;
}
pipelineInfo.pVertexInputState = state.stages.mesh ? nullptr : &input;
pipelineInfo.pInputAssemblyState = state.stages.mesh ? nullptr : &assembly;
pipelineInfo.pViewportState = &viewports;
pipelineInfo.pRasterizationState = &raster;
pipelineInfo.pMultisampleState = &samples;
pipelineInfo.pDepthStencilState = state.depth ? &depthStencil : nullptr;
pipelineInfo.pColorBlendState = &blend;
pipelineInfo.pDynamicState = &dynamic;
pipelineInfo.layout = layout;
pipelineInfo.renderPass = renderPass;
if (dynamicRendering) pipelineInfo.pNext = &rendering;
timing.Mark("modules_and_state");
if (prebuilding && !libraries) {
for (const auto module : _modules) context.Function<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(context.device, module, nullptr);
_modules.clear();
return;
}
if (prebuilding) {
static_cast<void>(LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, &optimized, true, _modules));
for (const auto module : _modules) context.Function<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(context.device, module, nullptr);
_modules.clear();
prebuilt = true;
return;
}
const VkPipelineCache pipelineCache = state.stages.tessellation && !context.tessellationPipelineCache ? VK_NULL_HANDLE : context.pipelineCache;
if (libraries) pipeline = LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, &optimized, false, _modules);
else {
auto pipelineCacheLock = context.LockPipelineCacheForUse();
Check(context.Function<PFN_vkCreateGraphicsPipelines>("vkCreateGraphicsPipelines")(context.device, pipelineCache, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateGraphicsPipelines");
}
if (alternateAlpha) {
blend.pAttachments = secondChannels.data();
auto pipelineCacheLock = context.LockPipelineCacheForUse();
Check(context.Function<PFN_vkCreateGraphicsPipelines>("vkCreateGraphicsPipelines")(context.device, pipelineCache, 1, &pipelineInfo, nullptr, &secondChannel), "vkCreateGraphicsPipelines");
}
if (state.depthBiasPerFace) {
raster.cullMode = VK_CULL_MODE_FRONT_BIT;
auto pipelineCacheLock = context.LockPipelineCacheForUse();
Check(context.Function<PFN_vkCreateGraphicsPipelines>("vkCreateGraphicsPipelines")(context.device, pipelineCache, 1, &pipelineInfo, nullptr, &backFaces), "vkCreateGraphicsPipelines");
}
for (const auto module : _modules) context.Function<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(context.device, module, nullptr);
_modules.clear();
timing.Mark("create");
PerformanceCounters::CountPipeline();
LogPipelineStatistics_nid_no_patch(context, pipeline);
} catch (...) {
release();
throw;
}
}
bool Pipeline::Prebuild(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders) {
if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return !shader.program->stencilReferences.empty(); })) return false;
struct Scope {
Scope() { prebuilding = true; prebuilt = false; }
~Scope() { prebuilding = false; }
} scope;
const Pipeline pipeline(context, state, vertexInput, resources, shaders);
return prebuilt;
}
Pipeline::~Pipeline() {
release();
}
void Pipeline::release() noexcept {
framebuffers.clear();
if (optimized != nullptr) optimized->Release();
optimized.reset();
if (pipeline) context.Function<PFN_vkDestroyPipeline>("vkDestroyPipeline")(context.device, pipeline, nullptr);
if (backFaces) context.Function<PFN_vkDestroyPipeline>("vkDestroyPipeline")(context.device, backFaces, nullptr);
if (secondChannel) context.Function<PFN_vkDestroyPipeline>("vkDestroyPipeline")(context.device, secondChannel, nullptr);
if (renderPass) context.Function<PFN_vkDestroyRenderPass>("vkDestroyRenderPass")(context.device, renderPass, nullptr);
if (layout) context.Function<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(context.device, layout, nullptr);
for (auto module : _modules) {
if (module) context.Function<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(context.device, module, nullptr);
}
pipeline = VK_NULL_HANDLE;
backFaces = VK_NULL_HANDLE;
secondChannel = VK_NULL_HANDLE;
renderPass = VK_NULL_HANDLE;
layout = VK_NULL_HANDLE;
_modules.clear();
}
void Pipeline::Abandon() noexcept {
if (optimized != nullptr) optimized->released.store(true);
optimized.reset();
for (auto& entry : framebuffers) entry.framebuffer->Abandon();
framebuffers.clear();
pipeline = VK_NULL_HANDLE;
backFaces = VK_NULL_HANDLE;
secondChannel = VK_NULL_HANDLE;
renderPass = VK_NULL_HANDLE;
layout = VK_NULL_HANDLE;
_modules.clear();
}
void Framebuffer::Abandon() noexcept {
framebuffer = VK_NULL_HANDLE;
}
VkPipelineLayout Pipeline::Layout() const {
return layout;
}
std::shared_ptr<Framebuffer> Pipeline::AcquireFramebuffer(std::span<const VkImageView> targets, std::span<const std::shared_ptr<void>> owners, VkExtent2D extent, std::uint32_t layers) {
Require(targets.size() == attachments && owners.size() == colorAttachments, "render targets do not match the pipeline's attachments");
bool resident = true;
for (const auto& owner : owners) resident = resident && owner != nullptr;
const auto depthReleases = attachments > colorAttachments ? DepthSurfacesReleased() : 0u;
if (resident) {
// Entries whose views are gone can never match again and go as soon as no recorded draw holds
// them (Kept keeps its framebuffer until the batch completes).
std::erase_if(framebuffers, [&](const CachedFramebuffer& entry) {
if (entry.framebuffer.use_count() != 1) return false;
if (entry.depthReleases != depthReleases) return true;
for (std::size_t i = 0; i < entry.owners.size(); ++i) {
if (entry.owned[i] && entry.owners[i].expired()) return true;
}
return false;
});
for (auto it = framebuffers.begin(); it != framebuffers.end(); ++it) {
if (it->extent.width != extent.width || it->extent.height != extent.height || it->layers != layers || it->depthReleases != depthReleases || !std::equal(it->views.begin(), it->views.end(), targets.begin(), targets.end())) continue;
// View handles are recycled once a StorageTexture is destroyed, so the owners must be the
// very objects the views were made for.
bool same = true;
for (std::size_t i = 0; i < owners.size() && same; ++i) same = it->owned[i] == (owners[i] != nullptr) && it->owners[i].lock().get() == owners[i].get();
if (!same) continue;
std::rotate(it, std::next(it), framebuffers.end());
return framebuffers.back().framebuffer;
}
}
std::vector<VkImageView> boundViews;
for (std::size_t i = 0; i < targets.size(); ++i) {
if (boundAttachments[i]) boundViews.push_back(targets[i]);
}
auto framebuffer = std::make_shared<Framebuffer>(context, renderPass, renderPass == VK_NULL_HANDLE ? targets : std::span<const VkImageView>(boundViews), extent, layers);
if (!resident) return framebuffer;
// Beyond the bound the least recently used unreferenced entry goes.
constexpr std::size_t bound = 8;
while (framebuffers.size() >= bound) {
const auto victim = std::find_if(framebuffers.begin(), framebuffers.end(), [](const CachedFramebuffer& entry) { return entry.framebuffer.use_count() == 1; });
if (victim == framebuffers.end()) break;
framebuffers.erase(victim);
}
CachedFramebuffer entry;
entry.views.assign(targets.begin(), targets.end());
entry.owners.assign(owners.begin(), owners.end());
for (const auto& owner : owners) entry.owned.push_back(owner != nullptr);
entry.extent = extent;
entry.layers = layers;
entry.depthReleases = depthReleases;
entry.framebuffer = framebuffer;
framebuffers.push_back(std::move(entry));
return framebuffer;
}
void Pipeline::Begin(VkCommandBuffer commands, const Framebuffer& framebuffer, VkExtent2D extent, const State& state) const {
if (dynamicRendering) {
const auto views = framebuffer.Views();
Require(views.size() == attachments, "render targets do not match the pipeline's attachments");
std::vector<VkRenderingAttachmentInfoKHR> colors(colorSlots.size(), VkRenderingAttachmentInfoKHR{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR});
for (std::size_t slot = 0; slot < colorSlots.size(); ++slot) {
if (colorSlots[slot] == ~0u) continue;
colors[slot].imageView = views[colorSlots[slot]];
colors[slot].imageLayout = attachmentLayout;
colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
}
VkRenderingAttachmentInfoKHR depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR};
if (depthFormat != VK_FORMAT_UNDEFINED) {
depth.imageView = views.back();
depth.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
}
VkRenderingInfoKHR rendering{VK_STRUCTURE_TYPE_RENDERING_INFO_KHR};
rendering.renderArea = {{0, 0}, extent};
rendering.layerCount = state.renderLayers;
const bool outputs = !state.rasterizerDiscard;
rendering.colorAttachmentCount = outputs ? static_cast<std::uint32_t>(colors.size()) : 0u;
rendering.pColorAttachments = outputs && !colors.empty() ? colors.data() : nullptr;
if (outputs && depthFormat != VK_FORMAT_UNDEFINED) rendering.pDepthAttachment = &depth;
if (outputs && depthFormat != VK_FORMAT_UNDEFINED && HasStencil(depthFormat)) rendering.pStencilAttachment = &depth;
context.Resolved(&DeviceFunctions::cmdBeginRendering, "vkCmdBeginRenderingKHR")(commands, &rendering);
Continue(commands, state);
return;
}
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = renderPass;
begin.framebuffer = framebuffer.Handle();
begin.renderArea = {{0, 0}, extent};
const auto locations = SampleLocations(state);
const auto grid = sampleLocationGrid;
const VkSampleLocationsInfoEXT info{VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, static_cast<VkSampleCountFlagBits>(state.samples), grid, state.samples * grid.width * grid.height, locations.data()};
const VkAttachmentSampleLocationsEXT initial{boundColorAttachments, info};
const VkSubpassSampleLocationsEXT post{0, info};
VkRenderPassSampleLocationsBeginInfoEXT sampleLocations{VK_STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT};
sampleLocations.attachmentInitialSampleLocationsCount = state.depth ? 1 : 0;
sampleLocations.pAttachmentInitialSampleLocations = state.depth ? &initial : nullptr;
sampleLocations.postSubpassSampleLocationsCount = 1;
sampleLocations.pPostSubpassSampleLocations = &post;
if (sampleLocationsEnabled) begin.pNext = &sampleLocations;
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
Continue(commands, state);
}
void Pipeline::Continue(VkCommandBuffer commands, const State& state) const {
if (optimized != nullptr) optimized->Schedule();
const auto best = optimized != nullptr ? optimized->handle.load() : VK_NULL_HANDLE;
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, best != VK_NULL_HANDLE ? best : pipeline);
context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &state.viewport);
context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &state.scissor);
if (state.stencilReplayReference) context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, *state.stencilReplayReference);
if (libraries) {
setLibraryState(commands, state);
return;
}
if (depthBias) context.Resolved(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, HostDepthBiasConstant(context, state.depth->format, state.depthBiasConstant), state.depthBiasClamp, state.depthBiasSlope);
if (!depthBounds) return;
context.Resolved(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, state.minDepthBounds, state.maxDepthBounds);
}
void Pipeline::setLibraryState(VkCommandBuffer commands, const State& state) const {
const bool depth = state.depth.has_value();
context.Resolved(&DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT")(commands, state.cullMode);
context.Resolved(&DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT")(commands, state.frontFace);
context.Resolved(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, depthBias ? HostDepthBiasConstant(context, state.depth->format, state.depthBiasConstant) : 0.0f, depthBias ? state.depthBiasClamp : 0.0f, depthBias ? state.depthBiasSlope : 0.0f);
context.Resolved(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, depthBounds ? state.minDepthBounds : 0.0f, depthBounds ? state.maxDepthBounds : 1.0f);
context.Resolved(&DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT")(commands, depth && state.depthTest);
context.Resolved(&DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT")(commands, depth && state.depthWrite);
context.Resolved(&DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT")(commands, depth ? state.depthCompare : VK_COMPARE_OP_ALWAYS);
context.Resolved(&DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT")(commands, depthBounds);
context.Resolved(&DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT")(commands, depth && state.stencilTest);
const auto stencil = [&](VkStencilFaceFlags face, const VkStencilOpState& op) {
context.Resolved(&DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT")(commands, face, op.failOp, op.passOp, op.depthFailOp, op.compareOp);
context.Resolved(&DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask")(commands, face, op.compareMask);
context.Resolved(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, face, op.writeMask);
context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, face, op.reference);
};
stencil(VK_STENCIL_FACE_FRONT_BIT, depth ? state.stencilFront : VkStencilOpState{});
stencil(VK_STENCIL_FACE_BACK_BIT, depth ? state.stencilBack : VkStencilOpState{});
}
void Pipeline::ContinueSecondChannel(VkCommandBuffer commands) const {
Require(secondChannel != VK_NULL_HANDLE, "the pipeline blends every channel in one pass");
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, secondChannel);
}
void Pipeline::ContinueBackFaces(VkCommandBuffer commands, const State& state) const {
Require(backFaces != VK_NULL_HANDLE, "the pipeline draws both faces in one pass");
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, backFaces);
context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &state.viewport);
context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &state.scissor);
context.Resolved(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, HostDepthBiasConstant(context, state.depth->format, state.backDepthBiasConstant), state.depthBiasClamp, state.backDepthBiasSlope);
if (depthBounds) context.Resolved(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, state.minDepthBounds, state.maxDepthBounds);
}
void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span<const std::byte, PipelinePushConstantBytes> bytes) const {
if (stages == 0) return;
if (dynamicRendering) {
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, pushStagesOf(context), 0, PipelinePushSlotBytes, bytes.data());
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes, bytes.data() + PipelinePushSlotBytes);
return;
}
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, stages, 0, PipelinePushSlotBytes, bytes.data());
}
namespace {
template<typename TValue>
void append(std::vector<std::byte>& key, const TValue& value) {
static_assert(std::is_trivially_copyable_v<TValue>);
const auto bytes = std::as_bytes(std::span(&value, 1));
key.insert(key.end(), bytes.begin(), bytes.end());
}