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