Repository navigation
Expand file tree
/
Copy pathVulkanDevice.cpp
More file actions
3775 lines (3637 loc) · 239 KB
/
Copy pathVulkanDevice.cpp
File metadata and controls
3775 lines (3637 loc) · 239 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/Graphics/include/PipelineSpecialization.hpp"
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "BdaAbi.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
#include "prx/libSceAgcDriver/Execution/include/BdaFeatures.hpp"
#include "prx/libSceAgcDriver/Execution/include/SubgroupClock.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp"
#include "prx/libSceAgcDriver/Execution/include/PresentationScaler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
#include "prx/libSceAgcDriver/Execution/include/DisplayFormat.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureCache.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineCache.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/General.hpp"
#ifdef _WIN32
#include <windows.h>
#endif
#include <atomic>
#include <chrono>
#include <charconv>
#include <condition_variable>
#include <fstream>
#include <cctype>
#include <cstdlib>
#include <mutex>
#include <SDL_loadso.h>
#include <SDL_error.h>
#include <spirv/unified1/spirv.hpp>
#include <array>
#include <optional>
#include <algorithm>
#include <cstring>
#include <deque>
#include <limits>
#include <list>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <vector>
#include <utility>
namespace AgcDriver {
namespace {
void check(VkResult result, const char* operation) {
if (result != VK_SUCCESS) {
throw std::runtime_error(std::string(operation) + ": Vulkan result " + std::to_string(result));
}
}
void require(bool condition, const char* reason) {
if (!condition) throw std::runtime_error(std::string("Vulkan presentation: ") + reason);
}
// The ShaderResources content cache dispatches share with recorded draws: Graphics::ResourceCache,
// one process-wide instance (see SharedResourceCache) that the State references so this file keeps
// its Find/Insert/Remove/Clear calls; the device clears it at teardown before its descriptor caches
// go. APS5_NO_RESOURCE_CACHE=1 builds every dispatch's resources as before.
using ResourceCache = Graphics::ResourceCache;
std::uint32_t DumpScale();
void WriteFrameBmp(int index, std::uint32_t fullWidth, std::uint32_t fullHeight, std::span<const std::byte> full, std::uint32_t scale);
class FrameDumpWriter {
public:
~FrameDumpWriter() {
{
std::lock_guard lock(mutex);
stopping = true;
}
changed.notify_one();
if (worker.joinable()) worker.join();
}
void Enqueue(int index, std::uint32_t width, std::uint32_t height, std::uint32_t scale, std::vector<std::byte> pixels) {
std::lock_guard lock(mutex);
require(!stopping, "frame dump writer has stopped");
require(pixels.size() <= maxBytes - queuedBytes, "frame dump queue exceeded 64 MiB");
if (!worker.joinable()) worker = std::thread([this] { run(); });
const auto bytes = pixels.size();
pending.push_back({index, width, height, scale, std::move(pixels)});
queuedBytes += bytes;
changed.notify_one();
}
private:
struct Frame {
int index;
std::uint32_t width;
std::uint32_t height;
std::uint32_t scale;
std::vector<std::byte> pixels;
};
void run() {
try {
for (;;) {
std::deque<Frame> batch;
{
std::unique_lock lock(mutex);
changed.wait(lock, [this] { return stopping || !pending.empty(); });
if (pending.empty() && stopping) return;
batch.swap(pending);
}
for (const auto& frame : batch) {
WriteFrameBmp(frame.index, frame.width, frame.height, frame.pixels, frame.scale);
std::lock_guard lock(mutex);
queuedBytes -= frame.pixels.size();
}
}
} catch (const std::exception& error) {
std::fprintf(stderr, "[gpu] frame dump writer failed: %s\n", error.what());
std::terminate();
}
}
static constexpr std::size_t maxBytes = 64 * 1024 * 1024;
std::mutex mutex;
std::condition_variable changed;
std::deque<Frame> pending;
std::thread worker;
std::size_t queuedBytes = 0;
bool stopping = false;
};
// The [present] line's counters (see the header); mutated under State::presentMutex.
VulkanDevice::PresentStatistics presentCounters{};
}
// A compute dispatch's Vulkan objects, shared by every dispatch of the same compiled variant and
// kept by the recorder until the batches using them completed (a Recipe references them weakly).
struct ComputePipelineObjects {
VkDevice device = VK_NULL_HANDLE;
PFN_vkDestroyShaderModule destroyModule = nullptr;
PFN_vkDestroyPipelineLayout destroyLayout = nullptr;
PFN_vkDestroyPipeline destroyPipeline = nullptr;
VkShaderModule module = VK_NULL_HANDLE;
VkPipelineLayout layout = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
~ComputePipelineObjects() {
if (pipeline != VK_NULL_HANDLE) destroyPipeline(device, pipeline, nullptr);
if (layout != VK_NULL_HANDLE) destroyLayout(device, layout, nullptr);
if (module != VK_NULL_HANDLE) destroyModule(device, module, nullptr);
}
};
struct VulkanDevice::State {
void* library = nullptr;
PFN_vkGetInstanceProcAddr instanceProc = nullptr;
PFN_vkGetDeviceProcAddr deviceProc = nullptr;
VkInstance instance = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkPhysicalDevice physical = VK_NULL_HANDLE;
VkQueue queue = VK_NULL_HANDLE;
VkCommandPool pool = VK_NULL_HANDLE;
void* window = nullptr;
VkSurfaceKHR surface = VK_NULL_HANDLE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
VkExtent2D extent{};
std::vector<VkImage> images;
VkFence acquireFence = VK_NULL_HANDLE;
struct RetiredSwapchain {
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
std::vector<VkSemaphore> rendered;
};
std::vector<VkSemaphore> rendered;
std::vector<RetiredSwapchain> retiredSwapchains;
VkPhysicalDeviceMemoryProperties memoryProperties{};
VkBuffer uploadBuffer = VK_NULL_HANDLE;
VkDeviceMemory uploadMemory = VK_NULL_HANDLE;
void* uploadMapping = nullptr;
VkDeviceSize uploadSize = 0;
VkPhysicalDeviceProperties properties{};
VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES};
std::vector<std::uint32_t> capabilities{1};
std::vector<std::string_view> spirvExtensions;
std::unique_ptr<const ShaderDeviceProfile> shaderProfile;
bool tessellationShader = false;
bool meshShader = false;
bool fragmentShaderBarycentric = false;
bool geometryShader = false;
bool sampleRateShading = false;
bool shaderClock = false;
bool narrowSubgroupClock = false;
// VK_EXT_descriptor_indexing with non-uniform image array indexing (bindless image tables in
// graphics stages, and compute workgroups wider than a wave).
bool descriptorIndexing = false;
bool imageInt64Atomics = false;
bool primitiveListRestart = false;
bool depthClipControl = false;
bool imageViewMinLod = false;
bool pipelineExecutableInfo = false;
bool maintenance8 = false;
std::uint32_t srgbDecodeFormats = 0;
bool depthClamp = false;
bool depthBounds = false;
bool depthBiasClamp = false;
bool occlusionQueryPrecise = false;
VkDeviceSize hostImportAlignment = 0;
bool dmaBufImport = false;
bool depthRangeUnrestricted = false;
bool samplerAnisotropy = false;
bool textureCompressionBC = false;
bool samplerFilterMinmax = false;
bool fragmentShaderPixelInterlock = false;
bool conservativeRasterization = false;
// VK_KHR_timeline_semaphore enabled: the recorder's unlocked waits are available.
bool timelineSemaphores = false;
bool computeWave32 = false;
std::uint32_t maxComputeSubgroupSize = 0;
// Indirect draw features enabled (see Graphics::Context).
bool drawIndirectFirstInstance = false;
bool multiDrawIndirect = false;
bool drawIndirectCount = false;
// The device's resolved entry points (Graphics::DeviceFunctions) and the Graphics::Context
// built once after setup (see graphicsContext); the context's pool reference is dropped before
// the pool at teardown.
Graphics::DeviceFunctions deviceFunctions;
bool functionsReady = false;
Graphics::Context context;
bool contextReady = false;
std::unique_ptr<Graphics::TextureDetiler> detiler;
std::unique_ptr<Graphics::Recorder> recorder;
// Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used
// last; each is filled once by a doubling chain in device memory.
std::vector<std::pair<std::array<std::uint32_t, 4>, std::shared_ptr<Graphics::DeviceBuffer>>> patternBuffers;
// Compute pipeline objects by variant (and push-constant use), under their own mutex: the
// dispatch's find-or-insert and the verify switch's lookups touch the map, recipes hold weak
// references to its objects.
std::mutex computePipelinesMutex;
std::map<std::uint64_t, std::shared_ptr<ComputePipelineObjects>> computePipelines;
std::unique_ptr<Graphics::GpuColorTransfer> colorTransfer;
std::shared_ptr<Graphics::BufferPool> bufferPool;
std::unique_ptr<Graphics::Buffer> emptyBuffer;
std::unique_ptr<Graphics::TextureCache> textureCache;
std::unique_ptr<Graphics::PipelineCache> pipelineCache;
std::unique_ptr<Graphics::DescriptorCache> descriptorCache;
std::unique_ptr<Graphics::SamplerCache> samplerCache;
Graphics::ResourceCache& resourceCache = Graphics::SharedResourceCache();
// Recorded dispatches that write a copied buffer (their results reach guest memory by a CPU
// write-back when the batch is reaped), listed until that write-back ran. An indirect dispatch
// whose arguments one of them writes must read them on the CPU (DispatchIndirect); GPU-direct
// writes into host imports need no entry. Under GuestMemory::GpuMutex; shared with the completion
// actions so they never outlive it.
std::shared_ptr<std::vector<std::shared_ptr<Graphics::ShaderResources>>> copiedWriters = std::make_shared<std::vector<std::shared_ptr<Graphics::ShaderResources>>>();
VkPhysicalDeviceMeshShaderPropertiesEXT meshLimits{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT};
std::unique_ptr<PresentationScaler> scaler;
// The swapchain image AcquireImage took for the next present(), consumed by that present.
bool imageAcquired = false;
std::uint32_t acquiredIndex = 0;
// Presentations in flight (see the header): FlipInFlight() + 1 slots used round robin from
// `presentCursor` (the slot there is the oldest). A slot's kept resident image and its dump
// buffer (APS5_DUMP_FRAMES: the frame read back by the blit's submission) live until its fence
// signaled. `presentMutex` orders the presenter's unlocked RetirePresents against a WaitIdle
// from a queue worker; it is never taken before GuestMemory::GpuMutex on a thread.
struct PresentSlot {
VkFence fence = VK_NULL_HANDLE;
VkCommandBuffer commands = VK_NULL_HANDLE;
std::shared_ptr<void> kept;
std::unique_ptr<Graphics::Buffer> dumpBuffer;
std::unique_ptr<PresentationScaler> dumpScaler;
std::uint32_t dumpWidth = 0;
std::uint32_t dumpHeight = 0;
std::uint32_t dumpScale = 1;
bool dumpRecorded = false;
int dumpIndex = 0;
std::uint32_t imageIndex = 0;
bool inFlight = false;
// The blit reads the single scaler source, staging or upload objects (not a direct blit
// from the resident image): the next use of those waits for this slot.
bool shared = false;
// Recorder::Submissions() when the blit was submitted and the previous slot's: the batches
// in between ran ahead of this blit.
std::uint64_t recorderSerial = 0;
std::uint64_t previousSerial = 0;
std::chrono::steady_clock::time_point submittedAt{};
// APS5_PROFILE_GPU: the blit's own two timestamps (the [gputime] present-blit class), read
// when the slot retires, and the swapchain bytes it wrote.
VkQueryPool queries = VK_NULL_HANDLE;
std::uint64_t blitBytes = 0;
};
std::vector<PresentSlot> presentSlots;
std::size_t presentCursor = 0;
std::uint64_t lastPresentSerial = 0;
// The batch ranges of retired slots whose GPU accounting waits for the batches' completion
// records (SettleRetired); under presentMutex.
struct RetiredRange {
std::uint64_t afterSerial;
std::uint64_t throughSerial;
};
std::deque<RetiredRange> retiredRanges;
std::mutex presentMutex;
// The presentation present() submitted and QueuePresent has not handed to the swapchain.
bool queuePending = false;
std::uint32_t queueIndex = 0;
int nextDumpIndex = 0;
FrameDumpWriter dumpWriter;
template<typename TFunction>
TFunction InstanceFunction(const char* name) const {
auto function = reinterpret_cast<TFunction>(instanceProc(instance, name));
if (function == nullptr) {
throw std::runtime_error(std::string("Vulkan instance function missing: ") + name);
}
return function;
}
template<typename TFunction>
TFunction DeviceFunction(const char* name) const {
++Graphics::DeviceProcLookups();
auto function = reinterpret_cast<TFunction>(deviceProc(device, name));
if (function == nullptr) {
throw std::runtime_error(std::string("Vulkan device function missing: ") + name);
}
return function;
}
void Upload(std::span<const std::byte> pixels) {
APS5_LOG_OUT("Upload pixels=%zu uploadSize=%llu buffer=%p memory=%p mapping=%p", pixels.size(), static_cast<unsigned long long>(uploadSize), reinterpret_cast<void*>(uploadBuffer), reinterpret_cast<void*>(uploadMemory), uploadMapping);
if (uploadSize < pixels.size()) {
APS5_LOG_OUT("Upload reallocating oldSize=%llu newSize=%zu", static_cast<unsigned long long>(uploadSize), pixels.size());
if (uploadMapping) DeviceFunction<PFN_vkUnmapMemory>("vkUnmapMemory")(device, uploadMemory);
uploadMapping = nullptr;
if (uploadBuffer) DeviceFunction<PFN_vkDestroyBuffer>("vkDestroyBuffer")(device, uploadBuffer, nullptr);
uploadBuffer = VK_NULL_HANDLE;
if (uploadMemory) DeviceFunction<PFN_vkFreeMemory>("vkFreeMemory")(device, uploadMemory, nullptr);
uploadMemory = VK_NULL_HANDLE;
uploadSize = 0;
VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
buffer.size = pixels.size();
buffer.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
buffer.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
check(DeviceFunction<PFN_vkCreateBuffer>("vkCreateBuffer")(device, &buffer, nullptr, &uploadBuffer), "vkCreateBuffer display upload");
VkMemoryRequirements requirements{};
DeviceFunction<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(device, uploadBuffer, &requirements);
std::uint32_t memoryType = memoryProperties.memoryTypeCount;
const auto flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
for (std::uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
if ((requirements.memoryTypeBits & (1u << i)) != 0 && (memoryProperties.memoryTypes[i].propertyFlags & flags) == flags) {
memoryType = i;
break;
}
}
require(memoryType < memoryProperties.memoryTypeCount, "coherent host upload memory is unavailable");
APS5_LOG_OUT("Upload requirements size=%llu alignment=%llu typeBits=0x%x memoryType=%u", static_cast<unsigned long long>(requirements.size), static_cast<unsigned long long>(requirements.alignment), requirements.memoryTypeBits, memoryType);
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
allocation.memoryTypeIndex = memoryType;
check(DeviceFunction<PFN_vkAllocateMemory>("vkAllocateMemory")(device, &allocation, nullptr, &uploadMemory), "vkAllocateMemory display upload");
check(DeviceFunction<PFN_vkBindBufferMemory>("vkBindBufferMemory")(device, uploadBuffer, uploadMemory, 0), "vkBindBufferMemory display upload");
check(DeviceFunction<PFN_vkMapMemory>("vkMapMemory")(device, uploadMemory, 0, pixels.size(), 0, &uploadMapping), "vkMapMemory display upload");
uploadSize = pixels.size();
APS5_LOG_OUT("Upload allocation complete buffer=%p memory=%p mapping=%p size=%llu", reinterpret_cast<void*>(uploadBuffer), reinterpret_cast<void*>(uploadMemory), uploadMapping, static_cast<unsigned long long>(uploadSize));
}
std::memcpy(uploadMapping, pixels.data(), pixels.size());
APS5_LOG_OUT("Upload memcpy complete bytes=%zu", pixels.size());
}
bool SharedSlotInFlight() {
std::lock_guard lock(presentMutex);
return std::any_of(presentSlots.begin(), presentSlots.end(), [](const auto& slot) { return slot.inFlight && slot.shared; });
}
// Whether a recorded dispatch's or draw's copied write-back (listed until it ran) stores into
// the range on the CPU; under GpuMutex.
bool CopiedWriterOverlaps(std::uint64_t address, std::size_t bytes) const {
const auto overlaps = [&](const auto& writer) { return writer->WritesOverlap(address, bytes); };
return std::any_of(copiedWriters->begin(), copiedWriters->end(), overlaps) || std::any_of(Graphics::DrawCopiedWriters()->begin(), Graphics::DrawCopiedWriters()->end(), overlaps);
}
void DestroyRetiredSwapchains() {
if (retiredSwapchains.empty()) return;
const auto destroySemaphore = DeviceFunction<PFN_vkDestroySemaphore>("vkDestroySemaphore");
const auto destroySwapchain = DeviceFunction<PFN_vkDestroySwapchainKHR>("vkDestroySwapchainKHR");
for (const auto& retired : retiredSwapchains) {
for (auto semaphore : retired.rendered) {
if (semaphore) destroySemaphore(device, semaphore, nullptr);
}
destroySwapchain(device, retired.swapchain, nullptr);
}
retiredSwapchains.clear();
}
// A presentation slot whose fence signaled: its frame dump is written, its kept image released
// and its statistics taken (under presentMutex).
void RetireSlot(PresentSlot& slot) {
slot.inFlight = false;
slot.kept.reset();
if (slot.dumpRecorded) {
slot.dumpRecorded = false;
WriteFrameDump(slot);
}
if (slot.queries != VK_NULL_HANDLE) {
std::uint64_t stamps[2] = {};
if (DeviceFunction<PFN_vkGetQueryPoolResults>("vkGetQueryPoolResults")(device, slot.queries, 0, 2, sizeof(stamps), stamps, sizeof(std::uint64_t), VK_QUERY_RESULT_64_BIT) == VK_SUCCESS && stamps[1] > stamps[0]) {
Graphics::Recorder::AddGpuTiming(Graphics::Recorder::CommandClass::PresentBlit, static_cast<double>(stamps[1] - stamps[0]) * properties.limits.timestampPeriod, slot.blitBytes);
}
}
if (!recorder) return;
const auto afterFlip = recorder->NewestSubmitted() - slot.recorderSerial;
presentCounters.batchesAfterFlip += afterFlip;
if (auto* frame = PerformanceContext::Current()) frame->NoteRetired(afterFlip, 0, 0);
retiredRanges.push_back({slot.previousSerial, slot.recorderSerial});
SettleRetired(false);
}
// The GPU accounting of retired slots ([present] line, frame record): a batch's completion
// record is written when a queue worker finishes it, which can be well after the blit's fence
// signaled (compute queues never reap), so a range read at the retire was mostly unread. Each
// range waits until every serial in it has a record, or until the ring could have dropped its
// oldest one (`force`: at teardown). Under presentMutex.
void SettleRetired(bool force) {
const auto newest = recorder->NewestSubmitted();
while (!retiredRanges.empty()) {
const auto range = retiredRanges.front();
std::size_t missing = 0;
const auto batches = recorder->CompletedBatches(range.afterSerial, range.throughSerial, missing);
if (missing != 0 && !force && newest < range.afterSerial + Graphics::Recorder::CompletedRingSize / 2) break;
retiredRanges.pop_front();
double busyMs = 0, firstNs = 0, lastNs = 0;
bool stamped = false;
std::uint64_t checked = 0, overwritten = 0;
for (const auto& batch : batches) {
if (batch.gpuEndNs > batch.gpuStartNs) {
busyMs += (batch.gpuEndNs - batch.gpuStartNs) / 1e6;
firstNs = stamped ? std::min(firstNs, batch.gpuStartNs) : batch.gpuStartNs;
lastNs = stamped ? std::max(lastNs, batch.gpuEndNs) : batch.gpuEndNs;
stamped = true;
}
if (batch.readGeneration == 0) continue;
for (const auto& [begin, end] : batch.reads) {
++checked;
GuestMemory::CollectWritesUncached(begin, end - begin);
if (!GuestMemory::UnchangedSince(begin, end - begin, batch.readGeneration)) ++overwritten;
}
}
const double gapMs = stamped ? (lastNs - firstNs) / 1e6 - busyMs : 0;
if (auto* frame = PerformanceContext::Current()) frame->NoteRetired(0, busyMs, gapMs);
presentCounters.gpuBusyMs += busyMs;
presentCounters.gpuGapMs += gapMs;
presentCounters.gpuUnread += missing;
presentCounters.readsChecked += checked;
presentCounters.readsOverwritten += overwritten;
}
}
void WriteFrameDump(const PresentSlot& slot) {
require(slot.dumpBuffer != nullptr, "frame dump was not recorded");
std::vector<std::byte> full(slot.dumpBuffer->Bytes().begin(), slot.dumpBuffer->Bytes().end());
const auto index = slot.dumpIndex;
const auto width = slot.dumpWidth;
const auto height = slot.dumpHeight;
static const auto start = std::chrono::steady_clock::now();
std::fprintf(stderr, "[gpu] frame_%03d.bmp: %ux%u display read back on the GPU at %.1f s\n", index, width, height, std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());
dumpWriter.Enqueue(index, width, height, slot.dumpScale, std::move(full));
}
// Blocks on the fence, or polls it every 50 us with APS5_PRESENT_POLL_FENCE=1 (the difference
// in the wait is the presenter's wake-up latency).
void WaitPresentFence(VkFence fence) {
static const bool poll = std::getenv("APS5_PRESENT_POLL_FENCE") != nullptr;
if (!poll) {
check(DeviceFunction<PFN_vkWaitForFences>("vkWaitForFences")(device, 1, &fence, VK_TRUE, std::numeric_limits<std::uint64_t>::max()), "vkWaitForFences present");
return;
}
const auto status = DeviceFunction<PFN_vkGetFenceStatus>("vkGetFenceStatus");
for (;;) {
const auto result = status(device, fence);
if (result == VK_SUCCESS) return;
if (result != VK_NOT_READY) check(result, "vkGetFenceStatus present");
const auto until = std::chrono::steady_clock::now() + std::chrono::microseconds(50);
while (std::chrono::steady_clock::now() < until) std::this_thread::yield();
}
}
~State() {
contextReady = false;
if (device != VK_NULL_HANDLE) {
const auto idle = reinterpret_cast<PFN_vkDeviceWaitIdle>(deviceProc(device, "vkDeviceWaitIdle"))(device);
if (idle != VK_SUCCESS && idle != VK_ERROR_DEVICE_LOST) std::terminate();
// Resident images kept for unfinished presentations go before the caches they came from.
{
std::lock_guard lock(presentMutex);
for (auto& slot : presentSlots) {
if (slot.inFlight) RetireSlot(slot);
}
if (recorder) SettleRetired(true);
}
for (auto& slot : presentSlots) {
slot.dumpBuffer.reset();
slot.dumpScaler.reset();
}
// Results still in the unit shadows reach guest memory before the device goes; the
// slabs (kept by the publishing batch) are freed by the recorder's teardown.
if (recorder) {
try {
Graphics::PublishAllShadows(context, Graphics::PublishReason::Teardown);
recorder->Sync();
} catch (const std::exception& error) {
std::fprintf(stderr, "[gpu] unit shadow teardown: %s\n", error.what());
}
}
Graphics::DestroyShadows(device);
recorder.reset();
// Cached graphics pipelines (with their framebuffers, modules, render passes and layouts)
// belong to this device and must be destroyed while it lives.
Graphics::ClearCachedPipelines(device);
Graphics::ClearDepthSurfaces(device);
{
std::lock_guard pipelines(computePipelinesMutex);
computePipelines.clear();
}
// Every ShaderResources (kept by the recorder or the resource cache) is gone now, so the
// sets and samplers they borrowed can go.
copiedWriters->clear();
resourceCache.Clear();
Graphics::ClearCachedTextures(device);
Graphics::ClearImageMirrors(device);
Graphics::ClearHostImports(device);
patternBuffers.clear();
descriptorCache.reset();
emptyBuffer.reset();
samplerCache.reset();
textureCache.reset();
detiler.reset();
colorTransfer.reset();
scaler.reset();
pipelineCache.reset();
context.bufferPool.reset();
bufferPool.reset();
const auto destroyFence = reinterpret_cast<PFN_vkDestroyFence>(deviceProc(device, "vkDestroyFence"));
if (acquireFence) destroyFence(device, acquireFence, nullptr);
const auto destroyQueryPool = reinterpret_cast<PFN_vkDestroyQueryPool>(deviceProc(device, "vkDestroyQueryPool"));
for (const auto& slot : presentSlots) {
if (slot.fence) destroyFence(device, slot.fence, nullptr);
if (slot.queries) destroyQueryPool(device, slot.queries, nullptr);
}
const auto destroySemaphore = reinterpret_cast<PFN_vkDestroySemaphore>(deviceProc(device, "vkDestroySemaphore"));
for (auto semaphore : rendered) {
if (semaphore) destroySemaphore(device, semaphore, nullptr);
}
DestroyRetiredSwapchains();
if (uploadMapping) reinterpret_cast<PFN_vkUnmapMemory>(deviceProc(device, "vkUnmapMemory"))(device, uploadMemory);
if (uploadBuffer) reinterpret_cast<PFN_vkDestroyBuffer>(deviceProc(device, "vkDestroyBuffer"))(device, uploadBuffer, nullptr);
if (uploadMemory) reinterpret_cast<PFN_vkFreeMemory>(deviceProc(device, "vkFreeMemory"))(device, uploadMemory, nullptr);
if (swapchain) reinterpret_cast<PFN_vkDestroySwapchainKHR>(deviceProc(device, "vkDestroySwapchainKHR"))(device, swapchain, nullptr);
const auto destroyPool = reinterpret_cast<PFN_vkDestroyCommandPool>(deviceProc(device, "vkDestroyCommandPool"));
const auto destroyDevice = reinterpret_cast<PFN_vkDestroyDevice>(deviceProc(device, "vkDestroyDevice"));
if (pool != VK_NULL_HANDLE) {
destroyPool(device, pool, nullptr);
}
destroyDevice(device, nullptr);
}
if (instance != VK_NULL_HANDLE) {
if (surface) reinterpret_cast<PFN_vkDestroySurfaceKHR>(instanceProc(instance, "vkDestroySurfaceKHR"))(instance, surface, nullptr);
reinterpret_cast<PFN_vkDestroyInstance>(instanceProc(instance, "vkDestroyInstance"))(instance, nullptr);
}
if (library != nullptr) {
SDL_UnloadObject(library);
}
}
};
VulkanDevice::VulkanDevice(const PresentationWindow* window) : state(std::make_unique<State>()), serial([] { static std::atomic<std::uint64_t> serials{0}; return serials.fetch_add(1, std::memory_order_relaxed) + 1; }()) {
APS5_LOG_OUT("VulkanDevice constructor window=%p", static_cast<const void*>(window));
#ifdef _WIN32
state->library = SDL_LoadObject("vulkan-1.dll");
#else
state->library = SDL_LoadObject("libvulkan.so.1");
#endif
if (state->library == nullptr) {
throw std::runtime_error(std::string("Vulkan loader: ") + SDL_GetError());
}
APS5_LOG_OUT("Vulkan loader loaded library=%p", state->library);
state->instanceProc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(SDL_LoadFunction(state->library, "vkGetInstanceProcAddr"));
if (state->instanceProc == nullptr) {
throw std::runtime_error("Vulkan loader: vkGetInstanceProcAddr missing");
}
AgcDriverLockVulkanLoader_nid_postfix();
struct LoaderUnlock {
~LoaderUnlock() { AgcDriverUnlockVulkanLoader_nid_postfix(); }
} loaderUnlock;
VkApplicationInfo application{VK_STRUCTURE_TYPE_APPLICATION_INFO};
application.pApplicationName = "AnyPS5 libSceAgcDriver";
application.apiVersion = VK_API_VERSION_1_1;
VkInstanceCreateInfo create{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
create.pApplicationInfo = &application;
std::vector<const char*> instanceExtensions;
if (window != nullptr) {
APS5_LOG_OUT("Presentation window context=%p extent=%ux%u extensions=%zu", window->context, window->width, window->height, window->extensions.size());
require(window->context && window->createSurface && window->getDrawableSize && window->width && window->height, "invalid window descriptor");
instanceExtensions.assign(window->extensions.begin(), window->extensions.end());
std::uint32_t availableCount = 0;
const auto enumerateExtensions = state->InstanceFunction<PFN_vkEnumerateInstanceExtensionProperties>("vkEnumerateInstanceExtensionProperties");
check(enumerateExtensions(nullptr, &availableCount, nullptr), "vkEnumerateInstanceExtensionProperties");
std::vector<VkExtensionProperties> available(availableCount);
check(enumerateExtensions(nullptr, &availableCount, available.data()), "vkEnumerateInstanceExtensionProperties");
for (const auto* name : instanceExtensions) {
require(name != nullptr, "null instance extension");
if (std::none_of(available.begin(), available.end(), [&](const auto& item) { return std::strcmp(item.extensionName, name) == 0; })) {
throw std::runtime_error(std::string("Vulkan presentation: required instance extension missing: ") + name);
}
}
create.enabledExtensionCount = static_cast<std::uint32_t>(instanceExtensions.size());
create.ppEnabledExtensionNames = instanceExtensions.data();
}
check(state->InstanceFunction<PFN_vkCreateInstance>("vkCreateInstance")(&create, nullptr, &state->instance), "vkCreateInstance");
APS5_LOG_OUT("Vulkan instance created instance=%p", reinterpret_cast<void*>(state->instance));
if (window != nullptr) {
state->surface = window->createSurface(window->context, state->instance);
require(state->surface != VK_NULL_HANDLE, "window returned a null surface");
state->window = window->context;
APS5_LOG_OUT("Vulkan surface created surface=%p window=%p", reinterpret_cast<void*>(state->surface), state->window);
}
state->deviceProc = state->InstanceFunction<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
const auto enumerate = state->InstanceFunction<PFN_vkEnumeratePhysicalDevices>("vkEnumeratePhysicalDevices");
std::uint32_t count = 0;
check(enumerate(state->instance, &count, nullptr), "vkEnumeratePhysicalDevices");
APS5_LOG_OUT("Physical device count=%u", count);
std::vector<VkPhysicalDevice> devices(count);
check(enumerate(state->instance, &count, devices.data()), "vkEnumeratePhysicalDevices");
devices.resize(count);
VkPhysicalDevice selected = VK_NULL_HANDLE;
std::uint32_t family = 0;
int selectedRank = -1;
const char* requestedName = std::getenv("ANYPS5_GPU");
if (requestedName != nullptr && *requestedName == '\0') requestedName = nullptr;
const auto matchesRequest = [&](const char* deviceName) {
const std::string_view name(deviceName);
const std::string_view request(requestedName);
if (request.size() > name.size()) return false;
for (std::size_t start = 0; start + request.size() <= name.size(); ++start) {
std::size_t index = 0;
while (index < request.size() && std::tolower(static_cast<unsigned char>(name[start + index])) == std::tolower(static_cast<unsigned char>(request[index]))) ++index;
if (index == request.size()) return true;
}
return false;
};
std::string candidateNames;
const auto rankDeviceType = [](VkPhysicalDeviceType type) {
switch (type) {
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return 3;
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return 2;
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return 1;
default: return 0;
}
};
const std::array<const char*, 1> presentationExtensions{VK_KHR_SWAPCHAIN_EXTENSION_NAME};
for (auto physical : devices) {
VkPhysicalDeviceProperties properties{};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties>("vkGetPhysicalDeviceProperties")(physical, &properties);
APS5_LOG_OUT("Physical device candidate=%p name=%s api=0x%x type=%d", reinterpret_cast<void*>(physical), properties.deviceName, properties.apiVersion, static_cast<int>(properties.deviceType));
if (!candidateNames.empty()) candidateNames += ", ";
candidateNames += properties.deviceName;
if (properties.apiVersion < VK_API_VERSION_1_1) {
continue;
}
if (requestedName != nullptr && !matchesRequest(properties.deviceName)) continue;
const int rank = requestedName != nullptr ? 4 : rankDeviceType(properties.deviceType);
if (rank <= selectedRank) {
continue;
}
if (window != nullptr) {
std::uint32_t extensionCount = 0;
auto enumerateExtensions = state->InstanceFunction<PFN_vkEnumerateDeviceExtensionProperties>("vkEnumerateDeviceExtensionProperties");
check(enumerateExtensions(physical, nullptr, &extensionCount, nullptr), "vkEnumerateDeviceExtensionProperties");
std::vector<VkExtensionProperties> extensions(extensionCount);
check(enumerateExtensions(physical, nullptr, &extensionCount, extensions.data()), "vkEnumerateDeviceExtensionProperties");
const bool supported = std::all_of(presentationExtensions.begin(), presentationExtensions.end(), [&](const char* name) {
return std::any_of(extensions.begin(), extensions.end(), [&](const auto& item) { return std::strcmp(item.extensionName, name) == 0; });
});
if (!supported) continue;
}
std::uint32_t families = 0;
auto getFamilies = state->InstanceFunction<PFN_vkGetPhysicalDeviceQueueFamilyProperties>("vkGetPhysicalDeviceQueueFamilyProperties");
getFamilies(physical, &families, nullptr);
std::vector<VkQueueFamilyProperties> queues(families);
getFamilies(physical, &families, queues.data());
for (std::uint32_t i = 0; i < families; ++i) {
if (queues[i].queueCount != 0 && (queues[i].queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) == (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) {
if (window != nullptr) {
VkBool32 supported = VK_FALSE;
check(state->InstanceFunction<PFN_vkGetPhysicalDeviceSurfaceSupportKHR>("vkGetPhysicalDeviceSurfaceSupportKHR")(physical, i, state->surface, &supported), "vkGetPhysicalDeviceSurfaceSupportKHR");
if (!supported) continue;
}
selected = physical;
family = i;
selectedRank = rank;
break;
}
}
}
if (selected == VK_NULL_HANDLE && requestedName != nullptr) {
throw std::runtime_error(std::string("Vulkan: no usable device whose name contains ANYPS5_GPU=\"") + requestedName + "\"; devices: " + candidateNames);
}
if (selected == VK_NULL_HANDLE) {
throw std::runtime_error(window ? "Vulkan: no Vulkan 1.1 device with graphics, compute and swapchain presentation" : "Vulkan: no Vulkan 1.1 graphics and compute queue");
}
APS5_LOG_OUT("Physical device selected physical=%p queueFamily=%u", reinterpret_cast<void*>(selected), family);
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
properties.pNext = &state->subgroup;
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &properties);
state->properties = properties.properties;
state->physical = selected;
state->srgbDecodeFormats = Graphics::SrgbDecodeFormats(state->InstanceFunction<PFN_vkGetPhysicalDeviceFormatProperties>("vkGetPhysicalDeviceFormatProperties"), selected);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) != 0) {
state->capabilities.push_back(spv::CapabilityGroupNonUniform);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformBallot);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformShuffle);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformArithmetic);
}
APS5_LOG_OUT("Selected GPU name=%s vendor=0x%x device=0x%x subgroup=%u", state->properties.deviceName, state->properties.vendorID, state->properties.deviceID, state->subgroup.subgroupSize);
state->InstanceFunction<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(selected, &state->memoryProperties);
for (std::uint32_t i = 0; i < state->memoryProperties.memoryHeapCount; ++i) APS5_LOG_OUT("Memory heap %u size=%.1f MiB flags=0x%x", i, state->memoryProperties.memoryHeaps[i].size / 1048576.0, state->memoryProperties.memoryHeaps[i].flags);
for (std::uint32_t i = 0; i < state->memoryProperties.memoryTypeCount; ++i) APS5_LOG_OUT("Memory type %u heap=%u flags=0x%x", i, state->memoryProperties.memoryTypes[i].heapIndex, state->memoryProperties.memoryTypes[i].propertyFlags);
std::uint32_t extensionCount = 0;
const auto enumerateDeviceExtensions = state->InstanceFunction<PFN_vkEnumerateDeviceExtensionProperties>("vkEnumerateDeviceExtensionProperties");
check(enumerateDeviceExtensions(selected, nullptr, &extensionCount, nullptr), "vkEnumerateDeviceExtensionProperties");
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
check(enumerateDeviceExtensions(selected, nullptr, &extensionCount, availableExtensions.data()), "vkEnumerateDeviceExtensionProperties");
const auto hasExtension = [&](const char* name) { return std::any_of(availableExtensions.begin(), availableExtensions.end(), [&](const auto& item) { return std::strcmp(item.extensionName, name) == 0; }); };
auto byteFeatures = QueryBdaByteFeatures(selected, state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2"), availableExtensions);
auto bdaFeatures = QueryBdaFeatures(selected, state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2"), availableExtensions);
require(hasExtension(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME), "VK_KHR_shader_float_controls is unavailable");
VkPhysicalDeviceFloatControlsProperties floatControls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES};
VkPhysicalDeviceProperties2 floatProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &floatControls};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &floatProperties);
require(floatControls.shaderSignedZeroInfNanPreserveFloat32 == VK_TRUE, "shaderSignedZeroInfNanPreserveFloat32 is unavailable");
const std::array<const char*, 2> meshExtensions{VK_EXT_MESH_SHADER_EXTENSION_NAME, VK_KHR_SPIRV_1_4_EXTENSION_NAME};
const bool meshAvailable = std::all_of(meshExtensions.begin(), meshExtensions.end(), hasExtension);
VkPhysicalDeviceMeshShaderFeaturesEXT meshFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
if (meshAvailable) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &meshFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->meshShader = meshFeatures.meshShader == VK_TRUE;
VkPhysicalDeviceProperties2 meshProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &state->meshLimits};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &meshProperties);
}
meshFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
meshFeatures.meshShader = state->meshShader;
VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentricFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
if (hasExtension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &barycentricFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->fragmentShaderBarycentric = barycentricFeatures.fragmentShaderBarycentric == VK_TRUE;
}
VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT interlockFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
if (hasExtension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &interlockFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->fragmentShaderPixelInterlock = interlockFeatures.fragmentShaderPixelInterlock == VK_TRUE;
}
interlockFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
interlockFeatures.fragmentShaderPixelInterlock = VK_TRUE;
VkPhysicalDeviceShaderClockFeaturesKHR clockFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
if (hasExtension(VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &clockFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->shaderClock = clockFeatures.shaderSubgroupClock == VK_TRUE && clockFeatures.shaderDeviceClock == VK_TRUE;
}
if (state->shaderClock && hasExtension(VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME)) {
VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceProperties2 driverProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &driverProperties);
state->narrowSubgroupClock = NarrowSubgroupClock(driver.driverID, state->properties.deviceName);
APS5_LOG_OUT("Shader clock driver=%d narrowSubgroupClock=%d", static_cast<int>(driver.driverID), state->narrowSubgroupClock ? 1 : 0);
}
std::vector<const char*> deviceExtensions;
if (window != nullptr) deviceExtensions.assign(presentationExtensions.begin(), presentationExtensions.end());
if (state->fragmentShaderBarycentric) {
deviceExtensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilityFragmentBarycentricKHR);
state->spirvExtensions.push_back("SPV_KHR_fragment_shader_barycentric");
}
if (state->fragmentShaderPixelInterlock) {
deviceExtensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilityFragmentShaderPixelInterlockEXT);
state->spirvExtensions.push_back("SPV_EXT_fragment_shader_interlock");
}
if (state->shaderClock) {
deviceExtensions.push_back(VK_KHR_SHADER_CLOCK_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilityShaderClockKHR);
state->spirvExtensions.push_back("SPV_KHR_shader_clock");
}
VkPhysicalDeviceShaderAtomicInt64FeaturesKHR atomicInt64Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR};
if (hasExtension(VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &atomicInt64Features};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
}
const bool bufferInt64Atomics = atomicInt64Features.shaderBufferInt64Atomics == VK_TRUE;
if (bufferInt64Atomics) state->capabilities.push_back(spv::CapabilityInt64Atomics);
atomicInt64Features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR};
atomicInt64Features.shaderBufferInt64Atomics = VK_TRUE;
if (bufferInt64Atomics) deviceExtensions.push_back(VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME);
VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT imageAtomicInt64Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT};
if (hasExtension(VK_EXT_SHADER_IMAGE_ATOMIC_INT64_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &imageAtomicInt64Features};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
}
const bool imageInt64Atomics = imageAtomicInt64Features.shaderImageInt64Atomics == VK_TRUE;
imageAtomicInt64Features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT};
imageAtomicInt64Features.shaderImageInt64Atomics = VK_TRUE;
if (imageInt64Atomics) {
deviceExtensions.push_back(VK_EXT_SHADER_IMAGE_ATOMIC_INT64_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilityInt64ImageEXT);
state->imageInt64Atomics = true;
state->spirvExtensions.push_back("SPV_EXT_shader_image_int64");
}
deviceExtensions.push_back(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilitySignedZeroInfNanPreserve);
state->spirvExtensions.push_back("SPV_KHR_float_controls");
deviceExtensions.push_back(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
deviceExtensions.push_back(VK_KHR_8BIT_STORAGE_EXTENSION_NAME);
state->capabilities.push_back(4448);
state->spirvExtensions.push_back("SPV_KHR_8bit_storage");
state->capabilities.push_back(11);
state->capabilities.push_back(5347);
state->spirvExtensions.push_back("SPV_KHR_physical_storage_buffer");
state->depthRangeUnrestricted = hasExtension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
if (state->depthRangeUnrestricted) deviceExtensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
// Guest dispatches cover whole thread groups past the edge of small images; robust image access
// drops those writes instead of faulting the device.
const bool imageRobustness = hasExtension(VK_EXT_IMAGE_ROBUSTNESS_EXTENSION_NAME);
if (imageRobustness) deviceExtensions.push_back(VK_EXT_IMAGE_ROBUSTNESS_EXTENSION_NAME);
if (hasExtension(VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME)) {
VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT minmaxProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT};
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &minmaxProperties};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &properties);
state->samplerFilterMinmax = minmaxProperties.filterMinmaxSingleComponentFormats == VK_TRUE && minmaxProperties.filterMinmaxImageComponentMapping == VK_TRUE;
if (state->samplerFilterMinmax) deviceExtensions.push_back(VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME);
}
if (hasExtension(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME)) {
VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservativeProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT};
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &conservativeProperties};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &properties);
state->conservativeRasterization = conservativeProperties.primitiveOverestimationSize <= 1.0f / 256.0f && conservativeProperties.degenerateTrianglesRasterized == VK_TRUE;
if (state->conservativeRasterization) deviceExtensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME);
}
// Indirect draws with a GPU-side count (DRAW_INDIRECT_MULTI with count_indirect); a device
// without it resolves such draws on the CPU.
state->drawIndirectCount = hasExtension(VK_KHR_DRAW_INDIRECT_COUNT_EXTENSION_NAME);
if (state->drawIndirectCount) deviceExtensions.push_back(VK_KHR_DRAW_INDIRECT_COUNT_EXTENSION_NAME);
// Guest memory is host memory: importing it lets address-based shaders use it in place instead of
// copying every registered allocation per draw.
if (hasExtension(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) && std::getenv("APS5_NO_HOST_IMPORT") == nullptr) {
VkPhysicalDeviceDriverProperties driverProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceExternalMemoryHostPropertiesEXT hostProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT, &driverProperties};
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &hostProperties};
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &properties);
state->hostImportAlignment = hostProperties.minImportedHostPointerAlignment;
#ifdef _WIN32
// Imported pages are locked; locking is bounded by the process working-set minimum.
if (const char* value = std::getenv("APS5_WORKING_SET_MIB")) {
const SIZE_T bytes = static_cast<SIZE_T>(std::strtoull(value, nullptr, 10)) << 20u;
if (!SetProcessWorkingSetSizeEx(GetCurrentProcess(), bytes, bytes * 2, QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE)) std::fprintf(stderr, "[gpu] SetProcessWorkingSetSizeEx failed: %lu\n", GetLastError());
}
#endif
deviceExtensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME);
#ifndef _WIN32
state->dmaBufImport = driverProperties.driverID != VK_DRIVER_ID_NVIDIA_PROPRIETARY && hasExtension(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME) && hasExtension(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME);
if (state->dmaBufImport) {
deviceExtensions.push_back(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME);
deviceExtensions.push_back(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME);
}
#endif
}
VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT listRestartFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVE_TOPOLOGY_LIST_RESTART_FEATURES_EXT};
if (hasExtension(VK_EXT_PRIMITIVE_TOPOLOGY_LIST_RESTART_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &listRestartFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->primitiveListRestart = listRestartFeatures.primitiveTopologyListRestart == VK_TRUE;
if (state->primitiveListRestart) deviceExtensions.push_back(VK_EXT_PRIMITIVE_TOPOLOGY_LIST_RESTART_EXTENSION_NAME);
}
listRestartFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVE_TOPOLOGY_LIST_RESTART_FEATURES_EXT};
listRestartFeatures.primitiveTopologyListRestart = state->primitiveListRestart ? VK_TRUE : VK_FALSE;
VkPhysicalDeviceImageViewMinLodFeaturesEXT minLodFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT};
if (hasExtension(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &minLodFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->imageViewMinLod = minLodFeatures.minLod == VK_TRUE;
if (state->imageViewMinLod) deviceExtensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
}
minLodFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT};
minLodFeatures.minLod = VK_TRUE;
VkPhysicalDeviceMaintenance8FeaturesKHR maintenance8Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR};
if (hasExtension(VK_KHR_MAINTENANCE_8_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance8Features};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->maintenance8 = maintenance8Features.maintenance8 == VK_TRUE;
if (state->maintenance8) deviceExtensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
}
maintenance8Features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR};
maintenance8Features.maintenance8 = VK_TRUE;
VkPhysicalDeviceDepthClipControlFeaturesEXT depthClipFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_CONTROL_FEATURES_EXT};
if (hasExtension(VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &depthClipFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->depthClipControl = depthClipFeatures.depthClipControl == VK_TRUE;
if (state->depthClipControl) deviceExtensions.push_back(VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME);
}
if (state->meshShader) {
deviceExtensions.insert(deviceExtensions.end(), meshExtensions.begin(), meshExtensions.end());
state->capabilities.push_back(5283);
state->spirvExtensions.push_back("SPV_EXT_mesh_shader");
}
const float priority = 1.0f;
VkDeviceQueueCreateInfo queueInfo{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
queueInfo.queueFamilyIndex = family;
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = &priority;
VkDeviceCreateInfo deviceInfo{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
deviceInfo.queueCreateInfoCount = 1;
deviceInfo.pQueueCreateInfos = &queueInfo;
VkPhysicalDeviceFeatures available{};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures>("vkGetPhysicalDeviceFeatures")(selected, &available);
require(available.vertexPipelineStoresAndAtomics && available.fragmentStoresAndAtomics, "graphics shader buffer writes and atomics are unavailable");
VkPhysicalDeviceFeatures enabled{};
enabled.shaderInt64 = VK_TRUE;
enabled.shaderFloat64 = available.shaderFloat64 && floatControls.shaderSignedZeroInfNanPreserveFloat64;
if (enabled.shaderFloat64) state->capabilities.push_back(spv::CapabilityFloat64);
enabled.vertexPipelineStoresAndAtomics = VK_TRUE;
enabled.fragmentStoresAndAtomics = VK_TRUE;
enabled.tessellationShader = available.tessellationShader;
state->tessellationShader = enabled.tessellationShader == VK_TRUE;
if (state->tessellationShader) state->capabilities.push_back(3);
APS5_LOG_OUT("Vulkan features tessellationAvailable=%u mesh=%u depthClip=%u depthRangeUnrestricted=%u", static_cast<unsigned>(state->tessellationShader), static_cast<unsigned>(state->meshShader), static_cast<unsigned>(state->depthClipControl), static_cast<unsigned>(state->depthRangeUnrestricted));
require(available.samplerAnisotropy && available.textureCompressionBC, "device lacks sampler anisotropy or BC texture compression support required for texture sampling");
enabled.samplerAnisotropy = VK_TRUE;
enabled.textureCompressionBC = VK_TRUE;
// Guest shaders routinely read past descriptor ranges; robust access turns that into zeros
// instead of a GPU fault that loses the device.
enabled.robustBufferAccess = available.robustBufferAccess;
// Indirect draw records with a non-zero first instance, and several records per call.
enabled.drawIndirectFirstInstance = available.drawIndirectFirstInstance;
enabled.multiDrawIndirect = available.multiDrawIndirect;
state->drawIndirectFirstInstance = enabled.drawIndirectFirstInstance == VK_TRUE;
state->multiDrawIndirect = enabled.multiDrawIndirect == VK_TRUE;
// PA_CL_CLIP_CNTL near/far clip disable maps to depth clamping.
enabled.depthClamp = available.depthClamp;
state->depthClamp = enabled.depthClamp == VK_TRUE;
enabled.depthBounds = available.depthBounds;
state->depthBounds = enabled.depthBounds == VK_TRUE;
enabled.depthBiasClamp = available.depthBiasClamp;
state->depthBiasClamp = enabled.depthBiasClamp == VK_TRUE;
enabled.occlusionQueryPrecise = available.occlusionQueryPrecise;
state->occlusionQueryPrecise = enabled.occlusionQueryPrecise == VK_TRUE;
// Recompiled storage-image access declares no format (the guest descriptor decides it).
enabled.shaderStorageImageMultisample = available.shaderStorageImageMultisample;
if (enabled.shaderStorageImageMultisample) state->capabilities.push_back(spv::CapabilityStorageImageMultisample);
state->capabilities.push_back(spv::CapabilityImageMSArray);
enabled.shaderStorageImageWriteWithoutFormat = available.shaderStorageImageWriteWithoutFormat;
enabled.shaderStorageImageReadWithoutFormat = available.shaderStorageImageReadWithoutFormat;
// Gathers with non-constant offsets (ImageGatherExtended).
enabled.shaderImageGatherExtended = available.shaderImageGatherExtended;
if (enabled.shaderImageGatherExtended) state->capabilities.push_back(spv::CapabilityImageGatherExtended);
enabled.shaderResourceMinLod = available.shaderResourceMinLod;
if (enabled.shaderResourceMinLod) state->capabilities.push_back(spv::CapabilityMinLod);
enabled.sampleRateShading = available.sampleRateShading;
enabled.geometryShader = available.geometryShader;
state->geometryShader = enabled.geometryShader == VK_TRUE;
state->sampleRateShading = enabled.sampleRateShading == VK_TRUE;
if (enabled.geometryShader) state->capabilities.push_back(spv::CapabilityGeometry);
enabled.shaderClipDistance = available.shaderClipDistance;
if (enabled.shaderStorageImageWriteWithoutFormat) state->capabilities.push_back(spv::CapabilityStorageImageWriteWithoutFormat);
if (enabled.shaderStorageImageReadWithoutFormat) state->capabilities.push_back(spv::CapabilityStorageImageReadWithoutFormat);
// Bindless image tables index an image array with a wave-uniform runtime slot.
enabled.shaderSampledImageArrayDynamicIndexing = available.shaderSampledImageArrayDynamicIndexing;
enabled.shaderStorageImageArrayDynamicIndexing = available.shaderStorageImageArrayDynamicIndexing;
if (enabled.shaderSampledImageArrayDynamicIndexing) state->capabilities.push_back(spv::CapabilitySampledImageArrayDynamicIndexing);
if (enabled.shaderStorageImageArrayDynamicIndexing) state->capabilities.push_back(spv::CapabilityStorageImageArrayDynamicIndexing);
VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptorIndexingFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT};
if (hasExtension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &descriptorIndexingFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->descriptorIndexing = descriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing == VK_TRUE && descriptorIndexingFeatures.shaderStorageImageArrayNonUniformIndexing == VK_TRUE;
}
descriptorIndexingFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT};
if (state->descriptorIndexing) {
descriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;
descriptorIndexingFeatures.shaderStorageImageArrayNonUniformIndexing = VK_TRUE;
deviceExtensions.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilityShaderNonUniform);
state->capabilities.push_back(spv::CapabilitySampledImageArrayNonUniformIndexing);
state->capabilities.push_back(spv::CapabilityStorageImageArrayNonUniformIndexing);