extern "C" so that I can also use c++
[vkrt] / src / vk.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "vk.h"
7
8 /* static variables */
9
10 static VkViewport viewport;
11 static VkRect2D scissor;
12 static VkPipelineCache pipeline_cache;
13
14 /* when I extend the program to use more than one buffers
15  * I might need to store them in this list and access it
16  * using multiple threads
17  *
18  * man realloc
19  */
20 #if 0
21 static VkCommandBuffer *command_buffers;
22 static uint32_t num_command_buffers;
23 #endif
24
25 /* static functions */
26
27 static VkSampleCountFlagBits
28 get_num_samples(uint32_t num_samples)
29 {
30     switch(num_samples) {
31     case 64:
32         return VK_SAMPLE_COUNT_64_BIT;
33     case 32:
34         return VK_SAMPLE_COUNT_32_BIT;
35     case 16:
36         return VK_SAMPLE_COUNT_16_BIT;
37     case 8:
38         return VK_SAMPLE_COUNT_8_BIT;
39     case 4:
40         return VK_SAMPLE_COUNT_4_BIT;
41     case 2:
42         return VK_SAMPLE_COUNT_2_BIT;
43     case 1:
44         break;
45     default:
46         fprintf(stderr, "Invalid number of samples in VkSampleCountFlagBits. Using one sample.\n");
47         break;
48     }
49     return VK_SAMPLE_COUNT_1_BIT;
50 }
51
52 static VkAccessFlagBits
53 get_access_mask(const VkImageLayout layout)
54 {
55     /* dstAccessMask of barriers must be supported from the pipeline
56      * stage, see also access scopes and this table:
57      * https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-access-types-supported
58      */
59     switch (layout) {
60     case VK_IMAGE_LAYOUT_UNDEFINED:
61         return 0;
62     case VK_IMAGE_LAYOUT_GENERAL:
63         return VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
64     case VK_IMAGE_LAYOUT_PREINITIALIZED:
65         return VK_ACCESS_HOST_WRITE_BIT;
66     case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
67         return VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
68                VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
69     case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
70         return VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
71     case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
72         return VK_ACCESS_TRANSFER_READ_BIT;
73     case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
74         return VK_ACCESS_TRANSFER_WRITE_BIT;
75     case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
76         return 0;
77     default:
78         return 0;
79     };
80
81     return 0;
82 }
83
84 static void
85 enable_validation_layers(VkInstanceCreateInfo *info)
86 {
87     int i;
88     uint32_t num_layers;
89     VkLayerProperties *layers;
90     static const char *layer_names[] = {
91         "VK_LAYER_KHRONOS_validation",
92     };
93
94     vkEnumerateInstanceLayerProperties(&num_layers, 0);
95     layers = alloca(num_layers * sizeof *layers);
96     vkEnumerateInstanceLayerProperties(&num_layers, layers);
97
98     if (num_layers) {
99         printf("Available validation layers:\n");
100         for(i = 0; i < (int)num_layers; i++) {
101             printf(" %s\n", layers[i].layerName);
102         }
103
104         info->ppEnabledLayerNames = layer_names;
105         info->enabledLayerCount = sizeof layer_names / sizeof *layer_names;
106     } else {
107         fprintf(stderr, "Vulkan validation layers not found.\n");
108     }
109 }
110
111 static void
112 enable_extensions(VkInstanceCreateInfo *info)
113 {
114     static const char *ext_names[] = {
115         "VK_KHR_xcb_surface",
116         "VK_KHR_surface"
117     };
118
119     uint32_t num_extensions;
120     VkExtensionProperties *extensions;
121     int i;
122
123     vkEnumerateInstanceExtensionProperties(0, &num_extensions, 0);
124     if (!num_extensions) {
125         fprintf(stderr, "No instance extensions found.\n");
126         return;
127     }
128
129     extensions = alloca(num_extensions * sizeof *extensions);
130     vkEnumerateInstanceExtensionProperties(0, &num_extensions, extensions);
131
132     printf("Available extensions:\n");
133     for (i = 0; i < num_extensions; i++) {
134        printf(" %s\n", extensions[i].extensionName);
135     }
136
137     info->ppEnabledExtensionNames = ext_names;
138     info->enabledExtensionCount = ARRAY_SIZE(ext_names);
139 }
140
141 static VkInstance
142 create_instance(bool enable_layers)
143 {
144     VkApplicationInfo app_info;
145     VkInstanceCreateInfo inst_info;
146     VkInstance inst;
147
148     /* VkApplicationInfo */
149     memset(&app_info, 0, sizeof app_info);
150     app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
151     app_info.pApplicationName = "vktest";
152     app_info.apiVersion = VK_API_VERSION_1_1;
153
154     /* VkInstanceCreateInfo */
155     memset(&inst_info, 0, sizeof inst_info);
156     inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
157     inst_info.pApplicationInfo = &app_info;
158
159     enable_extensions(&inst_info);
160     if (enable_layers) {
161         enable_validation_layers(&inst_info);
162     }
163
164     if (vkCreateInstance(&inst_info, 0, &inst) != VK_SUCCESS)
165         return 0;
166
167     return inst;
168 }
169
170 static VkPhysicalDevice
171 select_physical_device(VkInstance inst)
172 {
173     VkResult res = VK_SUCCESS;
174     uint32_t dev_count = 0;
175     VkPhysicalDevice *pdevices;
176     VkPhysicalDevice pdevice0;
177
178     if ((res =
179          vkEnumeratePhysicalDevices(inst, &dev_count, 0)) != VK_SUCCESS)
180         return 0;
181
182     pdevices = malloc(dev_count * sizeof(VkPhysicalDevice));
183     if (vkEnumeratePhysicalDevices(inst, &dev_count, pdevices) !=
184         VK_SUCCESS)
185         return 0;
186
187     pdevice0 = pdevices[0];
188     free(pdevices);
189
190     return pdevice0;
191 }
192
193 static VkDevice
194 create_device(struct vk_ctx *ctx, VkPhysicalDevice pdev)
195 {
196     const char *deviceExtensions[] = { "VK_KHR_swapchain" };
197     VkDeviceQueueCreateInfo dev_queue_info;
198     VkDeviceCreateInfo dev_info;
199     VkDevice dev;
200     uint32_t prop_count;
201     VkQueueFamilyProperties *fam_props;
202     uint32_t i;
203     float qprio = 0;
204
205     ctx->qfam_idx = -1;
206     vkGetPhysicalDeviceQueueFamilyProperties(pdev, &prop_count, 0);
207     if (prop_count < 0) {
208         fprintf(stderr, "Invalid queue family properties.\n");
209         return 0;
210     }
211
212     fam_props = malloc(prop_count * sizeof *fam_props);
213     vkGetPhysicalDeviceQueueFamilyProperties(pdev, &prop_count, fam_props);
214
215     for (i = 0; i < prop_count; i++) {
216         if (fam_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
217             ctx->qfam_idx = i;
218             break;
219         }
220     }
221     free(fam_props);
222
223     memset(&dev_queue_info, 0, sizeof dev_queue_info);
224     dev_queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
225     dev_queue_info.queueFamilyIndex = ctx->qfam_idx;
226     dev_queue_info.queueCount = 1;
227     dev_queue_info.pQueuePriorities = &qprio;
228
229     memset(&dev_info, 0, sizeof dev_info);
230     dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
231     dev_info.queueCreateInfoCount = 1;
232     dev_info.pQueueCreateInfos = &dev_queue_info;
233     dev_info.enabledExtensionCount = ARRAY_SIZE(deviceExtensions);
234     dev_info.ppEnabledExtensionNames = deviceExtensions;
235
236     if (vkCreateDevice(pdev, &dev_info, 0, &dev) != VK_SUCCESS)
237         return 0;
238
239     return dev;
240 }
241
242 static void
243 fill_uuid(VkPhysicalDevice pdev, uint8_t *deviceUUID, uint8_t *driverUUID)
244 {
245     VkPhysicalDeviceIDProperties devProp;
246     VkPhysicalDeviceProperties2 prop2;
247
248     memset(&devProp, 0, sizeof devProp);
249     devProp.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
250
251     memset(&prop2, 0, sizeof prop2);
252     prop2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
253     prop2.pNext = &devProp;
254
255     vkGetPhysicalDeviceProperties2(pdev, &prop2);
256     memcpy(deviceUUID, devProp.deviceUUID, VK_UUID_SIZE);
257     memcpy(driverUUID, devProp.driverUUID, VK_UUID_SIZE);
258 }
259
260 static VkCommandPool
261 create_cmd_pool(struct vk_ctx *ctx)
262 {
263     VkCommandPoolCreateInfo cmd_pool_info;
264     VkCommandPool cmd_pool;
265
266     memset(&cmd_pool_info, 0, sizeof cmd_pool_info);
267     cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
268     cmd_pool_info.queueFamilyIndex = ctx->qfam_idx;
269     cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
270
271     if (vkCreateCommandPool(ctx->dev, &cmd_pool_info, 0, &cmd_pool) != VK_SUCCESS)
272         return 0;
273
274     return cmd_pool;
275 }
276
277 static VkPipelineCache
278 create_pipeline_cache(struct vk_ctx *ctx)
279 {
280     VkPipelineCacheCreateInfo pc_info;
281     VkPipelineCache pcache;
282
283     memset(&pc_info, 0, sizeof pc_info);
284     pc_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
285
286     if (vkCreatePipelineCache(ctx->dev, &pc_info, 0, &pcache) != VK_SUCCESS) {
287         fprintf(stderr, "Failed to create a pipeline cache.\n");
288         return VK_NULL_HANDLE;
289     }
290
291     return pcache;
292 }
293
294 static VkRenderPass
295 create_renderpass(struct vk_ctx *ctx,
296                   uint32_t num_color_atts,
297                   struct vk_attachment *color_atts,
298                   struct vk_attachment *depth_att)
299 {
300     VkAttachmentDescription *att_dsc;
301     VkAttachmentReference *att_rfc;
302
303     /* one subpass for the moment: */
304     VkSubpassDescription subpass_dsc[1];
305     VkRenderPassCreateInfo rpass_info;
306
307     int i;
308     uint32_t num_atts = num_color_atts + 1;
309     bool has_layout = depth_att->props.in_layout !=
310                       VK_IMAGE_LAYOUT_UNDEFINED;
311
312     att_dsc = malloc(num_atts * sizeof att_dsc[0]);
313     att_rfc = malloc(num_atts * sizeof att_rfc[0]);
314
315     memset(att_dsc, 0, num_atts * sizeof att_dsc[0]);
316     memset(att_rfc, 0, num_atts * sizeof att_rfc[0]);
317
318     /* color attachments description (we can have many) */
319     for (i = 0; i < num_color_atts; i++) {
320         att_dsc[i].samples = get_num_samples(color_atts[i].props.num_samples);
321         att_dsc[i].initialLayout = color_atts[i].props.in_layout;
322         att_dsc[i].finalLayout = color_atts[i].props.end_layout;
323         att_dsc[i].format = color_atts[i].props.format;
324
325         att_dsc[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
326         att_dsc[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
327         att_dsc[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
328         att_dsc[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
329
330         att_rfc[i].attachment = i;
331         att_rfc[i].layout = color_atts[i].props.tiling != VK_IMAGE_TILING_OPTIMAL ?
332                             VK_IMAGE_LAYOUT_GENERAL :
333                             VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
334
335     }
336
337     /* depth attachment description (we can have only one) */
338     att_dsc[num_color_atts].samples = get_num_samples(depth_att->props.num_samples);
339     att_dsc[num_color_atts].initialLayout = depth_att->props.in_layout;
340     att_dsc[num_color_atts].finalLayout = depth_att->props.end_layout;
341     att_dsc[num_color_atts].format = depth_att->props.format;
342     /* we might want to reuse the depth buffer when it's filled */
343     att_dsc[num_color_atts].loadOp = has_layout ?
344                                VK_ATTACHMENT_LOAD_OP_LOAD :
345                                VK_ATTACHMENT_LOAD_OP_CLEAR;
346     att_dsc[num_color_atts].stencilLoadOp = has_layout ?
347                                       VK_ATTACHMENT_LOAD_OP_LOAD :
348                                       VK_ATTACHMENT_LOAD_OP_CLEAR;
349     att_dsc[num_color_atts].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
350     att_rfc[num_color_atts].layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
351     att_rfc[num_color_atts].attachment = num_color_atts;
352
353     /* VkSubpassDescription */
354     memset(&subpass_dsc, 0, sizeof subpass_dsc);
355     subpass_dsc[0].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
356     subpass_dsc[0].colorAttachmentCount = num_color_atts;
357     subpass_dsc[0].pColorAttachments = &att_rfc[0];
358     subpass_dsc[0].pDepthStencilAttachment = &att_rfc[num_color_atts];
359
360     /* VkRenderPassCreateInfo */
361     memset(&rpass_info, 0, sizeof rpass_info);
362     rpass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
363     rpass_info.attachmentCount = num_atts;
364     rpass_info.pAttachments = att_dsc;
365     rpass_info.subpassCount = 1;
366     rpass_info.pSubpasses = subpass_dsc;
367
368     VkRenderPass rpass;
369     if (vkCreateRenderPass(ctx->dev, &rpass_info, 0, &rpass) != VK_SUCCESS) {
370         fprintf(stderr, "Failed to create renderpass.\n");
371         rpass = VK_NULL_HANDLE;
372     }
373
374     free(att_dsc);
375     free(att_rfc);
376
377     return rpass;
378 }
379
380 static inline VkImageType
381 get_image_type(uint32_t h, uint32_t d)
382 {
383     if (h == 1)
384         return VK_IMAGE_TYPE_1D;
385
386     if (d > 1)
387         return VK_IMAGE_TYPE_3D;
388
389     return VK_IMAGE_TYPE_2D;
390 }
391
392 #if 0
393 static VkImageViewType
394 get_image_view_type(struct vk_att_props *props)
395 {
396     VkImageType type = get_image_type(props->h, props->depth);
397     switch(type) {
398         case VK_IMAGE_TYPE_1D:
399             return props->num_layers > 1 ?
400                 VK_IMAGE_VIEW_TYPE_1D_ARRAY :
401                 VK_IMAGE_VIEW_TYPE_1D;
402         case VK_IMAGE_TYPE_2D:
403             if (props->num_layers == 1)
404                 return VK_IMAGE_VIEW_TYPE_2D;
405             if (props->num_layers == 6)
406                 return VK_IMAGE_VIEW_TYPE_CUBE;
407             if (props->num_layers % 6 == 0)
408                 return VK_IMAGE_VIEW_TYPE_CUBE_ARRAY;
409             if (props->num_layers > 1)
410                 return VK_IMAGE_VIEW_TYPE_2D_ARRAY;
411         case VK_IMAGE_TYPE_3D:
412             if (props->num_layers == 1)
413                 return VK_IMAGE_VIEW_TYPE_3D;
414             if ((props->num_layers == 1) &&
415                 (props->num_levels == 1))
416                 return VK_IMAGE_VIEW_TYPE_2D;
417             if ((props->num_levels == 1) &&
418                 (props->num_layers > 1))
419                 return VK_IMAGE_VIEW_TYPE_2D_ARRAY;
420         default:
421             return VK_IMAGE_VIEW_TYPE_2D;
422     }
423 }
424 #endif
425
426 static VkImageAspectFlagBits
427 get_aspect_from_depth_format(VkFormat depth_format)
428 {
429     switch (depth_format) {
430     case VK_FORMAT_D16_UNORM:
431     case VK_FORMAT_X8_D24_UNORM_PACK32:
432     case VK_FORMAT_D32_SFLOAT:
433         return VK_IMAGE_ASPECT_DEPTH_BIT;
434     case VK_FORMAT_S8_UINT:
435         return VK_IMAGE_ASPECT_STENCIL_BIT;
436     case VK_FORMAT_D16_UNORM_S8_UINT:
437     case VK_FORMAT_D24_UNORM_S8_UINT:
438     case VK_FORMAT_D32_SFLOAT_S8_UINT:
439         return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
440     default:
441         break;
442     }
443     return 0;
444 }
445
446 static VkPipelineStageFlags
447 get_pipeline_stage_flags(const VkImageLayout layout)
448 {
449     switch (layout) {
450     case VK_IMAGE_LAYOUT_UNDEFINED:
451         return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
452     case VK_IMAGE_LAYOUT_GENERAL:
453         return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
454     case VK_IMAGE_LAYOUT_PREINITIALIZED:
455         return VK_PIPELINE_STAGE_HOST_BIT;
456     case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
457     case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
458         return VK_PIPELINE_STAGE_TRANSFER_BIT;
459     case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
460         return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
461     case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
462         return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
463                VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
464     case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
465         return VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
466     default:
467         break;
468     }
469     return 0;
470 }
471
472 static bool
473 create_image_view(struct vk_ctx *ctx,
474                   VkImage image,
475                   VkImageViewType view_type,
476                   VkFormat format,
477                   VkImageSubresourceRange sr,
478                   bool is_swapchain,
479                   VkImageView *image_view)
480 {
481     VkImageViewCreateInfo info;
482
483     memset(&info, 0, sizeof info);
484     info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
485     info.image = image;
486     info.viewType = view_type;
487     info.viewType = VK_IMAGE_VIEW_TYPE_2D;
488     info.format = format;
489     info.subresourceRange = sr;
490
491     if (is_swapchain) {
492         info.components.r = VK_COMPONENT_SWIZZLE_R;
493         info.components.g = VK_COMPONENT_SWIZZLE_G;
494         info.components.b = VK_COMPONENT_SWIZZLE_B;
495         info.components.a = VK_COMPONENT_SWIZZLE_A;
496     }
497
498     if (vkCreateImageView(ctx->dev, &info, 0, image_view) != VK_SUCCESS) {
499         fprintf(stderr, "Failed to create image view.\n");
500         image_view = VK_NULL_HANDLE;
501
502         return false;
503     }
504
505     return true;
506 }
507
508 static bool
509 create_attachment_views(struct vk_ctx *ctx, int num_color_att,
510                         struct vk_attachment *color_att,
511                         struct vk_attachment *depth_att)
512 {
513     VkImageSubresourceRange sr;
514     int i;
515
516     /* depth attachments */
517     memset(&sr, 0, sizeof sr);
518     sr.aspectMask = get_aspect_from_depth_format(depth_att->props.format);
519     sr.baseMipLevel = 0;
520     sr.levelCount = 1;
521     sr.baseArrayLayer = 0;
522     sr.layerCount = 1;
523
524     create_image_view(ctx, depth_att->obj.img, VK_IMAGE_VIEW_TYPE_2D,
525                       depth_att->props.format, sr, false,
526                       &depth_att->obj.img_view);
527
528     memset(&sr, 0, sizeof sr);
529     sr.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
530
531     for (i = 0; i < num_color_att; i++) {
532         /* FIXME: in case of mipmaps */
533         sr.baseMipLevel = 0;
534         sr.levelCount = color_att[i].props.num_levels;
535         sr.baseArrayLayer = 0;
536         sr.layerCount = color_att[i].props.num_layers;
537
538         create_image_view(ctx, color_att[i].obj.img, VK_IMAGE_VIEW_TYPE_2D,
539                           color_att[i].props.format, sr, color_att[i].props.is_swapchain,
540                           &color_att[i].obj.img_view);
541     }
542
543     return true;
544 }
545
546 static void
547 create_framebuffer(struct vk_ctx *ctx,
548                    int width, int height,
549                    int num_color_atts,
550                    struct vk_attachment *color_att,
551                    struct vk_attachment *depth_att,
552                    struct vk_renderer *renderer)
553 {
554     VkFramebufferCreateInfo fb_info;
555     VkImageView *atts;
556     int i;
557     int num_atts = num_color_atts + 1;
558
559     atts = malloc(num_atts * sizeof atts[0]);
560
561     for (i = 0; i < num_color_atts; i++) {
562         atts[i] = color_att[i].obj.img_view;
563     }
564     atts[num_color_atts] = depth_att->obj.img_view;
565
566     memset(&fb_info, 0, sizeof fb_info);
567     fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
568     fb_info.renderPass = renderer->renderpass;
569     fb_info.width = width;
570     fb_info.height = height;
571     fb_info.layers = 1;
572     fb_info.attachmentCount = num_atts;
573     fb_info.pAttachments = atts;
574
575     if (vkCreateFramebuffer(ctx->dev, &fb_info, 0, &renderer->fb) != VK_SUCCESS)
576         goto fail;
577
578     free(atts);
579     return;
580
581 fail:
582     fprintf(stderr, "Failed to create framebuffer.\n");
583     free(atts);
584     renderer->fb = VK_NULL_HANDLE;
585 }
586
587 static VkShaderModule
588 create_shader_module(struct vk_ctx *ctx,
589              const char *src,
590              unsigned int size)
591 {
592     VkShaderModuleCreateInfo sm_info;
593     VkShaderModule sm;
594
595     /* VkShaderModuleCreateInfo */
596     memset(&sm_info, 0, sizeof sm_info);
597     sm_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
598     sm_info.codeSize = size;
599     sm_info.pCode = (void*)src;
600
601     if (vkCreateShaderModule(ctx->dev, &sm_info, 0, &sm) != VK_SUCCESS) {
602         fprintf(stderr, "Failed to create shader module.\n");
603         sm = VK_NULL_HANDLE;
604     }
605
606     return sm;
607 }
608
609 static bool
610 create_graphics_pipeline(struct vk_ctx *ctx,
611                          uint32_t width,
612                          uint32_t height,
613                          uint32_t num_samples,
614                          uint32_t num_color_atts,
615                          bool enable_depth,
616                          bool enable_stencil,
617                          struct vk_renderer *renderer)
618 {
619     VkVertexInputBindingDescription vert_bind_dsc[1];
620     VkVertexInputAttributeDescription vert_att_dsc[1];
621
622     VkPipelineColorBlendAttachmentState *cb_att_state;
623     VkPipelineVertexInputStateCreateInfo vert_input_info;
624     VkPipelineInputAssemblyStateCreateInfo asm_info;
625     VkPipelineViewportStateCreateInfo viewport_info;
626     VkPipelineRasterizationStateCreateInfo rs_info;
627     VkPipelineMultisampleStateCreateInfo ms_info;
628     VkPipelineDepthStencilStateCreateInfo ds_info;
629     VkPipelineColorBlendStateCreateInfo cb_info;
630     VkPipelineShaderStageCreateInfo sdr_stages[2];
631     VkPipelineLayoutCreateInfo layout_info;
632     VkGraphicsPipelineCreateInfo pipeline_info;
633     VkFormat format;
634     VkFormatProperties fmt_props;
635     VkPushConstantRange pc_range[1];
636
637     VkStencilOpState front;
638     VkStencilOpState back;
639     int i;
640     VkPipelineLayout pipeline_layout;
641     uint32_t stride;
642
643     /* format of vertex attributes:
644      * we have 2D vectors so we need a RG format:
645      * R for x, G for y
646      * the stride (distance between 2 consecutive elements)
647      * must be 8 because we use 32 bit floats and
648      * 32bits = 8bytes */
649     format = VK_FORMAT_R32G32_SFLOAT;
650     vkGetPhysicalDeviceFormatProperties(ctx->pdev, format, &fmt_props);
651     assert(fmt_props.bufferFeatures & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT);
652     stride = 8;
653
654     /* VkVertexInputAttributeDescription */
655     memset(&vert_att_dsc, 0, sizeof vert_att_dsc);
656     vert_att_dsc[0].location = 0;
657     vert_att_dsc[0].binding = 0;
658     vert_att_dsc[0].format = format; /* see comment */
659     vert_att_dsc[0].offset = 0;
660
661     /* VkVertexInputBindingDescription */
662     memset(&vert_bind_dsc, 0, sizeof vert_bind_dsc);
663     vert_bind_dsc[0].binding = 0;
664     vert_bind_dsc[0].stride = stride;
665     vert_bind_dsc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
666
667     /* If using vbo, we have setup vertex_info in the renderer. */
668     bool use_vbo = renderer->vertex_info.num_verts > 0;
669
670     /* VkPipelineVertexInputStateCreateInfo */
671     memset(&vert_input_info, 0, sizeof vert_input_info);
672     vert_input_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
673     vert_input_info.vertexBindingDescriptionCount = use_vbo ? 1 : 0;
674     vert_input_info.pVertexBindingDescriptions = vert_bind_dsc;
675     vert_input_info.vertexAttributeDescriptionCount = use_vbo ? 1 : 0;
676     vert_input_info.pVertexAttributeDescriptions = vert_att_dsc;
677
678     /* VkPipelineInputAssemblyStateCreateInfo */
679     memset(&asm_info, 0, sizeof asm_info);
680     asm_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
681     asm_info.topology = renderer->vertex_info.topology ?
682                         renderer->vertex_info.topology
683                         : VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
684     asm_info.primitiveRestartEnable = false;
685
686     /* VkViewport */
687     viewport.x = viewport.y = 0;
688     viewport.width = width;
689     viewport.height = height;
690     viewport.minDepth = 0;
691     viewport.maxDepth = 1;
692
693     /* VkRect2D scissor */
694     scissor.offset.x = scissor.offset.y = 0;
695     scissor.extent.width = width;
696     scissor.extent.height = height;
697
698     /* VkPipelineViewportStateCreateInfo */
699     memset(&viewport_info, 0, sizeof viewport_info);
700     viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
701     viewport_info.viewportCount = 1;
702     viewport_info.pViewports = &viewport;
703     viewport_info.scissorCount = 1;
704     viewport_info.pScissors = &scissor;
705
706     /* VkPipelineRasterizationStateCreateInfo */
707     memset(&rs_info, 0, sizeof rs_info);
708     rs_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
709     rs_info.polygonMode = VK_POLYGON_MODE_FILL;
710     rs_info.cullMode = VK_CULL_MODE_NONE;
711     rs_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
712     rs_info.lineWidth = 1.0;
713
714     /* VkPipelineMultisampleStateCreateInfo */
715     memset(&ms_info, 0, sizeof ms_info);
716     ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
717     ms_info.rasterizationSamples = get_num_samples(num_samples);
718
719     /* VkStencilOpState */
720     /* The default values for ES are taken by Topi Pohjolainen's code */
721     /* defaults in OpenGL ES 3.1 */
722     memset(&front, 0, sizeof front);
723     front.compareMask = ~0;
724     front.writeMask = ~0;
725     front.reference = 0;
726
727     memset(&back, 0, sizeof back);
728     back.compareMask = ~0;
729     back.writeMask = ~0;
730     back.reference = 0;
731
732     /* VkPipelineDepthStencilStateCreateInfo */
733     memset(&ds_info, 0, sizeof ds_info);
734     ds_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
735     ds_info.front = front;
736     ds_info.back = back;
737     /* defaults in OpenGL ES 3.1 */
738     ds_info.minDepthBounds = 0;
739     ds_info.maxDepthBounds = 1;
740     /* z buffer, stencil buffer */
741     if (enable_depth) {
742         ds_info.depthTestEnable = VK_TRUE;
743         ds_info.depthWriteEnable = VK_TRUE;
744         ds_info.depthCompareOp = VK_COMPARE_OP_LESS;
745     }
746     if (enable_stencil) {
747         ds_info.stencilTestEnable = VK_TRUE;
748         ds_info.depthTestEnable = VK_FALSE;
749         ds_info.depthWriteEnable = VK_TRUE;
750     }
751
752     /* we only care about the passOp here */
753     ds_info.back.compareOp = VK_COMPARE_OP_ALWAYS;
754     ds_info.back.failOp = VK_STENCIL_OP_REPLACE;
755     ds_info.back.depthFailOp = VK_STENCIL_OP_REPLACE;
756     ds_info.back.passOp = VK_STENCIL_OP_REPLACE;
757     ds_info.back.compareMask = 0xffffffff;
758     ds_info.back.writeMask = 0xffffffff;
759     ds_info.back.reference = 1;
760     ds_info.front = ds_info.back;
761
762     /* VkPipelineColorBlendAttachmentState */
763     cb_att_state = malloc(num_color_atts * sizeof cb_att_state[0]);
764     if (!cb_att_state) {
765         fprintf(stderr, "Failed to allocate color blend attachment state for each attachment.\n");
766         goto fail;
767     }
768     memset(cb_att_state, 0, num_color_atts * sizeof cb_att_state[0]);
769     for (i = 0; i < num_color_atts; i++) {
770         cb_att_state[i].colorWriteMask = (VK_COLOR_COMPONENT_R_BIT |
771                                           VK_COLOR_COMPONENT_G_BIT |
772                                           VK_COLOR_COMPONENT_B_BIT |
773                                           VK_COLOR_COMPONENT_A_BIT);
774     }
775
776     /* VkPipelineColorBlendStateCreateInfo */
777     memset(&cb_info, 0, sizeof cb_info);
778     cb_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
779     cb_info.attachmentCount = num_color_atts;
780     cb_info.pAttachments = cb_att_state;
781     /* default in ES 3.1 */
782     for (i = 0; i < 4; i++) {
783         cb_info.blendConstants[i] = 0.0f;
784     }
785
786     /* VkPipelineShaderStageCreateInfo */
787     memset(sdr_stages, 0, 2 * sizeof sdr_stages[0]);
788
789     sdr_stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
790     sdr_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
791     sdr_stages[0].module = renderer->vs;
792     sdr_stages[0].pName = "main";
793
794     sdr_stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
795     sdr_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
796     sdr_stages[1].module = renderer->fs;
797     sdr_stages[1].pName = "main";
798
799     /* VkPushConstantRange */
800     memset(pc_range, 0, sizeof pc_range[0]);
801     pc_range[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
802     pc_range[0].size = sizeof (struct vk_dims); /* w, h */
803
804     /* VkPipelineLayoutCreateInfo */
805     memset(&layout_info, 0, sizeof layout_info);
806     layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
807     layout_info.pushConstantRangeCount = 1;
808     layout_info.pPushConstantRanges = pc_range;
809
810     if (vkCreatePipelineLayout(ctx->dev, &layout_info, 0, &pipeline_layout) != VK_SUCCESS) {
811         fprintf(stderr, "Failed to create pipeline layout\n");
812         renderer->pipeline = VK_NULL_HANDLE;
813         goto fail;
814     }
815
816     renderer->pipeline_layout = pipeline_layout;
817
818     /* VkGraphicsPipelineCreateInfo */
819     memset(&pipeline_info, 0, sizeof pipeline_info);
820     pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
821     pipeline_info.layout = pipeline_layout;
822     pipeline_info.renderPass = renderer->renderpass;
823     pipeline_info.pVertexInputState = &vert_input_info;
824     pipeline_info.pInputAssemblyState = &asm_info;
825     pipeline_info.pViewportState = &viewport_info;
826     pipeline_info.pRasterizationState = &rs_info;
827     pipeline_info.pMultisampleState = &ms_info;
828     pipeline_info.pDepthStencilState = &ds_info;
829     pipeline_info.pColorBlendState = &cb_info;
830     pipeline_info.stageCount = 2;
831     pipeline_info.pStages = sdr_stages;
832
833     if (vkCreateGraphicsPipelines(ctx->dev, 0, 1,
834                                   &pipeline_info, 0,
835                                   &renderer->pipeline) != VK_SUCCESS) {
836         fprintf(stderr, "Failed to create graphics pipeline.\n");
837         renderer->pipeline = VK_NULL_HANDLE;
838         goto fail;
839     }
840
841     free(cb_att_state);
842     return true;
843
844 fail:
845     free(cb_att_state);
846     return false;
847 }
848
849 static uint32_t
850 get_memory_type_idx(VkPhysicalDevice pdev,
851             const VkMemoryRequirements *mem_reqs,
852             VkMemoryPropertyFlagBits prop_flags)
853 {
854     VkPhysicalDeviceMemoryProperties pdev_mem_props;
855     uint32_t i;
856
857     vkGetPhysicalDeviceMemoryProperties(pdev, &pdev_mem_props);
858
859     for (i = 0; i < pdev_mem_props.memoryTypeCount; i++) {
860         const VkMemoryType *type = &pdev_mem_props.memoryTypes[i];
861
862         if ((mem_reqs->memoryTypeBits & (1 << i)) &&
863             (type->propertyFlags & prop_flags) == prop_flags) {
864             return i;
865             break;
866         }
867     }
868     return UINT32_MAX;
869 }
870
871 static VkDeviceMemory
872 alloc_memory(struct vk_ctx *ctx,
873              bool is_external,
874              const VkMemoryRequirements *mem_reqs,
875              VkImage image,
876              VkBuffer buffer,
877              VkMemoryPropertyFlagBits prop_flags)
878 {
879     VkExportMemoryAllocateInfo exp_mem_info;
880     VkMemoryAllocateInfo mem_alloc_info;
881     VkDeviceMemory mem;
882     VkMemoryDedicatedAllocateInfoKHR ded_info;
883
884     if (is_external) {
885         memset(&exp_mem_info, 0, sizeof exp_mem_info);
886         exp_mem_info.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
887         exp_mem_info.handleTypes =
888             VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
889     }
890
891     memset(&mem_alloc_info, 0, sizeof mem_alloc_info);
892     mem_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
893     mem_alloc_info.pNext = is_external ? &exp_mem_info : VK_NULL_HANDLE;
894     mem_alloc_info.allocationSize = mem_reqs->size;
895     mem_alloc_info.memoryTypeIndex =
896         get_memory_type_idx(ctx->pdev, mem_reqs, prop_flags);
897
898     if (mem_alloc_info.memoryTypeIndex == UINT32_MAX) {
899         fprintf(stderr, "No suitable memory type index found.\n");
900         return 0;
901     }
902
903     if (image || buffer) {
904         memset(&ded_info, 0, sizeof ded_info);
905         ded_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
906         ded_info.image = image;
907         ded_info.buffer = buffer;
908
909         exp_mem_info.pNext = &ded_info;
910     }
911
912     if (vkAllocateMemory(ctx->dev, &mem_alloc_info, 0, &mem) !=
913         VK_SUCCESS)
914         return 0;
915
916     return mem;
917 }
918
919 static bool
920 alloc_image_memory(struct vk_ctx *ctx, bool is_external, struct vk_image_obj *img_obj)
921 {
922     VkMemoryDedicatedRequirements ded_reqs;
923     VkImageMemoryRequirementsInfo2 req_info2;
924     VkMemoryRequirements2 mem_reqs2;
925
926     memset(&ded_reqs, 0, sizeof ded_reqs);
927     ded_reqs.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS;
928
929     /* VkImageMemoryRequirementsInfo2 */
930     memset(&req_info2, 0, sizeof req_info2);
931     req_info2.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2;
932     req_info2.image = img_obj->img;
933
934     /* VkMemoryRequirements2 */
935     memset(&mem_reqs2, 0, sizeof mem_reqs2);
936     mem_reqs2.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2;
937     mem_reqs2.pNext = &ded_reqs;
938
939     vkGetImageMemoryRequirements2(ctx->dev, &req_info2, &mem_reqs2);
940     img_obj->mobj.mem = alloc_memory(ctx,
941                                      is_external,
942                                      &mem_reqs2.memoryRequirements,
943                                      ded_reqs.requiresDedicatedAllocation ?
944                                         img_obj->img : VK_NULL_HANDLE,
945                                      VK_NULL_HANDLE,
946                                      mem_reqs2.memoryRequirements.memoryTypeBits &
947                                      VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
948
949     img_obj->mobj.mem_sz = mem_reqs2.memoryRequirements.size;
950     img_obj->mobj.dedicated = ded_reqs.requiresDedicatedAllocation;
951     if (img_obj->mobj.mem == VK_NULL_HANDLE) {
952         fprintf(stderr, "Failed to allocate image memory.\n");
953         return false;
954     }
955
956     if (vkBindImageMemory(ctx->dev, img_obj->img, img_obj->mobj.mem, 0) !=
957             VK_SUCCESS) {
958         fprintf(stderr, "Failed to bind image memory.\n");
959         return false;
960     }
961
962     return true;
963 }
964
965 static bool
966 are_props_supported(struct vk_ctx *ctx, struct vk_att_props *props)
967 {
968     VkPhysicalDeviceExternalImageFormatInfo ext_img_fmt_info;
969     VkExternalImageFormatProperties ext_img_fmt_props;
970
971     int i;
972     VkPhysicalDeviceImageFormatInfo2 img_fmt_info;
973     VkImageFormatProperties2 img_fmt_props;
974
975     VkImageUsageFlagBits all_flags[] = {
976         VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
977         VK_IMAGE_USAGE_TRANSFER_DST_BIT,
978         VK_IMAGE_USAGE_SAMPLED_BIT,
979         VK_IMAGE_USAGE_STORAGE_BIT,
980         VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
981         VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
982         VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT,
983         /* Shouldn't be used together with COLOR, DEPTH_STENCIL
984          * attachment bits:
985          * VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT,
986          * Provided by VK_EXT_fragment_density_map
987          * VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT,
988          * Provided by VK_NV_shading_rate_image
989          * VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV,
990          * Provided by VK_KHR_fragment_shading_rate
991          * VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR,
992          */
993     };
994     VkImageUsageFlagBits flags = 0;
995
996     VkExternalMemoryFeatureFlagBits export_feature_flags = props->need_export ?
997         VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT : 0;
998     VkExternalMemoryHandleTypeFlagBits handle_type = props->need_export ?
999         VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR : 0;
1000
1001     if (props->need_export) {
1002         memset(&ext_img_fmt_info, 0, sizeof ext_img_fmt_info);
1003         ext_img_fmt_info.sType =
1004             VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
1005         ext_img_fmt_info.handleType = handle_type;
1006
1007         memset(&ext_img_fmt_props, 0, sizeof ext_img_fmt_props);
1008         ext_img_fmt_props.sType =
1009             VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES;
1010     }
1011
1012     memset(&img_fmt_props, 0, sizeof img_fmt_props);
1013     img_fmt_props.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1014     img_fmt_props.pNext = props->need_export ? &ext_img_fmt_props : 0;
1015
1016     memset(&img_fmt_info, 0, sizeof img_fmt_info);
1017     img_fmt_info.sType =
1018         VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1019     img_fmt_info.pNext = props->need_export ? &ext_img_fmt_info : 0;
1020     img_fmt_info.format = props->format;
1021     img_fmt_info.type = VK_IMAGE_TYPE_2D;
1022     img_fmt_info.tiling = props->tiling;
1023
1024     for (i = 0; i < ARRAY_SIZE(all_flags); i++) {
1025         img_fmt_info.usage = all_flags[i];
1026         if (vkGetPhysicalDeviceImageFormatProperties2(ctx->pdev,
1027                                                       &img_fmt_info,
1028                                                       &img_fmt_props) == VK_SUCCESS) {
1029             flags |= all_flags[i];
1030         }
1031     }
1032
1033     /* usage can't be null */
1034     if (flags) {
1035         img_fmt_info.usage = flags;
1036     } else {
1037         if (!props->is_swapchain) {
1038             fprintf(stderr, "Unsupported Vulkan format properties: usage.\n");
1039             return false;
1040         }
1041         img_fmt_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1042     }
1043
1044     if (vkGetPhysicalDeviceImageFormatProperties2
1045         (ctx->pdev, &img_fmt_info, &img_fmt_props) != VK_SUCCESS) {
1046         fprintf(stderr,
1047             "Unsupported Vulkan format properties.\n");
1048         return false;
1049     }
1050     props->usage = flags;
1051
1052     if (props->need_export &&
1053         !(ext_img_fmt_props.externalMemoryProperties.externalMemoryFeatures
1054             & export_feature_flags)) {
1055         fprintf(stderr, "Unsupported Vulkan external memory features.\n");
1056         return false;
1057     }
1058
1059     return true;
1060 }
1061
1062 /* static swapchain / surf related functions */
1063
1064 static bool
1065 sc_validate_surface(struct vk_ctx *ctx,
1066                     VkSurfaceKHR surf)
1067 {
1068     VkBool32 supported;
1069     if (!surf) {
1070         fprintf(stderr, "No surface!\n");
1071         return false;
1072     }
1073
1074     if(vkGetPhysicalDeviceSurfaceSupportKHR(ctx->pdev, ctx->qfam_idx, surf, &supported) != VK_SUCCESS) {
1075         fprintf(stderr, "Failed to validate surface.\n");
1076         return false;
1077     }
1078
1079     if (!supported) {
1080         fprintf(stderr, "Invalid surface! Check if the surface with queue family index: %d supports presentation.\n", (int)ctx->qfam_idx);
1081         return false;
1082     }
1083
1084     return true;
1085 }
1086
1087 static bool
1088 sc_select_format(struct vk_ctx *ctx,
1089                  VkSurfaceKHR surf,
1090                  VkSwapchainCreateInfoKHR *s_info)
1091 {
1092     VkSurfaceFormatKHR *formats;
1093     uint32_t num_formats;
1094
1095     if (vkGetPhysicalDeviceSurfaceFormatsKHR(ctx->pdev, surf, &num_formats, 0) != VK_SUCCESS) {
1096         fprintf(stderr, "Failed to get the number of surface formats.\n");
1097         return false;
1098     }
1099
1100     if (!num_formats) {
1101         fprintf(stderr, "No surface formats found.\n");
1102         return false;
1103     }
1104
1105     formats = malloc(num_formats * sizeof *formats);
1106
1107     if (vkGetPhysicalDeviceSurfaceFormatsKHR(ctx->pdev, surf, &num_formats, formats) != VK_SUCCESS) {
1108         fprintf(stderr, "Failed to get the supported surface formats.\n");
1109         return false;
1110     }
1111
1112     if ((num_formats == 1) && (formats[0].format == VK_FORMAT_UNDEFINED)) {
1113         s_info->imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
1114         s_info->imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
1115     } else {
1116         s_info->imageFormat = formats[0].format;
1117         s_info->imageColorSpace = formats[0].colorSpace;
1118     }
1119     free(formats);
1120
1121     return true;
1122 }
1123
1124 static bool
1125 sc_select_supported_present_modes(struct vk_ctx *ctx,
1126                                   VkSurfaceKHR surf,
1127                                   bool has_vsync,
1128                                   VkSwapchainCreateInfoKHR *s_info)
1129 {
1130     VkPresentModeKHR *present_modes;
1131     uint32_t num_present_modes;
1132     int i;
1133
1134     /* find supported present modes */
1135     if (vkGetPhysicalDeviceSurfacePresentModesKHR(ctx->pdev, surf, &num_present_modes, 0) != VK_SUCCESS || !num_present_modes) {
1136         fprintf(stderr, "Failed to get the number of the supported presentation modes.\n");
1137         return false;
1138     }
1139
1140     present_modes = malloc(num_present_modes * sizeof *present_modes);
1141     if (vkGetPhysicalDeviceSurfacePresentModesKHR(ctx->pdev, surf, &num_present_modes, present_modes) != VK_SUCCESS) {
1142         fprintf(stderr, "Failed to get the number of supported presentation modes.\n");
1143         return false;
1144     }
1145     if (vkGetPhysicalDeviceSurfacePresentModesKHR(ctx->pdev, surf, &num_present_modes,
1146                                                   present_modes) != VK_SUCCESS) {
1147         fprintf(stderr, "Failed to get the supported presentation modes.\n");
1148         return false;
1149     }
1150
1151     s_info->presentMode = VK_PRESENT_MODE_FIFO_KHR;
1152     if (!has_vsync) {
1153         for (i = 0; i < num_present_modes; i++) {
1154             if (present_modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) {
1155                 s_info->presentMode = present_modes[i];
1156                 goto success;
1157             }
1158             if (present_modes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR) {
1159                 s_info->presentMode = present_modes[i];
1160                 goto success;
1161             }
1162         }
1163     }
1164
1165 success:
1166     free(present_modes);
1167     return true;
1168 }
1169
1170 /* end of static functions */
1171
1172 /* exposed Vulkan functions */
1173
1174 bool
1175 vk_init_ctx(struct vk_ctx *ctx,
1176             bool enable_layers)
1177 {
1178     if ((ctx->inst = create_instance(enable_layers)) == VK_NULL_HANDLE) {
1179         fprintf(stderr, "Failed to create Vulkan instance.\n");
1180         goto fail;
1181     }
1182
1183     if ((ctx->pdev = select_physical_device(ctx->inst)) == VK_NULL_HANDLE) {
1184         fprintf(stderr, "Failed to find suitable physical device.\n");
1185         goto fail;
1186     }
1187
1188     if ((ctx->dev = create_device(ctx, ctx->pdev)) == VK_NULL_HANDLE) {
1189         fprintf(stderr, "Failed to create Vulkan device.\n");
1190         goto fail;
1191     }
1192
1193     fill_uuid(ctx->pdev, ctx->deviceUUID, ctx->driverUUID);
1194     return true;
1195
1196 fail:
1197     vk_cleanup_ctx(ctx, enable_layers);
1198     return false;
1199 }
1200
1201 bool
1202 vk_init_ctx_for_rendering(struct vk_ctx *ctx,
1203                           bool enable_cache,
1204                           bool enable_layers)
1205 {
1206     if (!vk_init_ctx(ctx, enable_layers)) {
1207         fprintf(stderr, "Failed to initialize Vulkan.\n");
1208         return false;
1209     }
1210
1211     if ((ctx->cmd_pool = create_cmd_pool(ctx)) == VK_NULL_HANDLE) {
1212         fprintf(stderr, "Failed to create command pool.\n");
1213         goto fail;
1214     }
1215
1216     vkGetDeviceQueue(ctx->dev, ctx->qfam_idx, 0, &ctx->queue);
1217     if (!ctx->queue) {
1218         fprintf(stderr, "Failed to get command queue.\n");
1219         goto fail;
1220     }
1221
1222     if (enable_cache) {
1223         if (!(pipeline_cache = create_pipeline_cache(ctx))) {
1224             fprintf(stderr, "Failed to create pipeline cache.\n");
1225             goto fail;
1226         }
1227     }
1228
1229     return true;
1230
1231 fail:
1232     vk_cleanup_ctx(ctx, enable_layers);
1233     return false;
1234 }
1235
1236 void
1237 vk_destroy_cmd_bufs(struct vk_ctx *ctx,
1238                     uint32_t num_buffers,
1239                     VkCommandBuffer *buffers)
1240 {
1241     int i;
1242     for (i = 0; i < num_buffers; i++) {
1243         vkResetCommandBuffer(buffers[i],
1244                              VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
1245     }
1246     vkFreeCommandBuffers(ctx->dev, ctx->cmd_pool, num_buffers, &buffers[i]);
1247 }
1248
1249 void
1250 vk_cleanup_ctx(struct vk_ctx *ctx,
1251                bool enable_layers)
1252 {
1253     if (enable_layers) {
1254         return;
1255     }
1256
1257     if (ctx->cmd_pool != VK_NULL_HANDLE) {
1258         vkResetCommandPool(ctx->dev, ctx->cmd_pool,
1259                            VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT);
1260         vkDestroyCommandPool(ctx->dev, ctx->cmd_pool, 0);
1261         ctx->cmd_pool = VK_NULL_HANDLE;
1262     }
1263
1264     if (pipeline_cache != VK_NULL_HANDLE) {
1265         vkDestroyPipelineCache(ctx->dev, pipeline_cache, 0);
1266         pipeline_cache = VK_NULL_HANDLE;
1267     }
1268
1269     if (ctx->dev != VK_NULL_HANDLE) {
1270         vkDestroyDevice(ctx->dev, 0);
1271         ctx->dev = VK_NULL_HANDLE;
1272     }
1273
1274     if (ctx->inst != VK_NULL_HANDLE) {
1275         vkDestroyInstance(ctx->inst, 0);
1276         ctx->inst = VK_NULL_HANDLE;
1277     }
1278 }
1279
1280 bool
1281 vk_create_image(struct vk_ctx *ctx,
1282                 struct vk_att_props *props,
1283                 struct vk_image_obj *img)
1284 {
1285     VkImageCreateInfo img_info;
1286
1287     memset(&img_info, 0, sizeof img_info);
1288     img_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1289     img_info.pNext = 0; /* do something if external */
1290     img_info.imageType = get_image_type(props->h, props->depth);
1291     img_info.format = props->format;
1292     img_info.extent.width = props->w;
1293     img_info.extent.height = props->h;
1294     img_info.extent.depth = props->depth;
1295     img_info.mipLevels = props->num_levels ? props->num_levels : 1;
1296     img_info.arrayLayers = props->num_layers ?
1297                            props->num_layers : VK_SAMPLE_COUNT_1_BIT;
1298     img_info.samples = get_num_samples(props->num_samples);
1299     img_info.tiling = props->tiling;
1300     img_info.usage = props->usage ?
1301                      props->usage : VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
1302     img_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1303     img_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1304
1305     if (vkCreateImage(ctx->dev, &img_info, 0, &img->img) != VK_SUCCESS)
1306         goto fail;
1307
1308     if(!alloc_image_memory(ctx, props->need_export, img))
1309         goto fail;
1310
1311     return true;
1312
1313 fail:
1314     fprintf(stderr, "Failed to create external image.\n");
1315     vk_destroy_image(ctx, img);
1316     img->img = VK_NULL_HANDLE;
1317     img->mobj.mem = VK_NULL_HANDLE;
1318     return false;
1319 }
1320
1321 void
1322 vk_destroy_image(struct vk_ctx *ctx, struct vk_image_obj *img_obj)
1323 {
1324     if (img_obj->img != VK_NULL_HANDLE) {
1325         vkDestroyImage(ctx->dev, img_obj->img, 0);
1326         img_obj->img = VK_NULL_HANDLE;
1327     }
1328
1329     if (img_obj->mobj.mem != VK_NULL_HANDLE) {
1330         vkFreeMemory(ctx->dev, img_obj->mobj.mem, 0);
1331         img_obj->mobj.mem = VK_NULL_HANDLE;
1332     }
1333 }
1334
1335 bool
1336 vk_create_ext_image(struct vk_ctx *ctx,
1337                     struct vk_att_props *props, struct vk_image_obj *img)
1338 {
1339     VkExternalMemoryImageCreateInfo ext_img_info;
1340     VkImageCreateInfo img_info;
1341
1342     memset(&ext_img_info, 0, sizeof ext_img_info);
1343     ext_img_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
1344     ext_img_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
1345
1346     memset(&img_info, 0, sizeof img_info);
1347     img_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1348     img_info.pNext = &ext_img_info;
1349     img_info.imageType = get_image_type(props->h, props->depth);
1350     img_info.format = props->format;
1351     img_info.extent.width = props->w;
1352     img_info.extent.height = props->h;
1353     img_info.extent.depth = props->depth;
1354     img_info.mipLevels = props->num_levels ? props->num_levels : 1;
1355     img_info.arrayLayers = props->num_layers ? props->num_layers : VK_SAMPLE_COUNT_1_BIT;
1356     img_info.samples = get_num_samples(props->num_samples);
1357     img_info.tiling = props->tiling;
1358     img_info.usage = props->usage;
1359     img_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1360     img_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1361     /* issue 17 of EXT_external_objects
1362      * Required in OpenGL implementations that support
1363      * ARB_texture_view, OES_texture_view, EXT_texture_view,
1364      * or OpenGL 4.3 and above.
1365      */
1366     img_info.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
1367
1368     if (vkCreateImage(ctx->dev, &img_info, 0, &img->img) != VK_SUCCESS)
1369         goto fail;
1370
1371     if(!alloc_image_memory(ctx, true, img))
1372         goto fail;
1373
1374     return true;
1375
1376 fail:
1377     fprintf(stderr, "Failed to create external image.\n");
1378     vk_destroy_image(ctx, img);
1379     img->img = VK_NULL_HANDLE;
1380     img->mobj.mem = VK_NULL_HANDLE;
1381     return false;
1382 }
1383
1384 bool
1385 vk_fill_image_props(struct vk_ctx *ctx,
1386                     uint32_t w,
1387                     uint32_t h,
1388                     uint32_t d,
1389                     uint32_t num_samples,
1390                     uint32_t num_levels,
1391                     uint32_t num_layers,
1392                     VkFormat format,
1393                     VkImageTiling tiling,
1394                     VkImageLayout in_layout,
1395                     VkImageLayout end_layout,
1396                     bool is_swapchain,
1397                     bool is_depth,
1398                     bool need_export,
1399                     struct vk_att_props *props)
1400 {
1401     props->w = w;
1402     props->h = h;
1403     props->depth = d;
1404
1405     props->num_samples = num_samples;
1406     props->num_levels = num_levels;
1407     props->num_layers = num_layers;
1408
1409     props->format = format;
1410     props->tiling = tiling;
1411
1412     props->in_layout = in_layout;
1413     props->end_layout = end_layout;
1414
1415     props->is_swapchain = is_swapchain;
1416     props->is_depth = is_depth;
1417     props->need_export = need_export;
1418
1419     if (!are_props_supported(ctx, props))
1420         return false;
1421
1422     return true;
1423 }
1424
1425 bool
1426 vk_create_renderer(struct vk_ctx *ctx,
1427                    const char *vs_src,
1428                    unsigned int vs_size,
1429                    const char *fs_src,
1430                    unsigned int fs_size,
1431                    int w, int h,
1432                    uint32_t num_samples,
1433                    bool enable_depth,
1434                    bool enable_stencil,
1435                    int num_color_att,
1436                    struct vk_attachment *color_att,
1437                    struct vk_attachment *depth_att,
1438                    struct vk_vertex_info *vert_info,
1439                    struct vk_renderer *renderer)
1440 {
1441     memset(&renderer->vertex_info, 0, sizeof renderer->vertex_info);
1442     if (vert_info)
1443         renderer->vertex_info = *vert_info;
1444
1445     /* create image views for each attachment */
1446     if (!create_attachment_views(ctx, num_color_att, color_att, depth_att))
1447         goto fail;
1448
1449     renderer->renderpass = create_renderpass(ctx,
1450                                              num_color_att,
1451                                              color_att,
1452                                              depth_att);
1453
1454     if (renderer->renderpass == VK_NULL_HANDLE)
1455         goto fail;
1456
1457     create_framebuffer(ctx,
1458                        w, h,
1459                        num_color_att, color_att,
1460                        depth_att, renderer);
1461     if (renderer->fb == VK_NULL_HANDLE)
1462         goto fail;
1463
1464     renderer->vs = create_shader_module(ctx, vs_src, vs_size);
1465     if (renderer->vs == VK_NULL_HANDLE)
1466         goto fail;
1467
1468     renderer->fs = create_shader_module(ctx, fs_src, fs_size);
1469     if (renderer->fs == VK_NULL_HANDLE)
1470         goto fail;
1471
1472     /* FIXME this is only for graphics atm */
1473     if(!create_graphics_pipeline(ctx, w, h,
1474                                  num_samples,
1475                                  num_color_att,
1476                                  enable_depth,
1477                                  enable_stencil, renderer))
1478         goto fail;
1479
1480     if (renderer->pipeline == VK_NULL_HANDLE)
1481         goto fail;
1482
1483     return true;
1484
1485 fail:
1486     fprintf(stderr, "Failed to create renderer.\n");
1487     vk_destroy_renderer(ctx, renderer);
1488     return false;
1489 }
1490
1491 void
1492 vk_destroy_renderer(struct vk_ctx *ctx,
1493                     struct vk_renderer *renderer)
1494 {
1495     if (renderer->renderpass != VK_NULL_HANDLE) {
1496         vkDestroyRenderPass(ctx->dev, renderer->renderpass, 0);
1497         renderer->renderpass = VK_NULL_HANDLE;
1498     }
1499
1500     if (renderer->vs != VK_NULL_HANDLE) {
1501         vkDestroyShaderModule(ctx->dev, renderer->vs, 0);
1502         renderer->vs = VK_NULL_HANDLE;
1503     }
1504
1505     if (renderer->fs != VK_NULL_HANDLE) {
1506         vkDestroyShaderModule(ctx->dev, renderer->fs, 0);
1507         renderer->fs = VK_NULL_HANDLE;
1508     }
1509
1510     if (renderer->fb != VK_NULL_HANDLE) {
1511         vkDestroyFramebuffer(ctx->dev, renderer->fb, 0);
1512         renderer->fb = VK_NULL_HANDLE;
1513     }
1514
1515     if (renderer->pipeline != VK_NULL_HANDLE) {
1516         vkDestroyPipeline(ctx->dev, renderer->pipeline, 0);
1517         renderer->pipeline = VK_NULL_HANDLE;
1518     }
1519
1520     if (renderer->pipeline_layout != VK_NULL_HANDLE) {
1521         vkDestroyPipelineLayout(ctx->dev, renderer->pipeline_layout, 0);
1522         renderer->pipeline_layout = VK_NULL_HANDLE;
1523     }
1524 }
1525
1526 bool
1527 vk_create_ext_buffer(struct vk_ctx *ctx,
1528                      uint32_t sz,
1529                      VkBufferUsageFlagBits usage,
1530                      struct vk_buf *bo)
1531 {
1532     VkExternalMemoryBufferCreateInfo ext_bo_info;
1533
1534     memset(&ext_bo_info, 0, sizeof ext_bo_info);
1535     ext_bo_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO;
1536     ext_bo_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
1537
1538     if (!vk_create_buffer(ctx, true, sz, usage, &ext_bo_info, bo)) {
1539         fprintf(stderr, "Failed to allocate external buffer.\n");
1540         return false;
1541     }
1542
1543     return true;
1544 }
1545
1546 bool
1547 vk_create_buffer(struct vk_ctx *ctx,
1548                  bool is_external,
1549                  uint32_t sz,
1550                  VkBufferUsageFlagBits usage,
1551                  void *pnext,
1552                  struct vk_buf *bo)
1553 {
1554     VkBufferCreateInfo buf_info;
1555     VkMemoryRequirements mem_reqs;
1556
1557     bo->mobj.mem = VK_NULL_HANDLE;
1558     bo->buf = VK_NULL_HANDLE;
1559
1560     /* VkBufferCreateInfo */
1561     memset(&buf_info, 0, sizeof buf_info);
1562     buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1563     buf_info.size = sz;
1564     buf_info.usage = usage;
1565     buf_info.pNext = pnext;
1566     buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1567
1568     if (vkCreateBuffer(ctx->dev, &buf_info, 0, &bo->buf) != VK_SUCCESS)
1569         goto fail;
1570
1571     /* allocate buffer */
1572     vkGetBufferMemoryRequirements(ctx->dev, bo->buf, &mem_reqs);
1573     /* VK_MEMORY_PROPERTY_HOST_COHERENT_BIT bit specifies that the
1574      * host cache management commands vkFlushMappedMemoryRanges and
1575      * vkInvalidateMappedMemoryRanges are not needed to flush host
1576      * writes to the device or make device writes visible to the
1577      * host, respectively. */
1578     bo->mobj.mem = alloc_memory(ctx, is_external, &mem_reqs, VK_NULL_HANDLE,
1579                                 VK_NULL_HANDLE,
1580                                 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
1581                                 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
1582
1583     if (bo->mobj.mem == VK_NULL_HANDLE)
1584         goto fail;
1585
1586     bo->mobj.mem_sz = sz;
1587
1588     if (vkBindBufferMemory(ctx->dev, bo->buf, bo->mobj.mem, 0) != VK_SUCCESS) {
1589         fprintf(stderr, "Failed to bind buffer memory.\n");
1590         goto fail;
1591     }
1592
1593     return true;
1594
1595 fail:
1596     fprintf(stderr, "Failed to allocate buffer.\n");
1597     vk_destroy_buffer(ctx, bo);
1598     return false;
1599 }
1600
1601 bool
1602 vk_update_buffer_data(struct vk_ctx *ctx,
1603                       void *data,
1604                       uint32_t data_sz,
1605                       struct vk_buf *bo)
1606 {
1607     void *map;
1608
1609     if (vkMapMemory(ctx->dev, bo->mobj.mem, 0, data_sz, 0, &map) != VK_SUCCESS) {
1610         fprintf(stderr, "Failed to map buffer memory.\n");
1611         goto fail;
1612     }
1613
1614     memcpy(map, data, data_sz);
1615
1616     vkUnmapMemory(ctx->dev, bo->mobj.mem);
1617     return true;
1618
1619 fail:
1620     fprintf(stderr, "Failed to update buffer data. Destroying the buffer.\n");
1621     vk_destroy_buffer(ctx, bo);
1622
1623     return false;
1624 }
1625
1626 void
1627 vk_destroy_buffer(struct vk_ctx *ctx,
1628           struct vk_buf *bo)
1629 {
1630     if (bo->buf != VK_NULL_HANDLE)
1631         vkDestroyBuffer(ctx->dev, bo->buf, 0);
1632
1633     if (bo->mobj.mem != VK_NULL_HANDLE)
1634         vkFreeMemory(ctx->dev, bo->mobj.mem, 0);
1635
1636     bo->mobj.mem_sz = 0;
1637     bo->buf = VK_NULL_HANDLE;
1638     bo->mobj.mem = VK_NULL_HANDLE;
1639 }
1640
1641 VkCommandBuffer
1642 vk_create_cmd_buffer(struct vk_ctx *ctx)
1643 {
1644     VkCommandBuffer cmd_buf;
1645     VkCommandBufferAllocateInfo alloc_info;
1646
1647     memset(&alloc_info, 0, sizeof alloc_info);
1648     alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1649     alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1650     alloc_info.commandBufferCount = 1;
1651     alloc_info.commandPool = ctx->cmd_pool;
1652
1653     if (vkAllocateCommandBuffers(ctx->dev, &alloc_info, &cmd_buf) != VK_SUCCESS)
1654         return 0;
1655
1656     return cmd_buf;
1657 }
1658
1659 bool
1660 vk_record_cmd_buffer(struct vk_ctx *ctx,
1661                      VkCommandBuffer cmd_buf,
1662                      struct vk_renderer *renderer,
1663                      struct vk_buf *vbo,
1664                      uint32_t vk_fb_color_count,
1665                      float *vk_fb_color,
1666                      uint32_t num_atts,
1667                      struct vk_attachment *atts,
1668                      float x, float y,
1669                      float w, float h)
1670 {
1671     VkCommandBufferBeginInfo cmd_begin_info;
1672     VkRenderPassBeginInfo rp_begin_info;
1673     VkRect2D rp_area;
1674     VkClearValue *clear_values; int i;
1675     VkDeviceSize offsets[] = {0};
1676     int num_vertices;
1677     struct vk_dims img_size;
1678
1679     assert(vk_fb_color_count == 4);
1680
1681     /* if cmd_buf is null create it */
1682     if (!cmd_buf) {
1683         if ((cmd_buf = vk_create_cmd_buffer(ctx)) ==
1684                 VK_NULL_HANDLE) {
1685             fprintf(stderr, "Failed to create command buffer.\n");
1686             return false;
1687         }
1688     }
1689
1690     /* VkCommandBufferBeginInfo */
1691     memset(&cmd_begin_info, 0, sizeof cmd_begin_info);
1692     cmd_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1693     cmd_begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
1694
1695     /* VkRect2D render area */
1696     memset(&rp_area, 0, sizeof rp_area);
1697     rp_area.extent.width = (uint32_t)w;
1698     rp_area.extent.height = (uint32_t)h;
1699     rp_area.offset.x = x;
1700     rp_area.offset.y = y;
1701
1702     /* VkClearValue */
1703     clear_values = malloc(num_atts * sizeof clear_values[0]);
1704     memset(clear_values, 0, num_atts * sizeof clear_values[0]);
1705
1706     for (i = 0; i < num_atts - 1; i++) {
1707         clear_values[i].color.float32[0] = vk_fb_color[0];
1708         clear_values[i].color.float32[1] = vk_fb_color[1];
1709         clear_values[i].color.float32[2] = vk_fb_color[2];
1710         clear_values[i].color.float32[3] = vk_fb_color[3];
1711     }
1712     clear_values[num_atts - 1].depthStencil.depth = 1.0f;
1713     clear_values[num_atts - 1].depthStencil.stencil = 0;
1714
1715     /* VkRenderPassBeginInfo */
1716     memset(&rp_begin_info, 0, sizeof rp_begin_info);
1717     rp_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1718     rp_begin_info.renderPass = renderer->renderpass;
1719     rp_begin_info.framebuffer = renderer->fb;
1720     rp_begin_info.renderArea = rp_area;
1721     rp_begin_info.clearValueCount = num_atts;
1722     rp_begin_info.pClearValues = clear_values;
1723
1724     vkBeginCommandBuffer(cmd_buf, &cmd_begin_info);
1725     vkCmdBeginRenderPass(cmd_buf, &rp_begin_info, VK_SUBPASS_CONTENTS_INLINE);
1726
1727     viewport.x = x;
1728     viewport.y = y;
1729     viewport.width = w;
1730     viewport.height = h;
1731
1732     scissor.offset.x = x;
1733     scissor.offset.y = y;
1734     scissor.extent.width = w;
1735     scissor.extent.height = h;
1736
1737     vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
1738     vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
1739
1740     img_size.w = (float)w;
1741     img_size.h = (float)h;
1742     vkCmdPushConstants(cmd_buf,
1743                        renderer->pipeline_layout,
1744                        VK_SHADER_STAGE_FRAGMENT_BIT,
1745                        0, sizeof (struct vk_dims),
1746                        &img_size);
1747
1748     if (vbo) {
1749         vkCmdBindVertexBuffers(cmd_buf, 0, 1, &vbo->buf, offsets);
1750     }
1751
1752     vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, renderer->pipeline);
1753
1754     num_vertices = vbo ? renderer->vertex_info.num_verts : 4;
1755     vkCmdDraw(cmd_buf, num_vertices, 1, 0, 0);
1756     vkCmdEndRenderPass(cmd_buf);
1757
1758     free(clear_values);
1759 #if 0
1760     if (atts) {
1761         VkImageMemoryBarrier *barriers =
1762             calloc(num_atts, sizeof(VkImageMemoryBarrier));
1763         VkImageMemoryBarrier *barrier = barriers;
1764         for (uint32_t n = 0; n < num_atts; n++, barrier++) {
1765             struct vk_attachment *att = &atts[n];
1766             VkImageAspectFlagBits depth_stencil_flags =
1767                 get_aspect_from_depth_format(att->props.format);
1768             bool is_depth = (depth_stencil_flags != 0);
1769
1770             /* Insert barrier to mark ownership transfer. */
1771             barrier->sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1772             barrier->oldLayout = is_depth ?
1773                 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL :
1774                 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1775             barrier->newLayout = VK_IMAGE_LAYOUT_GENERAL;
1776             barrier->srcAccessMask = get_access_mask(barrier->oldLayout);
1777             barrier->dstAccessMask = get_access_mask(barrier->newLayout);
1778             barrier->srcQueueFamilyIndex = ctx->qfam_idx;
1779             barrier->dstQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL;
1780             barrier->image = att->obj.img;
1781             barrier->subresourceRange.aspectMask = is_depth ?
1782                 depth_stencil_flags :
1783                 VK_IMAGE_ASPECT_COLOR_BIT;
1784             barrier->subresourceRange.baseMipLevel = 0;
1785             barrier->subresourceRange.levelCount = 1;
1786             barrier->subresourceRange.baseArrayLayer = 0;
1787             barrier->subresourceRange.layerCount = 1;
1788         }
1789
1790         vkCmdPipelineBarrier(cmd_buf,
1791                      VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1792                      VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1793                      0,
1794                      0, NULL,
1795                      0, NULL,
1796                      num_atts, barriers);
1797         free(barriers);
1798     }
1799 #endif
1800
1801     vkEndCommandBuffer(cmd_buf);
1802     return true;
1803 }
1804
1805 void
1806 vk_draw(struct vk_ctx *ctx,
1807         struct vk_semaphores *semaphores,
1808         uint32_t num_buffers,
1809         VkCommandBuffer *cmd_buf)
1810 {
1811     VkSubmitInfo submit_info;
1812     VkPipelineStageFlagBits stage_flags;
1813
1814     stage_flags = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
1815
1816     /* VkSubmitInfo */
1817     memset(&submit_info, 0, sizeof submit_info);
1818     submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1819     submit_info.commandBufferCount = num_buffers;
1820     submit_info.pCommandBuffers = cmd_buf;
1821
1822     /* semaphores */
1823     if (semaphores) {
1824         assert(semaphores->frame_ready);
1825         assert(semaphores->frame_done);
1826
1827         submit_info.pWaitDstStageMask = &stage_flags;
1828         submit_info.waitSemaphoreCount = 1;
1829         submit_info.pWaitSemaphores = &semaphores->frame_done;
1830
1831         submit_info.signalSemaphoreCount = 1;
1832         submit_info.pSignalSemaphores = &semaphores->frame_ready;
1833     }
1834
1835
1836     if (vkQueueSubmit(ctx->queue, 1, &submit_info, VK_NULL_HANDLE) != VK_SUCCESS) {
1837         fprintf(stderr, "Failed to submit queue.\n");
1838     }
1839
1840     vkQueueWaitIdle(ctx->queue);
1841 }
1842
1843 void
1844 vk_clear_color(struct vk_ctx *ctx,
1845                VkCommandBuffer cmd_buf,
1846                struct vk_buf *vbo,
1847                struct vk_renderer *renderer,
1848                float *vk_fb_color,
1849                uint32_t vk_fb_color_count,
1850                struct vk_semaphores *semaphores,
1851                bool has_wait, bool has_signal,
1852                struct vk_attachment *attachments,
1853                uint32_t n_attachments,
1854                float x, float y,
1855                float w, float h)
1856 {
1857     VkCommandBufferBeginInfo cmd_begin_info;
1858     VkRenderPassBeginInfo rp_begin_info;
1859     VkRect2D rp_area;
1860     VkClearValue clear_values[2];
1861     VkSubmitInfo submit_info;
1862     VkPipelineStageFlagBits stage_flags;
1863     VkImageSubresourceRange img_range;
1864
1865     assert(vk_fb_color_count == 4);
1866
1867     /* VkCommandBufferBeginInfo */
1868     memset(&cmd_begin_info, 0, sizeof cmd_begin_info);
1869     cmd_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1870     cmd_begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1871
1872     /* VkRect2D render area */
1873     memset(&rp_area, 0, sizeof rp_area);
1874     rp_area.extent.width = (uint32_t)w;
1875     rp_area.extent.height = (uint32_t)h;
1876     rp_area.offset.x = x;
1877     rp_area.offset.y = y;
1878
1879     /* VkClearValue */
1880     memset(&clear_values[0], 0, sizeof clear_values[0]);
1881     clear_values[0].color.float32[0] = vk_fb_color[0]; /* red */
1882     clear_values[0].color.float32[1] = vk_fb_color[1]; /* green */
1883     clear_values[0].color.float32[2] = vk_fb_color[2]; /* blue */
1884     clear_values[0].color.float32[3] = vk_fb_color[3]; /* alpha */
1885
1886     memset(&clear_values[1], 0, sizeof clear_values[1]);
1887     clear_values[1].depthStencil.depth = 1.0;
1888     clear_values[1].depthStencil.stencil = 0;
1889
1890     /* VkRenderPassBeginInfo */
1891     memset(&rp_begin_info, 0, sizeof rp_begin_info);
1892     rp_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1893     rp_begin_info.renderPass = renderer->renderpass;
1894     rp_begin_info.framebuffer = renderer->fb;
1895     rp_begin_info.renderArea = rp_area;
1896     rp_begin_info.clearValueCount = 2;
1897     rp_begin_info.pClearValues = clear_values;
1898
1899     /* VkSubmitInfo */
1900     stage_flags = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
1901
1902     memset(&submit_info, 0, sizeof submit_info);
1903     submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1904     submit_info.commandBufferCount = 1;
1905     submit_info.pCommandBuffers = &cmd_buf;
1906
1907     /* FIXME */
1908     if (has_wait) {
1909         submit_info.pWaitDstStageMask = &stage_flags;
1910         submit_info.waitSemaphoreCount = 1;
1911         submit_info.pWaitSemaphores = &semaphores->frame_done;
1912     }
1913
1914     if (has_signal) {
1915         submit_info.signalSemaphoreCount = 1;
1916         submit_info.pSignalSemaphores = &semaphores->frame_ready;
1917     }
1918
1919     img_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1920     img_range.baseMipLevel = 0;
1921     img_range.levelCount = 1;
1922     img_range.baseArrayLayer = 0;
1923     img_range.layerCount = 1;
1924
1925     vkBeginCommandBuffer(cmd_buf, &cmd_begin_info);
1926     vk_transition_image_layout(&attachments[0],
1927                                cmd_buf,
1928                                VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1929                                VK_IMAGE_LAYOUT_GENERAL,
1930                                VK_QUEUE_FAMILY_EXTERNAL,
1931                                ctx->qfam_idx);
1932     vkCmdClearColorImage(cmd_buf,
1933                          attachments[0].obj.img,
1934                          VK_IMAGE_LAYOUT_GENERAL,
1935                          &clear_values[0].color,
1936                          1,
1937                          &img_range);
1938
1939     vkCmdBeginRenderPass(cmd_buf, &rp_begin_info, VK_SUBPASS_CONTENTS_INLINE);
1940
1941     viewport.x = x;
1942     viewport.y = y;
1943     viewport.width = w;
1944     viewport.height = h;
1945
1946     scissor.offset.x = x;
1947     scissor.offset.y = y;
1948     scissor.extent.width = w;
1949     scissor.extent.height = h;
1950
1951     vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
1952     vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
1953
1954     vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, renderer->pipeline);
1955
1956     vkCmdEndRenderPass(cmd_buf);
1957
1958     if (attachments) {
1959         VkImageMemoryBarrier *barriers =
1960             calloc(n_attachments, sizeof(VkImageMemoryBarrier));
1961         VkImageMemoryBarrier *barrier = barriers;
1962
1963         for (uint32_t n = 0; n < n_attachments; n++, barrier++) {
1964             struct vk_attachment *att = &attachments[n];
1965
1966             /* Insert barrier to mark ownership transfer. */
1967             barrier->sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1968
1969             bool is_depth =
1970                 get_aspect_from_depth_format(att->props.format) != VK_NULL_HANDLE;
1971
1972             barrier->oldLayout = is_depth ?
1973                 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL :
1974                 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1975             barrier->newLayout = VK_IMAGE_LAYOUT_GENERAL;
1976             barrier->srcAccessMask = get_access_mask(barrier->oldLayout);
1977             barrier->dstAccessMask = get_access_mask(barrier->newLayout);
1978             barrier->srcQueueFamilyIndex = ctx->qfam_idx;
1979             barrier->dstQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL;
1980             barrier->image = att->obj.img;
1981             barrier->subresourceRange.aspectMask = is_depth ?
1982                 VK_IMAGE_ASPECT_DEPTH_BIT :
1983                 VK_IMAGE_ASPECT_COLOR_BIT;
1984             barrier->subresourceRange.baseMipLevel = 0;
1985             barrier->subresourceRange.levelCount = 1;
1986             barrier->subresourceRange.baseArrayLayer = 0;
1987             barrier->subresourceRange.layerCount = 1;
1988         }
1989
1990         vkCmdPipelineBarrier(cmd_buf,
1991                      VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1992                      VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1993                      0,
1994                      0, NULL,
1995                      0, NULL,
1996                      n_attachments, barriers);
1997         free(barriers);
1998     }
1999
2000     vkEndCommandBuffer(cmd_buf);
2001
2002     if (vkQueueSubmit(ctx->queue, 1, &submit_info, VK_NULL_HANDLE) != VK_SUCCESS) {
2003         fprintf(stderr, "Failed to submit queue.\n");
2004     }
2005
2006     if (!semaphores && !has_wait && !has_signal)
2007         vkQueueWaitIdle(ctx->queue);
2008 }
2009
2010 bool
2011 vk_create_swapchain(struct vk_ctx *ctx,
2012                     int width, int height,
2013                     bool has_vsync,
2014                     VkSurfaceKHR surf,
2015                     struct vk_swapchain *old_swapchain,
2016                     struct vk_swapchain *swapchain)
2017 {
2018     VkSurfaceCapabilitiesKHR surf_cap;
2019     VkSwapchainCreateInfoKHR s_info;
2020     VkExtent2D extent;
2021     VkImageSubresourceRange sr;
2022     VkImage *s_images;
2023     int i;
2024
2025     if (!sc_validate_surface(ctx, surf)) {
2026         fprintf(stderr, "Failed to validate surface!\n");
2027         return false;
2028     }
2029
2030     /* get pdevice capabilities
2031      * will need that to determine the swapchain number of images
2032      */
2033     if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(ctx->pdev, surf, &surf_cap) != VK_SUCCESS) {
2034         fprintf(stderr, "Failed to query surface capabilities.\n");
2035         return false;
2036     }
2037
2038     memset(swapchain, 0, sizeof *swapchain);
2039
2040     memset(&s_info, 0, sizeof s_info);
2041     s_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
2042     s_info.flags = 0;
2043     if (!sc_select_format(ctx, surf, &s_info)) {
2044         fprintf(stderr, "Failed to determine the surface format.\n");
2045         return false;
2046     }
2047     s_info.surface = surf;
2048     s_info.minImageCount = surf_cap.minImageCount;
2049     {
2050         extent.width = width;
2051         extent.height = height;
2052     }
2053     if (!sc_select_supported_present_modes(ctx, surf, has_vsync, &s_info)) {
2054         s_info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
2055     }
2056     s_info.imageExtent = extent;
2057     s_info.imageArrayLayers = 1;
2058     {
2059         s_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
2060         if (surf_cap.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT)
2061             s_info.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
2062         if (surf_cap.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)
2063             s_info.imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
2064     }
2065     s_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
2066     s_info.queueFamilyIndexCount = ctx->qfam_idx;
2067
2068     /* we might want to use this function when we recreate the swapchain too */
2069     s_info.preTransform = surf_cap.supportedTransforms &
2070                           VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR ?
2071                           VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR :
2072                           surf_cap.currentTransform;
2073
2074     /* we could also write a sc_select_supported_composite_alpha
2075      * later but VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR is universally
2076      * supported */
2077     s_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
2078     s_info.clipped = VK_TRUE;
2079
2080     if (vkCreateSwapchainKHR(ctx->dev, &s_info, 0,
2081                              &swapchain->swapchain) != VK_SUCCESS) {
2082         fprintf(stderr, "Failed to create a swapchain.\n");
2083         return false;
2084     }
2085
2086     if (!swapchain->swapchain) {
2087         fprintf(stderr, "The swapchain seems null\n");
2088         return false;
2089     }
2090
2091     /* get the number of swapchain images and the swapchain images
2092      * and store the new swapchain images
2093      */
2094     vkGetSwapchainImagesKHR(ctx->dev, swapchain->swapchain, &swapchain->num_atts, 0);
2095     printf("number of swapchain images: %d\n", swapchain->num_atts);
2096
2097     /* create images */
2098     s_images = malloc(swapchain->num_atts * sizeof(VkImage));
2099     if (!s_images) {
2100         fprintf(stderr, "Failed to allocate swapchain images.\n");
2101         return false;
2102     }
2103
2104     vkGetSwapchainImagesKHR(ctx->dev, swapchain->swapchain, &swapchain->num_atts, s_images);
2105
2106     swapchain->image_fmt = s_info.imageFormat;
2107     swapchain->atts = malloc(swapchain->num_atts * sizeof swapchain->atts[0]);
2108     if (!swapchain->atts) {
2109         fprintf(stderr, "Failed to allocate swapchain images.\n");
2110         goto fail;
2111     }
2112     memset(swapchain->atts, 0, sizeof swapchain->atts[0]);
2113
2114     memset(&sr, 0, sizeof sr);
2115     sr.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2116     sr.levelCount = 1;
2117     sr.layerCount = 1;
2118
2119     for (i = 0; i < swapchain->num_atts; i++) {
2120         /* we store the image */
2121         swapchain->atts[i].obj.img = s_images[i];
2122
2123         /* filling attachment properties here where that info
2124          * is available */
2125
2126         vk_fill_image_props(ctx, width, height, 1,
2127                             1, 1, 1,
2128                             s_info.imageFormat,
2129                             0,
2130                             VK_IMAGE_LAYOUT_UNDEFINED,
2131                             VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
2132                             true, false, false,
2133                             &swapchain->atts[i].props);
2134         swapchain->atts[i].props.usage = s_info.imageUsage;
2135
2136         if (!create_image_view(ctx, s_images[i],
2137                                VK_IMAGE_VIEW_TYPE_2D,
2138                                s_info.imageFormat, sr, true,
2139                                &swapchain->atts[i].obj.img_view)) {
2140             fprintf(stderr, "Failed to create image view for image: %d\n", i);
2141             goto fail;
2142         }
2143     }
2144
2145     free(s_images);
2146     return true;
2147
2148 fail:
2149     free(s_images);
2150     return false;
2151 }
2152
2153 void
2154 vk_destroy_swapchain(struct vk_ctx *ctx,
2155                      struct vk_swapchain *swapchain)
2156 {
2157     vkDestroySwapchainKHR(ctx->dev, swapchain->swapchain, 0);
2158     swapchain = 0;
2159 }
2160
2161 bool
2162 vk_present_queue(struct vk_swapchain *swapchain,
2163                  VkQueue queue,
2164                  uint32_t image_idx,
2165                  VkSemaphore wait_sema)
2166 {
2167     VkPresentInfoKHR pinfo;
2168
2169     memset(&pinfo, 0, sizeof pinfo);
2170     pinfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
2171     pinfo.swapchainCount = 1;
2172     pinfo.pImageIndices = &image_idx;
2173
2174     if (wait_sema != VK_NULL_HANDLE) {
2175         pinfo.pWaitSemaphores = &wait_sema;
2176         pinfo.waitSemaphoreCount = 1;
2177     }
2178
2179     if (vkQueuePresentKHR(queue, &pinfo) != VK_SUCCESS) {
2180         fprintf(stderr, "Failed to present queue.\n");
2181         return false;
2182     }
2183
2184     return true;
2185 }
2186
2187 void
2188 vk_copy_image_to_buffer(struct vk_ctx *ctx,
2189                         VkCommandBuffer cmd_buf,
2190                         struct vk_attachment *src_img,
2191                         struct vk_buf *dst_bo,
2192                         float w, float h)
2193 {
2194     VkCommandBufferBeginInfo cmd_begin_info;
2195     VkSubmitInfo submit_info;
2196     VkImageAspectFlagBits aspect_mask = get_aspect_from_depth_format(src_img->props.format);
2197
2198     /* VkCommandBufferBeginInfo */
2199     memset(&cmd_begin_info, 0, sizeof cmd_begin_info);
2200     cmd_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
2201     cmd_begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
2202
2203     memset(&submit_info, 0, sizeof submit_info);
2204     submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
2205     submit_info.commandBufferCount = 1;
2206     submit_info.pCommandBuffers = &cmd_buf;
2207
2208     vkBeginCommandBuffer(cmd_buf, &cmd_begin_info);
2209     if (src_img->props.end_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && dst_bo) {
2210         vk_transition_image_layout(src_img,
2211                                    cmd_buf,
2212                                    VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
2213                                    VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2214                                    VK_QUEUE_FAMILY_EXTERNAL,
2215                                    ctx->qfam_idx);
2216
2217         /* copy image to buf */
2218         VkBufferImageCopy copy_region = {
2219             .bufferOffset = 0,
2220             .bufferRowLength = w,
2221             .bufferImageHeight = h,
2222             .imageSubresource = {
2223                 .aspectMask = aspect_mask ? aspect_mask
2224                               : VK_IMAGE_ASPECT_COLOR_BIT,
2225                 .mipLevel = 0,
2226                 .baseArrayLayer = 0,
2227                 .layerCount = 1,
2228             },
2229             .imageOffset = { 0, 0, 0 },
2230             .imageExtent = { w, h, 1 }
2231                 };
2232
2233         vkCmdCopyImageToBuffer(cmd_buf,
2234                                src_img->obj.img,
2235                                VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2236                                dst_bo->buf, 1, &copy_region);
2237
2238         vk_transition_image_layout(src_img,
2239                                    cmd_buf,
2240                                    VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2241                                    VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
2242                                    VK_QUEUE_FAMILY_EXTERNAL,
2243                                    ctx->qfam_idx);
2244
2245         VkBufferMemoryBarrier write_finish_buffer_memory_barrier = {
2246             .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
2247             .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
2248             .dstAccessMask = VK_ACCESS_HOST_READ_BIT,
2249             .srcQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL,
2250             .dstQueueFamilyIndex = ctx->qfam_idx,
2251             .buffer = dst_bo->buf,
2252             .offset = 0,
2253             .size = VK_WHOLE_SIZE
2254         };
2255
2256         vkCmdPipelineBarrier(cmd_buf,
2257                              VK_PIPELINE_STAGE_TRANSFER_BIT,
2258                              VK_PIPELINE_STAGE_HOST_BIT,
2259                              (VkDependencyFlags) 0, 0, NULL,
2260                              1, &write_finish_buffer_memory_barrier,
2261                              0, NULL);
2262     }
2263     vkEndCommandBuffer(cmd_buf);
2264
2265     if (vkQueueSubmit(ctx->queue, 1, &submit_info, VK_NULL_HANDLE) != VK_SUCCESS) {
2266         fprintf(stderr, "Failed to submit queue.\n");
2267     }
2268     vkQueueWaitIdle(ctx->queue);
2269 }
2270
2271 bool
2272 vk_create_semaphores(struct vk_ctx *ctx,
2273                      bool is_external,
2274                      struct vk_semaphores *semaphores)
2275 {
2276     VkSemaphoreCreateInfo sema_info;
2277     VkExportSemaphoreCreateInfo exp_sema_info;
2278
2279     if (is_external) {
2280         /* VkExportSemaphoreCreateInfo */
2281         memset(&exp_sema_info, 0, sizeof exp_sema_info);
2282         exp_sema_info.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO;
2283         exp_sema_info.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
2284     }
2285
2286     /* VkSemaphoreCreateInfo */
2287     memset(&sema_info, 0, sizeof sema_info);
2288     sema_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2289     sema_info.pNext = is_external ? &exp_sema_info : 0;
2290
2291     if (vkCreateSemaphore(ctx->dev, &sema_info, 0, &semaphores->frame_ready) != VK_SUCCESS) {
2292         fprintf(stderr, "Failed to create semaphore frame_ready.\n");
2293         return false;
2294     }
2295
2296     if (vkCreateSemaphore(ctx->dev, &sema_info, 0, &semaphores->frame_done) != VK_SUCCESS) {
2297         fprintf(stderr, "Failed to create semaphore frame_done.\n");
2298         return false;
2299     }
2300
2301     return true;
2302 }
2303
2304 void
2305 vk_destroy_semaphores(struct vk_ctx *ctx,
2306                       struct vk_semaphores *semaphores)
2307 {
2308     if (semaphores->frame_ready)
2309         vkDestroySemaphore(ctx->dev, semaphores->frame_ready, 0);
2310     if (semaphores->frame_done)
2311         vkDestroySemaphore(ctx->dev, semaphores->frame_done, 0);
2312 }
2313
2314 bool
2315 vk_create_fences(struct vk_ctx *ctx,
2316                  int num_cmd_buf,
2317                  VkFenceCreateFlagBits flags,
2318                  VkFence *fences)
2319 {
2320     VkFenceCreateInfo f_info;
2321     int i, j = -1;
2322
2323     memset(&f_info, 0, sizeof f_info);
2324     f_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
2325     f_info.flags = flags ? flags : VK_FENCE_CREATE_SIGNALED_BIT;
2326
2327
2328     fences = malloc(num_cmd_buf * sizeof(VkFence));
2329     for (i = 0; i < num_cmd_buf; i++) {
2330         if (vkCreateFence(ctx->dev, &f_info, 0, &fences[i]) != VK_SUCCESS) {
2331             fprintf(stderr, "Failed to create fence number: %d\n", (i + 1));
2332             j = i;
2333             break;
2334         }
2335     }
2336
2337     if (j == i) {
2338         for (i = 0; i < j; i++) {
2339             vkDestroyFence(ctx->dev, fences[i], 0);
2340         }
2341         return false;
2342     }
2343
2344     return true;
2345 }
2346
2347 void
2348 vk_destroy_fences(struct vk_ctx *ctx,
2349                   int num_fences,
2350                   VkFence *fences)
2351 {
2352     int i;
2353     for (i = 0; i < num_fences; i++) {
2354         vkDestroyFence(ctx->dev, fences[i], 0);
2355     }
2356 }
2357
2358 void
2359 vk_transition_image_layout(struct vk_attachment *img_att,
2360                            VkCommandBuffer cmd_buf,
2361                            VkImageLayout old_layout,
2362                            VkImageLayout new_layout,
2363                            uint32_t src_queue_fam_idx,
2364                            uint32_t dst_queue_fam_idx)
2365 {
2366     VkImageMemoryBarrier barrier;
2367     struct vk_att_props props = img_att->props;
2368     VkImageAspectFlagBits aspect_mask = get_aspect_from_depth_format(props.format);
2369
2370     memset(&barrier, 0, sizeof barrier);
2371     barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2372     barrier.srcAccessMask = get_access_mask(old_layout);
2373     barrier.dstAccessMask = get_access_mask(new_layout);
2374     barrier.oldLayout = old_layout;
2375     barrier.newLayout = new_layout;
2376     barrier.srcQueueFamilyIndex = src_queue_fam_idx;
2377     barrier.dstQueueFamilyIndex = dst_queue_fam_idx;
2378     barrier.image = img_att->obj.img;
2379     barrier.subresourceRange.aspectMask = aspect_mask ? aspect_mask :
2380                                           VK_IMAGE_ASPECT_COLOR_BIT;
2381     barrier.subresourceRange.levelCount = 1;
2382     barrier.subresourceRange.layerCount = 1;
2383
2384     vkCmdPipelineBarrier(cmd_buf,
2385                          get_pipeline_stage_flags(old_layout),
2386                          get_pipeline_stage_flags(new_layout),
2387                          0, 0, VK_NULL_HANDLE, 0, VK_NULL_HANDLE, 1, &barrier);
2388 }