#define GLFW_INCLUDE_NONE #define GLFW_INCLUDE_VULKAN #include "backends/imgui_impl_glfw.h" #include "backends/imgui_impl_vulkan.h" #include "window.hpp" #include "asset-manager.hpp" #include "camera.hpp" #include "ecs.hpp" #include "game-settings.hpp" #include "math-helpers.hpp" #include "plugins.hpp" #include "static-cube.hpp" #include "static-missing-texture.hpp" #include "window-types.hpp" #include "glm/ext/matrix_transform.hpp" #include struct pk_membucket *MemBkt_Vulkan = nullptr; struct pke_vkAllocData { void *data; std::size_t size; }; DynArray *vulkanAllocs = nullptr; #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) const bool ENABLE_VALIDATION_LAYERS = true; const bool VULKAN_DEBUG_REPORT = true; /* * Initialization */ GLFWwindow *window = nullptr; GLFWmonitor *monitor = nullptr; GLFWvidmode vidMode; VkInstance vkInstance = nullptr; VkPhysicalDevice vkPhysicalDevice = nullptr; VkPhysicalDeviceProperties vkPhysicalDeviceProperties; VkPhysicalDeviceMemoryProperties vkPhysicalDeviceMemoryProperties; VkDevice vkDevice = nullptr; VkQueue graphicsQueue = nullptr; VkQueue presentQueue = nullptr; VkQueue transferQueue = nullptr; VkSurfaceKHR vkSurfaceKHR = nullptr; VkDebugReportCallbackEXT vkDebugReport = nullptr; VkAllocationCallbacks vkAllocatorStruct = {}; VkAllocationCallbacks *vkAllocator = nullptr; unsigned int graphicsFamilyIndex; unsigned int presentFamilyIndex; unsigned int transferFamilyIndex; /* * Instantiation */ bool shouldRecreateSwapchain = false; unsigned int CURRENT_FRAME = 0; unsigned int selectedSurfaceIndex = -1u; unsigned int swapchainLength = 0u; VkSwapchainKHR vkSwapchainKHR = VK_NULL_HANDLE; VkSurfaceFormatKHR vkSurfaceFormatKHR; VkFormat depthFormat; VkPresentModeKHR vkPresentModeKHR = VK_PRESENT_MODE_FIFO_KHR; VkExtent2D Extent; VkImage *swapchainImages = nullptr; VkImageView *swapchainImageViews = nullptr; VkImage *renderImages = nullptr; VkImageView *renderImageViews = nullptr; VkDeviceMemory renderImagesMemory; VkImage *colorImages = nullptr; VkImageView *colorImageViews = nullptr; VkDeviceMemory colorImagesMemory; VkImage *depthImages = nullptr; VkImageView *depthImageViews = nullptr; VkDeviceMemory depthImagesMemory; VkImage *d2OverlayImages = nullptr; VkImageView *d2OverlayImageViews = nullptr; VkDeviceMemory d2OverlayImagesMemory; VkSampler presentSampler; VkSampleCountFlagBits renderSampleCount; VkRenderPass presentRenderPass; VkRenderPass renderRenderPass; VkRenderPass d2OverlayRenderPass; VkDescriptorSetLayout vkDescriptorSetLayout; VkDescriptorPool presentDescriptorPool; VkDescriptorSet presentDescriptorSets[MAX_FRAMES_IN_FLIGHT]; VkPipelineLayout pipelineLayout; VkPipeline graphicsPipeline; VkFramebuffer *swapchainFramebuffers = nullptr; VkFramebuffer *renderImageFramebuffers = nullptr; VkFramebuffer *d2OverlayImageFramebuffers = nullptr; VkCommandPool transferCommandPool; VkCommandBuffer transferCommandBuffer; VkCommandPool graphicsCommandPool; VkCommandBuffer graphicsCommandBuffer; VkCommandBuffer presentCommandBuffers[MAX_FRAMES_IN_FLIGHT]; VkSemaphore presentImageAvailableSemaphores[MAX_FRAMES_IN_FLIGHT]; VkSemaphore presentRenderFinishedSemaphores[MAX_FRAMES_IN_FLIGHT]; VkFence presentInFlightFences[MAX_FRAMES_IN_FLIGHT]; UniformBufferObject UBO{ .model = glm::mat4(1), .view = glm::lookAt(glm::vec3(0), glm::vec3(2, 2, 0), glm::vec3(0, 1, 0)), .proj = glm::mat4(1), }; VkDeviceMemory uniformBufferMemory; VkDeviceSize paddedUboBufferSize; // public VkBuffer UniformBuffers[MAX_FRAMES_IN_FLIGHT]; DebugHitbox pkeDebugHitbox{}; ImplementedPipelines pkePipelines{}; /* * ImGui */ VkDescriptorPool imGuiDescriptorPool; const std::vector REQUIRED_EXTENSIONS = std::vector { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; static void ImGuiCheckVkResult(VkResult err) { if (err == 0) { return; } fprintf(stderr, "[imgui][vulkan] Error: VkResult = %d\n", err); if (err < 0) { abort(); } } VkBool32 UserDebugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, void *pUserData) { (void)messageSeverity; (void)messageType; (void)pUserData; printf("Validation Layer: %s\n", pCallbackData->pMessage); return VK_FALSE; } static VKAPI_ATTR VkBool32 VKAPI_CALL DebugReport(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, unsigned long object, size_t location, int messageCode, const char *pLayerPrefix, const char *pMessage, void *pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } unsigned int FindMemoryTypeIndex(uint32_t typeFilter, VkMemoryPropertyFlags memPropertyFlags) { for (uint32_t i = 0; i < vkPhysicalDeviceMemoryProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (vkPhysicalDeviceMemoryProperties.memoryTypes[i].propertyFlags & memPropertyFlags) == memPropertyFlags) { return i; } } fprintf(stdout, "[vulkan] Failed to find appropriate memory type index: typeFilter: %u - memPropertyFlags: %u\n", typeFilter, memPropertyFlags); return 0; } VkFormat FindSupportedFormat(long candidateCount, const VkFormat *candidates, VkImageTiling tiling, VkFormatFeatureFlags flags) { for (long i = 0; i < candidateCount; ++i) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(vkPhysicalDevice, candidates[i], &props); if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & flags) == flags) { return candidates[i]; } else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & flags) == flags) { return candidates[i]; } } fprintf(stdout, "[vulkan] Failed to find appropriate format: tiling: %u - flags: %u\n", tiling, flags); return VkFormat(0); } void BeginTransferBuffer(VkDeviceSize requestedMemorySize, VkBuffer &buffer, VkDeviceMemory &deviceMemory, void *&deviceData) { VkBufferCreateInfo transferBufferCI; transferBufferCI.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; transferBufferCI.pNext = nullptr; transferBufferCI.flags = 0; transferBufferCI.size = requestedMemorySize; transferBufferCI.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; transferBufferCI.sharingMode = VK_SHARING_MODE_EXCLUSIVE; transferBufferCI.queueFamilyIndexCount = 1; transferBufferCI.pQueueFamilyIndices = &transferFamilyIndex; VkResult vkResult = vkCreateBuffer(vkDevice, &transferBufferCI, vkAllocator, &buffer); assert(vkResult == VK_SUCCESS); VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(vkDevice, buffer, &memoryRequirements); VkMemoryAllocateInfo transferMemAllocInfo; transferMemAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; transferMemAllocInfo.pNext = nullptr; transferMemAllocInfo.allocationSize = memoryRequirements.size; transferMemAllocInfo.memoryTypeIndex = FindMemoryTypeIndex(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); vkResult = vkAllocateMemory(vkDevice, &transferMemAllocInfo, vkAllocator, &deviceMemory); assert(vkResult == VK_SUCCESS); vkResult = vkBindBufferMemory(vkDevice, buffer, deviceMemory, 0); assert(vkResult == VK_SUCCESS); vkResult = vkMapMemory(vkDevice, deviceMemory, 0, transferMemAllocInfo.allocationSize, 0, &deviceData); assert(vkResult == VK_SUCCESS); } void EndTransferBuffer(VkBuffer &buffer, VkDeviceMemory &deviceMemory) { vkUnmapMemory(vkDevice, deviceMemory); vkDestroyBuffer(vkDevice, buffer, vkAllocator); vkFreeMemory(vkDevice, deviceMemory, vkAllocator); } unsigned int FindQueueFamilyIndex(VkPhysicalDevice device, char hasPresentSupport = -1, VkQueueFlagBits includeBits = (VkQueueFlagBits)0U, VkQueueFlagBits excludeBits = (VkQueueFlagBits)0U) { if (hasPresentSupport == -1 && includeBits == 0 && excludeBits == 0) { return 0U; } unsigned int queueFamilyPropertyCount = 0U; vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyPropertyCount, nullptr); auto *queueFamilyProperties = pk_new(queueFamilyPropertyCount); vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyPropertyCount, queueFamilyProperties); for (unsigned int i = 0; i < queueFamilyPropertyCount; i++) { if (includeBits != 0 && (queueFamilyProperties[i].queueFlags & includeBits) == 0) { continue; } if (excludeBits != 0 && (queueFamilyProperties[i].queueFlags & excludeBits) != 0) { continue; } if (hasPresentSupport != -1) { VkBool32 presentSupport; VkResult vkResult = vkGetPhysicalDeviceSurfaceSupportKHR(device, i, vkSurfaceKHR, &presentSupport); assert(vkResult == VK_SUCCESS); if (presentSupport != (VkBool32)hasPresentSupport) { continue; } } pk_delete(queueFamilyProperties, queueFamilyPropertyCount); return i; } pk_delete(queueFamilyProperties, queueFamilyPropertyCount); return 0xFFFFFFFF; } void PKE_vkFreeFunction(void *pUserData, void *pMemory) { (void)pUserData; if (pMemory == nullptr) return; pke_vkAllocData *chunk = nullptr; size_t index = -1; int64_t count = vulkanAllocs->Count(); for (int64_t i = 0; i < count; ++i) { if ((*vulkanAllocs)[i].data == pMemory) { chunk = &(*vulkanAllocs)[i]; index = i; break; } } if (chunk != nullptr) { assert(chunk != nullptr); pk_delete_bkt(chunk->data, chunk->size, MemBkt_Vulkan); vulkanAllocs->Remove(index); } else { fprintf(stderr, "%s\n", "PKE_vkFreeFunction - untracked pointer"); } } void *PKE_vkAllocateFunction(void *pUserData, size_t size, size_t alignment, VkSystemAllocationScope allocScope) { (void)pUserData; (void)allocScope; if (size == 0) { return nullptr; } void *ptr = pk_new_bkt(size, alignment, MemBkt_Vulkan); vulkanAllocs->Push({ .data = ptr, .size = size, }); return ptr; } void *PKE_vkReallocationFunction(void *pUserData, void *pOriginal, size_t size, size_t alignment, VkSystemAllocationScope allocScope) { (void)pUserData; if (pOriginal == nullptr) { return PKE_vkAllocateFunction(pUserData, size, alignment, allocScope); } if (size == 0) { PKE_vkFreeFunction(pUserData, pOriginal); return nullptr; } pke_vkAllocData *chunk = nullptr; size_t index = -1; int64_t count = vulkanAllocs->Count(); for (int64_t i = 0; i < count; ++i) { if ((*vulkanAllocs)[i].data == pOriginal) { chunk = &((*vulkanAllocs)[i]); index = i; break; } } if (chunk != nullptr) { if (chunk->size >= size) { return pOriginal; } } void *newPtr = PKE_vkAllocateFunction(pUserData, size, alignment, allocScope); if (chunk != nullptr) { memcpy(newPtr, chunk->data, (chunk->size < size ? chunk->size : size) - 1); pk_delete_bkt(chunk->data, chunk->size, MemBkt_Vulkan); vulkanAllocs->Remove(index); } else { } return newPtr; } void PKE_vkInternalAllocationNotification(void *pUserData, size_t size, VkInternalAllocationType allocationType, VkSystemAllocationScope allocationScope) { (void)pUserData; (void)size; (void)allocationType; (void)allocationScope; return; } void PKE_vkInternalFreeNotification(void *pUserData, size_t size, VkInternalAllocationType allocationType, VkSystemAllocationScope allocationScope) { (void)pUserData; (void)size; (void)allocationType; (void)allocationScope; return; } void InitVulkan() { vkAllocator = pk_new(MemBkt_Vulkan); vkAllocator->pUserData = nullptr; vkAllocator->pfnAllocation = PKE_vkAllocateFunction; vkAllocator->pfnReallocation = PKE_vkReallocationFunction; vkAllocator->pfnFree = PKE_vkFreeFunction; vkAllocator->pfnInternalAllocation = PKE_vkInternalAllocationNotification; vkAllocator->pfnInternalFree = PKE_vkInternalFreeNotification; VkResult vkResult; if (ENABLE_VALIDATION_LAYERS) { unsigned int layerCount; vkResult = vkEnumerateInstanceLayerProperties(&layerCount, nullptr); assert(vkResult == VK_SUCCESS); VkLayerProperties *availableLayerProperties = pk_new(layerCount); vkResult = vkEnumerateInstanceLayerProperties(&layerCount, availableLayerProperties); assert(vkResult == VK_SUCCESS); printf("Available Layers:\n"); for (long i = 0; i < layerCount; ++i) { printf("\t%s\n", availableLayerProperties[i].layerName); } pk_delete(availableLayerProperties, layerCount); } VkApplicationInfo appInfo; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pNext = nullptr; appInfo.pApplicationName = "pikul"; appInfo.applicationVersion = 1; appInfo.pEngineName = "pikul"; appInfo.engineVersion = 1; appInfo.apiVersion = VK_API_VERSION_1_3; VkInstanceCreateInfo createInfo; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pNext = nullptr; createInfo.flags = {}; createInfo.pApplicationInfo = &appInfo; createInfo.enabledLayerCount = 0; std::vector enabledLayerNames(1); enabledLayerNames[0] = "VK_LAYER_KHRONOS_validation"; printf("Requested Layers:\n"); for (const char *s : enabledLayerNames) { printf("\t%s\n", s); } VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo; debugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; debugCreateInfo.pNext = nullptr; debugCreateInfo.flags = {}; if (ENABLE_VALIDATION_LAYERS) { createInfo.enabledLayerCount = enabledLayerNames.size(); createInfo.ppEnabledLayerNames = enabledLayerNames.data(); debugCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; debugCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; debugCreateInfo.pfnUserCallback = UserDebugCallback; debugCreateInfo.pUserData = nullptr; createInfo.pNext = &debugCreateInfo; } std::vector allGlfwExtensions; { unsigned int extensionCount = 0; const char **glfwExtensions = glfwGetRequiredInstanceExtensions(&extensionCount); allGlfwExtensions.reserve(extensionCount + 2); copy(&glfwExtensions[0], &glfwExtensions[extensionCount], back_inserter(allGlfwExtensions)); if (ENABLE_VALIDATION_LAYERS) { allGlfwExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); allGlfwExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } createInfo.enabledExtensionCount = allGlfwExtensions.size(); createInfo.ppEnabledExtensionNames = allGlfwExtensions.data(); } printf("Required Extensions:\n"); for (const auto &ext : allGlfwExtensions) { printf("\t%s\n", ext); } if (ENABLE_VALIDATION_LAYERS) { unsigned int extensionCount = 0; vkResult = vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); assert(vkResult == VK_SUCCESS); auto *extensions = pk_new(extensionCount); vkResult = vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions); assert(vkResult == VK_SUCCESS); printf("Available Extensions:\n"); for (long i = 0; i < extensionCount; ++i) { printf("\t%s\n", extensions[i].extensionName); } pk_delete(extensions, extensionCount); } vkResult = vkCreateInstance(&createInfo, vkAllocator, &vkInstance); if (vkResult != VK_SUCCESS) { printf("Failed to create VkInstance! : %d\n", vkResult); throw vkResult; } if (VULKAN_DEBUG_REPORT) { PFN_vkCreateDebugReportCallbackEXT func = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(vkInstance, "vkCreateDebugReportCallbackEXT"); assert(func != nullptr && "vkCreateDebugReportCallbackEXT ProcAddr was nullptr"); VkDebugReportCallbackCreateInfoEXT debugReportCallbackCreateInfo; debugReportCallbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debugReportCallbackCreateInfo.pNext = nullptr; debugReportCallbackCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debugReportCallbackCreateInfo.pfnCallback = DebugReport; debugReportCallbackCreateInfo.pUserData = nullptr; vkResult = func(vkInstance, &debugReportCallbackCreateInfo, vkAllocator, &vkDebugReport); if (vkResult != VK_SUCCESS) { fprintf(stderr, "%s\n", "Failed to create debug report!"); } } // create surface if (glfwCreateWindowSurface(vkInstance, window, vkAllocator, &vkSurfaceKHR) != VK_SUCCESS) { throw "Failed to create window surface"; } // pick physical device unsigned int physicalDeviceCount = 0; vkResult = vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, nullptr); assert(vkResult == VK_SUCCESS); assert(physicalDeviceCount > 0); auto *physicalDevices = pk_new(physicalDeviceCount); vkResult = vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDevices); assert(vkResult == VK_SUCCESS); graphicsFamilyIndex = 0; presentFamilyIndex = 0; for (long i = 0; i < physicalDeviceCount; ++i) { const auto &device = physicalDevices[i]; // check queue families graphicsFamilyIndex = FindQueueFamilyIndex(device, -1, VK_QUEUE_GRAPHICS_BIT); presentFamilyIndex = FindQueueFamilyIndex(device, 1); if (graphicsFamilyIndex == 0xFFFFFFFF || presentFamilyIndex == 0xFFFFFFFF) { continue; } // check device extension support std::vector requiredExtensions(REQUIRED_EXTENSIONS.begin(), REQUIRED_EXTENSIONS.end()); unsigned int extensionCount = 0; vkResult = vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); assert(vkResult == VK_SUCCESS); auto *extensionProperties = pk_new(extensionCount); vkResult = vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, extensionProperties); assert(vkResult == VK_SUCCESS); for (long k = 0; k < extensionCount; ++k) { const auto &property = extensionProperties[k]; auto it = requiredExtensions.begin(); while (it != requiredExtensions.end()) { if (strcmp(*it.base(), property.extensionName)) { it = requiredExtensions.erase(it); } else { it++; } } } pk_delete(extensionProperties, extensionCount); if (requiredExtensions.empty() == false) { continue; } // surface formats unsigned int surfaceCount = 0; vkResult = vkGetPhysicalDeviceSurfaceFormatsKHR(device, vkSurfaceKHR, &surfaceCount, nullptr); assert(vkResult == VK_SUCCESS); if (surfaceCount == 0) { continue; } // check present modes unsigned int presentModeCount = 0; vkResult = vkGetPhysicalDeviceSurfacePresentModesKHR(device, vkSurfaceKHR, &presentModeCount, nullptr); assert(vkResult == VK_SUCCESS); if (presentModeCount == 0) { continue; } vkPhysicalDevice = device; vkGetPhysicalDeviceProperties(vkPhysicalDevice, &vkPhysicalDeviceProperties); printf("Selected VkPhysicalDevice: %s\n", vkPhysicalDeviceProperties.deviceName); vkGetPhysicalDeviceMemoryProperties(vkPhysicalDevice, &vkPhysicalDeviceMemoryProperties); break; } assert(vkPhysicalDevice != nullptr && "Failed to find suitable physical device"); pk_delete(physicalDevices, physicalDeviceCount); // Create logical device { transferFamilyIndex = FindQueueFamilyIndex(vkPhysicalDevice, 0, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_GRAPHICS_BIT); if (transferFamilyIndex == 0xFFFFFFFF) { transferFamilyIndex = FindQueueFamilyIndex(vkPhysicalDevice, -1, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_GRAPHICS_BIT); } if (transferFamilyIndex == 0xFFFFFFFF) { transferFamilyIndex = FindQueueFamilyIndex(vkPhysicalDevice, -1, VK_QUEUE_TRANSFER_BIT); } if (transferFamilyIndex == 0xFFFFFFFF) { printf("Failed to find transfer queue index\n"); throw("Failed to find transfer queue index"); } VkDeviceQueueCreateInfo deviceQueueCreateInfos[2]; float graphicsPriorities[1] = { 1.0f }; deviceQueueCreateInfos[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; deviceQueueCreateInfos[0].pNext = nullptr; deviceQueueCreateInfos[0].flags = 0; deviceQueueCreateInfos[0].queueFamilyIndex = graphicsFamilyIndex; deviceQueueCreateInfos[0].queueCount = 1l; deviceQueueCreateInfos[0].pQueuePriorities = graphicsPriorities; float transferPriorities[1] = { 0.5f }; deviceQueueCreateInfos[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; deviceQueueCreateInfos[1].pNext = nullptr; deviceQueueCreateInfos[1].flags = 0; deviceQueueCreateInfos[1].queueFamilyIndex = transferFamilyIndex; deviceQueueCreateInfos[1].queueCount = 1l; deviceQueueCreateInfos[1].pQueuePriorities = transferPriorities; VkPhysicalDeviceFeatures vkPhysicalDeviceFeatures; vkGetPhysicalDeviceFeatures(vkPhysicalDevice, &vkPhysicalDeviceFeatures); VkPhysicalDeviceFeatures requestedFeatures{}; // {} to initialize everything to 0 requestedFeatures.samplerAnisotropy = VK_TRUE; requestedFeatures.sampleRateShading = VK_TRUE; requestedFeatures.wideLines = VK_TRUE; requestedFeatures.fillModeNonSolid = vkPhysicalDeviceFeatures.fillModeNonSolid; VkDeviceCreateInfo vkDeviceCreateInfo; vkDeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; vkDeviceCreateInfo.pNext = nullptr; vkDeviceCreateInfo.flags = 0; vkDeviceCreateInfo.queueCreateInfoCount = 2; vkDeviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfos; if (ENABLE_VALIDATION_LAYERS) { vkDeviceCreateInfo.enabledLayerCount = enabledLayerNames.size(); vkDeviceCreateInfo.ppEnabledLayerNames = enabledLayerNames.data(); } vkDeviceCreateInfo.enabledExtensionCount = REQUIRED_EXTENSIONS.size(); vkDeviceCreateInfo.ppEnabledExtensionNames = REQUIRED_EXTENSIONS.data(); vkDeviceCreateInfo.pEnabledFeatures = &requestedFeatures; vkResult = vkCreateDevice(vkPhysicalDevice, &vkDeviceCreateInfo, vkAllocator, &vkDevice); if (vkResult != VK_SUCCESS) { printf("Failed to create VkInstance! : %d\n", vkResult); throw vkResult; } } // queues { vkGetDeviceQueue(vkDevice, graphicsFamilyIndex, 0, &graphicsQueue); vkGetDeviceQueue(vkDevice, presentFamilyIndex, 0, &presentQueue); vkGetDeviceQueue(vkDevice, transferFamilyIndex, 0, &transferQueue); } // surface formats { const VkFormat acceptableDepthFormats[3] = { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT, }; depthFormat = FindSupportedFormat(3, acceptableDepthFormats, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); } // sampler { VkSampleCountFlags counts = vkPhysicalDeviceProperties.limits.framebufferColorSampleCounts & vkPhysicalDeviceProperties.limits.framebufferDepthSampleCounts; if (counts & VK_SAMPLE_COUNT_64_BIT) { renderSampleCount = VK_SAMPLE_COUNT_64_BIT; } else if (counts & VK_SAMPLE_COUNT_32_BIT) { renderSampleCount = VK_SAMPLE_COUNT_32_BIT; } else if (counts & VK_SAMPLE_COUNT_16_BIT) { renderSampleCount = VK_SAMPLE_COUNT_16_BIT; } else if (counts & VK_SAMPLE_COUNT_8_BIT) { renderSampleCount = VK_SAMPLE_COUNT_8_BIT; } else if (counts & VK_SAMPLE_COUNT_4_BIT) { renderSampleCount = VK_SAMPLE_COUNT_4_BIT; } else if (counts & VK_SAMPLE_COUNT_2_BIT) { renderSampleCount = VK_SAMPLE_COUNT_2_BIT; } } // generic present sampler VkSamplerCreateInfo samplerCreateInfo; samplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerCreateInfo.pNext = nullptr; samplerCreateInfo.flags = 0U; samplerCreateInfo.magFilter = VK_FILTER_NEAREST; samplerCreateInfo.minFilter = VK_FILTER_NEAREST; samplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerCreateInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCreateInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCreateInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCreateInfo.mipLodBias = 0.0f; samplerCreateInfo.anisotropyEnable = VK_FALSE; samplerCreateInfo.maxAnisotropy = 1.0f; samplerCreateInfo.compareEnable = VK_FALSE; samplerCreateInfo.compareOp = {}; samplerCreateInfo.minLod = 0.0f; samplerCreateInfo.maxLod = 1.0f; samplerCreateInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; samplerCreateInfo.unnormalizedCoordinates = {}; vkResult = vkCreateSampler(vkDevice, &samplerCreateInfo, vkAllocator, &presentSampler); assert(vkResult == VK_SUCCESS); } void CreateImageResources_Inner(VkImageCreateInfo *imageCreateInfo, VkImageViewCreateInfo *imageViewCreateInfo, VkBufferUsageFlagBits bufferUsageFlagBits, VkBuffer *imagesBuffer, VkImage *images, VkImageView *imageViews, VkDeviceMemory *deviceMemory) { (void)bufferUsageFlagBits; (void)imagesBuffer; VkImage tmpImage; VkResult vkResult; vkResult = vkCreateImage(vkDevice, imageCreateInfo, vkAllocator, &tmpImage); assert(vkResult == VK_SUCCESS); VkMemoryRequirements imageMemoryRequirements; vkGetImageMemoryRequirements(vkDevice, tmpImage, &imageMemoryRequirements); VkDeviceSize paddedImageSize = imageMemoryRequirements.size + (imageMemoryRequirements.alignment - (imageMemoryRequirements.size % imageMemoryRequirements.alignment)); assert(paddedImageSize % imageMemoryRequirements.alignment == 0); vkDestroyImage(vkDevice, tmpImage, vkAllocator); VkMemoryAllocateInfo vkMemoryAllocateInfo{}; vkMemoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vkMemoryAllocateInfo.pNext = nullptr; vkMemoryAllocateInfo.allocationSize = paddedImageSize * MAX_FRAMES_IN_FLIGHT; vkMemoryAllocateInfo.memoryTypeIndex = FindMemoryTypeIndex(imageMemoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); vkResult = vkAllocateMemory(vkDevice, &vkMemoryAllocateInfo, vkAllocator, deviceMemory); assert(vkResult == VK_SUCCESS); for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { vkResult = vkCreateImage(vkDevice, imageCreateInfo, vkAllocator, &images[i]); assert(vkResult == VK_SUCCESS); vkResult = vkBindImageMemory(vkDevice, images[i], *deviceMemory, paddedImageSize * i); assert(vkResult == VK_SUCCESS); imageViewCreateInfo->image = images[i]; vkResult = vkCreateImageView(vkDevice, imageViewCreateInfo, vkAllocator, &imageViews[i]); assert(vkResult == VK_SUCCESS); } } void CreateSwapchain() { VkResult vkResult; VkSurfaceCapabilitiesKHR surfaceCapabilities; vkResult = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkPhysicalDevice, vkSurfaceKHR, &surfaceCapabilities); assert(vkResult == VK_SUCCESS); assert(MAX_FRAMES_IN_FLIGHT >= surfaceCapabilities.minImageCount); assert(surfaceCapabilities.maxImageCount == 0 || MAX_FRAMES_IN_FLIGHT <= surfaceCapabilities.maxImageCount); if (selectedSurfaceIndex == -1u) { unsigned int surfaceFormatCounts; vkResult = vkGetPhysicalDeviceSurfaceFormatsKHR(vkPhysicalDevice, vkSurfaceKHR, &surfaceFormatCounts, nullptr); assert(vkResult == VK_SUCCESS); VkSurfaceFormatKHR *surfaceFormats = pk_new(surfaceFormatCounts); vkResult = vkGetPhysicalDeviceSurfaceFormatsKHR(vkPhysicalDevice, vkSurfaceKHR, &surfaceFormatCounts, surfaceFormats); assert(vkResult == VK_SUCCESS); selectedSurfaceIndex = 0; for (long i = 0; i < surfaceFormatCounts; ++i) { if (surfaceFormats[i].format != VkFormat::VK_FORMAT_B8G8R8A8_SRGB) continue; if (surfaceFormats[i].colorSpace != VkColorSpaceKHR::VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) continue; selectedSurfaceIndex = i; vkSurfaceFormatKHR.colorSpace = surfaceFormats[i].colorSpace; vkSurfaceFormatKHR.format = surfaceFormats[i].format; break; } pk_delete(surfaceFormats, surfaceFormatCounts); } int width, height; glfwGetFramebufferSize(window, &width, &height); Extent.width = width; Extent.height = height; // clamp Extent.width = PK_CLAMP(Extent.width, surfaceCapabilities.minImageExtent.width, surfaceCapabilities.maxImageExtent.width); Extent.height = PK_CLAMP(Extent.height, surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height); vkPresentModeKHR = VK_PRESENT_MODE_FIFO_KHR; if (pkeSettings.graphicsSettings.isWaitingForVsync == false || pkeSettings.graphicsSettings.isFramerateUnlocked == true) { unsigned int presentModeCount = 0; vkResult = vkGetPhysicalDeviceSurfacePresentModesKHR(vkPhysicalDevice, vkSurfaceKHR, &presentModeCount, nullptr); assert(vkResult == VK_SUCCESS); VkPresentModeKHR *presentModes = pk_new(presentModeCount); vkResult = vkGetPhysicalDeviceSurfacePresentModesKHR(vkPhysicalDevice, vkSurfaceKHR, &presentModeCount, presentModes); assert(vkResult == VK_SUCCESS); int32_t immediateIndex = -1; int32_t fifoRelaxedIndex = -1; /* uint32_t mailboxIndex = -1; uint32_t fifoIndex = -1; */ for (long i = 0; i < presentModeCount; ++i) { if (presentModes[i] == VkPresentModeKHR::VK_PRESENT_MODE_IMMEDIATE_KHR) { immediateIndex = i; } else if (presentModes[i] == VkPresentModeKHR::VK_PRESENT_MODE_FIFO_RELAXED_KHR) { fifoRelaxedIndex = i; } /* // TODO returns 5 swapchain images, which causes other unhandled issues else if (presentModes[i] == VkPresentModeKHR::VK_PRESENT_MODE_MAILBOX_KHR) { mailboxIndex = i; } else if (presentModes[i] == VkPresentModeKHR::VK_PRESENT_MODE_FIFO_KHR) { fifoIndex = i; } */ } if (fifoRelaxedIndex != -1) { vkPresentModeKHR = VK_PRESENT_MODE_FIFO_RELAXED_KHR; } /* if (mailboxIndex != -1) { vkPresentModeKHR = VK_PRESENT_MODE_MAILBOX_KHR; } else */ if (immediateIndex != -1) { vkPresentModeKHR = VK_PRESENT_MODE_IMMEDIATE_KHR; } pk_delete(presentModes, presentModeCount); } VkSwapchainCreateInfoKHR vkSwapchainCreateInfo; vkSwapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; vkSwapchainCreateInfo.pNext = nullptr; vkSwapchainCreateInfo.flags = 0; vkSwapchainCreateInfo.surface = vkSurfaceKHR; vkSwapchainCreateInfo.minImageCount = MAX_FRAMES_IN_FLIGHT; vkSwapchainCreateInfo.imageFormat = vkSurfaceFormatKHR.format; vkSwapchainCreateInfo.imageColorSpace = vkSurfaceFormatKHR.colorSpace; vkSwapchainCreateInfo.imageExtent = Extent; vkSwapchainCreateInfo.imageArrayLayers = 1; vkSwapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; // vkSwapchainCreateInfo.imageSharingMode = {}; vkSwapchainCreateInfo.queueFamilyIndexCount = 0; vkSwapchainCreateInfo.pQueueFamilyIndices = nullptr; vkSwapchainCreateInfo.preTransform = surfaceCapabilities.currentTransform; vkSwapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; vkSwapchainCreateInfo.presentMode = vkPresentModeKHR; vkSwapchainCreateInfo.clipped = VK_TRUE; // vkSwapchainCreateInfo.oldSwapchain = vkSwapchainKHR; vkSwapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE; unsigned int qfi[2] = { graphicsFamilyIndex, presentFamilyIndex }; if (graphicsFamilyIndex != presentFamilyIndex) { vkSwapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; vkSwapchainCreateInfo.queueFamilyIndexCount = 2; vkSwapchainCreateInfo.pQueueFamilyIndices = qfi; } else { vkSwapchainCreateInfo.imageSharingMode = VkSharingMode::VK_SHARING_MODE_EXCLUSIVE; vkSwapchainCreateInfo.queueFamilyIndexCount = 0; } vkResult = vkCreateSwapchainKHR(vkDevice, &vkSwapchainCreateInfo, vkAllocator, &vkSwapchainKHR); assert(vkResult == VK_SUCCESS); VkImageSubresourceRange vkImageSubresourceRange; vkImageSubresourceRange.aspectMask = VkImageAspectFlagBits::VK_IMAGE_ASPECT_COLOR_BIT; vkImageSubresourceRange.baseMipLevel = 0u; vkImageSubresourceRange.levelCount = 1u; vkImageSubresourceRange.baseArrayLayer = 0u; vkImageSubresourceRange.layerCount = 1u; VkImageViewCreateInfo vkImageViewCreateInfo; vkImageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; vkImageViewCreateInfo.pNext = nullptr; vkImageViewCreateInfo.flags = 0; vkImageViewCreateInfo.viewType = VkImageViewType::VK_IMAGE_VIEW_TYPE_2D; vkImageViewCreateInfo.format = vkSurfaceFormatKHR.format; vkImageViewCreateInfo.components = { VkComponentSwizzle::VK_COMPONENT_SWIZZLE_IDENTITY, VkComponentSwizzle::VK_COMPONENT_SWIZZLE_IDENTITY, VkComponentSwizzle::VK_COMPONENT_SWIZZLE_IDENTITY, VkComponentSwizzle::VK_COMPONENT_SWIZZLE_IDENTITY, }; vkImageViewCreateInfo.subresourceRange = vkImageSubresourceRange; assert(swapchainImages == nullptr || swapchainImages == CAFE_BABE(VkImage)); assert(swapchainImageViews == nullptr || swapchainImageViews == CAFE_BABE(VkImageView)); assert(renderImages == nullptr || renderImages == CAFE_BABE(VkImage)); assert(renderImageViews == nullptr || renderImageViews == CAFE_BABE(VkImageView)); assert(colorImages == nullptr || colorImages == CAFE_BABE(VkImage)); assert(colorImageViews == nullptr || colorImageViews == CAFE_BABE(VkImageView)); assert(depthImages == nullptr || depthImages == CAFE_BABE(VkImage)); assert(depthImageViews == nullptr || depthImageViews == CAFE_BABE(VkImageView)); assert(d2OverlayImages == nullptr || d2OverlayImages == CAFE_BABE(VkImage)); assert(d2OverlayImageViews == nullptr || d2OverlayImageViews == CAFE_BABE(VkImageView)); vkResult = vkGetSwapchainImagesKHR(vkDevice, vkSwapchainKHR, &swapchainLength, nullptr); assert(vkResult == VK_SUCCESS); swapchainImages = pk_new(swapchainLength); vkResult = vkGetSwapchainImagesKHR(vkDevice, vkSwapchainKHR, &swapchainLength, swapchainImages); assert(vkResult == VK_SUCCESS); swapchainImageViews = pk_new(swapchainLength); for (long i = 0; i < swapchainLength; ++i) { vkImageViewCreateInfo.image = swapchainImages[i]; vkResult = vkCreateImageView(vkDevice, &vkImageViewCreateInfo, vkAllocator, &swapchainImageViews[i]); assert(vkResult == VK_SUCCESS); } // render target items VkImageCreateInfo renderTargetImageCI{}; renderTargetImageCI.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; renderTargetImageCI.pNext = nullptr; renderTargetImageCI.flags = 0; renderTargetImageCI.imageType = VK_IMAGE_TYPE_2D; renderTargetImageCI.format = vkSurfaceFormatKHR.format; renderTargetImageCI.extent.width = Extent.width; renderTargetImageCI.extent.height = Extent.height; renderTargetImageCI.extent.depth = 1; renderTargetImageCI.mipLevels = 1; renderTargetImageCI.arrayLayers = 1; renderTargetImageCI.samples = VK_SAMPLE_COUNT_1_BIT; renderTargetImageCI.tiling = VK_IMAGE_TILING_OPTIMAL; renderTargetImageCI.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; renderTargetImageCI.sharingMode = VK_SHARING_MODE_EXCLUSIVE; renderTargetImageCI.queueFamilyIndexCount = 0; renderTargetImageCI.pQueueFamilyIndices = nullptr; renderTargetImageCI.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // render images renderImages = pk_new(MAX_FRAMES_IN_FLIGHT); renderImageViews = pk_new(MAX_FRAMES_IN_FLIGHT); CreateImageResources_Inner(&renderTargetImageCI, &vkImageViewCreateInfo, VkBufferUsageFlagBits(0), nullptr, renderImages, renderImageViews, &renderImagesMemory); // color images colorImages = pk_new(MAX_FRAMES_IN_FLIGHT); colorImageViews = pk_new(MAX_FRAMES_IN_FLIGHT); renderTargetImageCI.samples = renderSampleCount; renderTargetImageCI.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; CreateImageResources_Inner(&renderTargetImageCI, &vkImageViewCreateInfo, VkBufferUsageFlagBits(0), nullptr, colorImages, colorImageViews, &colorImagesMemory); // 2d overlay images d2OverlayImages = pk_new(MAX_FRAMES_IN_FLIGHT); d2OverlayImageViews = pk_new(MAX_FRAMES_IN_FLIGHT); CreateImageResources_Inner(&renderTargetImageCI, &vkImageViewCreateInfo, VkBufferUsageFlagBits(0), nullptr, d2OverlayImages, d2OverlayImageViews, &d2OverlayImagesMemory); // depth images depthImages = pk_new(MAX_FRAMES_IN_FLIGHT); depthImageViews = pk_new(MAX_FRAMES_IN_FLIGHT); renderTargetImageCI.format = depthFormat; vkImageViewCreateInfo.format = depthFormat; renderTargetImageCI.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; vkImageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; CreateImageResources_Inner(&renderTargetImageCI, &vkImageViewCreateInfo, VkBufferUsageFlagBits(0), nullptr, depthImages, depthImageViews, &depthImagesMemory); } void UpdatePresentDescriptorSets() { VkWriteDescriptorSet writeDescriptorSets[MAX_FRAMES_IN_FLIGHT]; VkDescriptorImageInfo descriptorImageInfo[MAX_FRAMES_IN_FLIGHT]; for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { writeDescriptorSets[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSets[i].pNext = nullptr; writeDescriptorSets[i].dstBinding = 0U; writeDescriptorSets[i].dstArrayElement = 0U; writeDescriptorSets[i].descriptorCount = 1; writeDescriptorSets[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptorSets[i].pBufferInfo = nullptr; writeDescriptorSets[i].pTexelBufferView = nullptr; descriptorImageInfo[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; descriptorImageInfo[i].sampler = presentSampler; descriptorImageInfo[i].imageView = renderImageViews[i]; writeDescriptorSets[i].pImageInfo = &descriptorImageInfo[i]; writeDescriptorSets[i].dstSet = presentDescriptorSets[i]; } vkUpdateDescriptorSets(vkDevice, MAX_FRAMES_IN_FLIGHT, writeDescriptorSets, 0, nullptr); } void UpdateCamera() { if (ActiveCamera->stale == PkeCameraStaleFlags{0}) return; CompInstance *inst = nullptr; CompInstance *targetInst = nullptr; glm::vec3 gPos; glm::quat gRot; btTransform trfm; if (ActiveCamera == &NullCamera) { inst = &NullCameraInstance; } else { inst = ECS_GetInstance(ActiveCamera->phys.instHandle); } inst->bt.motionState->getWorldTransform(trfm); BulletToGlm(trfm.getOrigin(), gPos); BulletToGlm(trfm.getRotation(), gRot); if (bool(ActiveCamera->stale & PKE_CAMERA_STALE_POS)) { UBO.model = glm::translate(glm::mat4(1.f), gPos); } if (bool(ActiveCamera->stale & PKE_CAMERA_STALE_ROT)) { if (bool(ActiveCamera->view == PKE_CAMERA_VIEW_FREE)) { UBO.view = glm::mat4_cast(gRot); } else if (bool(ActiveCamera->view == PKE_CAMERA_VIEW_TARGET)) { glm::vec3 gTargetPos{0.f, 0.f, 0.f}; targetInst = ECS_GetInstance(ActiveCamera->phys.targetInstHandle); if (targetInst != nullptr && targetInst != CAFE_BABE(CompInstance)) { btTransform targetTrfm; targetInst->bt.motionState->getWorldTransform(targetTrfm); BulletToGlm(targetTrfm.getOrigin(), gTargetPos); } UBO.view = glm::lookAt(glm::vec3(0), gPos + gTargetPos, glm::vec3(0.f, 1.f, 0.f)); } } if (bool(ActiveCamera->stale & PKE_CAMERA_STALE_PERSPECTIVE)) { if (bool(ActiveCamera->type == PKE_CAMERA_TYPE_PERSPECTIVE)) { UBO.proj = glm::perspective(glm::radians(45.f), Extent.width / (float)Extent.height, 0.1f, 1000.f); UBO.proj[1][1] *= -1; } else if (bool(ActiveCamera->type == PKE_CAMERA_TYPE_ORTHOGONAL)) { UBO.proj = glm::ortho(0.f, (float)Extent.width, 0.f, (float)Extent.height, 0.f, 1000.f); UBO.proj[1][1] *= -1; } } ActiveCamera->stale = PkeCameraStaleFlags{0}; } void CreateRenderPass() { VkAttachmentDescription colorAttachment; colorAttachment.flags = {}; colorAttachment.format = vkSurfaceFormatKHR.format; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass; subpass.flags = {}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.inputAttachmentCount = 0; subpass.pInputAttachments = nullptr; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; subpass.pResolveAttachments = nullptr; subpass.pDepthStencilAttachment = nullptr; subpass.preserveAttachmentCount = 0; subpass.pPreserveAttachments = nullptr; VkSubpassDependency subpassDependencies[2]; for (long i = 0; i < 2; ++i) { subpassDependencies[i].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; } subpassDependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; subpassDependencies[0].dstSubpass = 0U; subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; subpassDependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; subpassDependencies[1].srcSubpass = 0U; subpassDependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; subpassDependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; subpassDependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; subpassDependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; VkRenderPassCreateInfo renderPassInfo; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.pNext = nullptr; renderPassInfo.flags = {}; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = 2; renderPassInfo.pDependencies = subpassDependencies; if (vkCreateRenderPass(vkDevice, &renderPassInfo, vkAllocator, &presentRenderPass) != VK_SUCCESS) { throw "failed to create present render pass!"; } colorAttachment.samples = renderSampleCount; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentDescription colorAttachmentResolve{colorAttachment}; colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkAttachmentReference colorAttachmentReseolveRef; colorAttachmentReseolveRef.attachment = 1; colorAttachmentReseolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; subpass.pColorAttachments = &colorAttachmentRef; subpass.pResolveAttachments = &colorAttachmentReseolveRef; subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT; subpassDependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; subpassDependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; subpassDependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; subpassDependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; VkAttachmentDescription d2o_attachments[2] = { colorAttachment, colorAttachmentResolve }; renderPassInfo.attachmentCount = 2; renderPassInfo.pAttachments = d2o_attachments; renderPassInfo.dependencyCount = 2; renderPassInfo.pDependencies = subpassDependencies; if (vkCreateRenderPass(vkDevice, &renderPassInfo, vkAllocator, &d2OverlayRenderPass) != VK_SUCCESS) { throw "failed to create render pass!"; } colorAttachment.samples = renderSampleCount; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentDescription depthAttachment; depthAttachment.flags = 0; depthAttachment.format = depthFormat; depthAttachment.samples = renderSampleCount; depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkAttachmentReference depthAttachmentRef; depthAttachmentRef.attachment = 1; depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; colorAttachmentReseolveRef.attachment = 2; colorAttachmentReseolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; subpass.pColorAttachments = &colorAttachmentRef; subpass.pResolveAttachments = &colorAttachmentReseolveRef; subpass.pDepthStencilAttachment = &depthAttachmentRef; subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT; subpassDependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; subpassDependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; subpassDependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; subpassDependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; VkAttachmentDescription attachments[3] = { colorAttachment, depthAttachment, colorAttachmentResolve }; renderPassInfo.attachmentCount = 3; renderPassInfo.pAttachments = attachments; renderPassInfo.dependencyCount = 2; renderPassInfo.pDependencies = subpassDependencies; if (vkCreateRenderPass(vkDevice, &renderPassInfo, vkAllocator, &renderRenderPass) != VK_SUCCESS) { throw "failed to create render pass!"; } } void CreatePresentPipeline() { // enqueue asset loading AssetHandle vertShaderAsset{AM_GetHandle(AssetKey{"pke_prsnt_vrt\0\0"})}; AssetHandle fragShaderAsset{AM_GetHandle(AssetKey{"pke_prsnt_frg\0\0"})}; VkPipelineShaderStageCreateInfo shaderStages[2]; for (long i = 0; i < 2; ++i) { shaderStages[i].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[i].pNext = nullptr; shaderStages[i].flags = 0; shaderStages[i].pName = "main"; shaderStages[i].pSpecializationInfo = nullptr; } shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; // shaderStages[0].module = // see below // shaderStages[1].module = // see below VkDynamicState dynamicStates[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState; dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicState.pNext = nullptr; dynamicState.flags = {}; dynamicState.dynamicStateCount = 2; dynamicState.pDynamicStates = dynamicStates; VkPipelineVertexInputStateCreateInfo vertexInputInfo; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.pNext = nullptr; vertexInputInfo.flags = {}; vertexInputInfo.vertexBindingDescriptionCount = 0; vertexInputInfo.pVertexBindingDescriptions = nullptr; vertexInputInfo.vertexAttributeDescriptionCount = 0; vertexInputInfo.pVertexAttributeDescriptions = nullptr; VkPipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.pNext = nullptr; inputAssembly.flags = {}; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float) Extent.width; viewport.height = (float) Extent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor; scissor.offset = {0, 0}; scissor.extent = Extent; VkPipelineViewportStateCreateInfo viewportState; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.pNext = nullptr; viewportState.flags = {}; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.pNext = nullptr; rasterizer.flags = {}; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; rasterizer.depthBiasConstantFactor = 0.0f; rasterizer.depthBiasClamp = 0.0f; rasterizer.depthBiasSlopeFactor = 0.0f; rasterizer.lineWidth = 1.0f; VkPipelineMultisampleStateCreateInfo multisampling; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.pNext = nullptr; multisampling.flags = {}; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.sampleShadingEnable = VK_FALSE; multisampling.minSampleShading = 1.0f; multisampling.pSampleMask = nullptr; multisampling.alphaToCoverageEnable = VK_FALSE; multisampling.alphaToOneEnable = VK_FALSE; // TODO VkPipelineDepthStencilStateCreateInfo depthStencilInfo{}; depthStencilInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencilInfo.pNext = nullptr; depthStencilInfo.flags = 0; depthStencilInfo.depthTestEnable = VK_FALSE; depthStencilInfo.depthWriteEnable = VK_FALSE; depthStencilInfo.depthCompareOp = VK_COMPARE_OP_LESS; depthStencilInfo.depthBoundsTestEnable = VK_FALSE; depthStencilInfo.stencilTestEnable = VK_FALSE; depthStencilInfo.front = {}; depthStencilInfo.back = {}; depthStencilInfo.minDepthBounds = {}; depthStencilInfo.maxDepthBounds = {}; VkPipelineColorBlendAttachmentState colorBlendAttachment; colorBlendAttachment.blendEnable = VK_FALSE; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineColorBlendStateCreateInfo colorBlending; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.pNext = nullptr; colorBlending.flags = {}; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; /* * PipelineLayout + DescriptorSets */ VkDescriptorSetLayoutBinding imageSamplerLayoutBinding; imageSamplerLayoutBinding.binding = 0; imageSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; imageSamplerLayoutBinding.descriptorCount = 1; imageSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; imageSamplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo; descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutCreateInfo.pNext = nullptr; descriptorSetLayoutCreateInfo.flags = 0; descriptorSetLayoutCreateInfo.bindingCount = 1; descriptorSetLayoutCreateInfo.pBindings = &imageSamplerLayoutBinding; auto vkResult = vkCreateDescriptorSetLayout(vkDevice, &descriptorSetLayoutCreateInfo, vkAllocator, &vkDescriptorSetLayout); if (vkResult != VK_SUCCESS) { throw "failed to create descriptor set layout"; } VkDescriptorPoolSize vkDescriptorPoolSize; vkDescriptorPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; vkDescriptorPoolSize.descriptorCount = swapchainLength; VkDescriptorPoolCreateInfo descriptorPoolCreateInfo; descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPoolCreateInfo.pNext = nullptr; descriptorPoolCreateInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; descriptorPoolCreateInfo.maxSets = MAX_FRAMES_IN_FLIGHT; descriptorPoolCreateInfo.poolSizeCount = 1; descriptorPoolCreateInfo.pPoolSizes = &vkDescriptorPoolSize; vkResult = vkCreateDescriptorPool(vkDevice, &descriptorPoolCreateInfo, vkAllocator, &presentDescriptorPool); assert(vkResult == VK_SUCCESS); VkDescriptorSetLayout setLayouts[MAX_FRAMES_IN_FLIGHT]; for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { setLayouts[i] = vkDescriptorSetLayout; } VkDescriptorSetAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.descriptorPool = presentDescriptorPool; allocInfo.descriptorSetCount = MAX_FRAMES_IN_FLIGHT; allocInfo.pSetLayouts = setLayouts; vkResult = vkAllocateDescriptorSets(vkDevice, &allocInfo, presentDescriptorSets); if (vkResult != VK_SUCCESS) { throw "failed to allocate present descriptor sets"; } VkPipelineLayoutCreateInfo pipelineLayoutInfo; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.pNext = nullptr; pipelineLayoutInfo.flags = {}; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &vkDescriptorSetLayout; pipelineLayoutInfo.pushConstantRangeCount = 0; pipelineLayoutInfo.pPushConstantRanges = nullptr; vkResult = vkCreatePipelineLayout(vkDevice, &pipelineLayoutInfo, vkAllocator, &pipelineLayout); if (vkResult != VK_SUCCESS) { throw "failed to create pipeline layout"; } VkGraphicsPipelineCreateInfo pipelineInfo; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineInfo.pNext = nullptr; pipelineInfo.flags = {}; pipelineInfo.stageCount = 2; pipelineInfo.pStages = shaderStages; pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pTessellationState = nullptr; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = &depthStencilInfo; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = &dynamicState; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = presentRenderPass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; pipelineInfo.basePipelineIndex = {}; /* 2023-12-22 JCB * This happens just before needed because we want to let this * thread run while background threads load the assets. */ auto vertShader = UploadShader(vertShaderAsset); auto fragShader = UploadShader(fragShaderAsset); shaderStages[0].module = vertShader; shaderStages[1].module = fragShader; vkResult = vkCreateGraphicsPipelines(vkDevice, VK_NULL_HANDLE, 1, &pipelineInfo, vkAllocator, &graphicsPipeline); if (vkResult != VK_SUCCESS) { throw "failed to create graphics pipeline."; } vkDestroyShaderModule(vkDevice, fragShader, vkAllocator); vkDestroyShaderModule(vkDevice, vertShader, vkAllocator); AM_Release(fragShaderAsset); AM_Release(vertShaderAsset); } void CreateFramebuffers() { assert(swapchainFramebuffers == nullptr || swapchainFramebuffers == CAFE_BABE(VkFramebuffer)); assert(renderImageFramebuffers == nullptr || renderImageFramebuffers == CAFE_BABE(VkFramebuffer)); assert(d2OverlayImageFramebuffers == nullptr || d2OverlayImageFramebuffers == CAFE_BABE(VkFramebuffer)); swapchainFramebuffers = pk_new(swapchainLength); renderImageFramebuffers = pk_new(swapchainLength); d2OverlayImageFramebuffers = pk_new(swapchainLength); VkFramebufferCreateInfo framebufferInfo; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.pNext = nullptr; framebufferInfo.flags = {}; framebufferInfo.renderPass = presentRenderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = nullptr; framebufferInfo.width = Extent.width; framebufferInfo.height = Extent.height; framebufferInfo.layers = 1; for (long i = 0; i < swapchainLength; ++i) { VkImageView attachments[] = { swapchainImageViews[i] }; framebufferInfo.pAttachments = attachments; auto result = vkCreateFramebuffer(vkDevice, &framebufferInfo, vkAllocator, &swapchainFramebuffers[i]); if (result != VK_SUCCESS) { throw "failed to create present framebuffer"; } } framebufferInfo.attachmentCount = 2; framebufferInfo.renderPass = d2OverlayRenderPass; for (long i = 0; i < swapchainLength; ++i) { VkImageView attachments[] = { colorImageViews[i], renderImageViews[i], }; framebufferInfo.pAttachments = attachments; auto result = vkCreateFramebuffer(vkDevice, &framebufferInfo, vkAllocator, &d2OverlayImageFramebuffers[i]); if (result != VK_SUCCESS) { throw "failed to create 2d overlay framebuffer"; } } framebufferInfo.attachmentCount = 3; framebufferInfo.renderPass = renderRenderPass; for (long i = 0; i < swapchainLength; ++i) { VkImageView attachments[] = { colorImageViews[i], depthImageViews[i], renderImageViews[i], }; framebufferInfo.pAttachments = attachments; auto result = vkCreateFramebuffer(vkDevice, &framebufferInfo, vkAllocator, &renderImageFramebuffers[i]); if (result != VK_SUCCESS) { throw "failed to create render framebuffer"; } } } void CreateCommandPool() { VkCommandPoolCreateInfo poolInfo; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.pNext = nullptr; poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; poolInfo.queueFamilyIndex = graphicsFamilyIndex; auto result = vkCreateCommandPool(vkDevice, &poolInfo, vkAllocator, &graphicsCommandPool); if (result != VK_SUCCESS) { throw "failed to create command pool"; } poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; poolInfo.queueFamilyIndex = transferFamilyIndex; result = vkCreateCommandPool(vkDevice, &poolInfo, vkAllocator, &transferCommandPool); if (result != VK_SUCCESS) { throw "failed to create transfer command pool"; } } void CreateCommandBuffer() { VkCommandBufferAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.commandPool = graphicsCommandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = MAX_FRAMES_IN_FLIGHT; auto result = vkAllocateCommandBuffers(vkDevice, &allocInfo, presentCommandBuffers); if (result != VK_SUCCESS) { throw "failed to allocate command buffer"; } allocInfo.commandBufferCount = 1; result = vkAllocateCommandBuffers(vkDevice, &allocInfo, &graphicsCommandBuffer); if (result != VK_SUCCESS) { throw "failed to allocate command buffer"; } allocInfo.commandPool = transferCommandPool; result = vkAllocateCommandBuffers(vkDevice, &allocInfo, &transferCommandBuffer); if (result != VK_SUCCESS) { throw "failed to allocate command buffer"; } } void CreateUniformBuffers() { uint32_t queueFamilyIndexes[2] = {graphicsFamilyIndex, transferFamilyIndex}; VkBufferCreateInfo vkBufferCreateInfo; vkBufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; vkBufferCreateInfo.pNext = nullptr; vkBufferCreateInfo.flags = {}; vkBufferCreateInfo.size = sizeof(UniformBufferObject); vkBufferCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; vkBufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; vkBufferCreateInfo.queueFamilyIndexCount = graphicsFamilyIndex == transferFamilyIndex ? 1 : 2; vkBufferCreateInfo.pQueueFamilyIndices = queueFamilyIndexes; VkResult result; result = vkCreateBuffer(vkDevice, &vkBufferCreateInfo, vkAllocator, &UniformBuffers[0]); assert(result == VK_SUCCESS); VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(vkDevice, UniformBuffers[0], &memReqs); paddedUboBufferSize = memReqs.size + (memReqs.alignment - (memReqs.size & memReqs.alignment)); VkMemoryAllocateInfo vkMemoryAllocateInfo; vkMemoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vkMemoryAllocateInfo.pNext = nullptr; vkMemoryAllocateInfo.allocationSize = paddedUboBufferSize * MAX_FRAMES_IN_FLIGHT; vkMemoryAllocateInfo.memoryTypeIndex = FindMemoryTypeIndex(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); result = vkAllocateMemory(vkDevice, &vkMemoryAllocateInfo, vkAllocator, &uniformBufferMemory); assert(result == VK_SUCCESS); vkDestroyBuffer(vkDevice, UniformBuffers[0], vkAllocator); vkBufferCreateInfo.size = paddedUboBufferSize; for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { result = vkCreateBuffer(vkDevice, &vkBufferCreateInfo, vkAllocator, &UniformBuffers[i]); assert(result == VK_SUCCESS); result = vkBindBufferMemory(vkDevice, UniformBuffers[i], uniformBufferMemory, paddedUboBufferSize * i); assert(result == VK_SUCCESS); } } void CreateSyncObjects() { VkSemaphoreCreateInfo semaphoreInfo; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphoreInfo.pNext = nullptr; semaphoreInfo.flags = {}; VkFenceCreateInfo fenceInfo; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext = nullptr; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { auto result1 = vkCreateSemaphore(vkDevice, &semaphoreInfo, vkAllocator, &presentImageAvailableSemaphores[i]); auto result2 = vkCreateSemaphore(vkDevice, &semaphoreInfo, vkAllocator, &presentRenderFinishedSemaphores[i]); auto result3 = vkCreateFence(vkDevice, &fenceInfo, vkAllocator, &presentInFlightFences[i]); auto result = result1 == result2 && result2 == result3 && result3 == VK_SUCCESS; if (!result) { throw "failed to create sync objects"; } } } void CreateGraphicsPipelines() { // layouts & sampler { VkDescriptorSetLayoutBinding vkDescriptorSetLayoutBindings[2]; for (long i = 0; i < 2; ++i) { vkDescriptorSetLayoutBindings[i].pImmutableSamplers = nullptr; } vkDescriptorSetLayoutBindings[0].binding = 0; vkDescriptorSetLayoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; vkDescriptorSetLayoutBindings[0].descriptorCount = 1; vkDescriptorSetLayoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; vkDescriptorSetLayoutBindings[1].binding = 1; vkDescriptorSetLayoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; vkDescriptorSetLayoutBindings[1].descriptorCount = 1; vkDescriptorSetLayoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutCreateInfo vkDescriptorSetLayoutCreateInfo { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .pNext = nullptr, .flags = 0, .bindingCount = 2, .pBindings = vkDescriptorSetLayoutBindings, }; vkCreateDescriptorSetLayout(vkDevice, &vkDescriptorSetLayoutCreateInfo, vkAllocator, &pkePipelines.vkDescriptorSetLayout_Texture); VkPipelineLayoutCreateInfo vkPipelineLayoutCreateInfo { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .pNext = nullptr, .flags = 0, .setLayoutCount = 1, .pSetLayouts = &pkePipelines.vkDescriptorSetLayout_Texture, .pushConstantRangeCount = 0, .pPushConstantRanges = nullptr, }; vkCreatePipelineLayout(vkDevice, &vkPipelineLayoutCreateInfo, vkAllocator, &pkePipelines.vkPipelineLayout_Texture); VkSamplerCreateInfo vkSamplerCreateInfo; vkSamplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; vkSamplerCreateInfo.pNext = nullptr; vkSamplerCreateInfo.flags = 0; vkSamplerCreateInfo.magFilter = VK_FILTER_NEAREST; vkSamplerCreateInfo.minFilter = VK_FILTER_NEAREST; vkSamplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; vkSamplerCreateInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; vkSamplerCreateInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; vkSamplerCreateInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; vkSamplerCreateInfo.mipLodBias = 0.0f; vkSamplerCreateInfo.anisotropyEnable = VK_TRUE; vkSamplerCreateInfo.maxAnisotropy = vkPhysicalDeviceProperties.limits.maxSamplerAnisotropy; vkSamplerCreateInfo.compareEnable = VK_FALSE; vkSamplerCreateInfo.compareOp = VK_COMPARE_OP_ALWAYS; vkSamplerCreateInfo.minLod = 0.0f; // TODO MipMap vkSamplerCreateInfo.maxLod = 1; vkSamplerCreateInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; vkSamplerCreateInfo.unnormalizedCoordinates = VK_FALSE; vkCreateSampler(vkDevice, &vkSamplerCreateInfo, vkAllocator, &pkePipelines.vkSampler_Texture); } // pipelines { // enqueue asset loading AssetHandle vertShaderAssetHandle{AM_GetHandle(AssetKey{"pke_txtr_vrt\0\0\0"})}; AssetHandle textureFragShaderAssetHandle { AM_GetHandle(AssetKey{"pke_txtr_frg\0\0\0"})}; const long vertexBindingCount = 4; long index = 0; VkVertexInputBindingDescription vertInputBD[vertexBindingCount]; // model vertex vertInputBD[index].binding = index; vertInputBD[index].stride = sizeof(glm::vec3); vertInputBD[index].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; index += 1; // model normals vertInputBD[index].binding = index; vertInputBD[index].stride = sizeof(glm::vec3); vertInputBD[index].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; index += 1; // model UV vertInputBD[index].binding = index; vertInputBD[index].stride = sizeof(glm::vec2); vertInputBD[index].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; index += 1; // model index // vertInputBD[index].binding = index; // vertInputBD[index].stride = sizeof(uint16_t); // vertInputBD[index].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // index += 1; // instance vertInputBD[index].binding = index; vertInputBD[index].stride = sizeof(glm::mat4); vertInputBD[index].inputRate = VK_VERTEX_INPUT_RATE_INSTANCE; const long vertexAttrDescCount = 7; index = 0; VkVertexInputAttributeDescription vertAttrDesc[vertexAttrDescCount]; for (long i = 0; i < vertexAttrDescCount; ++i) { vertAttrDesc[i].location = i; } // model vertex vertAttrDesc[index].binding = 0; vertAttrDesc[index].format = VK_FORMAT_R32G32B32_SFLOAT; vertAttrDesc[index].offset = 0; index += 1; // model normals vertAttrDesc[index].binding = 1; vertAttrDesc[index].format = VK_FORMAT_R32G32B32_SFLOAT; vertAttrDesc[index].offset = 0; index += 1; // model UV vertAttrDesc[index].binding = 2; vertAttrDesc[index].format = VK_FORMAT_R32G32_SFLOAT; vertAttrDesc[index].offset = 0; index += 1; // instPosRotScale for (long i = 0; i < 4; ++i) { vertAttrDesc[index].binding = 3; vertAttrDesc[index].format = VK_FORMAT_R32G32B32A32_SFLOAT; vertAttrDesc[index].offset = sizeof(glm::vec4) * i; index += 1; } // instance texture index // vertAttrDesc[index].binding = 3; // vertAttrDesc[index].format = VK_FORMAT_R32_SFLOAT; // vertAttrDesc[index].offset = runningOffset; // runningOffset += sizeof(float); // index += 1; VkPipelineVertexInputStateCreateInfo vkPipelineVertexInputStateCreateInfo; vkPipelineVertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vkPipelineVertexInputStateCreateInfo.pNext = nullptr; vkPipelineVertexInputStateCreateInfo.flags = {}; vkPipelineVertexInputStateCreateInfo.vertexBindingDescriptionCount = vertexBindingCount; vkPipelineVertexInputStateCreateInfo.pVertexBindingDescriptions = vertInputBD; vkPipelineVertexInputStateCreateInfo.vertexAttributeDescriptionCount = vertexAttrDescCount; vkPipelineVertexInputStateCreateInfo.pVertexAttributeDescriptions = vertAttrDesc; VkPipelineInputAssemblyStateCreateInfo vkPipelineInputAssemblyStateCreateInfo; vkPipelineInputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; vkPipelineInputAssemblyStateCreateInfo.pNext = nullptr; vkPipelineInputAssemblyStateCreateInfo.flags = {}; vkPipelineInputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; vkPipelineInputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; // TODO - is this right? set to dynamic later VkPipelineViewportStateCreateInfo vkPipelineViewportStateCreateInfo; vkPipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vkPipelineViewportStateCreateInfo.pNext = nullptr; vkPipelineViewportStateCreateInfo.flags = {}; vkPipelineViewportStateCreateInfo.viewportCount = 1; vkPipelineViewportStateCreateInfo.pViewports = nullptr; vkPipelineViewportStateCreateInfo.scissorCount = 1; vkPipelineViewportStateCreateInfo.pScissors = nullptr; VkPipelineRasterizationStateCreateInfo vkPipelineRasterizationStateCreateInfoFill; vkPipelineRasterizationStateCreateInfoFill.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; vkPipelineRasterizationStateCreateInfoFill.pNext = nullptr; vkPipelineRasterizationStateCreateInfoFill.flags = {}; vkPipelineRasterizationStateCreateInfoFill.depthClampEnable = VK_FALSE; vkPipelineRasterizationStateCreateInfoFill.rasterizerDiscardEnable = VK_FALSE; vkPipelineRasterizationStateCreateInfoFill.polygonMode = VK_POLYGON_MODE_FILL; vkPipelineRasterizationStateCreateInfoFill.cullMode = VK_CULL_MODE_BACK_BIT; vkPipelineRasterizationStateCreateInfoFill.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; vkPipelineRasterizationStateCreateInfoFill.depthBiasEnable = VK_FALSE; vkPipelineRasterizationStateCreateInfoFill.depthBiasConstantFactor = 0.0f; vkPipelineRasterizationStateCreateInfoFill.depthBiasClamp = 0.0f; vkPipelineRasterizationStateCreateInfoFill.depthBiasSlopeFactor = 0.0f; vkPipelineRasterizationStateCreateInfoFill.lineWidth = 1.0f; VkPipelineRasterizationStateCreateInfo vkPipelineRasterizationStateCreateInfoLine{vkPipelineRasterizationStateCreateInfoFill}; vkPipelineRasterizationStateCreateInfoLine.cullMode = VK_CULL_MODE_NONE; vkPipelineRasterizationStateCreateInfoLine.polygonMode = VK_POLYGON_MODE_LINE; vkPipelineRasterizationStateCreateInfoLine.lineWidth = 5.f; VkPipelineMultisampleStateCreateInfo vkPipelineMultisampleStateCreateInfo; vkPipelineMultisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; vkPipelineMultisampleStateCreateInfo.pNext = nullptr; vkPipelineMultisampleStateCreateInfo.flags = 0; vkPipelineMultisampleStateCreateInfo.rasterizationSamples = renderSampleCount; vkPipelineMultisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; vkPipelineMultisampleStateCreateInfo.minSampleShading = 0.0f; vkPipelineMultisampleStateCreateInfo.pSampleMask = nullptr; vkPipelineMultisampleStateCreateInfo.alphaToCoverageEnable = VK_FALSE; vkPipelineMultisampleStateCreateInfo.alphaToOneEnable = VK_FALSE; // TODO Transparency VkPipelineColorBlendAttachmentState vkPipelineColorBlendAttachmentState[1]; vkPipelineColorBlendAttachmentState[0].blendEnable = VK_FALSE; vkPipelineColorBlendAttachmentState[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; vkPipelineColorBlendAttachmentState[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; vkPipelineColorBlendAttachmentState[0].colorBlendOp = VK_BLEND_OP_ADD; vkPipelineColorBlendAttachmentState[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; vkPipelineColorBlendAttachmentState[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; vkPipelineColorBlendAttachmentState[0].alphaBlendOp = VK_BLEND_OP_SUBTRACT; vkPipelineColorBlendAttachmentState[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineColorBlendStateCreateInfo vkPipelineColorBlendStateCreateInfo; vkPipelineColorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; vkPipelineColorBlendStateCreateInfo.pNext = nullptr; vkPipelineColorBlendStateCreateInfo.flags = {}; vkPipelineColorBlendStateCreateInfo.logicOpEnable = VK_FALSE; vkPipelineColorBlendStateCreateInfo.logicOp = VK_LOGIC_OP_COPY; vkPipelineColorBlendStateCreateInfo.attachmentCount = 1; vkPipelineColorBlendStateCreateInfo.pAttachments = vkPipelineColorBlendAttachmentState; vkPipelineColorBlendStateCreateInfo.blendConstants[0] = 0.0f; vkPipelineColorBlendStateCreateInfo.blendConstants[1] = 0.0f; vkPipelineColorBlendStateCreateInfo.blendConstants[2] = 0.0f; vkPipelineColorBlendStateCreateInfo.blendConstants[3] = 0.0f; VkDynamicState dynamicStates[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo vkPipelineDynamicStateCreateInfo; vkPipelineDynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; vkPipelineDynamicStateCreateInfo.pNext = nullptr; vkPipelineDynamicStateCreateInfo.flags = {}; vkPipelineDynamicStateCreateInfo.dynamicStateCount = 2; vkPipelineDynamicStateCreateInfo.pDynamicStates = dynamicStates; VkPipelineDepthStencilStateCreateInfo vkPipelineDepthStencilStateCreateInfo; vkPipelineDepthStencilStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; vkPipelineDepthStencilStateCreateInfo.pNext = nullptr; vkPipelineDepthStencilStateCreateInfo.flags = {}; vkPipelineDepthStencilStateCreateInfo.depthTestEnable = VK_TRUE; vkPipelineDepthStencilStateCreateInfo.depthWriteEnable = VK_TRUE; vkPipelineDepthStencilStateCreateInfo.depthCompareOp = VK_COMPARE_OP_LESS; vkPipelineDepthStencilStateCreateInfo.depthBoundsTestEnable = VK_FALSE; vkPipelineDepthStencilStateCreateInfo.stencilTestEnable = VK_FALSE; vkPipelineDepthStencilStateCreateInfo.front = {}; vkPipelineDepthStencilStateCreateInfo.back = {}; vkPipelineDepthStencilStateCreateInfo.minDepthBounds = {}; vkPipelineDepthStencilStateCreateInfo.maxDepthBounds = {}; const Asset *textureVertShaderAsset = AM_Get(vertShaderAssetHandle); const Asset *textureFragShaderAsset = AM_Get(textureFragShaderAssetHandle); assert(textureVertShaderAsset != nullptr && textureVertShaderAsset->state == PKE_ASSET_LOADING_STATE_LOADED); assert(textureFragShaderAsset != nullptr && textureFragShaderAsset->state == PKE_ASSET_LOADING_STATE_LOADED); VkPipelineShaderStageCreateInfo vkPipelineShaderStageCreateInfo[2]; for (long i = 0; i < 2; ++i) { vkPipelineShaderStageCreateInfo[i].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vkPipelineShaderStageCreateInfo[i].pNext = nullptr; vkPipelineShaderStageCreateInfo[i].flags = {}; vkPipelineShaderStageCreateInfo[i].pName = "main"; vkPipelineShaderStageCreateInfo[i].pSpecializationInfo = nullptr; } vkPipelineShaderStageCreateInfo[0].stage = VK_SHADER_STAGE_VERTEX_BIT; vkPipelineShaderStageCreateInfo[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; // vkPipelineShaderStageCreateInfo[0].module = // deferred // vkPipelineShaderStageCreateInfo[1].module = // deferred VkGraphicsPipelineCreateInfo vkGraphicsPipelineCreateInfo[2]; for (long i = 0; i < 2; ++i) { vkGraphicsPipelineCreateInfo[i].sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; vkGraphicsPipelineCreateInfo[i].pNext = nullptr; vkGraphicsPipelineCreateInfo[i].flags = {}; vkGraphicsPipelineCreateInfo[i].stageCount = 2; vkGraphicsPipelineCreateInfo[i].pStages = vkPipelineShaderStageCreateInfo; vkGraphicsPipelineCreateInfo[i].pVertexInputState = &vkPipelineVertexInputStateCreateInfo; vkGraphicsPipelineCreateInfo[i].pInputAssemblyState = &vkPipelineInputAssemblyStateCreateInfo; vkGraphicsPipelineCreateInfo[i].pTessellationState = nullptr; vkGraphicsPipelineCreateInfo[i].pViewportState = &vkPipelineViewportStateCreateInfo; vkGraphicsPipelineCreateInfo[i].pMultisampleState = &vkPipelineMultisampleStateCreateInfo; vkGraphicsPipelineCreateInfo[i].pDepthStencilState = &vkPipelineDepthStencilStateCreateInfo; vkGraphicsPipelineCreateInfo[i].pColorBlendState = &vkPipelineColorBlendStateCreateInfo; vkGraphicsPipelineCreateInfo[i].pDynamicState = &vkPipelineDynamicStateCreateInfo; vkGraphicsPipelineCreateInfo[i].layout = pkePipelines.vkPipelineLayout_Texture; vkGraphicsPipelineCreateInfo[i].renderPass = renderRenderPass; vkGraphicsPipelineCreateInfo[i].subpass = 0; vkGraphicsPipelineCreateInfo[i].basePipelineHandle = VK_NULL_HANDLE; vkGraphicsPipelineCreateInfo[i].basePipelineIndex = {}; } vkGraphicsPipelineCreateInfo[0].pRasterizationState = &vkPipelineRasterizationStateCreateInfoFill; vkGraphicsPipelineCreateInfo[1].pRasterizationState = &vkPipelineRasterizationStateCreateInfoLine; // deffered shader creation vkPipelineShaderStageCreateInfo[0].module = UploadShader(vertShaderAssetHandle); vkPipelineShaderStageCreateInfo[1].module = UploadShader(textureFragShaderAssetHandle); vkCreateGraphicsPipelines(vkDevice, VK_NULL_HANDLE, 2, vkGraphicsPipelineCreateInfo, vkAllocator, pkePipelines.pipelines.arr); for (long i = 0; i < 2; ++i) { vkDestroyShaderModule(vkDevice, vkPipelineShaderStageCreateInfo[i].module, vkAllocator); } AM_Release(textureFragShaderAssetHandle); AM_Release(vertShaderAssetHandle); } // debug texture { VkImageCreateInfo dbgTextureCI; dbgTextureCI.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; dbgTextureCI.pNext = nullptr; dbgTextureCI.flags = 0; dbgTextureCI.imageType = VK_IMAGE_TYPE_2D; dbgTextureCI.format = VK_FORMAT_R8G8B8A8_SRGB; dbgTextureCI.extent = VkExtent3D { .width = 2, .height = 2, .depth = 1, }; dbgTextureCI.mipLevels = 1; dbgTextureCI.arrayLayers = 1; dbgTextureCI.samples = VK_SAMPLE_COUNT_1_BIT; dbgTextureCI.tiling = VK_IMAGE_TILING_OPTIMAL; dbgTextureCI.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; dbgTextureCI.sharingMode = VK_SHARING_MODE_EXCLUSIVE; dbgTextureCI.queueFamilyIndexCount = 0; dbgTextureCI.pQueueFamilyIndices = nullptr; dbgTextureCI.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VkResult result; result = vkCreateImage(vkDevice, &dbgTextureCI, vkAllocator, &pkeDebugHitbox.vkImage); assert(result == VK_SUCCESS); VkMemoryRequirements imageMemReqs; vkGetImageMemoryRequirements(vkDevice, pkeDebugHitbox.vkImage, &imageMemReqs); VkMemoryAllocateInfo imageAllocInfo; imageAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; imageAllocInfo.pNext = nullptr; imageAllocInfo.allocationSize = imageMemReqs.size; imageAllocInfo.memoryTypeIndex = FindMemoryTypeIndex(imageMemReqs.memoryTypeBits, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); if (imageAllocInfo.memoryTypeIndex == 0) { imageAllocInfo.memoryTypeIndex = FindMemoryTypeIndex(imageMemReqs.memoryTypeBits, 0); } result = vkAllocateMemory(vkDevice, &imageAllocInfo, vkAllocator, &pkeDebugHitbox.textureMemory); assert(result == VK_SUCCESS); result = vkBindImageMemory(vkDevice, pkeDebugHitbox.vkImage, pkeDebugHitbox.textureMemory, 0); assert(result == VK_SUCCESS); VkImageViewCreateInfo dbgImageViewCI; dbgImageViewCI.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; dbgImageViewCI.pNext = nullptr; dbgImageViewCI.flags = 0; dbgImageViewCI.image = pkeDebugHitbox.vkImage; dbgImageViewCI.viewType = VK_IMAGE_VIEW_TYPE_2D; dbgImageViewCI.format = VK_FORMAT_R8G8B8A8_SRGB; dbgImageViewCI.components = VkComponentMapping { .r = VK_COMPONENT_SWIZZLE_IDENTITY, .g = VK_COMPONENT_SWIZZLE_IDENTITY, .b = VK_COMPONENT_SWIZZLE_IDENTITY, .a = VK_COMPONENT_SWIZZLE_IDENTITY, }; dbgImageViewCI.subresourceRange = VkImageSubresourceRange { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1, }; result = vkCreateImageView(vkDevice, &dbgImageViewCI, vkAllocator, &pkeDebugHitbox.vkImageView); assert(result == VK_SUCCESS); VkBuffer transferImageBuffer; VkDeviceMemory transferImageMemory; void *deviceData; BeginTransferBuffer(4 * 4, transferImageBuffer, transferImageMemory, deviceData); memcpy(deviceData, PKE_MISSING_TEXTURE_DATA, 4 * 4); { VkImageMemoryBarrier vkImageMemoryBarrier; vkImageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; vkImageMemoryBarrier.pNext = nullptr; vkImageMemoryBarrier.srcAccessMask = {}; vkImageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkImageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; vkImageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vkImageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkImageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkImageMemoryBarrier.image = pkeDebugHitbox.vkImage; vkImageMemoryBarrier.subresourceRange = VkImageSubresourceRange { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1, }; VkCommandBufferBeginInfo vkCommandBufferBeginInfo; vkCommandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; vkCommandBufferBeginInfo.pNext = nullptr; vkCommandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkCommandBufferBeginInfo.pInheritanceInfo = nullptr; vkBeginCommandBuffer(transferCommandBuffer, &vkCommandBufferBeginInfo); vkCmdPipelineBarrier(transferCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &vkImageMemoryBarrier); VkBufferImageCopy vkBufferImageCopy; vkBufferImageCopy.bufferOffset = 0; vkBufferImageCopy.bufferRowLength = 2; vkBufferImageCopy.bufferImageHeight = 2; vkBufferImageCopy.imageSubresource = VkImageSubresourceLayers { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .mipLevel = 0, .baseArrayLayer = 0, .layerCount = 1, }; vkBufferImageCopy.imageOffset = VkOffset3D { .x = 0, .y = 0, .z = 0, }; vkBufferImageCopy.imageExtent = VkExtent3D { .width = 2, .height = 2, .depth = 1, }; vkCmdCopyBufferToImage(transferCommandBuffer, transferImageBuffer, pkeDebugHitbox.vkImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &vkBufferImageCopy); vkEndCommandBuffer(transferCommandBuffer); VkSubmitInfo submitInfo; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pNext = nullptr; submitInfo.waitSemaphoreCount = 0; submitInfo.pWaitSemaphores = nullptr; submitInfo.pWaitDstStageMask = nullptr; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &transferCommandBuffer; submitInfo.signalSemaphoreCount = 0; submitInfo.pSignalSemaphores = nullptr; vkQueueSubmit(transferQueue, 1, &submitInfo, nullptr); vkQueueWaitIdle(transferQueue); vkResetCommandBuffer(transferCommandBuffer, 0); } EndTransferBuffer(transferImageBuffer, transferImageMemory); { VkImageMemoryBarrier vkImageMemoryBarrier; vkImageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; vkImageMemoryBarrier.pNext = nullptr; vkImageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkImageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; vkImageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vkImageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; vkImageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkImageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkImageMemoryBarrier.image = pkeDebugHitbox.vkImage; vkImageMemoryBarrier.subresourceRange = VkImageSubresourceRange { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1, }; VkCommandBufferBeginInfo vkCommandBufferBeginInfo; vkCommandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; vkCommandBufferBeginInfo.pNext = nullptr; vkCommandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkCommandBufferBeginInfo.pInheritanceInfo = nullptr; vkBeginCommandBuffer(graphicsCommandBuffer, &vkCommandBufferBeginInfo); vkCmdPipelineBarrier(graphicsCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &vkImageMemoryBarrier); vkEndCommandBuffer(graphicsCommandBuffer); VkSubmitInfo submitInfo; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pNext = nullptr; submitInfo.waitSemaphoreCount = 0; submitInfo.pWaitSemaphores = nullptr; submitInfo.pWaitDstStageMask = nullptr; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &graphicsCommandBuffer; submitInfo.signalSemaphoreCount = 0; submitInfo.pSignalSemaphores = nullptr; vkQueueSubmit(graphicsQueue, 1, &submitInfo, nullptr); vkQueueWaitIdle(graphicsQueue); } } // debug model { // ((sizeof(glm::vec3) + sizeof(glm::vec3) + sizeof(glm::vec2)) * 8) // + (sizeof(uint16_t) * 36); long index = 0; VkMemoryRequirements vkMemoryRequirements[4]; VkBufferCreateInfo dbgModelBufferCI{}; dbgModelBufferCI.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; dbgModelBufferCI.pNext = nullptr; dbgModelBufferCI.flags = 0; dbgModelBufferCI.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; dbgModelBufferCI.sharingMode = VK_SHARING_MODE_EXCLUSIVE; dbgModelBufferCI.queueFamilyIndexCount = 1; dbgModelBufferCI.pQueueFamilyIndices = &graphicsFamilyIndex; // vertex dbgModelBufferCI.size = sizeof(glm::vec3) * 8; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.vertexBuffer); vkGetBufferMemoryRequirements(vkDevice, pkeDebugHitbox.vertexBuffer, &vkMemoryRequirements[index]); index++; // normals dbgModelBufferCI.size = sizeof(glm::vec3) * 8; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.normalsBuffer); vkGetBufferMemoryRequirements(vkDevice, pkeDebugHitbox.normalsBuffer, &vkMemoryRequirements[index]); index++; // uv dbgModelBufferCI.size = sizeof(glm::vec2) * 8; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.uvBuffer); vkGetBufferMemoryRequirements(vkDevice, pkeDebugHitbox.uvBuffer, &vkMemoryRequirements[index]); index++; // index dbgModelBufferCI.size = sizeof(uint16_t) * 36; dbgModelBufferCI.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.indexBuffer); vkGetBufferMemoryRequirements(vkDevice, pkeDebugHitbox.indexBuffer, &vkMemoryRequirements[index]); pkeDebugHitbox.indexCount = 36; // index++; VkMemoryRequirements combinedMemReqs{}; combinedMemReqs.alignment = vkMemoryRequirements[0].alignment; combinedMemReqs.memoryTypeBits = 0; combinedMemReqs.size = 0; for (long i = 1; i < 4; ++i) { if (combinedMemReqs.alignment == vkMemoryRequirements[i].alignment) { continue; } int larger, smaller; if (combinedMemReqs.alignment > vkMemoryRequirements[i].alignment) { larger = combinedMemReqs.alignment; smaller = vkMemoryRequirements[i].alignment; } else { larger = vkMemoryRequirements[i].alignment; smaller = combinedMemReqs.alignment; } if (larger % smaller == 0) { combinedMemReqs.alignment = larger; continue; } int combined = larger * smaller; while ((combined / 2) % 2 == 0 && (combined / 2) % larger == 0) { combined /= 2; } combinedMemReqs.alignment = combined; } for (long i = 0; i < 4; ++i) { uint32_t alignmentPadding = vkMemoryRequirements[i].size % combinedMemReqs.alignment; combinedMemReqs.size += vkMemoryRequirements[i].size + (alignmentPadding == 0 ? 0 : combinedMemReqs.alignment - alignmentPadding); combinedMemReqs.memoryTypeBits |= vkMemoryRequirements[i].memoryTypeBits; } VkMemoryAllocateInfo vkMemoryAllocateInfo; vkMemoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vkMemoryAllocateInfo.pNext = nullptr; vkMemoryAllocateInfo.allocationSize = combinedMemReqs.size; vkMemoryAllocateInfo.memoryTypeIndex = FindMemoryTypeIndex(combinedMemReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); vkAllocateMemory(vkDevice, &vkMemoryAllocateInfo, vkAllocator, &pkeDebugHitbox.vertBufferMemory); vkDestroyBuffer(vkDevice, pkeDebugHitbox.indexBuffer, vkAllocator); vkDestroyBuffer(vkDevice, pkeDebugHitbox.uvBuffer, vkAllocator); vkDestroyBuffer(vkDevice, pkeDebugHitbox.normalsBuffer, vkAllocator); vkDestroyBuffer(vkDevice, pkeDebugHitbox.vertexBuffer, vkAllocator); // bind buffers uint32_t runningOffset = 0; uint32_t alignmentPadding; // vertex uint32_t offsetVert = runningOffset; uint32_t sizeVert = sizeof(glm::vec3) * 8; alignmentPadding = sizeVert % combinedMemReqs.alignment; alignmentPadding = alignmentPadding == 0 ? 0 : combinedMemReqs.alignment - alignmentPadding; sizeVert += alignmentPadding; dbgModelBufferCI.size = sizeVert; dbgModelBufferCI.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.vertexBuffer); vkBindBufferMemory(vkDevice, pkeDebugHitbox.vertexBuffer, pkeDebugHitbox.vertBufferMemory, offsetVert); runningOffset += sizeVert; // norm uint32_t offsetNorm = runningOffset; uint32_t sizeNorm = sizeof(glm::vec3) * 8; alignmentPadding = sizeNorm % combinedMemReqs.alignment; alignmentPadding = alignmentPadding == 0 ? 0 : combinedMemReqs.alignment - alignmentPadding; sizeNorm += alignmentPadding; dbgModelBufferCI.size = sizeNorm; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.normalsBuffer); vkBindBufferMemory(vkDevice, pkeDebugHitbox.normalsBuffer, pkeDebugHitbox.vertBufferMemory, offsetNorm); runningOffset += sizeNorm; // uv uint32_t offsetUV = runningOffset; uint32_t sizeUV = sizeof(glm::vec2) * 8; alignmentPadding = sizeUV % combinedMemReqs.alignment; alignmentPadding = alignmentPadding == 0 ? 0 : combinedMemReqs.alignment - alignmentPadding; sizeUV += alignmentPadding; dbgModelBufferCI.size = sizeUV; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.uvBuffer); vkBindBufferMemory(vkDevice, pkeDebugHitbox.uvBuffer , pkeDebugHitbox.vertBufferMemory, offsetUV); runningOffset += sizeUV; // index uint32_t offsetIndex = runningOffset; uint32_t sizeIndex = sizeof(uint16_t) * 36; alignmentPadding = sizeIndex % combinedMemReqs.alignment; alignmentPadding = alignmentPadding == 0 ? 0 : combinedMemReqs.alignment - alignmentPadding; sizeIndex += alignmentPadding; dbgModelBufferCI.size = sizeIndex; dbgModelBufferCI.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT; vkCreateBuffer(vkDevice, &dbgModelBufferCI, vkAllocator, &pkeDebugHitbox.indexBuffer); vkBindBufferMemory(vkDevice, pkeDebugHitbox.indexBuffer, pkeDebugHitbox.vertBufferMemory, offsetIndex); runningOffset += sizeIndex; assert(runningOffset == combinedMemReqs.size); // create transfer items && transfer { VkDeviceMemory transferDeviceMemory; VkBuffer transferBuffer; void *data; BeginTransferBuffer(combinedMemReqs.size, transferBuffer, transferDeviceMemory, data); memset(data, '\0', combinedMemReqs.size); char *dstPtr = nullptr; char *srcPtr = nullptr; dstPtr = static_cast(data) + offsetVert; srcPtr = reinterpret_cast(pkeIntrinsicsCube.vert); memcpy(dstPtr, srcPtr, sizeVert); dstPtr = static_cast(data) + offsetNorm; srcPtr = reinterpret_cast(pkeIntrinsicsCube.norm); memcpy(dstPtr, srcPtr, sizeNorm); dstPtr = static_cast(data) + offsetUV; srcPtr = reinterpret_cast(pkeIntrinsicsCube.uv); memcpy(dstPtr, srcPtr, sizeUV); dstPtr = static_cast(data) + offsetIndex; srcPtr = reinterpret_cast(pkeIntrinsicsCube.index); memcpy(dstPtr, srcPtr, sizeIndex); VkCommandBufferBeginInfo vkCommandBufferBeginInfo; vkCommandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; vkCommandBufferBeginInfo.pNext = nullptr; // TODO consider single-use? vkCommandBufferBeginInfo.flags = 0; vkCommandBufferBeginInfo.pInheritanceInfo = nullptr; vkBeginCommandBuffer(transferCommandBuffer, &vkCommandBufferBeginInfo); VkBufferCopy bufferCopys[4]; for (long i = 0; i < 4; ++i) { bufferCopys[i].dstOffset = 0; } index = 0; bufferCopys[index].srcOffset = offsetVert; bufferCopys[index].size = sizeVert; vkCmdCopyBuffer(transferCommandBuffer, transferBuffer, pkeDebugHitbox.vertexBuffer, 1, &bufferCopys[index]); index+=1; bufferCopys[index].srcOffset = offsetNorm; bufferCopys[index].size = sizeNorm; vkCmdCopyBuffer(transferCommandBuffer, transferBuffer, pkeDebugHitbox.normalsBuffer, 1, &bufferCopys[index]); index+=1; bufferCopys[index].srcOffset = offsetUV; bufferCopys[index].size = sizeUV; vkCmdCopyBuffer(transferCommandBuffer, transferBuffer, pkeDebugHitbox.uvBuffer, 1, &bufferCopys[index]); index+=1; bufferCopys[index].srcOffset = offsetIndex; bufferCopys[index].size = sizeIndex; vkCmdCopyBuffer(transferCommandBuffer, transferBuffer, pkeDebugHitbox.indexBuffer, 1, &bufferCopys[index]); // index+=1; vkEndCommandBuffer(transferCommandBuffer); VkSubmitInfo submitInfo; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pNext = nullptr; submitInfo.waitSemaphoreCount = 0; submitInfo.pWaitSemaphores = nullptr; submitInfo.pWaitDstStageMask = nullptr; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &transferCommandBuffer; submitInfo.signalSemaphoreCount = 0; submitInfo.pSignalSemaphores = nullptr; vkQueueSubmit(transferQueue, 1, &submitInfo, nullptr); vkQueueWaitIdle(transferQueue); EndTransferBuffer(transferBuffer, transferDeviceMemory); } } } void UpdateDebugGraphicsPipeline() { // descriptor pool & sets VkDescriptorPoolSize descriptorPoolSizes[2]; descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorPoolSizes[0].descriptorCount = MAX_FRAMES_IN_FLIGHT; descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorPoolSizes[1].descriptorCount = MAX_FRAMES_IN_FLIGHT; VkDescriptorPoolCreateInfo vkDescriptorPoolCreateInfo; vkDescriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; vkDescriptorPoolCreateInfo.pNext = nullptr; vkDescriptorPoolCreateInfo.flags = 0; vkDescriptorPoolCreateInfo.maxSets = MAX_FRAMES_IN_FLIGHT; vkDescriptorPoolCreateInfo.poolSizeCount = (uint32_t)2; vkDescriptorPoolCreateInfo.pPoolSizes = descriptorPoolSizes; // consider making me a global pool auto vkResult = vkCreateDescriptorPool(vkDevice, &vkDescriptorPoolCreateInfo, vkAllocator, &pkeDebugHitbox.vkDescriptorPool); assert(vkResult == VK_SUCCESS); VkDescriptorSetLayout descriptorSets[MAX_FRAMES_IN_FLIGHT]; for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { descriptorSets[i] = pkePipelines.vkDescriptorSetLayout_Texture; } VkDescriptorSetAllocateInfo vkDescriptorSetAllocateInfo; vkDescriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; vkDescriptorSetAllocateInfo.pNext = nullptr; vkDescriptorSetAllocateInfo.descriptorPool = pkeDebugHitbox.vkDescriptorPool; vkDescriptorSetAllocateInfo.descriptorSetCount = MAX_FRAMES_IN_FLIGHT; vkDescriptorSetAllocateInfo.pSetLayouts = descriptorSets; pkeDebugHitbox.vkDescriptorSets = pk_new(MAX_FRAMES_IN_FLIGHT); for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { pkeDebugHitbox.vkDescriptorSets[i] = VkDescriptorSet{}; } vkResult = vkAllocateDescriptorSets(vkDevice, &vkDescriptorSetAllocateInfo, pkeDebugHitbox.vkDescriptorSets); assert(vkResult == VK_SUCCESS); VkWriteDescriptorSet writeDescriptorSets[2 * MAX_FRAMES_IN_FLIGHT]; for (long i = 0; i < 2 * MAX_FRAMES_IN_FLIGHT; ++i) { writeDescriptorSets[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSets[i].pNext = nullptr; writeDescriptorSets[i].dstSet = nullptr; writeDescriptorSets[i].dstBinding = i % 2; writeDescriptorSets[i].dstArrayElement = 0; writeDescriptorSets[i].descriptorCount = 1; writeDescriptorSets[i].descriptorType = (i % 2) == 0 ? VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER : VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptorSets[i].pImageInfo = nullptr; writeDescriptorSets[i].pBufferInfo = nullptr; writeDescriptorSets[i].pTexelBufferView = nullptr; } VkDescriptorImageInfo textureDescriptorInfo; textureDescriptorInfo.sampler = pkePipelines.vkSampler_Texture; textureDescriptorInfo.imageView = pkeDebugHitbox.vkImageView; textureDescriptorInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkDescriptorBufferInfo vkDescriptorBufferInfo[MAX_FRAMES_IN_FLIGHT]; for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { vkDescriptorBufferInfo[i].buffer = UniformBuffers[i]; vkDescriptorBufferInfo[i].offset = 0; vkDescriptorBufferInfo[i].range = sizeof(UniformBufferObject); long uboIndex = i * 2; long samplerIndex = uboIndex + 1; writeDescriptorSets[uboIndex].pBufferInfo = &vkDescriptorBufferInfo[i]; writeDescriptorSets[uboIndex].dstSet = pkeDebugHitbox.vkDescriptorSets[i]; writeDescriptorSets[samplerIndex].pImageInfo = &textureDescriptorInfo; writeDescriptorSets[samplerIndex].dstSet = pkeDebugHitbox.vkDescriptorSets[i]; } vkUpdateDescriptorSets(vkDevice, 2 * MAX_FRAMES_IN_FLIGHT, writeDescriptorSets, 0, nullptr); } void CreateImGui() { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; ImGui::StyleColorsDark(); VkDescriptorPoolSize poolSizes[] = { {VK_DESCRIPTOR_TYPE_SAMPLER, 1000}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000}, {VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000}, }; VkDescriptorPoolCreateInfo descriptorPoolCreateInfo; descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPoolCreateInfo.pNext = nullptr; descriptorPoolCreateInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; descriptorPoolCreateInfo.maxSets = 1000 * IM_ARRAYSIZE(poolSizes), descriptorPoolCreateInfo.poolSizeCount = static_cast(IM_ARRAYSIZE(poolSizes)); descriptorPoolCreateInfo.pPoolSizes = poolSizes; vkCreateDescriptorPool(vkDevice, &descriptorPoolCreateInfo, vkAllocator, &imGuiDescriptorPool); ImGui_ImplGlfw_InitForVulkan(window, true); ImGui_ImplVulkan_InitInfo initInfo = {}; initInfo.Allocator = vkAllocator; initInfo.CheckVkResultFn = ImGuiCheckVkResult; // initInfo.ColorAttachmentFormat = VkFormat::VK_FORMAT_B8G8R8A8_SRGB; initInfo.DescriptorPool = imGuiDescriptorPool; initInfo.Device = vkDevice; initInfo.ImageCount = MAX_FRAMES_IN_FLIGHT; initInfo.Instance = vkInstance; initInfo.MSAASamples = VK_SAMPLE_COUNT_1_BIT; initInfo.MinImageCount = MAX_FRAMES_IN_FLIGHT; initInfo.PhysicalDevice = vkPhysicalDevice; initInfo.PipelineCache = {}; initInfo.Queue = graphicsQueue; initInfo.QueueFamily = graphicsFamilyIndex; initInfo.RenderPass = presentRenderPass; initInfo.Subpass = 0; initInfo.UseDynamicRendering = false; ImGui_ImplVulkan_Init(&initInfo); // font // { // VkCommandBufferBeginInfo begInfo; // begInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // begInfo.pNext = nullptr; // begInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; // begInfo.pInheritanceInfo = {}; // vkBeginCommandBuffer(presentCommandBuffers[0], &begInfo); // ImGui_ImplVulkan_CreateFontsTexture(); // ImGui_ImplVulkan_CreateFontsTexture(presentCommandBuffers[0]); // vkEndCommandBuffer(presentCommandBuffers[0]); // VkSubmitInfo submitInfo; // submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; // submitInfo.pNext = nullptr; // submitInfo.waitSemaphoreCount = 0; // submitInfo.pWaitSemaphores = nullptr; // submitInfo.pWaitDstStageMask = nullptr; // submitInfo.commandBufferCount = 1; // submitInfo.pCommandBuffers = presentCommandBuffers; // submitInfo.signalSemaphoreCount = 0; // submitInfo.pSignalSemaphores = nullptr; // vkQueueSubmit(graphicsQueue, 1, &submitInfo, nullptr); // vkQueueWaitIdle(graphicsQueue); // } // ImGui_ImplVulkan_DestroyFontsTexture(); // ImGui_ImplVulkan_DestroyFontUploadObjects(); } void RecordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex) { vkResetCommandBuffer(commandBuffer, 0); VkCommandBufferBeginInfo beginInfo; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.pNext = nullptr; beginInfo.flags = 0; beginInfo.pInheritanceInfo = nullptr; auto result = vkBeginCommandBuffer(commandBuffer, &beginInfo); if (result != VK_SUCCESS) { throw "failed to begin recording command buffer"; } // VkClearColorValue clearColorTransparent = {{0.0f, 0.0f, 0.0f, 0.0f}}; VkClearColorValue clearColorBlack = {{0.0f, 0.0f, 0.0f, 1.0f}}; VkClearDepthStencilValue clearDepth; clearDepth.depth = 1.0; clearDepth.stencil = 0; VkClearValue clearValues[2] = { VkClearValue { .color = clearColorBlack }, VkClearValue { .depthStencil = clearDepth }, }; VkRenderPassBeginInfo renderPassInfo; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderRenderPass; renderPassInfo.framebuffer = renderImageFramebuffers[imageIndex]; renderPassInfo.renderArea.offset = {0, 0}; renderPassInfo.renderArea.extent = Extent; renderPassInfo.clearValueCount = 2; renderPassInfo.pClearValues = clearValues; renderPassInfo.pNext = VK_NULL_HANDLE; vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float)Extent.width; viewport.height = (float)Extent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor; scissor.offset = {0, 0}; scissor.extent = Extent; vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); VkDeviceSize offsets[1] = {0U}; pk_handle_bucket_index_T bindBucketCount = ECS_GetGrBinds_BucketCount(); for (pk_handle_bucket_index_T b = 0; b < bindBucketCount; ++b) { pk_handle_item_index_T itemCount; CompGrBinds *items = ECS_GetGrBinds(b, itemCount); for (pk_handle_item_index_T i = 0; i < itemCount; ++i) { CompGrBinds *binder = &items[i]; if (binder->grBindsHandle == GrBindsHandle_MAX) continue; if (!binder->vkPipelineLayout) continue; if (binder->instanceBindingCount < 1) { continue; } vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, binder->graphicsPipeline); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, binder->vkPipelineLayout, 0, 1, &binder->vkDescriptorSets[imageIndex], 0, {}); vkCmdBindVertexBuffers(commandBuffer, 0, 1, &UniformBuffers[imageIndex], offsets); vkCmdBindIndexBuffer(commandBuffer, binder->indexBuffer, binder->indexOffsets, VK_INDEX_TYPE_UINT16); vkCmdBindVertexBuffers(commandBuffer, binder->vertexFirstBinding, binder->vertexBindingCount, &binder->vertexBuffer, &binder->vertexOffsets); vkCmdBindVertexBuffers(commandBuffer, binder->normalsFirstBinding, binder->normalsBindingCount, &binder->normalsBuffer, &binder->normalsOffsets); vkCmdBindVertexBuffers(commandBuffer, binder->uvFirstBinding, binder->uvBindingCount, &binder->uvBuffer, &binder->uvOffsets); vkCmdBindVertexBuffers(commandBuffer, binder->instanceFirstBinding, binder->instanceBindingCount, &binder->instanceBuffer, &binder->instanceOffsets); vkCmdDrawIndexed(commandBuffer, binder->indexCount, binder->instanceCounter, 0, 0, 0); if (pkeSettings.isRenderingDebug) { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pkePipelines.pipelines.named.TextureWireframe); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pkePipelines.vkPipelineLayout_Texture, 0, 1, &pkeDebugHitbox.vkDescriptorSets[imageIndex], 0, {}); vkCmdBindVertexBuffers(commandBuffer, binder->physVertBD.firstBinding, 1, &binder->physVertBD.buffer, binder->physVertBD.offsets); vkCmdBindVertexBuffers(commandBuffer, binder->physNormBD.firstBinding, 1, &binder->physNormBD.buffer, binder->physVertBD.offsets); vkCmdBindVertexBuffers(commandBuffer, binder->physUvBD.firstBinding, 1, &binder->physUvBD.buffer, binder->physVertBD.offsets); vkCmdBindIndexBuffer(commandBuffer, binder->physIndxBD.buffer, binder->physIndxBD.offsets[0], VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(commandBuffer, binder->physIndxBD.bindingCount, binder->instanceCounter, 0, 0, 0); } } } if (pkeDebugHitbox.instanceBuffer != VK_NULL_HANDLE) { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pkePipelines.pipelines.named.TextureWireframe); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pkePipelines.vkPipelineLayout_Texture, 0, 1, &pkeDebugHitbox.vkDescriptorSets[imageIndex], 0, {}); vkCmdBindVertexBuffers(commandBuffer, 0, 1, &UniformBuffers[imageIndex], offsets); // TODO don't hardcode firstBinding vkCmdBindVertexBuffers(commandBuffer, 0, 1, &pkeDebugHitbox.vertexBuffer, offsets); vkCmdBindVertexBuffers(commandBuffer, 1, 1, &pkeDebugHitbox.normalsBuffer, offsets); vkCmdBindVertexBuffers(commandBuffer, 2, 1, &pkeDebugHitbox.uvBuffer, offsets); vkCmdBindIndexBuffer(commandBuffer, pkeDebugHitbox.indexBuffer, offsets[0], VK_INDEX_TYPE_UINT16); vkCmdBindVertexBuffers(commandBuffer, 3, 1, &pkeDebugHitbox.instanceBuffer, offsets); vkCmdDrawIndexed(commandBuffer, pkeDebugHitbox.indexCount, pkeDebugHitbox.instanceCount, 0, 0, pkeDebugHitbox.instanceStartingIndex); } vkCmdEndRenderPass(commandBuffer); /* // 2d overlay pass renderPassInfo.renderPass = d2OverlayRenderPass; renderPassInfo.framebuffer = d2OverlayImageFramebuffers[imageIndex]; renderPassInfo.clearValueCount = 1; clearValues[0].color = clearColorTransparent; vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); // TODO 2d overlay grbinds { } vkCmdEndRenderPass(commandBuffer); */ // present pass renderPassInfo.renderPass = presentRenderPass; renderPassInfo.framebuffer = swapchainFramebuffers[imageIndex]; renderPassInfo.clearValueCount = 1; clearValues[0].color = clearColorBlack; vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &presentDescriptorSets[imageIndex], 0, nullptr); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline); vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); // reminder that present.vert is a triangle vkCmdDraw(commandBuffer, 3, 1, 0, 0); // ImGui const auto count = LoadedPkePlugins.Count(); bool any = false; for (long i = 0; i < count; ++i) { if (LoadedPkePlugins[i].OnImGuiRender != nullptr) { any = true; break; } } if (any) { ImGui_ImplVulkan_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); for (long i = 0; i < count; ++i) { if (LoadedPkePlugins[i].OnImGuiRender != nullptr) { LoadedPkePlugins[i].OnImGuiRender(); } } ImGui::Render(); auto drawData = ImGui::GetDrawData(); const bool isMinimized = drawData->DisplaySize.x <= 0.0f || drawData->DisplaySize.y <= 0.0f; if (isMinimized) return; ImGui_ImplVulkan_RenderDrawData(drawData, commandBuffer); } vkCmdEndRenderPass(commandBuffer); result = vkEndCommandBuffer(commandBuffer); if (result != VK_SUCCESS) { throw "failed to record command buffer!"; } } void DestroySwapchain() { if (d2OverlayImageFramebuffers != nullptr && d2OverlayImageFramebuffers != CAFE_BABE(VkFramebuffer)) { for (long i = 0; i < swapchainLength; ++i) { vkDestroyFramebuffer(vkDevice, d2OverlayImageFramebuffers[i], vkAllocator); } pk_delete(d2OverlayImageFramebuffers, swapchainLength); d2OverlayImageFramebuffers = CAFE_BABE(VkFramebuffer); } if (renderImageFramebuffers != nullptr && renderImageFramebuffers != CAFE_BABE(VkFramebuffer)) { for (long i = 0; i < swapchainLength; ++i) { vkDestroyFramebuffer(vkDevice, renderImageFramebuffers[i], vkAllocator); } pk_delete(renderImageFramebuffers, swapchainLength); renderImageFramebuffers = CAFE_BABE(VkFramebuffer); } if (swapchainFramebuffers != nullptr && swapchainFramebuffers != CAFE_BABE(VkFramebuffer)) { for (long i = 0; i < swapchainLength; ++i) { vkDestroyFramebuffer(vkDevice, swapchainFramebuffers[i], vkAllocator); } pk_delete(swapchainFramebuffers, swapchainLength); swapchainFramebuffers = CAFE_BABE(VkFramebuffer); } if (renderImageViews!= nullptr && renderImageViews != CAFE_BABE(VkImageView)) { for (long i = 0; i < swapchainLength; ++i) { vkDestroyImageView(vkDevice, depthImageViews[i], vkAllocator); vkDestroyImage(vkDevice, depthImages[i], vkAllocator); vkDestroyImageView(vkDevice, d2OverlayImageViews[i], vkAllocator); vkDestroyImage(vkDevice, d2OverlayImages[i], vkAllocator); vkDestroyImageView(vkDevice, colorImageViews[i], vkAllocator); vkDestroyImage(vkDevice, colorImages[i], vkAllocator); vkDestroyImageView(vkDevice, renderImageViews[i], vkAllocator); vkDestroyImage(vkDevice, renderImages[i], vkAllocator); } pk_delete(depthImageViews, swapchainLength); depthImageViews = CAFE_BABE(VkImageView); pk_delete(depthImages, swapchainLength); depthImages = CAFE_BABE(VkImage); pk_delete(d2OverlayImageViews, swapchainLength); d2OverlayImageViews = CAFE_BABE(VkImageView); pk_delete(d2OverlayImages, swapchainLength); d2OverlayImages = CAFE_BABE(VkImage); pk_delete(colorImageViews, swapchainLength); colorImageViews = CAFE_BABE(VkImageView); pk_delete(colorImages, swapchainLength); colorImages = CAFE_BABE(VkImage); pk_delete(renderImageViews, swapchainLength); renderImageViews = CAFE_BABE(VkImageView); pk_delete(renderImages, swapchainLength); renderImages = CAFE_BABE(VkImage); vkFreeMemory(vkDevice, d2OverlayImagesMemory, vkAllocator); vkFreeMemory(vkDevice, depthImagesMemory, vkAllocator); vkFreeMemory(vkDevice, colorImagesMemory, vkAllocator); vkFreeMemory(vkDevice, renderImagesMemory, vkAllocator); } if (swapchainImageViews!= nullptr && swapchainImageViews != CAFE_BABE(VkImageView)) { for (long i = 0; i < swapchainLength; ++i) { vkDestroyImageView(vkDevice, swapchainImageViews[i], vkAllocator); } pk_delete(swapchainImageViews, swapchainLength); swapchainImageViews = CAFE_BABE(VkImageView); pk_delete(swapchainImages, swapchainLength); swapchainImages = CAFE_BABE(VkImage); } vkDestroySwapchainKHR(vkDevice, vkSwapchainKHR, vkAllocator); } void DetermineMonitor() { int monitorCount; GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); assert(monitors != nullptr); // TODO - actually determine monitor monitor = monitors[0]; const auto *videoMode = glfwGetVideoMode(monitor); vidMode.width = videoMode->width; vidMode.height = videoMode->height; vidMode.redBits = videoMode->redBits; vidMode.greenBits = videoMode->greenBits; vidMode.blueBits = videoMode->blueBits; vidMode.refreshRate = videoMode->refreshRate; } void RecreateSwapchain() { int width, height = 0; glfwGetFramebufferSize(window, &width, &height); while (width == 0 || height == 0) { glfwGetFramebufferSize(window, &width, &height); glfwWaitEvents(); } Extent.width = width; Extent.height = height; ActiveCamera->stale = ActiveCamera->stale | PKE_CAMERA_STALE_PERSPECTIVE; DetermineMonitor(); vkDeviceWaitIdle(vkDevice); DestroySwapchain(); CreateSwapchain(); UpdatePresentDescriptorSets(); UpdateCamera(); CreateFramebuffers(); shouldRecreateSwapchain = false; } void FramebufferResizeCallback(GLFWwindow *window, int width, int height) { (void)window; assert(width > -1); assert(height > -1); if (Extent.width == (uint32_t)width && Extent.height != (uint32_t)height) { return; } shouldRecreateSwapchain = true; } void CreateWindow(PKEWindowProperties wp) { if (vkInstance != nullptr) return; MemBkt_Vulkan = pk_bucket_create("vulkan", PK_DEFAULT_BUCKET_SIZE, false); vulkanAllocs = pk_new>(MemBkt_Vulkan); new (vulkanAllocs) DynArray(MemBkt_Vulkan); vulkanAllocs->Reserve(2048); glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); window = glfwCreateWindow(wp.width, wp.height, "Pikul", nullptr, nullptr); InitVulkan(); glfwSetFramebufferSizeCallback(window, FramebufferResizeCallback); CreateSwapchain(); CreateRenderPass(); CreatePresentPipeline(); UpdatePresentDescriptorSets(); UpdateCamera(); CreateFramebuffers(); CreateCommandPool(); CreateCommandBuffer(); CreateUniformBuffers(); CreateSyncObjects(); CreateGraphicsPipelines(); UpdateDebugGraphicsPipeline(); CreateImGui(); DetermineMonitor(); } void DestroyWindow() { if (vkInstance == nullptr) return; ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); DestroySwapchain(); vkDestroyDescriptorPool(vkDevice, pkeDebugHitbox.vkDescriptorPool, vkAllocator); pk_delete(pkeDebugHitbox.vkDescriptorSets, MAX_FRAMES_IN_FLIGHT); vkDestroyBuffer(vkDevice, pkeDebugHitbox.indexBuffer, vkAllocator); vkDestroyBuffer(vkDevice, pkeDebugHitbox.uvBuffer, vkAllocator); vkDestroyBuffer(vkDevice, pkeDebugHitbox.normalsBuffer, vkAllocator); vkDestroyBuffer(vkDevice, pkeDebugHitbox.vertexBuffer, vkAllocator); vkFreeMemory(vkDevice, pkeDebugHitbox.vertBufferMemory, vkAllocator); vkDestroyImageView(vkDevice, pkeDebugHitbox.vkImageView, vkAllocator); vkDestroyImage(vkDevice, pkeDebugHitbox.vkImage, vkAllocator); vkFreeMemory(vkDevice, pkeDebugHitbox.textureMemory, vkAllocator); if (pkePipelines.vkSampler_Texture != VK_NULL_HANDLE) vkDestroySampler(vkDevice, pkePipelines.vkSampler_Texture, vkAllocator); for (long i = 0; i < 2; ++i) { if (pkePipelines.pipelines.arr[i] != VK_NULL_HANDLE) vkDestroyPipeline(vkDevice, pkePipelines.pipelines.arr[i], vkAllocator); } if (pkePipelines.vkPipelineLayout_Texture != VK_NULL_HANDLE) vkDestroyPipelineLayout(vkDevice, pkePipelines.vkPipelineLayout_Texture, vkAllocator); if (pkePipelines.vkDescriptorSetLayout_Texture != VK_NULL_HANDLE) vkDestroyDescriptorSetLayout(vkDevice, pkePipelines.vkDescriptorSetLayout_Texture, vkAllocator); for (long i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { vkDestroyBuffer(vkDevice, UniformBuffers[i], vkAllocator); vkDestroySemaphore(vkDevice, presentImageAvailableSemaphores[i], vkAllocator); vkDestroySemaphore(vkDevice, presentRenderFinishedSemaphores[i], vkAllocator); vkDestroyFence(vkDevice, presentInFlightFences[i], vkAllocator); } vkFreeMemory(vkDevice, uniformBufferMemory, vkAllocator); vkDestroyCommandPool(vkDevice, graphicsCommandPool, vkAllocator); vkDestroyCommandPool(vkDevice, transferCommandPool, vkAllocator); vkDestroyPipeline(vkDevice, graphicsPipeline, vkAllocator); vkDestroyPipelineLayout(vkDevice, pipelineLayout, vkAllocator); vkFreeDescriptorSets(vkDevice, presentDescriptorPool, MAX_FRAMES_IN_FLIGHT, presentDescriptorSets); vkDestroyDescriptorPool(vkDevice, presentDescriptorPool, vkAllocator); vkDestroyDescriptorPool(vkDevice, imGuiDescriptorPool, vkAllocator); vkDestroyDescriptorSetLayout(vkDevice, vkDescriptorSetLayout, vkAllocator); vkDestroyRenderPass(vkDevice, d2OverlayRenderPass, vkAllocator); vkDestroyRenderPass(vkDevice, renderRenderPass, vkAllocator); vkDestroyRenderPass(vkDevice, presentRenderPass, vkAllocator); vkDestroySurfaceKHR(vkInstance, vkSurfaceKHR, vkAllocator); vkDestroySampler(vkDevice, presentSampler, vkAllocator); vkDestroyDevice(vkDevice, vkAllocator); if (VULKAN_DEBUG_REPORT) { auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(vkInstance, "vkDestroyDebugReportCallbackEXT"); vkDestroyDebugReportCallbackEXT(vkInstance, vkDebugReport, vkAllocator); } vkDestroyInstance(vkInstance, vkAllocator); glfwDestroyWindow(window); glfwTerminate(); vulkanAllocs->~DynArray(); pk_bucket_destroy(MemBkt_Vulkan); } VkShaderModule UploadShader(AssetHandle handle) { const Asset *asset = AM_Get(handle); assert(asset != nullptr && asset->state == PKE_ASSET_LOADING_STATE_LOADED); #ifndef NDEBUG fprintf(stdout, "Uploading Shader: '%s'\n", asset->basePath); #endif VkShaderModuleCreateInfo createInfo; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.pNext = nullptr; createInfo.flags = {}; createInfo.codeSize = asset->size; createInfo.pCode = static_cast(asset->ptr); VkShaderModule vkShaderModule; if (vkCreateShaderModule(vkDevice, &createInfo, vkAllocator, &vkShaderModule) != VK_SUCCESS) { throw "failed to create shader module for asset"; } return vkShaderModule; } void Render() { vkWaitForFences(vkDevice, 1, &presentInFlightFences[CURRENT_FRAME], VK_TRUE, UINT64_MAX); uint32_t imageIndex; auto result = vkAcquireNextImageKHR(vkDevice, vkSwapchainKHR, UINT64_MAX, presentImageAvailableSemaphores[CURRENT_FRAME], VK_NULL_HANDLE, &imageIndex); if (result == VK_ERROR_OUT_OF_DATE_KHR) { RecreateSwapchain(); return; } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { throw "failed to acquire swapchain"; } // update uniform buffer { UpdateCamera(); void *mappedUboMemory; vkMapMemory(vkDevice, uniformBufferMemory, paddedUboBufferSize * imageIndex, sizeof(UniformBufferObject), 0, &mappedUboMemory); memcpy(mappedUboMemory, &UBO, sizeof(UniformBufferObject)); vkUnmapMemory(vkDevice, uniformBufferMemory); } vkResetFences(vkDevice, 1, &presentInFlightFences[CURRENT_FRAME]); vkResetCommandBuffer(presentCommandBuffers[CURRENT_FRAME], 0); RecordCommandBuffer(presentCommandBuffers[CURRENT_FRAME], imageIndex); VkSemaphore waitSemaphores[] = {presentImageAvailableSemaphores[CURRENT_FRAME]}; VkSemaphore signalSemaphores[] = {presentRenderFinishedSemaphores[CURRENT_FRAME]}; VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; VkSubmitInfo submitInfo; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pNext = nullptr; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &presentCommandBuffers[CURRENT_FRAME]; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; result = vkQueueSubmit(graphicsQueue, 1, &submitInfo, presentInFlightFences[CURRENT_FRAME]); if (result != VK_SUCCESS) { throw "failed to submit queue"; } VkSwapchainKHR swapchains[] = {vkSwapchainKHR}; VkPresentInfoKHR presentInfo; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.pNext = nullptr; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = signalSemaphores; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapchains; presentInfo.pImageIndices = &imageIndex; presentInfo.pResults = nullptr; result = vkQueuePresentKHR(presentQueue, &presentInfo); if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || shouldRecreateSwapchain) { RecreateSwapchain(); } else if (result != VK_SUCCESS) { throw "failed to present swapchain image"; } CURRENT_FRAME = (CURRENT_FRAME + 1) % MAX_FRAMES_IN_FLIGHT; }