quick backup
[demo] / src / vulkan / vkutil.cc
1 #include <vulkan/vulkan.h>
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <string>
7 #include <vector>
8
9 #include "vkutil.h"
10
11 /* global variables */
12
13 VkPipeline *vkgraphics_pipeline;
14 VkFramebuffer *vkfbufs;
15 VkRenderPass vkrpass;
16 VkSwapchainKHR vkswapchain;
17 VkImage *vkswapchain_images;
18 VkImageView *vkswapchain_views;
19 int vknum_swapchain_images;
20 int vknext_swapchain_image;
21 VkSurfaceKHR vksurface;
22 VkInstance vkinst;
23 VkPhysicalDevice vkpdev;
24 VkDevice vkdev;
25 VkQueue vkq;
26 VkCommandPool vkcmdpool;
27 VkCommandBuffer vkcmdbuf;       /* primary command buffer */
28 int vkqfamily;
29
30 /* static functions */
31 static const char *get_device_name_str(VkPhysicalDeviceType type);
32 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags);
33 static const char *get_queue_flags_str(VkQueueFlags flags);
34 static const char *get_mem_size_str(long sz);
35 static int ver_major(uint32_t ver);
36 static int ver_minor(uint32_t ver);
37 static int ver_patch(uint32_t ver);
38
39 /* static variables */
40 static VkPhysicalDevice *phys_devices;
41
42 static int sel_dev;
43 static int sel_qfamily;
44
45 static VkExtensionProperties *vkext, *vkdevext;
46 static uint32_t vkext_count, vkdevext_count;
47
48 bool vku_have_extension(const char *name)
49 {
50         if(!vkext) {
51                 vkext_count = 0;
52                 vkEnumerateInstanceExtensionProperties(0, &vkext_count, 0);
53                 if(vkext_count) {
54                         vkext = new VkExtensionProperties[vkext_count];
55                         vkEnumerateInstanceExtensionProperties(0, &vkext_count, vkext);
56
57                         printf("instance extensions:\n");
58                         for(int i=0; i<(int)vkext_count; i++) {
59                                 printf(" %s (ver: %u)\n", vkext[i].extensionName, (unsigned int)vkext[i].specVersion);
60                         }
61                 }
62         }
63
64         for(int i=0; i<(int)vkext_count; i++) {
65                 if(strcmp(vkext[i].extensionName, name) == 0) {
66                         return true;
67                 }
68         }
69         return false;
70 }
71
72 bool vku_have_device_extension(const char *name)
73 {
74         if(sel_dev < 0) return false;
75
76         if(!vkdevext) {
77                 vkdevext_count = 0;
78                 vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, 0);
79                 if(vkdevext_count) {
80                         vkdevext = new VkExtensionProperties[vkdevext_count];
81                         vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, vkdevext);
82
83                         printf("selected device extensions:\n");
84                         for(int i=0; i<(int)vkdevext_count; i++) {
85                                 printf(" %s (ver: %u)\n", vkdevext[i].extensionName, (unsigned int)vkdevext[i].specVersion);
86                         }
87                 }
88         }
89
90         for(int i=0; i<(int)vkdevext_count; i++) {
91                 if(strcmp(vkdevext[i].extensionName, name) == 0) {
92                         return true;
93                 }
94         }
95         return false;
96 }
97
98 bool vku_create_device()
99 {
100         VkInstanceCreateInfo inst_info;
101         VkDeviceCreateInfo dev_info;
102         VkDeviceQueueCreateInfo queue_info;
103         VkCommandPoolCreateInfo cmdpool_info;
104         uint32_t num_devices;
105         float qprio = 0.0f;
106
107         static const char *ext_names[] = {
108                 "VK_KHR_xcb_surface",
109                 "VK_KHR_surface"
110         };
111
112         static const char *devext_names[] = {
113                 "VK_KHR_swapchain"
114         };
115
116         sel_dev = -1;
117         sel_qfamily = -1;
118
119         for(unsigned int i=0; i<sizeof ext_names / sizeof *ext_names; i++) {
120                 if(!vku_have_extension(ext_names[i])) {
121                         fprintf(stderr, "required extension (%s) not found\n", ext_names[i]);
122                         return false;
123                 }
124         }
125         memset(&inst_info, 0, sizeof inst_info);
126         inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
127         inst_info.ppEnabledExtensionNames = ext_names;
128         inst_info.enabledExtensionCount = sizeof ext_names / sizeof *ext_names;
129
130         if(vkCreateInstance(&inst_info, 0, &vkinst) != 0) {
131                 fprintf(stderr, "failed to create vulkan instance\n");
132                 return false;
133         }
134         printf("created vulkan instance\n");
135         if(vkEnumeratePhysicalDevices(vkinst, &num_devices, 0) != 0) {
136                 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
137                 return false;
138         }
139         phys_devices = new VkPhysicalDevice[num_devices];
140         if(vkEnumeratePhysicalDevices(vkinst, &num_devices, phys_devices) != 0) {
141                 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
142                 return false;
143         }
144         printf("found %u physical device(s)\n", (unsigned int)num_devices);
145
146         for(int i=0; i<(int)num_devices; i++) {
147                 VkPhysicalDeviceProperties dev_prop;
148                 VkPhysicalDeviceMemoryProperties mem_prop;
149                 VkQueueFamilyProperties *qprop;
150                 uint32_t qprop_count;
151
152                 vkGetPhysicalDeviceProperties(phys_devices[i], &dev_prop);
153
154                 printf("Device %d: %s\n", i, dev_prop.deviceName);
155                 printf("  type: %s\n", get_device_name_str(dev_prop.deviceType));
156                 printf("  API version: %d.%d.%d\n", ver_major(dev_prop.apiVersion), ver_minor(dev_prop.apiVersion),
157                        ver_patch(dev_prop.apiVersion));
158                 printf("  driver version: %d.%d.%d\n", ver_major(dev_prop.driverVersion), ver_minor(dev_prop.driverVersion),
159                        ver_patch(dev_prop.driverVersion));
160                 printf("  vendor id: %x  device id: %x\n", dev_prop.vendorID, dev_prop.deviceID);
161
162
163                 vkGetPhysicalDeviceMemoryProperties(phys_devices[i], &mem_prop);
164                 printf("  %d memory heaps:\n", mem_prop.memoryHeapCount);
165                 for(unsigned int j=0; j<mem_prop.memoryHeapCount; j++) {
166                         VkMemoryHeap heap = mem_prop.memoryHeaps[j];
167                         printf("    Heap %d - size: %s, flags: %s\n", j, get_mem_size_str(heap.size),
168                                heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT ? "device-local" : "-");
169                 }
170                 printf("  %d memory types:\n", mem_prop.memoryTypeCount);
171                 for(unsigned int j=0; j<mem_prop.memoryTypeCount; j++) {
172                         VkMemoryType type = mem_prop.memoryTypes[j];
173                         printf("    Type %d - heap: %d, flags: %s\n", j, type.heapIndex,
174                                get_memtype_flags_str(type.propertyFlags));
175                 }
176
177                 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, 0);
178                 if(qprop_count <= 0) {
179                         continue;
180                 }
181                 qprop = new VkQueueFamilyProperties[qprop_count];
182                 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, qprop);
183
184                 for(unsigned int j=0; j<qprop_count; j++) {
185                         printf("  Queue family %d:\n", j);
186                         printf("    flags: %s\n", get_queue_flags_str(qprop[j].queueFlags));
187                         printf("    num queues: %u\n", qprop[j].queueCount);
188
189                         if(qprop[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
190                                 sel_dev = i;
191                                 sel_qfamily = j;
192                         }
193                 }
194                 delete [] qprop;
195         }
196
197         if(sel_dev < 0 || sel_qfamily < 0) {
198                 fprintf(stderr, "failed to find any device with a graphics-capable command queue\n");
199                 vkDestroyDevice(vkdev, 0);
200                 return false;
201         }
202
203         for(unsigned int i=0; i<sizeof devext_names / sizeof *devext_names; i++) {
204                 if(!vku_have_device_extension(devext_names[i])) {
205                         fprintf(stderr, "required extension (%s) not found on the selected device (%d)\n",
206                                 ext_names[i], sel_dev);
207                         return false;
208                 }
209         }
210
211         /* create device & command queue */
212         memset(&queue_info, 0, sizeof queue_info);
213         queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
214         queue_info.queueFamilyIndex = sel_qfamily;
215         queue_info.queueCount = 1;
216         queue_info.pQueuePriorities = &qprio;
217
218         memset(&dev_info, 0, sizeof dev_info);
219         dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
220         dev_info.queueCreateInfoCount = 1;
221         dev_info.pQueueCreateInfos = &queue_info;
222         dev_info.enabledExtensionCount = sizeof devext_names / sizeof *devext_names;
223         dev_info.ppEnabledExtensionNames = devext_names;
224
225         if(vkCreateDevice(phys_devices[sel_dev], &dev_info, 0, &vkdev) != 0) {
226                 fprintf(stderr, "failed to create device %d\n", sel_dev);
227                 return false;
228         }
229         printf("created device %d\n", sel_dev);
230
231         vkpdev = phys_devices[sel_dev];
232         vkqfamily = sel_qfamily;
233
234         vkGetDeviceQueue(vkdev, sel_qfamily, 0, &vkq);
235
236         /* create command buffer pool */
237         memset(&cmdpool_info, 0, sizeof cmdpool_info);
238         cmdpool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
239         cmdpool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
240         cmdpool_info.queueFamilyIndex = sel_qfamily;
241
242         if(vkCreateCommandPool(vkdev, &cmdpool_info, 0, &vkcmdpool) != 0) {
243                 fprintf(stderr, "failed to get command quque!\n");
244                 return false;
245         }
246
247         if(!(vkcmdbuf = vku_alloc_cmdbuf(vkcmdpool, VK_COMMAND_BUFFER_LEVEL_PRIMARY))) {
248                 fprintf(stderr, "failed to create primary command buffer\n");
249                 return false;
250         }
251
252         return true;
253 }
254
255 void vku_cleanup()
256 {
257         if(vkinst) {
258                 vkDeviceWaitIdle(vkdev);
259                 vkDestroyCommandPool(vkdev, vkcmdpool, 0);
260                 vkDestroyDevice(vkdev, 0);
261                 vkDestroyInstance(vkinst, 0);
262                 vkinst = 0;
263         }
264
265         delete [] phys_devices;
266         phys_devices = 0;
267 }
268
269 VkCommandBuffer vku_alloc_cmdbuf(VkCommandPool pool, VkCommandBufferLevel level)
270 {
271         VkCommandBuffer cmdbuf;
272         VkCommandBufferAllocateInfo inf;
273
274         memset(&inf, 0, sizeof inf);
275         inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
276         inf.commandPool = pool;
277         inf.level = level;
278         inf.commandBufferCount = 1;
279
280         if(vkAllocateCommandBuffers(vkdev, &inf, &cmdbuf) != 0) {
281                 return 0;
282         }
283         return cmdbuf;
284 }
285
286 void vku_free_cmdbuf(VkCommandPool pool, VkCommandBuffer buf)
287 {
288         vkFreeCommandBuffers(vkdev, pool, 1, &buf);
289 }
290
291 void vku_begin_cmdbuf(VkCommandBuffer buf, unsigned int flags)
292 {
293         VkCommandBufferBeginInfo inf;
294
295         memset(&inf, 0, sizeof inf);
296         inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
297         inf.flags = flags;
298
299         vkBeginCommandBuffer(buf, &inf);
300 }
301
302
303 void vku_end_cmdbuf(VkCommandBuffer buf)
304 {
305         vkEndCommandBuffer(buf);
306 }
307
308 void vku_reset_cmdbuf(VkCommandBuffer buf)
309 {
310         vkResetCommandBuffer(buf, 0);
311 }
312
313 void vku_submit_cmdbuf(VkQueue q, VkCommandBuffer buf, VkFence done_fence)
314 {
315         VkSubmitInfo info;
316
317         memset(&info, 0, sizeof info);
318         info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
319         info.commandBufferCount = 1;
320         info.pCommandBuffers = &buf;
321
322         vkQueueSubmit(q, 1, &info, done_fence);
323 }
324
325 VkSwapchainKHR vku_create_swapchain(VkSurfaceKHR surf, int xsz, int ysz, int n,
326                                     VkPresentModeKHR pmode, VkSwapchainKHR prev)
327 {
328         VkSwapchainKHR sc;
329         VkSwapchainCreateInfoKHR inf;
330
331         memset(&inf, 0, sizeof inf);
332         inf.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
333         inf.surface = surf;
334         inf.minImageCount = n;
335         inf.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;     /* TODO enumerate and choose */
336         inf.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
337         inf.imageExtent.width = xsz;
338         inf.imageExtent.height = ysz;
339         inf.imageArrayLayers = 1;
340         inf.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
341         inf.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;       /* XXX make this an option? */
342         inf.preTransform = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
343         inf.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
344         inf.presentMode = pmode;
345         inf.oldSwapchain = prev;
346
347         if(vkCreateSwapchainKHR(vkdev, &inf, 0, &sc) != 0) {
348                 return 0;
349         }
350         return sc;
351 }
352
353 VkImage *vku_get_swapchain_images(VkSwapchainKHR sc, int *count)
354 {
355         uint32_t nimg;
356         VkImage *images;
357
358         if(vkGetSwapchainImagesKHR(vkdev, sc, &nimg, 0) != 0) {
359                 return 0;
360         }
361         images = new VkImage[nimg];
362         vkGetSwapchainImagesKHR(vkdev, sc, &nimg, images);
363
364         if(count) *count = (int)nimg;
365         return images;
366 }
367
368 VkImageView *vku_create_image_views(VkImage *images, int count)
369 {
370         VkImageView *iviews;
371
372         iviews = new VkImageView[count];
373         for(int i=0; i<count; i++) {
374                 VkImageViewCreateInfo inf;
375                 memset(&inf, 0, sizeof inf);
376
377                 inf.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
378                 inf.image = images[i];
379                 inf.viewType = VK_IMAGE_VIEW_TYPE_2D;
380                 inf.format = VK_FORMAT_B8G8R8A8_UNORM; //TODO
381                 inf.components.r = inf.components.g = inf.components.b =
382                         inf.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
383                 inf.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
384                 inf.subresourceRange.levelCount = 1;
385                 inf.subresourceRange.layerCount = 1;
386
387                 if(vkCreateImageView(vkdev, &inf, 0, iviews) != 0) {
388                         fprintf(stderr, "Failed to create image views.\n");
389                         delete iviews;
390                         return 0;
391                 }
392         }
393
394         return iviews;
395 }
396
397 int vku_get_next_image(VkSwapchainKHR sc)
398 {
399         uint32_t next;
400
401         if(vkAcquireNextImageKHR(vkdev, sc, UINT64_MAX, 0, 0, &next) != 0) {
402                 return -1;
403         }
404         return (int)next;
405 }
406
407 void vku_present(VkSwapchainKHR sc, int img_idx)
408 {
409         VkPresentInfoKHR inf;
410         VkResult res;
411         uint32_t index = img_idx;
412
413         memset(&inf, 0, sizeof inf);
414         inf.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
415         inf.swapchainCount = 1;
416         inf.pSwapchains = &sc;
417         inf.pImageIndices = &index;
418         inf.pResults = &res;
419
420         vkQueuePresentKHR(vkq, &inf);
421 }
422
423 bool vku_create_renderpass()
424 {
425         VkAttachmentDescription attachments[2];
426         memset(&attachments, 0, 2 * sizeof *attachments);
427
428         /* color */
429         attachments[0].format = VK_FORMAT_B8G8R8A8_UNORM;
430         attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
431         attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
432         attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
433         attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
434         attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
435         attachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
436         attachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
437
438         /* depth */
439         attachments[1].format = VK_FORMAT_D32_SFLOAT_S8_UINT; //TODO
440         attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
441         attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
442         attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
443         attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
444         attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
445         attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
446         attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
447
448         VkAttachmentReference color_ref;
449         color_ref.attachment = 0;
450         color_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
451
452         VkAttachmentReference depth_ref;
453         depth_ref.attachment = 1;
454         depth_ref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
455
456         VkSubpassDescription subpass_desc;
457         memset(&subpass_desc, 0, sizeof subpass_desc);
458
459         subpass_desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
460         subpass_desc.colorAttachmentCount = 1;
461         subpass_desc.pColorAttachments = &color_ref;
462         subpass_desc.pDepthStencilAttachment = &depth_ref;
463
464         VkRenderPassCreateInfo inf;
465         memset(&inf, 0, sizeof inf);
466
467         inf.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
468         inf.attachmentCount = 2;
469         inf.pAttachments = attachments;
470         inf.subpassCount = 1;
471         inf.pSubpasses = &subpass_desc;
472
473         if(vkCreateRenderPass(vkdev, &inf, 0, &vkrpass) != VK_SUCCESS) {
474                 return false;
475         }
476
477         return true;
478 }
479
480 bool vku_create_framebuffers(VkImageView *image_views, int count, int w, int h)
481 {
482         delete vkfbufs;
483         vkfbufs = new VkFramebuffer[count];
484
485         VkFramebufferCreateInfo inf;
486         memset(&inf, 0, sizeof inf);
487
488         inf.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
489         inf.renderPass = vkrpass;
490         inf.attachmentCount = count;
491         inf.pAttachments = image_views;
492         inf.width = w;
493         inf.height = h;
494         inf.layers = 1;
495
496         for(int i=0; i<count; i++) {
497                 if(vkCreateFramebuffer(vkdev, &inf, 0, &vkfbufs[i]) != VK_SUCCESS) {
498                         fprintf(stderr, "Failed to create framebuffer for image view: %d\n", i);
499                         delete vkfbufs;
500                         return false;
501                 }
502         }
503         return true;
504 }
505
506 struct vku_buffer *vku_create_buffer(int sz, unsigned int usage)
507 {
508         struct vku_buffer *buf;
509         VkBufferCreateInfo binfo;
510
511         buf = new vku_buffer;
512
513         memset(&binfo, 0, sizeof binfo);
514         binfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
515         binfo.size = sz;
516         binfo.usage = usage;
517         binfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
518
519         if(vkCreateBuffer(vkdev, &binfo, 0, &buf->buf) != 0) {
520                 fprintf(stderr, "failed to create %d byte buffer (usage: %x)\n", sz, usage);
521                 return 0;
522         }
523         // TODO back with memory
524         return buf;
525 }
526
527 void vku_destroy_buffer(struct vku_buffer *buf)
528 {
529         if(buf) {
530                 vkDestroyBuffer(vkdev, buf->buf, 0);
531                 delete buf;
532         }
533 }
534
535 void vku_cmd_copybuf(VkCommandBuffer cmdbuf, VkBuffer dest, int doffs,
536                      VkBuffer src, int soffs, int size)
537 {
538         VkBufferCopy copy;
539         copy.size = size;
540         copy.srcOffset = soffs;
541         copy.dstOffset = doffs;
542
543         vkCmdCopyBuffer(cmdbuf, src, dest, 1, &copy);
544 }
545
546 /* paste
547
548 static bool create_instance()
549 {
550         uint32_t layer_count = 0;
551         std::vector<const char *> enabled_layers;
552
553         if(vkEnumerateInstanceLayerProperties(&layer_count, 0) != VK_SUCCESS) {
554                 fprintf(stderr, "Failed to query layer properties.\n");
555                 return false;
556         }
557
558         if(layer_count > 0) {
559                 VkLayerProperties *layers = (VkLayerProperties *)alloca(layer_count * sizeof *layers);
560                 vkEnumerateInstanceLayerProperties(&layer_count, layers);
561                 for(uint32_t i=0; i<layer_count; i++) {
562                         if(strcmp(layers[i].layerName, "VK_LAYER_LUNARG_standard_validation")) {
563                                 enabled_layers.push_back(layers[i].layerName);
564                         }
565                 }
566         }
567
568         uint32_t extensions_count = 0;
569         std::vector<const char *> enabled_extensions;
570
571         if(vkEnumerateInstanceExtensionProperties(0, &extensions_count, 0) != VK_SUCCESS) {
572                 fprintf(stderr, "Failed to enumerate instance extension properties\n");
573                 return false;
574         }
575
576         if(extensions_count > 0) {
577                 VkExtensionProperties *extensions = (VkExtensionProperties *)alloca(extensions_count * sizeof *extensions);
578                 vkEnumerateInstanceExtensionProperties(0, &extensions_count, extensions);
579
580                 for(uint32_t i=0; i<extensions_count; i++) {
581                         printf("Extension %u: %s %u.\n", i, extensions[i].extensionName, extensions[i].specVersion);
582                         //enable all the available extensions
583                         enabled_extensions.push_back(extensions[i].extensionName);
584                         enabled_extension_names.push_back(std::string(extensions[i].extensionName));
585                 }
586         }
587
588         VkInstanceCreateInfo create_info;
589         memset(&create_info, 0, sizeof create_info);
590         create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
591
592         if(!enabled_layers.empty()) {
593                 create_info.enabledLayerCount = enabled_layers.size();
594                 create_info.ppEnabledLayerNames = enabled_layers.data();
595         }
596
597         if(!enabled_extensions.empty()) {
598                 create_info.enabledExtensionCount = enabled_extensions.size();
599                 create_info.ppEnabledExtensionNames = enabled_extensions.data();
600         }
601
602         if(vkCreateInstance(&create_info, 0, &inst) != VK_SUCCESS) {
603                 fprintf(stderr, "Failed to create instance.\n");
604                 return false;
605         }
606
607         if(!create_device())
608                 return false;
609
610         return true;
611 }
612
613 static bool create_device()
614 {
615         int qfam_idx = -1;
616         int pdev_idx = -1;
617
618         uint32_t dev_count;
619         if(vkEnumeratePhysicalDevices(inst, &dev_count, 0) != VK_SUCCESS) {
620                 fprintf(stderr, "Failed to enumerate physical devices.\n");
621                 return false;
622         }
623         printf("%u devices found.\n", (unsigned int)dev_count);
624
625         VkPhysicalDevice *phys_dev = (VkPhysicalDevice *)alloca(dev_count * sizeof *phys_dev);
626         vkEnumeratePhysicalDevices(inst, &dev_count, phys_dev);
627         VkPhysicalDeviceMemoryProperties memprop;
628
629         for(uint32_t i=0; i<dev_count; i++) {
630                 VkPhysicalDeviceProperties dev_props;
631                 vkGetPhysicalDeviceProperties(phys_dev[i], &dev_props);
632
633                 //memory heaps:
634                 vkGetPhysicalDeviceMemoryProperties(phys_dev[i], &memprop);
635                 printf("\tNumber of heaps: %u\n", memprop.memoryHeapCount);
636                 for(uint32_t j=0; j<memprop.memoryHeapCount; j++) {
637                         printf("\t\tHeap %u size: %lu\n", j, (unsigned long)memprop.memoryHeaps[j].size);
638                         printf("\t\tHeap %u flags: %s\n", j, heap_flags_str(memprop.memoryHeaps[j].flags));
639                 }
640                 //memory types
641                 printf("\tMemory types: %u\n", memprop.memoryTypeCount);
642                 for(uint32_t j=0; j<memprop.memoryTypeCount; j++) {
643                         printf("\t\tType %u heap index: %u\n", j, memprop.memoryTypes[j].heapIndex);
644                         printf("\t\tType %u flags: %s\n", j, memtype_flags_str(memprop.memoryTypes[j].propertyFlags));
645                 }
646
647                 //supported features
648                 VkPhysicalDeviceFeatures features;
649                 vkGetPhysicalDeviceFeatures(phys_dev[i], &features);
650
651                 //queue families
652                 uint32_t qfam_count;
653                 vkGetPhysicalDeviceQueueFamilyProperties(phys_dev[i], &qfam_count, 0);
654                 printf("\tQueue Families: %u\n", qfam_count);
655                 VkQueueFamilyProperties *qfam_props = new VkQueueFamilyProperties[qfam_count];
656                 vkGetPhysicalDeviceQueueFamilyProperties(phys_dev[i], &qfam_count, qfam_props);
657                 for(uint32_t j=0; j<qfam_count; j++) {
658                         printf("\t\tFamily %u flags: %s\n", j, queue_flags_str(qfam_props[j].queueFlags));
659                         printf("\t\tFamily %u number of queues: %u\n", j, qfam_props[j].queueCount);
660
661                         if((qfam_props[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) && (pdev_idx == -1)) {
662                                 pdev_idx = i;
663                                 qfam_idx = j;
664                                 num_queues = qfam_props[j].queueCount;
665                         }
666                 }
667                 delete [] qfam_props;
668         }
669
670         if(pdev_idx == -1) {
671                 fprintf(stderr, "No suitable devices found.\n");
672                 return false;
673         }
674
675         pdev = *(phys_dev + pdev_idx);
676         qfamily_idx = qfam_idx;
677
678                 uint32_t layer_count;
679                 if(vkEnumerateDeviceLayerProperties(pdev, &layer_count, 0) != VK_SUCCESS) {
680                         fprintf(stderr, "Failed to enumerate device layers.\n");
681                         return false;
682                 }
683                 if(layer_count > 0) {
684                         VkLayerProperties *layers = (VkLayerProperties*)alloca(layer_count * sizeof *layers);
685                         vkEnumerateDeviceLayerProperties(pdev, &layer_count, layers);
686                         printf("%u layers found.\n", layer_count);
687                         for(uint32_t i=0; i<layer_count; i++) {
688                                 printf("Layer %u: %s (%u, %u)\n", i, layers[i].layerName,
689                                                 layers[i].specVersion, layers[i].implementationVersion);
690                                 printf("\tDesc: %s\n", layers[i].description);
691                         }
692                 }
693
694         VkDeviceCreateInfo dev_info;
695         memset(&dev_info, 0, sizeof dev_info);
696         dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
697
698         VkDeviceQueueCreateInfo dev_qinfo;
699         memset(&dev_qinfo, 0, sizeof dev_qinfo);
700         dev_qinfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
701         dev_qinfo.queueFamilyIndex = qfam_idx;
702         dev_qinfo.queueCount = 1;
703
704         dev_info.queueCreateInfoCount = 1;
705         dev_info.pQueueCreateInfos = &dev_qinfo;
706
707         if(vkCreateDevice(pdev, &dev_info, 0, &device) != VK_SUCCESS) {
708                 fprintf(stderr, "Failed to create logical device.\n");
709                 return false;
710         }
711
712         vkGetPhysicalDeviceMemoryProperties(pdev, &memprop);
713         for(uint32_t j=0; j<memprop.memoryTypeCount; j++) {
714                 if(memprop.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
715                         device_mem_idx = j;
716                         printf("Selected device memory index: %u\n", device_mem_idx);
717                         break;
718                 }
719         }
720
721         return true;
722 }
723
724 static const char *dev_type_str(VkPhysicalDeviceType type)
725 {
726         switch(type) {
727         case VK_PHYSICAL_DEVICE_TYPE_OTHER:
728                 return "other";
729         case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
730                 return "integrated GPU";
731         case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
732                 return "discrete GPU";
733         case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
734                 return "virtual GPU";
735         case VK_PHYSICAL_DEVICE_TYPE_CPU:
736                 return "CPU";
737         default:
738                 break;
739         }
740         return "unknown";
741 }
742
743 static const char *heap_flags_str(VkMemoryHeapFlags flags)
744 {
745         static std::string str;
746         str.clear();
747         if(flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
748                 str += "device-local ";
749         }
750         if(!str.empty())
751                 str.pop_back();
752         return str.c_str();
753 }
754
755 static const char *memtype_flags_str(VkMemoryPropertyFlags flags)
756 {
757         static std::string str;
758         str.clear();
759         if(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
760                 str += "device-local ";
761         }
762         if(flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
763                 str += "host-visible ";
764         }
765         if(flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
766                 str += "host-coherent ";
767         }
768         if(flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) {
769                 str += "host-cached ";
770         }
771         if(flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
772                 str += "lazily-allocated ";
773         }
774         if(!str.empty())
775                 str.pop_back();
776         return str.c_str();
777 }
778
779 static const char *queue_flags_str(VkQueueFlags flags)
780 {
781         static std::string str;
782         str.clear();
783         if(flags & VK_QUEUE_GRAPHICS_BIT)
784                 str += "graphics ";
785         if(flags & VK_QUEUE_COMPUTE_BIT)
786                 str += "compute ";
787         if(flags & VK_QUEUE_TRANSFER_BIT)
788                 str += "transfer ";
789         if(flags & VK_QUEUE_SPARSE_BINDING_BIT)
790                 str += "sparse-binding ";
791         if(!str.empty())
792                 str.pop_back();
793         return str.c_str();
794 }
795 */
796
797 const char *vku_get_vulkan_error_str(VkResult error)
798 {
799         std::string errmsg;
800         switch(error) {
801         case VK_SUCCESS:
802                 errmsg = std::string("VK_SUCCESS");
803                 break;
804         case VK_NOT_READY:
805                 errmsg = std::string("VK_NOT_READY");
806                 break;
807         case VK_TIMEOUT:
808                 errmsg = std::string("VK_TIMEOUT");
809                 break;
810         case VK_EVENT_SET:
811                 errmsg = std::string("VK_EVENT_SET");
812                 break;
813         case VK_EVENT_RESET:
814                 errmsg = std::string("VK_EVENT_RESET");
815                 break;
816         case VK_INCOMPLETE:
817                 errmsg = std::string("VK_EVENT");
818                 break;
819         case VK_ERROR_OUT_OF_HOST_MEMORY:
820                 errmsg = std::string("VK_ERROR_OUT_OF_HOST_MEMORY");
821                 break;
822         case VK_ERROR_OUT_OF_DEVICE_MEMORY:
823                 errmsg = std::string("VK_ERROR_OUT_OF_DEVICE_MEMORY");
824                 break;
825         case VK_ERROR_INITIALIZATION_FAILED:
826                 errmsg = std::string("VK_ERROR_INITIALIZATION_FAILED");
827                 break;
828         case VK_ERROR_DEVICE_LOST:
829                 errmsg = std::string("VK_ERROR_DEVICE_LOST");
830                 break;
831         case VK_ERROR_MEMORY_MAP_FAILED:
832                 errmsg = std::string("VK_ERROR_MEMORY_MAP_FAILED");
833                 break;
834         case VK_ERROR_LAYER_NOT_PRESENT:
835                 errmsg = std::string("VK_ERROR_LAYER_NOT_PRESENT");
836                 break;
837         case VK_ERROR_EXTENSION_NOT_PRESENT:
838                 errmsg = std::string("VK_ERROR_EXTENSION_NOT_PRESENT");
839                 break;
840         case VK_ERROR_FEATURE_NOT_PRESENT:
841                 errmsg = std::string("VK_ERROR_FEATURE_NOT_PRESENT");
842                 break;
843         case VK_ERROR_INCOMPATIBLE_DRIVER:
844                 errmsg = std::string("VK_ERROR_INCOMPATIBLE_DRIVER");
845                 break;
846         case VK_ERROR_TOO_MANY_OBJECTS:
847                 errmsg = std::string("VK_ERROR_TOO_MANY_OBJECTS");
848                 break;
849         case VK_ERROR_FORMAT_NOT_SUPPORTED:
850                 errmsg = std::string("VK_ERROR_FORMAT_NOT_SUPPORTED");
851                 break;
852         case VK_ERROR_FRAGMENTED_POOL:
853                 errmsg = std::string("VK_ERROR_FRAGMENTED_POOL");
854                 break;
855         default:
856                 errmsg = std::string("UNKNOWN");
857                 break;
858         }
859
860         return errmsg.c_str();
861 }
862
863 bool vku_create_graphics_pipeline(VkPipelineLayout *layout)
864 {
865         VkGraphicsPipelineCreateInfo inf;
866         memset(&inf, 0, sizeof inf);
867
868         inf.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
869         inf.layout = *layout;
870         inf.renderPass = vkrpass;
871
872         /* states */
873
874         /* how primitives are assembled */
875         VkPipelineInputAssemblyStateCreateInfo ias;
876         memset(&ias, 0, sizeof ias);
877         ias.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
878         ias.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
879
880         /* rasterisation */
881         VkPipelineRasterizationStateCreateInfo rsi;
882         memset(&rsi, 0, sizeof rsi);
883         rsi.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
884         rsi.polygonMode = VK_POLYGON_MODE_FILL;
885         rsi.cullMode = VK_CULL_MODE_BACK_BIT;
886         rsi.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
887         rsi.lineWidth = 1.0f;
888
889         /* blend factors */
890         VkPipelineColorBlendAttachmentState bas[1];
891         memset(&bas[0], 0, sizeof bas[0]);
892
893         VkPipelineColorBlendStateCreateInfo cbs;
894         memset(&cbs, 0, sizeof cbs);
895         cbs.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
896         cbs.attachmentCount = 1;
897         cbs.pAttachments = bas;
898
899         /* number of viewport and scissors in this pipeline */
900         VkPipelineViewportStateCreateInfo vs;
901         memset(&vs, 0, sizeof vs);
902         vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
903         vs.viewportCount = 1;
904         vs.scissorCount = 1;
905
906         /* dynamic states: that can be changed later */
907         std::vector<VkDynamicState> ds_enabled;
908         ds_enabled.push_back(VK_DYNAMIC_STATE_VIEWPORT);
909         //ds_enabled.push_back(VK_DYNAMIC_STATE_SCISSOR);
910         VkPipelineDynamicStateCreateInfo ds;
911         ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
912         ds.pDynamicStates = ds_enabled.data();
913         ds.dynamicStateCount = static_cast<uint32_t>(ds_enabled.size());
914
915         /* depth tests */
916         VkPipelineDepthStencilStateCreateInfo dsi;
917         memset(&dsi, 0, sizeof dsi);
918         dsi.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
919         dsi.depthTestEnable = VK_TRUE;
920         dsi.depthWriteEnable = VK_TRUE;
921         dsi.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
922         dsi.back.failOp = VK_STENCIL_OP_KEEP;
923         dsi.back.passOp = VK_STENCIL_OP_KEEP;
924         dsi.back.compareOp = VK_COMPARE_OP_ALWAYS;
925         dsi.front = dsi.back;
926
927         /* multisampling - must be set even if not used */
928         VkPipelineMultisampleStateCreateInfo msi;
929         memset(&msi, 0, sizeof msi);
930         msi.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
931         msi.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
932
933         //TODO in progress
934         return true;
935 }
936
937 static const char *get_device_name_str(VkPhysicalDeviceType type)
938 {
939         switch(type) {
940         case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
941                 return "integrated GPU";
942         case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
943                 return "discrete GPU";
944         case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
945                 return "virtual GPU";
946         case VK_PHYSICAL_DEVICE_TYPE_CPU:
947                 return "CPU";
948         default:
949                 break;
950         }
951         return "unknown";
952 }
953
954 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags)
955 {
956         static char str[128];
957
958         str[0] = 0;
959         if(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
960                 strcat(str, "device-local ");
961         }
962         if(flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
963                 strcat(str, "host-visible ");
964         }
965         if(flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
966                 strcat(str, "host-coherent ");
967         }
968         if(flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) {
969                 strcat(str, "host-cached ");
970         }
971         if(flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
972                 strcat(str, "lazily-allocated ");
973         }
974
975         if(!*str) {
976                 strcat(str, "-");
977         }
978         return str;
979 }
980
981 static const char *get_queue_flags_str(VkQueueFlags flags)
982 {
983         static char str[128];
984
985         str[0] = 0;
986         if(flags & VK_QUEUE_GRAPHICS_BIT) {
987                 strcat(str, "graphics ");
988         }
989         if(flags & VK_QUEUE_COMPUTE_BIT) {
990                 strcat(str, "compute ");
991         }
992         if(flags & VK_QUEUE_TRANSFER_BIT) {
993                 strcat(str, "transfer ");
994         }
995         if(flags & VK_QUEUE_SPARSE_BINDING_BIT) {
996                 strcat(str, "sparse-binding ");
997         }
998         if(!*str) {
999                 strcat(str, "-");
1000         }
1001         return str;
1002 }
1003
1004 static int ver_major(uint32_t ver)
1005 {
1006         return (ver >> 22) & 0x3ff;
1007 }
1008
1009 static int ver_minor(uint32_t ver)
1010 {
1011         return (ver >> 12) & 0x3ff;
1012 }
1013
1014 static int ver_patch(uint32_t ver)
1015 {
1016         return ver & 0xfff;
1017 }
1018
1019 static const char *get_mem_size_str(long sz)
1020 {
1021         static char str[64];
1022         static const char *unitstr[] = { "bytes", "KB", "MB", "GB", "TB", "PB", 0 };
1023         int uidx = 0;
1024         sz *= 10;
1025
1026         while(sz >= 10240 && unitstr[uidx + 1]) {
1027                 sz /= 1024;
1028                 ++uidx;
1029         }
1030         sprintf(str, "%ld.%ld %s", sz / 10, sz % 10, unitstr[uidx]);
1031         return str;
1032 }