1 #include <gmath/gmath.h>
2 #include <vulkan/vulkan.h>
10 #include "allocator.h"
13 /* global variables */
14 VkPhysicalDevice vk_physical;
16 VkInstance vk_instance;
19 VkCommandPool vk_pool;
20 VkSurfaceKHR vk_surface;
21 VkSwapchainKHR vk_swapchain;
22 VkDescriptorPool vk_dpool;
24 /* static functions */
25 static const char *get_device_name_str(VkPhysicalDeviceType type);
26 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags);
27 static const char *get_queue_flags_str(VkQueueFlags flags);
28 static const char *get_mem_size_str(long sz);
29 static int ver_major(uint32_t ver);
30 static int ver_minor(uint32_t ver);
31 static int ver_patch(uint32_t ver);
33 /* static variables */
34 static VkPhysicalDevice *phys_devices;
37 static int sel_qfamily;
39 static VkExtensionProperties *vkext, *vkdevext;
40 static uint32_t vkext_count, vkdevext_count;
42 bool vku_have_extension(const char *name)
46 vkEnumerateInstanceExtensionProperties(0, &vkext_count, 0);
48 vkext = new VkExtensionProperties[vkext_count];
49 vkEnumerateInstanceExtensionProperties(0, &vkext_count, vkext);
51 printf("instance extensions:\n");
52 for(int i=0; i<(int)vkext_count; i++) {
53 printf(" %s (ver: %u)\n", vkext[i].extensionName, (unsigned int)vkext[i].specVersion);
58 for(int i=0; i<(int)vkext_count; i++) {
59 if(strcmp(vkext[i].extensionName, name) == 0) {
66 bool vku_have_device_extension(const char *name)
68 if(sel_dev < 0) return false;
72 vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, 0);
74 vkdevext = new VkExtensionProperties[vkdevext_count];
75 vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, vkdevext);
77 printf("selected device extensions:\n");
78 for(int i=0; i<(int)vkdevext_count; i++) {
79 printf(" %s (ver: %u)\n", vkdevext[i].extensionName, (unsigned int)vkdevext[i].specVersion);
84 for(int i=0; i<(int)vkdevext_count; i++) {
85 if(strcmp(vkdevext[i].extensionName, name) == 0) {
92 bool vku_create_device()
94 VkInstanceCreateInfo inst_info;
95 VkDeviceCreateInfo dev_info;
96 VkDeviceQueueCreateInfo queue_info;
97 VkCommandPoolCreateInfo cmdpool_info;
101 static const char *ext_names[] = {
102 "VK_KHR_xcb_surface",
106 static const char *devext_names[] = {
113 for(unsigned int i=0; i<sizeof ext_names / sizeof *ext_names; i++) {
114 if(!vku_have_extension(ext_names[i])) {
115 fprintf(stderr, "required extension (%s) not found\n", ext_names[i]);
119 memset(&inst_info, 0, sizeof inst_info);
120 inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
121 inst_info.ppEnabledExtensionNames = ext_names;
122 inst_info.enabledExtensionCount = sizeof ext_names / sizeof *ext_names;
124 if(vkCreateInstance(&inst_info, 0, &vk_instance) != 0) {
125 fprintf(stderr, "failed to create vulkan instance\n");
128 printf("created vulkan instance\n");
129 if(vkEnumeratePhysicalDevices(vk_instance, &num_devices, 0) != 0) {
130 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
133 phys_devices = new VkPhysicalDevice[num_devices];
134 if(vkEnumeratePhysicalDevices(vk_instance, &num_devices, phys_devices) != 0) {
135 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
138 printf("found %u physical device(s)\n", (unsigned int)num_devices);
140 for(int i=0; i<(int)num_devices; i++) {
141 VkPhysicalDeviceProperties dev_prop;
142 VkPhysicalDeviceMemoryProperties mem_prop;
143 VkQueueFamilyProperties *qprop;
144 uint32_t qprop_count;
146 vkGetPhysicalDeviceProperties(phys_devices[i], &dev_prop);
148 printf("Device %d: %s\n", i, dev_prop.deviceName);
149 printf(" type: %s\n", get_device_name_str(dev_prop.deviceType));
150 printf(" API version: %d.%d.%d\n", ver_major(dev_prop.apiVersion), ver_minor(dev_prop.apiVersion),
151 ver_patch(dev_prop.apiVersion));
152 printf(" driver version: %d.%d.%d\n", ver_major(dev_prop.driverVersion), ver_minor(dev_prop.driverVersion),
153 ver_patch(dev_prop.driverVersion));
154 printf(" vendor id: %x device id: %x\n", dev_prop.vendorID, dev_prop.deviceID);
157 vkGetPhysicalDeviceMemoryProperties(phys_devices[i], &mem_prop);
158 printf(" %d memory heaps:\n", mem_prop.memoryHeapCount);
159 for(unsigned int j=0; j<mem_prop.memoryHeapCount; j++) {
160 VkMemoryHeap heap = mem_prop.memoryHeaps[j];
161 printf(" Heap %d - size: %s, flags: %s\n", j, get_mem_size_str(heap.size),
162 heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT ? "device-local" : "-");
164 printf(" %d memory types:\n", mem_prop.memoryTypeCount);
165 for(unsigned int j=0; j<mem_prop.memoryTypeCount; j++) {
166 VkMemoryType type = mem_prop.memoryTypes[j];
167 printf(" Type %d - heap: %d, flags: %s\n", j, type.heapIndex,
168 get_memtype_flags_str(type.propertyFlags));
171 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, 0);
172 if(qprop_count <= 0) {
175 qprop = new VkQueueFamilyProperties[qprop_count];
176 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, qprop);
178 for(unsigned int j=0; j<qprop_count; j++) {
179 printf(" Queue family %d:\n", j);
180 printf(" flags: %s\n", get_queue_flags_str(qprop[j].queueFlags));
181 printf(" num queues: %u\n", qprop[j].queueCount);
183 if(qprop[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
191 if(sel_dev < 0 || sel_qfamily < 0) {
192 fprintf(stderr, "failed to find any device with a graphics-capable command queue\n");
193 vkDestroyDevice(vk_device, 0);
197 for(unsigned int i=0; i<sizeof devext_names / sizeof *devext_names; i++) {
198 if(!vku_have_device_extension(devext_names[i])) {
199 fprintf(stderr, "required extension (%s) not found on the selected device (%d)\n",
200 ext_names[i], sel_dev);
205 /* create device & command queue */
206 memset(&queue_info, 0, sizeof queue_info);
207 queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
208 queue_info.queueFamilyIndex = sel_qfamily;
209 queue_info.queueCount = 1;
210 queue_info.pQueuePriorities = &qprio;
212 memset(&dev_info, 0, sizeof dev_info);
213 dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
214 dev_info.queueCreateInfoCount = 1;
215 dev_info.pQueueCreateInfos = &queue_info;
216 dev_info.enabledExtensionCount = sizeof devext_names / sizeof *devext_names;
217 dev_info.ppEnabledExtensionNames = devext_names;
219 if(vkCreateDevice(phys_devices[sel_dev], &dev_info, 0, &vk_device) != 0) {
220 fprintf(stderr, "failed to create device %d\n", sel_dev);
223 printf("created device %d\n", sel_dev);
225 vk_physical = phys_devices[sel_dev];
226 vk_qfamily = sel_qfamily;
228 vkGetDeviceQueue(vk_device, sel_qfamily, 0, &vk_queue);
230 /* create command buffer pool */
231 memset(&cmdpool_info, 0, sizeof cmdpool_info);
232 cmdpool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
233 cmdpool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
234 cmdpool_info.queueFamilyIndex = sel_qfamily;
236 if(vkCreateCommandPool(vk_device, &cmdpool_info, 0, &vk_pool) != 0) {
237 fprintf(stderr, "failed to get command queue!\n");
241 /* if(!(vkcmdbuf = vku_alloc_cmdbuf(vk_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY))) {
242 fprintf(stderr, "failed to create primary command buffer\n");
252 vkDeviceWaitIdle(vk_device);
253 vkDestroyCommandPool(vk_device, vk_pool, 0);
255 vkDestroyDevice(vk_device, 0);
256 vkDestroyInstance(vk_instance, 0);
260 delete [] phys_devices;
264 VkCommandBuffer vku_alloc_cmdbuf(VkCommandPool pool, VkCommandBufferLevel level)
266 VkCommandBuffer cmdbuf;
267 VkCommandBufferAllocateInfo inf;
269 memset(&inf, 0, sizeof inf);
270 inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
271 inf.commandPool = pool;
273 inf.commandBufferCount = 1;
275 if(vkAllocateCommandBuffers(vk_device, &inf, &cmdbuf) != 0) {
281 bool vku_alloc_cmdbufs(VkCommandPool pool, VkCommandBufferLevel level, unsigned int count, VkCommandBuffer *buf_array)
283 VkCommandBufferAllocateInfo cinf;
284 memset(&cinf, 0, sizeof cinf);
286 cinf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
287 cinf.commandPool = vk_pool;
289 cinf.commandBufferCount = count;
291 if(vkAllocateCommandBuffers(vk_device, &cinf, buf_array) != VK_SUCCESS) {
292 fprintf(stderr, "Failed to allocate command buffer\n");
299 void vku_free_cmdbuf(VkCommandPool pool, VkCommandBuffer buf)
301 vkFreeCommandBuffers(vk_device, pool, 1, &buf);
304 void vku_begin_cmdbuf(VkCommandBuffer buf, unsigned int flags)
306 VkCommandBufferBeginInfo inf;
308 memset(&inf, 0, sizeof inf);
309 inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
312 vkBeginCommandBuffer(buf, &inf);
316 void vku_end_cmdbuf(VkCommandBuffer buf)
318 vkEndCommandBuffer(buf);
321 void vku_reset_cmdbuf(VkCommandBuffer buf)
323 vkResetCommandBuffer(buf, 0);
326 void vku_submit_cmdbuf(VkQueue q, VkCommandBuffer buf, VkFence done_fence)
330 memset(&info, 0, sizeof info);
331 info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
332 info.commandBufferCount = 1;
333 info.pCommandBuffers = &buf;
335 vkQueueSubmit(q, 1, &info, done_fence);
338 bool vku_get_surface_format(VkPhysicalDevice gpu, VkSurfaceKHR surface, VkSurfaceFormatKHR *sformat)
342 if(vkGetPhysicalDeviceSurfaceFormatsKHR(vk_physical,
343 vk_surface, &fcount, 0) != VK_SUCCESS) {
344 fprintf(stderr, "Failed to get format count for physical device.\n");
348 fprintf(stderr, "No color formats were found.\n");
352 VkSurfaceFormatKHR *formats = new VkSurfaceFormatKHR[fcount];
353 if(vkGetPhysicalDeviceSurfaceFormatsKHR(vk_physical, vk_surface,
354 &fcount, formats) != VK_SUCCESS) {
356 fprintf(stderr, "Failed to get surface formats.\n");
360 *sformat = formats[0];
362 if((fcount == 1) && (formats[0].format == VK_FORMAT_UNDEFINED)) {
363 sformat->format = VK_FORMAT_B8G8R8_UNORM;
371 int vku_get_next_image(VkSwapchainKHR sc)
375 if(vkAcquireNextImageKHR(vk_device, sc, UINT64_MAX, 0, 0, &next) != 0) {
381 void vku_present(VkSwapchainKHR sc, int img_idx)
383 VkPresentInfoKHR inf;
385 uint32_t index = img_idx;
387 memset(&inf, 0, sizeof inf);
388 inf.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
389 inf.swapchainCount = 1;
390 inf.pSwapchains = ≻
391 inf.pImageIndices = &index;
394 vkQueuePresentKHR(vk_queue, &inf);
397 struct vku_buffer *vku_create_buffer(int sz, unsigned int usage)
399 struct vku_buffer *buf;
400 VkBufferCreateInfo binfo;
402 buf = new vku_buffer;
404 memset(&binfo, 0, sizeof binfo);
405 binfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
408 binfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
410 if(vkCreateBuffer(vk_device, &binfo, 0, &buf->buf) != 0) {
411 fprintf(stderr, "failed to create %d byte buffer (usage: %x)\n", sz, usage);
415 VkMemoryRequirements mr;
416 vkGetBufferMemoryRequirements(vk_device, buf->buf, &mr);
419 if(!vku_allocate(mr.size, &block))
422 buf->mem_pool = block.dev_mem;
427 void vku_destroy_buffer(struct vku_buffer *buf)
430 //TODO change when the allocator changes
431 vku_free(buf->mem_pool);
433 vkDestroyBuffer(vk_device, buf->buf, 0);
438 bool vku_update_buffer(vku_buffer *buf, int size, void *data)
441 if(vkMapMemory(vk_device, buf->mem_pool, 0, size, 0, (void**)&pdata) != VK_SUCCESS) {
442 fprintf(stderr, "Failed to map memory.\n");
445 memcpy(pdata, data, size);
446 vkUnmapMemory(vk_device, buf->mem_pool);
451 void vku_cmd_copybuf(VkCommandBuffer cmdbuf, VkBuffer dest, int doffs,
452 VkBuffer src, int soffs, int size)
456 copy.srcOffset = soffs;
457 copy.dstOffset = doffs;
459 vkCmdCopyBuffer(cmdbuf, src, dest, 1, ©);
462 const char *vku_get_vulkan_error_str(VkResult error)
467 errmsg = std::string("VK_SUCCESS");
470 errmsg = std::string("VK_NOT_READY");
473 errmsg = std::string("VK_TIMEOUT");
476 errmsg = std::string("VK_EVENT_SET");
479 errmsg = std::string("VK_EVENT_RESET");
482 errmsg = std::string("VK_EVENT");
484 case VK_ERROR_OUT_OF_HOST_MEMORY:
485 errmsg = std::string("VK_ERROR_OUT_OF_HOST_MEMORY");
487 case VK_ERROR_OUT_OF_DEVICE_MEMORY:
488 errmsg = std::string("VK_ERROR_OUT_OF_DEVICE_MEMORY");
490 case VK_ERROR_INITIALIZATION_FAILED:
491 errmsg = std::string("VK_ERROR_INITIALIZATION_FAILED");
493 case VK_ERROR_DEVICE_LOST:
494 errmsg = std::string("VK_ERROR_DEVICE_LOST");
496 case VK_ERROR_MEMORY_MAP_FAILED:
497 errmsg = std::string("VK_ERROR_MEMORY_MAP_FAILED");
499 case VK_ERROR_LAYER_NOT_PRESENT:
500 errmsg = std::string("VK_ERROR_LAYER_NOT_PRESENT");
502 case VK_ERROR_EXTENSION_NOT_PRESENT:
503 errmsg = std::string("VK_ERROR_EXTENSION_NOT_PRESENT");
505 case VK_ERROR_FEATURE_NOT_PRESENT:
506 errmsg = std::string("VK_ERROR_FEATURE_NOT_PRESENT");
507 case VK_ERROR_INCOMPATIBLE_DRIVER:
508 errmsg = std::string("VK_ERROR_INCOMPATIBLE_DRIVER");
510 case VK_ERROR_TOO_MANY_OBJECTS:
511 errmsg = std::string("VK_ERROR_TOO_MANY_OBJECTS");
513 case VK_ERROR_FORMAT_NOT_SUPPORTED:
514 errmsg = std::string("VK_ERROR_FORMAT_NOT_SUPPORTED");
516 case VK_ERROR_FRAGMENTED_POOL:
517 errmsg = std::string("VK_ERROR_FRAGMENTED_POOL");
520 errmsg = std::string("UNKNOWN");
524 return errmsg.c_str();
528 static const char *get_device_name_str(VkPhysicalDeviceType type)
531 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
532 return "integrated GPU";
533 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
534 return "discrete GPU";
535 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
536 return "virtual GPU";
537 case VK_PHYSICAL_DEVICE_TYPE_CPU:
545 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags)
547 static char str[128];
550 if(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
551 strcat(str, "device-local ");
553 if(flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
554 strcat(str, "host-visible ");
556 if(flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
557 strcat(str, "host-coherent ");
559 if(flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) {
560 strcat(str, "host-cached ");
562 if(flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
563 strcat(str, "lazily-allocated ");
572 static const char *get_queue_flags_str(VkQueueFlags flags)
574 static char str[128];
577 if(flags & VK_QUEUE_GRAPHICS_BIT) {
578 strcat(str, "graphics ");
580 if(flags & VK_QUEUE_COMPUTE_BIT) {
581 strcat(str, "compute ");
583 if(flags & VK_QUEUE_TRANSFER_BIT) {
584 strcat(str, "transfer ");
586 if(flags & VK_QUEUE_SPARSE_BINDING_BIT) {
587 strcat(str, "sparse-binding ");
595 static int ver_major(uint32_t ver)
597 return (ver >> 22) & 0x3ff;
600 static int ver_minor(uint32_t ver)
602 return (ver >> 12) & 0x3ff;
605 static int ver_patch(uint32_t ver)
610 static const char *get_mem_size_str(long sz)
613 static const char *unitstr[] = { "bytes", "KB", "MB", "GB", "TB", "PB", 0 };
617 while(sz >= 10240 && unitstr[uidx + 1]) {
621 sprintf(str, "%ld.%ld %s", sz / 10, sz % 10, unitstr[uidx]);
625 vku_descriptor *vku_create_descriptor(VkDescriptorType type,
626 VkFlags stage, int binding_point,
627 int size, int num_desc)
629 vku_descriptor *desc = new vku_descriptor;
633 desc->stage_flags = stage;
634 desc->binding_point = binding_point;
636 VkDescriptorSetLayoutBinding dslb;
637 memset(&dslb, 0, sizeof dslb);
639 dslb.binding = binding_point;
640 dslb.descriptorType = type;
641 dslb.descriptorCount = num_desc;
642 dslb.stageFlags = stage;
644 VkDescriptorSetLayoutCreateInfo dslinf;
645 memset(&dslinf, 0, sizeof dslinf);
647 dslinf.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
648 dslinf.bindingCount = 1;
649 dslinf.pBindings = &dslb;
651 if(vkCreateDescriptorSetLayout(vk_device, &dslinf, 0, &desc->layout) != VK_SUCCESS) {
652 fprintf(stderr, "Failed to create vku_descriptor.\n");
659 void vku_destroy_descriptor(vku_descriptor *desc)
661 vkDestroyDescriptorSetLayout(vk_device, desc->layout, 0);
665 bool vku_create_descriptor_pool(vku_descriptor **descriptors, int num_desc)
668 vkDestroyDescriptorPool(vk_device, vk_dpool, 0);
670 VkDescriptorPoolCreateInfo dpinf;
671 memset(&dpinf, 0, sizeof dpinf);
672 dpinf.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
675 dpinf.poolSizeCount = num_desc;
677 std::vector<VkDescriptorPoolSize> sizes;
678 for(int i=0; i<num_desc; i++) {
679 VkDescriptorPoolSize psz;
680 psz.type = descriptors[i]->type;
681 psz.descriptorCount = 1;
682 sizes.push_back(psz);
685 dpinf.pPoolSizes = sizes.data();
687 if(vkCreateDescriptorPool(vk_device, &dpinf, 0, &vk_dpool) != VK_SUCCESS) {
688 fprintf(stderr, "Failed to create descriptor pool.\n");
695 void vku_destroy_descriptor_pool()
697 vkDestroyDescriptorPool(vk_device, vk_dpool, 0);
700 bool vku_allocate_descriptor_sets(vku_descriptor **desc, int num_desc, VkDescriptorSet set)
702 VkDescriptorSetAllocateInfo dainf;
703 memset(&dainf, 0, sizeof dainf);
705 dainf.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
706 dainf.descriptorPool = vk_dpool;
707 dainf.descriptorSetCount = num_desc;
709 std::vector<VkDescriptorSetLayout> layouts;
710 for(int i=0; i<num_desc; i++) {
711 layouts.push_back(desc[i]->layout);
714 dainf.pSetLayouts = layouts.data();
716 if(vkAllocateDescriptorSets(vk_device, &dainf, &set) != VK_SUCCESS) {
717 fprintf(stderr, "Failed to allocate descriptor sets.\n");
723 void vku_free_descriptor_sets(VkDescriptorSet *sets, int num)
725 vkFreeDescriptorSets(vk_device, vk_dpool, num, sets);