-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vulkan.d
1563 lines (1353 loc) · 55.4 KB
/
vulkan.d
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
/// Authors: Chance Snow
/// Copyright: Copyright © 2020 Chance Snow. All rights reserved.
/// License: 3-Clause BSD License
module teraflop.vulkan;
import bindbc.glfw : GLFWwindow;
import erupted;
import erupted.vulkan_lib_loader;
import std.algorithm.iteration : map;
import std.algorithm.searching : any;
import std.array : array;
import std.conv : to;
import std.exception : enforce;
import std.string : toStringz;
import teraflop.components : IResource;
import teraflop.platform.window : Window;
import teraflop.math : Size;
// https://www.glfw.org/docs/3.3/vulkan_guide.html#vulkan_present
alias GLFWvkproc = void function();
extern(C) @nogc nothrow {
private const(char)** glfwGetRequiredInstanceExtensions(uint*);
private GLFWvkproc glfwGetInstanceProcAddress(VkInstance, const(char)*);
private int glfwGetPhysicalDevicePresentationSupport(VkInstance,VkPhysicalDevice, uint);
package (teraflop) VkResult glfwCreateWindowSurface(
VkInstance, GLFWwindow*, const(VkAllocationCallbacks)*, VkSurfaceKHR*
);
}
package (teraflop) void enforceVk(VkResult res) {
enforce(res == VkResult.VK_SUCCESS, res.to!string);
}
package (teraflop) bool initVulkan() {
return loadGlobalLevelFunctions();
}
// https://vulkan.lunarg.com/doc/view/1.1.114.0/windows/khronos_validation_layer.html
// VK_LAYER_KHRONOS_validation
private string[] validationLayers = [
"VK_LAYER_GOOGLE_threading",
"VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_core_validation",
"VK_LAYER_GOOGLE_unique_objects"
];
debug {
private enum bool enableValidationLayers = true;
} else {
private enum bool enableValidationLayers = false;
}
package (teraflop) bool checkValidationLayerSupport() {
import std.algorithm.iteration : filter;
import std.algorithm.searching : all;
import std.string : icmp, fromStringz;
import std.stdio : writefln;
import std.math : abs;
import std.range : enumerate;
uint layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, null);
VkLayerProperties[] availableLayers = new VkLayerProperties[layerCount];
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.ptr);
auto availableLayerNames = new string[layerCount];
foreach (i, layer; availableLayers.enumerate()) {
availableLayerNames[i] = fromStringz(layer.layerName.ptr).to!string;
}
if (availableLayerNames.any!(availableLayer => icmp(availableLayer, "VK_LAYER_KHRONOS_validation") == 0)) {
validationLayers = new string[1];
validationLayers[0] = "VK_LAYER_KHRONOS_validation";
}
return validationLayers.all!(layer => availableLayerNames.any!(availableLayer => icmp(availableLayer, layer) == 0));
}
private const string[] defaultDeviceExtensions = [VK_KHR_SWAPCHAIN_EXTENSION_NAME];
package (teraflop) final class Device {
private VkInstance instance_;
private VkDevice device = VK_NULL_HANDLE;
private const string[] deviceExtensions;
private VkPhysicalDevice physicalDevice_ = VK_NULL_HANDLE;
private uint graphicsQueueFamilyIndex = uint.max;
private VkCommandPool commandPool_;
private VkCommandBuffer[] commandBuffers;
private VkQueue presentQueue_;
this(string appName, const string[] deviceExtensions = defaultDeviceExtensions) {
this.deviceExtensions = deviceExtensions;
// Create instance
VkApplicationInfo appInfo = {
pApplicationName: toStringz(appName),
pEngineName: "Teraflop",
engineVersion: VK_MAKE_VERSION(0, 1, 0),
apiVersion: VK_MAKE_VERSION(1, 1, 0),
};
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
VkInstanceCreateInfo instanceCreateInfo = {
pApplicationInfo: &appInfo,
enabledLayerCount: 0,
enabledExtensionCount: glfwExtensionCount,
ppEnabledExtensionNames: glfwExtensions
};
if (enableValidationLayers) {
auto hasReqs = checkValidationLayerSupport();
enforce(hasReqs, "validation layers requested, but not available!");
instanceCreateInfo.enabledLayerCount = validationLayers.length.to!uint;
const layers = validationLayers.map!(layer => toStringz(layer)).array;
instanceCreateInfo.ppEnabledLayerNames = layers.ptr;
}
enforceVk(vkCreateInstance(&instanceCreateInfo, null, &instance_));
loadInstanceLevelFunctions(instance_);
}
~this() {
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
vkDestroyCommandPool(device, commandPool_, null);
vkDestroyDevice(device, null);
}
if (instance_ != VK_NULL_HANDLE) vkDestroyInstance(instance_, null);
}
bool ready() @property const {
return device != VK_NULL_HANDLE && physicalDevice_ != VK_NULL_HANDLE;
}
VkInstance instance() @property const {
return cast(VkInstance) instance_;
}
VkDevice handle() @property const {
return cast(VkDevice) device;
}
VkPhysicalDevice physicalDevice() @property const {
return cast(VkPhysicalDevice) physicalDevice_;
}
VkCommandPool commandPool() @property const {
return cast(VkCommandPool) commandPool_;
}
// TODO: Rename this to `graphicsQueue`?
VkQueue presentQueue() @property const {
return cast(VkQueue) presentQueue_;
}
void acquire() {
// Acquire graphics device
uint numPhysicalDevices;
enforceVk(vkEnumeratePhysicalDevices(instance_, &numPhysicalDevices, null));
assert(numPhysicalDevices > 0);
auto physicalDevices = new VkPhysicalDevice[](numPhysicalDevices);
enforceVk(vkEnumeratePhysicalDevices(instance_, &numPhysicalDevices, physicalDevices.ptr));
physicalDevice_ = physicalDevices[0];
// Pick the queue that supports presentation over GLFW
uint numQueues;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevices[0], &numQueues, null);
assert(numQueues >= 1);
auto queueFamilyProperties = new VkQueueFamilyProperties[numQueues];
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevices[0], &numQueues, queueFamilyProperties.ptr);
for (auto i = 0; i < numQueues; i += 1) {
// Presumably, this checks for VK_QUEUE_GRAPHICS_BIT
if (glfwGetPhysicalDevicePresentationSupport(instance_, physicalDevices[0], i)) {
assert(queueFamilyProperties[i].queueCount >= 1);
graphicsQueueFamilyIndex = i.to!uint;
}
}
// Use first queue if no graphics queue was found
// TODO: Is this correct?
if (graphicsQueueFamilyIndex == uint.max) graphicsQueueFamilyIndex = 0;
// Create the logical device
const float[1] queuePriorities = [ 1.0f ];
VkDeviceQueueCreateInfo queueCreateInfo = {
queueFamilyIndex: graphicsQueueFamilyIndex,
queueCount: 1,
pQueuePriorities: queuePriorities.ptr,
};
VkPhysicalDeviceFeatures deviceFeatures = {
samplerAnisotropy: VK_TRUE,
};
const enabledExtensions = deviceExtensions.map!(name => toStringz(name)).array;
VkDeviceCreateInfo deviceCreateInfo = {
queueCreateInfoCount: 1,
pQueueCreateInfos: &queueCreateInfo,
pEnabledFeatures: &deviceFeatures,
enabledExtensionCount: deviceExtensions.length.to!uint,
ppEnabledExtensionNames: enabledExtensions.ptr,
};
enforceVk(vkCreateDevice(physicalDevices[0], &deviceCreateInfo, null, &device));
loadDeviceLevelFunctions(device);
// Create the command buffer pool
VkCommandPoolCreateInfo poolInfo = {
queueFamilyIndex: graphicsQueueFamilyIndex,
flags: VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // Graphics command buffers may be reset
// TODO: In a separate _transient_ command pool, set the VK_COMMAND_POOL_CREATE_TRANSIENT_BIT
};
enforceVk(vkCreateCommandPool(device, &poolInfo, null, &commandPool_));
// Get the command buffer queue
vkGetDeviceQueue(device, graphicsQueueFamilyIndex, 0, &presentQueue_);
}
SwapChain createSwapChain(const Surface surface, const Size framebufferSize, const SwapChain oldSwapChain = null) {
import teraflop.graphics : Color;
VkBool32 supported = VK_FALSE;
enforceVk(vkGetPhysicalDeviceSurfaceSupportKHR(
physicalDevice_, graphicsQueueFamilyIndex, surface.surfaceKhr, &supported
));
enforce(supported == VK_TRUE, "Surface is not supported for presentation");
auto swapChain = new SwapChain(this, surface, framebufferSize, oldSwapChain);
// Setup default command buffer
auto commands = createCommandBuffer(swapChain);
auto clearColor = Color.black.toVulkan;
commands.beginRenderPass(&clearColor);
commands.endRenderPass();
return swapChain;
}
Buffer createBuffer(ulong size, BufferUsage usage = BufferUsage.vertexBuffer) const {
return new Buffer(this, size, usage);
}
CommandBuffer createCommandBuffer(SwapChain swapChain) {
return swapChain.presentationCommands = new CommandBuffer(
this, swapChain.framebuffers, swapChain.extent, swapChain.presentationPass
);
}
CommandBuffer createSingleTimeCommandBuffer() inout {
return new CommandBuffer(this);
}
}
package (teraflop) class Surface {
private VkInstance instance;
private VkSurfaceKHR surface_;
this(VkInstance instance, VkSurfaceKHR surface) {
this.instance = instance;
this.surface_ = surface;
}
~this() {
vkDestroySurfaceKHR(instance, surface_, null);
}
static Surface fromGlfw(VkInstance instance, GLFWwindow* window) {
VkSurfaceKHR surface;
enforceVk(glfwCreateWindowSurface(instance, window, null, &surface));
return new Surface(instance, surface);
}
VkSurfaceKHR surfaceKhr() @property const {
return cast(VkSurfaceKHR) surface_;
}
}
// https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_KHR_swapchain.html
package (teraflop) final class SwapChain {
import std.algorithm.iteration : filter, joiner, map;
import std.array : array;
import teraflop.graphics : Material;
const int MAX_FRAMES_IN_FLIGHT = 2;
private Device device;
private const VkSurfaceFormatKHR surfaceFormat = {
format: VK_FORMAT_B8G8R8A8_SRGB,
colorSpace: VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
};
private VkPresentModeKHR presentMode;
package VkExtent2D extent;
private VkSwapchainKHR handle;
private VkImage[] swapChainImages;
private VkImageView[] imageViews;
private Image depthStencilImage;
package (teraflop) RenderPass presentationPass_;
private VkFramebuffer[] framebuffers;
package CommandBuffer presentationCommands;
private VkSemaphore[MAX_FRAMES_IN_FLIGHT] imageAvailableSemaphores;
private VkSemaphore[MAX_FRAMES_IN_FLIGHT] renderFinishedSemaphores;
private VkFence[MAX_FRAMES_IN_FLIGHT] inFlightFences;
private VkFence[] imagesInFlight;
private VkDescriptorPool descriptorPool;
private VkDescriptorSetLayout[] descriptorSetLayouts;
private VkDescriptorSet[] descriptorSets;
private BindingGroup[] descriptorGroups;
private Buffer[] uniformBuffers;
private Pipeline[const Material] pipelines;
private auto dirty_ = false;
private auto currentFrame = 0;
this(Device device, const Surface surface, const Size framebufferSize, const SwapChain oldSwapChain = null) {
this.device = device;
SupportDetails details = getSupportDetails(device, surface);
presentMode = choosePresentMode(details.presentModes);
extent = chooseExtent(details.capabilities, framebufferSize);
presentationPass_ = new RenderPass(device, true);
uint imageCount = details.capabilities.minImageCount + 1;
if (details.capabilities.maxImageCount > 0 && imageCount > details.capabilities.maxImageCount)
imageCount = details.capabilities.maxImageCount;
VkSwapchainCreateInfoKHR createInfo = {
surface: surface.surfaceKhr,
minImageCount: imageCount,
imageFormat: surfaceFormat.format,
imageColorSpace: surfaceFormat.colorSpace,
imageExtent: extent,
imageArrayLayers: 1,
imageUsage: VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
imageSharingMode: VK_SHARING_MODE_EXCLUSIVE,
queueFamilyIndexCount: 0,
pQueueFamilyIndices: null,
preTransform: details.capabilities.currentTransform,
compositeAlpha: VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
presentMode: presentMode,
clipped: VK_TRUE,
oldSwapchain: oldSwapChain is null ? VK_NULL_HANDLE : cast(VkSwapchainKHR) oldSwapChain.handle,
};
enforceVk(vkCreateSwapchainKHR(device.handle, &createInfo, null, &handle));
// Get the swap chain's images
vkGetSwapchainImagesKHR(device.handle, handle, &imageCount, null);
swapChainImages = new VkImage[imageCount];
vkGetSwapchainImagesKHR(device.handle, handle, &imageCount, swapChainImages.ptr);
// Create image views for the swap chain's images
imageViews = new VkImageView[imageCount];
for (auto i = 0; i < imageCount; i += 1) {
VkImageViewCreateInfo view = {
image: swapChainImages[i],
viewType: VK_IMAGE_VIEW_TYPE_2D,
format: surfaceFormat.format,
};
view.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
view.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
view.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
view.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
view.subresourceRange.baseMipLevel = 0;
view.subresourceRange.levelCount = 1;
view.subresourceRange.baseArrayLayer = 0;
view.subresourceRange.layerCount = 1;
enforceVk(vkCreateImageView(device.handle, &view, null, &imageViews[i]));
}
// Create depth buffer
depthStencilImage = new Image(device, framebufferSize, ImageUsage.depthStencil);
auto transition = device.createSingleTimeCommandBuffer();
transition.transitionImageLayout(depthStencilImage, ImageLayoutTransition.undefinedToDepthStencilOptimal);
transition.flush();
destroy(transition);
// Create frame buffers for the swap chain's images
framebuffers = new VkFramebuffer[imageViews.length];
for (auto i = 0; i < imageViews.length; i += 1) {
const attachments = [imageViews[i], depthStencilImage.defaultView];
VkFramebufferCreateInfo framebufferInfo = {
renderPass: presentationPass_.handle,
attachmentCount: attachments.length.to!uint,
pAttachments: attachments.ptr,
width: extent.width,
height: extent.height,
layers: 1,
};
enforceVk(vkCreateFramebuffer(device.handle, &framebufferInfo, null, &framebuffers[i]));
}
// Create the swap chain's descriptor pool, for UBOs and whatnot
VkDescriptorPoolSize poolSize = {
descriptorCount: swapChainImages.length.to!uint,
};
VkDescriptorPoolCreateInfo poolInfo = {
poolSizeCount: 1,
pPoolSizes: &poolSize,
maxSets: swapChainImages.length.to!uint,
flags: VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
};
enforceVk(vkCreateDescriptorPool(device.handle, &poolInfo, null, &descriptorPool));
// Create the swap chain's synchronization primitives
VkSemaphoreCreateInfo semaphoreInfo;
VkFenceCreateInfo fenceInfo = {flags: VK_FENCE_CREATE_SIGNALED_BIT};
imagesInFlight = new VkFence[imageCount];
for (auto i = 0; i < imageCount; i += 1) {
if (i < MAX_FRAMES_IN_FLIGHT) {
enforceVk(vkCreateSemaphore(device.handle, &semaphoreInfo, null, &imageAvailableSemaphores[i]));
enforceVk(vkCreateSemaphore(device.handle, &semaphoreInfo, null, &renderFinishedSemaphores[i]));
enforceVk(vkCreateFence(device.handle, &fenceInfo, null, &inFlightFences[i]));
}
imagesInFlight[i] = VK_NULL_HANDLE;
}
if (oldSwapChain !is null) {
vkDeviceWaitIdle(device.handle);
destroy(oldSwapChain);
}
}
~this() {
vkDeviceWaitIdle(device.handle);
foreach (framebuffer; framebuffers)
vkDestroyFramebuffer(device.handle, framebuffer, null);
destroy(depthStencilImage);
destroy(presentationCommands);
foreach (pipeline; pipelines.values)
destroy(pipeline);
destroy(presentationPass_);
foreach (imageView; imageViews)
vkDestroyImageView(device.handle, imageView, null);
vkDestroyDescriptorPool(device.handle, descriptorPool, null);
foreach (descriptorSetLayout; descriptorSetLayouts)
vkDestroyDescriptorSetLayout(device.handle, descriptorSetLayout, null);
foreach (buffer; uniformBuffers)
destroy(buffer);
for (auto i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
vkDestroySemaphore(device.handle, renderFinishedSemaphores[i], null);
vkDestroySemaphore(device.handle, imageAvailableSemaphores[i], null);
vkDestroyFence(device.handle, inFlightFences[i], null);
}
vkDestroySwapchainKHR(device.handle, handle, null);
}
bool ready() @property const {
return presentationCommands !is null;
}
const(RenderPass) presentationPass() @property const {
return presentationPass_;
}
inout(CommandBuffer) commandBuffer() @property inout {
return presentationCommands;
}
bool hasPipeline(const Material material) {
return (material in pipelines) !is null;
}
const(Pipeline) pipelineOf(const Material material) {
assert(hasPipeline(material));
return pipelines[material];
}
const(Pipeline) trackPipeline(const Material material, const PipelineLayout layout) {
descriptorGroups ~= layout.bindingGroups;
// Recreate descriptor sets and uniform buffers to fit new pipeline's descriptor layout
vkDeviceWaitIdle(device.handle);
if (descriptorSets.length)
vkFreeDescriptorSets(device.handle, descriptorPool, descriptorSets.length.to!uint, descriptorSets.ptr);
foreach (descriptorSetLayout; descriptorSetLayouts)
vkDestroyDescriptorSetLayout(device.handle, descriptorSetLayout, null);
foreach (buffer; uniformBuffers)
destroy(buffer);
descriptorSetLayouts = new VkDescriptorSetLayout[0];
createDescriptorSets();
presentationCommands.descriptorSets = descriptorSets;
return pipelines[material] = new Pipeline(
device, extent, presentationPass_, material, layout, descriptorSetLayouts
);
}
bool dirty() @property const {
return dirty_;
}
private void createDescriptorSets() {
import std.algorithm.iteration : sum;
import std.range : enumerate, repeat;
if (descriptorGroups.length == 0) return;
descriptorSetLayouts = descriptorGroups.map!(group => {
const descriptorLayoutBindings = group.bindings.map!(descriptor => {
VkDescriptorSetLayoutBinding descriptorLayout = {
binding: descriptor.bindingLocation,
descriptorType: descriptor.bindingType,
descriptorCount: 1,
stageFlags: descriptor.shaderStage,
pImmutableSamplers: null,
};
return descriptorLayout;
}()).array;
VkDescriptorSetLayoutCreateInfo layoutInfo = {
bindingCount: descriptorLayoutBindings.length.to!uint,
pBindings: descriptorLayoutBindings.ptr,
};
VkDescriptorSetLayout setLayout;
enforceVk(vkCreateDescriptorSetLayout(device.handle, &layoutInfo, null, &setLayout));
return setLayout;
}()).array;
// Create a uniform buffer for each swap chain image
uniformBuffers = new Buffer[swapChainImages.length];
const size_t size = descriptorGroups
.map!(group => group.bindings.filter!(b => b.bindingType == BindingType.uniform).map!(u => u.size))
.joiner.sum;
for (size_t i = 0; i < swapChainImages.length; i += 1) {
uniformBuffers[i] = new Buffer(device, size, BufferUsage.uniformBuffer);
}
const layouts = descriptorSetLayouts.repeat(swapChainImages.length).joiner.array;
descriptorSets = new VkDescriptorSet[swapChainImages.length];
VkDescriptorSetAllocateInfo allocInfo = {
descriptorPool: descriptorPool,
descriptorSetCount: layouts.length.to!uint,
pSetLayouts: layouts.ptr,
};
enforceVk(vkAllocateDescriptorSets(device.handle, &allocInfo, descriptorSets.ptr));
const(VkWriteDescriptorSet)[] descriptorWrites;
for (size_t i = 0; i < swapChainImages.length; i += 1) {
foreach (v, group; descriptorGroups.enumerate()) {
descriptorWrites ~= group.bindings.map!(binding => binding.descriptorWrite(
descriptorSets[i + v], uniformBuffers[i]
)).array;
}
}
vkUpdateDescriptorSets(device.handle, descriptorWrites.length.to!uint, descriptorWrites.ptr, 0, null);
}
void drawFrame() {
import std.algorithm.mutation : copy;
assert(ready);
assert(presentationCommands.handles.length == swapChainImages.length);
vkWaitForFences(device.handle, 1, &inFlightFences[currentFrame], VK_TRUE, ulong.max);
uint imageIndex;
VkResult result = vkAcquireNextImageKHR(
device.handle, handle, ulong.max, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex
);
if (result == VK_ERROR_OUT_OF_DATE_KHR) return;
enforce(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR, "Failed to acquire swap chain image!");
// Check if a previous frame is using this image, i.e. it has a fence to wait on
if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
vkWaitForFences(device.handle, 1, &imagesInFlight[imageIndex], VK_TRUE, ulong.max);
}
// Mark the image as now being in use by this frame
imagesInFlight[imageIndex] = inFlightFences[currentFrame];
const commandBuffer = presentationCommands.handles[imageIndex];
if (uniformBuffers.length) {
// TODO: Only blit dirty uniforms?
byte[] uniformData;
auto uniforms = descriptorGroups
.map!(group => group.bindings.filter!(b => b.bindingType == BindingType.uniform))
.joiner;
foreach (uniform; uniforms)
uniformData ~= uniform.data;
const unfilled = uniformData.copy(uniformBuffers[imageIndex].map());
assert(unfilled.length == 0);
uniformBuffers[imageIndex].unmap();
}
VkSubmitInfo submitInfo;
const VkSemaphore[] waitSemaphores = [imageAvailableSemaphores[currentFrame]];
const VkPipelineStageFlags[] waitStages = [VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT];
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores.ptr;
submitInfo.pWaitDstStageMask = waitStages.ptr;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
const VkSemaphore[] signalSemaphores = [renderFinishedSemaphores[currentFrame]];
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores.ptr;
vkResetFences(device.handle, 1, &inFlightFences[currentFrame]);
enforceVk(vkQueueSubmit(device.presentQueue, 1, &submitInfo, inFlightFences[currentFrame]));
const VkSwapchainKHR[] swapChains = [handle];
VkPresentInfoKHR presentInfo = {
waitSemaphoreCount: 1,
pWaitSemaphores: signalSemaphores.ptr,
swapchainCount: 1,
pSwapchains: swapChains.ptr,
pImageIndices: &imageIndex,
pResults: null,
};
result = vkQueuePresentKHR(device.presentQueue, &presentInfo);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) {
dirty_ = true;
} else enforce(result == VK_SUCCESS, "Failed to present swap chain image!");
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
static bool supported(const Device device, const Surface surface) {
SupportDetails details = getSupportDetails(device, surface);
// Require VK_FORMAT_B8G8R8A8_SRGB (BGRA8 is what Ultrlight uses)
return details.formats.any!(availableFormat =>
availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB &&
availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR
) && details.presentModes.length;
}
private struct SupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
VkSurfaceFormatKHR[] formats;
VkPresentModeKHR[] presentModes;
}
private static SupportDetails getSupportDetails(const Device device, const Surface surface) {
auto physicalDevice = device.physicalDevice;
auto surfaceKhr = surface.surfaceKhr;
SupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surfaceKhr, &details.capabilities);
// Get supported texture formats
uint formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surfaceKhr, &formatCount, null);
if (formatCount) {
details.formats = new VkSurfaceFormatKHR[formatCount];
vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surfaceKhr, &formatCount, details.formats.ptr);
}
// Get supported present modes
uint presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surfaceKhr, &presentModeCount, null);
if (presentModeCount != 0) {
details.presentModes = new VkPresentModeKHR[presentModeCount];
vkGetPhysicalDeviceSurfacePresentModesKHR(
physicalDevice, surfaceKhr, &presentModeCount, details.presentModes.ptr
);
}
return details;
}
private VkPresentModeKHR choosePresentMode(VkPresentModeKHR[] availablePresentModes) {
foreach (availablePresentMode; availablePresentModes) {
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) return availablePresentMode;
}
return VK_PRESENT_MODE_FIFO_KHR;
}
private VkExtent2D chooseExtent(const VkSurfaceCapabilitiesKHR capabilities, Size framebufferSize) {
import std.algorithm.comparison : max, min;
if (capabilities.currentExtent.width != uint.max) {
return capabilities.currentExtent;
} else {
auto actualExtent = VkExtent2D(framebufferSize.width, framebufferSize.height);
actualExtent.width = max(
capabilities.minImageExtent.width,
min(capabilities.maxImageExtent.width, actualExtent.width)
);
actualExtent.height = max(
capabilities.minImageExtent.height,
min(capabilities.maxImageExtent.height, actualExtent.height)
);
return actualExtent;
}
}
}
/// Allowed usage of a buffer. May be used in bitwise combinations.
enum BufferUsage : VkBufferUsageFlagBits {
/// Buffer can be used as source in a memory transfer operation.
transferSrc = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
/// Buffer can be used as destination in a memory transfer operation.
transferDst = VK_BUFFER_USAGE_TRANSFER_DST_BIT,
uniformTexelBuffer = VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
storageTexelBuffer = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT,
uniformBuffer = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
storageBuffer = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
indexBuffer = VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
vertexBuffer = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
indirectBuffer = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT,
}
package (teraflop) class Buffer {
const BufferUsage usage;
private const Device device;
private VkBufferCreateInfo bufferInfo;
private VkBuffer buffer = VK_NULL_HANDLE;
private VkDeviceMemory bufferMemory = VK_NULL_HANDLE;
this(const Device device, ulong size, BufferUsage usage = BufferUsage.vertexBuffer, bool hostVisible = true) {
this.device = device;
this.usage = usage;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
enforceVk(vkCreateBuffer(device.handle, &bufferInfo, null, &buffer));
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device.handle, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo = {
allocationSize: memRequirements.size,
memoryTypeIndex: findMemoryType(
device,
memRequirements.memoryTypeBits,
hostVisible
? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
: VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
),
};
enforceVk(vkAllocateMemory(device.handle, &allocInfo, null, &bufferMemory));
vkBindBufferMemory(device.handle, buffer, bufferMemory, 0);
}
~this() {
vkDestroyBuffer(device.handle, buffer, null);
vkFreeMemory(device.handle, bufferMemory, null);
}
VkBuffer handle() @property const {
return cast(VkBuffer) buffer;
}
bool ready() @property const {
return buffer != VK_NULL_HANDLE && bufferMemory != VK_NULL_HANDLE;
}
ulong size() @property const {
return bufferInfo.size;
}
ubyte[] map(ulong offset = 0, ulong size = VK_WHOLE_SIZE) {
ubyte* data;
enforceVk(vkMapMemory(device.handle, bufferMemory, offset, size, 0, cast(void**) &data));
const mappedSize = size == VK_WHOLE_SIZE ? bufferInfo.size : size;
return data[0 .. mappedSize];
}
void unmap() {
vkUnmapMemory(device.handle, bufferMemory);
}
}
package (teraflop) enum ImageFormat : VkFormat {
bgra8Srgb = VK_FORMAT_B8G8R8A8_SRGB,
d32Sfloat = VK_FORMAT_D32_SFLOAT,
d32SfloatS8Uint = VK_FORMAT_D32_SFLOAT_S8_UINT,
d24UnormS8Uint = VK_FORMAT_D24_UNORM_S8_UINT,
depthStencil = ImageFormat.d32Sfloat | ImageFormat.d32SfloatS8Uint | ImageFormat.d24UnormS8Uint
}
package (teraflop) enum ImageUsage : VkImageUsageFlagBits {
transferDst = VK_IMAGE_USAGE_TRANSFER_DST_BIT,
sampled = VK_IMAGE_USAGE_SAMPLED_BIT,
colorAttachment = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
depthStencil = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
}
package (teraflop) enum ImageLayoutTransition {
undefinedToTransferOptimal,
undefinedToDepthStencilOptimal,
transferOptimalToShaderReadOnlyOptimal
}
package (teraflop) class Image {
const ImageFormat format;
const Size size;
const uint mipLevels;
const uint arrayLayers;
const VkExtent3D extent;
const VkExtent2D extent2d;
private const Device device;
private VkImage image;
private VkDeviceMemory imageMemory;
private VkImageView imageView;
static const defaultFormat = ImageFormat.bgra8Srgb;
static const defaultUsage = ImageUsage.transferDst | ImageUsage.sampled;
this(const Device device, const Size size, const ImageUsage usage = defaultUsage) {
this.format = usage == ImageUsage.depthStencil ? findDepthFormat(device) : format;
this.size = size;
this.device = device;
VkImageCreateInfo imageInfo = {
imageType: VK_IMAGE_TYPE_2D,
format: format,
mipLevels: 1,
arrayLayers: 1,
tiling: VK_IMAGE_TILING_OPTIMAL,
initialLayout: VK_IMAGE_LAYOUT_UNDEFINED,
usage: usage,
sharingMode: VK_SHARING_MODE_EXCLUSIVE,
samples: VK_SAMPLE_COUNT_1_BIT,
};
imageInfo.extent.width = cast(uint) size.width;
imageInfo.extent.height = cast(uint) size.height;
imageInfo.extent.depth = 1;
this.mipLevels = imageInfo.mipLevels;
this.arrayLayers = imageInfo.arrayLayers;
this.extent = imageInfo.extent;
this.extent2d = VkExtent2D(imageInfo.extent.width, imageInfo.extent.height);
enforceVk(vkCreateImage(device.handle, &imageInfo, null, &image));
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device.handle, image, &memRequirements);
VkMemoryAllocateInfo allocInfo = {
allocationSize: memRequirements.size,
memoryTypeIndex: findMemoryType(device, memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
};
enforceVk(vkAllocateMemory(device.handle, &allocInfo, null, &imageMemory));
vkBindImageMemory(device.handle, image, imageMemory, 0);
// Create default image view
VkImageViewCreateInfo viewInfo = {
image: image,
viewType: VK_IMAGE_VIEW_TYPE_2D,
format: imageInfo.format,
};
viewInfo.subresourceRange.aspectMask = hasDepthComponent(format)
? VK_IMAGE_ASPECT_DEPTH_BIT
: VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = arrayLayers;
enforceVk(vkCreateImageView(device.handle, &viewInfo, null, &imageView));
}
~this() {
vkDestroyImageView(device.handle, imageView, null);
vkDestroyImage(device.handle, image, null);
vkFreeMemory(device.handle, imageMemory, null);
}
VkImage handle() @property const {
return cast(VkImage) image;
}
static bool hasDepthComponent(ImageFormat format) {
return format == ImageFormat.d32Sfloat || hasStencilComponent(format);
}
static bool hasStencilComponent(ImageFormat format) {
return format == ImageFormat.d32SfloatS8Uint || format == ImageFormat.d24UnormS8Uint;
}
VkImageView defaultView() @property const {
return cast(VkImageView) imageView;
}
}
private ImageFormat findDepthFormat(const Device device) {
return findSupportedFormat(
device.physicalDevice,
[ImageFormat.d32Sfloat, ImageFormat.d32SfloatS8Uint, ImageFormat.d24UnormS8Uint],
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
);
}
private ImageFormat findSupportedFormat(
VkPhysicalDevice physicalDevice, const ImageFormat[] candidates,
VkFormatFeatureFlags features, VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL
) {
foreach (format; candidates) {
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features) {
return format;
} else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features) {
return format;
}
}
enforce(false, "Failed to find supported image format!");
assert(0);
}
package (teraflop) class Sampler {
private const Device device;
private VkSampler sampler;
this(const Device device) {
this.device = device;
VkSamplerCreateInfo samplerInfo = {
magFilter: VK_FILTER_LINEAR,
minFilter: VK_FILTER_LINEAR,
addressModeU: VK_SAMPLER_ADDRESS_MODE_REPEAT,
addressModeV: VK_SAMPLER_ADDRESS_MODE_REPEAT,
addressModeW: VK_SAMPLER_ADDRESS_MODE_REPEAT,
anisotropyEnable: VK_TRUE,
maxAnisotropy: 16.0f,
borderColor: VK_BORDER_COLOR_INT_OPAQUE_BLACK,
unnormalizedCoordinates: VK_FALSE,
compareEnable: VK_FALSE,
compareOp: VK_COMPARE_OP_ALWAYS,
mipmapMode: VK_SAMPLER_MIPMAP_MODE_LINEAR,
mipLodBias: 0.0f,
minLod: 0.0f,
maxLod: 0.0f,
};
enforceVk(vkCreateSampler(device.handle, &samplerInfo, null, &sampler));
}
~this() {
vkDestroySampler(device.handle, sampler, null);
}
VkSampler handle() @property const {
return cast(VkSampler) sampler;
}
}
private uint findMemoryType(const Device device, uint typeFilter, VkMemoryPropertyFlags properties) {
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(device.physicalDevice, &memProperties);
for (uint i = 0; i < memProperties.memoryTypeCount; i += 1) {
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
return i;
}
}
enforce(false, "Failed to find suitable GPU memory type!");
assert(0);
}
package (teraflop) class CommandBuffer {
private const Device device;
private const RenderPass presentationPass = null;
private const VkFramebuffer[] framebuffers = [];
private const VkExtent2D extent = VkExtent2D();
private VkDescriptorSet[] descriptorSets_;
private VkCommandBuffer[] commandBuffers;
/// Create a one-time use command buffer
this(const Device device) {
this.device = device;
commandBuffers = new VkCommandBuffer[1];
VkCommandBufferAllocateInfo allocInfo = {
commandPool: device.commandPool,
level: VK_COMMAND_BUFFER_LEVEL_PRIMARY,
commandBufferCount: commandBuffers.length.to!uint,
};
enforceVk(vkAllocateCommandBuffers(device.handle, &allocInfo, commandBuffers.ptr));
VkCommandBufferBeginInfo beginInfo = {
flags: VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
enforceVk(vkBeginCommandBuffer(commandBuffers[0], &beginInfo));
}
this(
const Device device, const VkFramebuffer[] framebuffers, const VkExtent2D extent, const RenderPass presentationPass
) {
this.device = device;
this.presentationPass = presentationPass;
this.framebuffers = framebuffers;
this.extent = extent;
commandBuffers = new VkCommandBuffer[framebuffers.length];
VkCommandBufferAllocateInfo allocInfo = {
commandPool: device.commandPool,
level: VK_COMMAND_BUFFER_LEVEL_PRIMARY,
commandBufferCount: commandBuffers.length.to!uint,
};
enforceVk(vkAllocateCommandBuffers(device.handle, &allocInfo, commandBuffers.ptr));
}
~this() {
vkFreeCommandBuffers(device.handle, device.commandPool, commandBuffers.length.to!uint, commandBuffers.ptr);
}
VkCommandBuffer[] handles() @property const {