blob: 5884b41653440dad4311486ec57b003888928629 [file] [log] [blame]
Adam Sawickie6e498f2017-06-16 17:21:31 +02001//
Adam Sawickiaa183742021-02-16 17:28:49 +01002// Copyright (c) 2017-2021 Advanced Micro Devices, Inc. All rights reserved.
Adam Sawickie6e498f2017-06-16 17:21:31 +02003//
4// Permission is hereby granted, free of charge, to any person obtaining a copy
5// of this software and associated documentation files (the "Software"), to deal
6// in the Software without restriction, including without limitation the rights
7// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8// copies of the Software, and to permit persons to whom the Software is
9// furnished to do so, subject to the following conditions:
10//
11// The above copyright notice and this permission notice shall be included in
12// all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20// THE SOFTWARE.
21//
22
Adam Sawickif1a793c2018-03-13 15:42:22 +010023#ifdef _WIN32
Adam Sawicki59a3e7e2017-08-21 15:47:30 +020024
Adam Sawicki51fa9662018-10-03 13:44:29 +020025#include "SparseBindingTest.h"
Adam Sawickif1a793c2018-03-13 15:42:22 +010026#include "Tests.h"
27#include "VmaUsage.h"
28#include "Common.h"
Adam Sawicki8317ba92019-11-18 13:14:11 +010029#include <atomic>
Adam Sawickie6e498f2017-06-16 17:21:31 +020030
31static const char* const SHADER_PATH1 = "./";
32static const char* const SHADER_PATH2 = "../bin/";
33static const wchar_t* const WINDOW_CLASS_NAME = L"VULKAN_MEMORY_ALLOCATOR_SAMPLE";
Adam Sawicki8caf0bd2020-07-15 16:56:30 +020034static const char* const VALIDATION_LAYER_NAME = "VK_LAYER_KHRONOS_validation";
Adam Sawicki8ef0d202020-03-02 15:43:47 +010035static const char* const APP_TITLE_A = "Vulkan Memory Allocator Sample 2.4.0";
36static const wchar_t* const APP_TITLE_W = L"Vulkan Memory Allocator Sample 2.4.0";
Adam Sawickie6e498f2017-06-16 17:21:31 +020037
38static const bool VSYNC = true;
39static const uint32_t COMMAND_BUFFER_COUNT = 2;
Adam Sawickia68c01c2018-03-13 16:40:45 +010040static void* const CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA = (void*)(intptr_t)43564544;
Adam Sawicki8317ba92019-11-18 13:14:11 +010041static const bool USE_CUSTOM_CPU_ALLOCATION_CALLBACKS = true;
Adam Sawickie6e498f2017-06-16 17:21:31 +020042
Adam Sawickib8333fb2018-03-13 16:15:53 +010043VkPhysicalDevice g_hPhysicalDevice;
44VkDevice g_hDevice;
45VmaAllocator g_hAllocator;
Adam Sawicki4ac8ff82019-11-18 14:47:33 +010046VkInstance g_hVulkanInstance;
Adam Sawickib8333fb2018-03-13 16:15:53 +010047
Adam Sawicki50882502020-02-07 16:51:31 +010048bool g_EnableValidationLayer = true;
49bool VK_KHR_get_memory_requirements2_enabled = false;
50bool VK_KHR_get_physical_device_properties2_enabled = false;
51bool VK_KHR_dedicated_allocation_enabled = false;
52bool VK_KHR_bind_memory2_enabled = false;
53bool VK_EXT_memory_budget_enabled = false;
54bool VK_AMD_device_coherent_memory_enabled = false;
Adam Sawickie73e9882020-03-20 18:05:42 +010055bool VK_EXT_buffer_device_address_enabled = false;
56bool VK_KHR_buffer_device_address_enabled = false;
Adam Sawickif2012052021-01-11 18:04:42 +010057bool VK_EXT_memory_priority_enabled = false;
Adam Sawicki8caf0bd2020-07-15 16:56:30 +020058bool VK_EXT_debug_utils_enabled = false;
Adam Sawicki51fa9662018-10-03 13:44:29 +020059bool g_SparseBindingEnabled = false;
Adam Sawickie73e9882020-03-20 18:05:42 +010060bool g_BufferDeviceAddressEnabled = false;
61
62// # Pointers to functions from extensions
63PFN_vkGetBufferDeviceAddressEXT g_vkGetBufferDeviceAddressEXT;
Adam Sawicki6cc5e852018-03-13 16:37:54 +010064
Adam Sawickie6e498f2017-06-16 17:21:31 +020065static HINSTANCE g_hAppInstance;
66static HWND g_hWnd;
67static LONG g_SizeX = 1280, g_SizeY = 720;
Adam Sawickie6e498f2017-06-16 17:21:31 +020068static VkSurfaceKHR g_hSurface;
Adam Sawickie6e498f2017-06-16 17:21:31 +020069static VkQueue g_hPresentQueue;
70static VkSurfaceFormatKHR g_SurfaceFormat;
71static VkExtent2D g_Extent;
72static VkSwapchainKHR g_hSwapchain;
73static std::vector<VkImage> g_SwapchainImages;
74static std::vector<VkImageView> g_SwapchainImageViews;
75static std::vector<VkFramebuffer> g_Framebuffers;
76static VkCommandPool g_hCommandPool;
77static VkCommandBuffer g_MainCommandBuffers[COMMAND_BUFFER_COUNT];
78static VkFence g_MainCommandBufferExecutedFances[COMMAND_BUFFER_COUNT];
Adam Sawicki51fa9662018-10-03 13:44:29 +020079VkFence g_ImmediateFence;
Adam Sawickie6e498f2017-06-16 17:21:31 +020080static uint32_t g_NextCommandBufferIndex;
81static VkSemaphore g_hImageAvailableSemaphore;
82static VkSemaphore g_hRenderFinishedSemaphore;
83static uint32_t g_GraphicsQueueFamilyIndex = UINT_MAX;
84static uint32_t g_PresentQueueFamilyIndex = UINT_MAX;
Adam Sawicki51fa9662018-10-03 13:44:29 +020085static uint32_t g_SparseBindingQueueFamilyIndex = UINT_MAX;
Adam Sawickie6e498f2017-06-16 17:21:31 +020086static VkDescriptorSetLayout g_hDescriptorSetLayout;
87static VkDescriptorPool g_hDescriptorPool;
88static VkDescriptorSet g_hDescriptorSet; // Automatically destroyed with m_DescriptorPool.
89static VkSampler g_hSampler;
90static VkFormat g_DepthFormat;
91static VkImage g_hDepthImage;
Adam Sawicki819860e2017-07-04 14:30:38 +020092static VmaAllocation g_hDepthImageAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +020093static VkImageView g_hDepthImageView;
94
95static VkSurfaceCapabilitiesKHR g_SurfaceCapabilities;
96static std::vector<VkSurfaceFormatKHR> g_SurfaceFormats;
97static std::vector<VkPresentModeKHR> g_PresentModes;
98
Adam Sawicki8caf0bd2020-07-15 16:56:30 +020099static const VkDebugUtilsMessageSeverityFlagsEXT DEBUG_UTILS_MESSENGER_MESSAGE_SEVERITY =
100 //VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
101 //VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
102 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
103 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
104static const VkDebugUtilsMessageTypeFlagsEXT DEBUG_UTILS_MESSENGER_MESSAGE_TYPE =
105 VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
106 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
107 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
108static PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT_Func;
109static PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT_Func;
110static VkDebugUtilsMessengerEXT g_DebugUtilsMessenger;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200111
Adam Sawickie6e498f2017-06-16 17:21:31 +0200112static VkQueue g_hGraphicsQueue;
Adam Sawicki51fa9662018-10-03 13:44:29 +0200113VkQueue g_hSparseBindingQueue;
Adam Sawicki978fcf52018-12-05 14:38:48 +0100114VkCommandBuffer g_hTemporaryCommandBuffer;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200115
116static VkPipelineLayout g_hPipelineLayout;
117static VkRenderPass g_hRenderPass;
118static VkPipeline g_hPipeline;
119
120static VkBuffer g_hVertexBuffer;
Adam Sawicki819860e2017-07-04 14:30:38 +0200121static VmaAllocation g_hVertexBufferAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200122static VkBuffer g_hIndexBuffer;
Adam Sawicki819860e2017-07-04 14:30:38 +0200123static VmaAllocation g_hIndexBufferAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200124static uint32_t g_VertexCount;
125static uint32_t g_IndexCount;
126
127static VkImage g_hTextureImage;
Adam Sawicki819860e2017-07-04 14:30:38 +0200128static VmaAllocation g_hTextureImageAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200129static VkImageView g_hTextureImageView;
130
Adam Sawicki8317ba92019-11-18 13:14:11 +0100131static std::atomic_uint32_t g_CpuAllocCount;
132
Adam Sawickia68c01c2018-03-13 16:40:45 +0100133static void* CustomCpuAllocation(
134 void* pUserData, size_t size, size_t alignment,
135 VkSystemAllocationScope allocationScope)
136{
137 assert(pUserData == CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA);
Adam Sawicki8317ba92019-11-18 13:14:11 +0100138 void* const result = _aligned_malloc(size, alignment);
139 if(result)
140 {
141 ++g_CpuAllocCount;
142 }
143 return result;
Adam Sawickia68c01c2018-03-13 16:40:45 +0100144}
145
146static void* CustomCpuReallocation(
147 void* pUserData, void* pOriginal, size_t size, size_t alignment,
148 VkSystemAllocationScope allocationScope)
149{
150 assert(pUserData == CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA);
Adam Sawicki8317ba92019-11-18 13:14:11 +0100151 void* const result = _aligned_realloc(pOriginal, size, alignment);
152 if(pOriginal && !result)
153 {
154 --g_CpuAllocCount;
155 }
156 else if(!pOriginal && result)
157 {
158 ++g_CpuAllocCount;
159 }
160 return result;
Adam Sawickia68c01c2018-03-13 16:40:45 +0100161}
162
163static void CustomCpuFree(void* pUserData, void* pMemory)
164{
165 assert(pUserData == CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA);
Adam Sawicki8317ba92019-11-18 13:14:11 +0100166 if(pMemory)
167 {
168 const uint32_t oldAllocCount = g_CpuAllocCount.fetch_sub(1);
169 TEST(oldAllocCount > 0);
170 _aligned_free(pMemory);
171 }
Adam Sawickia68c01c2018-03-13 16:40:45 +0100172}
173
Adam Sawicki1f84f622019-07-02 13:40:01 +0200174static const VkAllocationCallbacks g_CpuAllocationCallbacks = {
175 CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA, // pUserData
176 &CustomCpuAllocation, // pfnAllocation
177 &CustomCpuReallocation, // pfnReallocation
178 &CustomCpuFree // pfnFree
179};
180
181const VkAllocationCallbacks* g_Allocs;
182
Adam Sawicki978fcf52018-12-05 14:38:48 +0100183void BeginSingleTimeCommands()
Adam Sawickie6e498f2017-06-16 17:21:31 +0200184{
185 VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
186 cmdBufBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
187 ERR_GUARD_VULKAN( vkBeginCommandBuffer(g_hTemporaryCommandBuffer, &cmdBufBeginInfo) );
188}
189
Adam Sawicki978fcf52018-12-05 14:38:48 +0100190void EndSingleTimeCommands()
Adam Sawickie6e498f2017-06-16 17:21:31 +0200191{
192 ERR_GUARD_VULKAN( vkEndCommandBuffer(g_hTemporaryCommandBuffer) );
193
194 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
195 submitInfo.commandBufferCount = 1;
196 submitInfo.pCommandBuffers = &g_hTemporaryCommandBuffer;
197
198 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) );
199 ERR_GUARD_VULKAN( vkQueueWaitIdle(g_hGraphicsQueue) );
200}
201
Adam Sawickida6c1942018-12-05 17:34:34 +0100202void LoadShader(std::vector<char>& out, const char* fileName)
Adam Sawickie6e498f2017-06-16 17:21:31 +0200203{
204 std::ifstream file(std::string(SHADER_PATH1) + fileName, std::ios::ate | std::ios::binary);
205 if(file.is_open() == false)
206 file.open(std::string(SHADER_PATH2) + fileName, std::ios::ate | std::ios::binary);
207 assert(file.is_open());
208 size_t fileSize = (size_t)file.tellg();
209 if(fileSize > 0)
210 {
211 out.resize(fileSize);
212 file.seekg(0);
213 file.read(out.data(), fileSize);
214 file.close();
215 }
216 else
217 out.clear();
218}
219
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200220static VkBool32 VKAPI_PTR MyDebugReportCallback(
221 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
222 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
223 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
224 void* pUserData)
Adam Sawickie6e498f2017-06-16 17:21:31 +0200225{
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200226 assert(pCallbackData && pCallbackData->pMessageIdName && pCallbackData->pMessage);
Adam Sawickib8333fb2018-03-13 16:15:53 +0100227
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200228 switch(messageSeverity)
Adam Sawickib8333fb2018-03-13 16:15:53 +0100229 {
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200230 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
Adam Sawickib8333fb2018-03-13 16:15:53 +0100231 SetConsoleColor(CONSOLE_COLOR::WARNING);
232 break;
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200233 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
Adam Sawickib8333fb2018-03-13 16:15:53 +0100234 SetConsoleColor(CONSOLE_COLOR::ERROR_);
235 break;
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200236 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
237 SetConsoleColor(CONSOLE_COLOR::NORMAL);
238 break;
239 default: // VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT
Adam Sawickib8333fb2018-03-13 16:15:53 +0100240 SetConsoleColor(CONSOLE_COLOR::INFO);
241 }
242
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200243 printf("%s \xBA %s\n", pCallbackData->pMessageIdName, pCallbackData->pMessage);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200244
Adam Sawickib8333fb2018-03-13 16:15:53 +0100245 SetConsoleColor(CONSOLE_COLOR::NORMAL);
246
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200247 if(messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT ||
248 messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
Adam Sawickie6e498f2017-06-16 17:21:31 +0200249 {
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200250 OutputDebugStringA(pCallbackData->pMessage);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200251 OutputDebugStringA("\n");
252 }
253
254 return VK_FALSE;
255}
256
257static VkSurfaceFormatKHR ChooseSurfaceFormat()
258{
259 assert(!g_SurfaceFormats.empty());
260
261 if((g_SurfaceFormats.size() == 1) && (g_SurfaceFormats[0].format == VK_FORMAT_UNDEFINED))
262 {
263 VkSurfaceFormatKHR result = { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
264 return result;
265 }
266
267 for(const auto& format : g_SurfaceFormats)
268 {
269 if((format.format == VK_FORMAT_B8G8R8A8_UNORM) &&
270 (format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR))
271 {
272 return format;
273 }
274 }
275
276 return g_SurfaceFormats[0];
277}
278
279VkPresentModeKHR ChooseSwapPresentMode()
280{
281 VkPresentModeKHR preferredMode = VSYNC ? VK_PRESENT_MODE_MAILBOX_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR;
282
283 if(std::find(g_PresentModes.begin(), g_PresentModes.end(), preferredMode) !=
284 g_PresentModes.end())
285 {
286 return preferredMode;
287 }
288
289 return VK_PRESENT_MODE_FIFO_KHR;
290}
291
292static VkExtent2D ChooseSwapExtent()
293{
294 if(g_SurfaceCapabilities.currentExtent.width != UINT_MAX)
295 return g_SurfaceCapabilities.currentExtent;
296
297 VkExtent2D result = {
298 std::max(g_SurfaceCapabilities.minImageExtent.width,
299 std::min(g_SurfaceCapabilities.maxImageExtent.width, (uint32_t)g_SizeX)),
300 std::max(g_SurfaceCapabilities.minImageExtent.height,
301 std::min(g_SurfaceCapabilities.maxImageExtent.height, (uint32_t)g_SizeY)) };
302 return result;
303}
304
305struct Vertex
306{
307 float pos[3];
308 float color[3];
309 float texCoord[2];
310};
311
312static void CreateMesh()
313{
314 assert(g_hAllocator);
315
316 static Vertex vertices[] = {
317 // -X
318 { { -1.f, -1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 0.f} },
319 { { -1.f, -1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 0.f} },
320 { { -1.f, 1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 1.f} },
321 { { -1.f, 1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 1.f} },
322 // +X
323 { { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 0.f} },
324 { { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 0.f} },
325 { { 1.f, 1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 1.f} },
326 { { 1.f, 1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 1.f} },
327 // -Z
328 { { 1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 0.f} },
329 { {-1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 0.f} },
330 { { 1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 1.f} },
331 { {-1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 1.f} },
332 // +Z
333 { {-1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 0.f} },
334 { { 1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 0.f} },
335 { {-1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 1.f} },
336 { { 1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 1.f} },
337 // -Y
338 { {-1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 0.f} },
339 { { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 0.f} },
340 { {-1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 1.f} },
341 { { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 1.f} },
342 // +Y
343 { { 1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 0.f} },
344 { {-1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 0.f} },
345 { { 1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 1.f} },
346 { {-1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 1.f} },
347 };
348 static uint16_t indices[] = {
349 0, 1, 2, 3, USHRT_MAX,
350 4, 5, 6, 7, USHRT_MAX,
351 8, 9, 10, 11, USHRT_MAX,
352 12, 13, 14, 15, USHRT_MAX,
353 16, 17, 18, 19, USHRT_MAX,
354 20, 21, 22, 23, USHRT_MAX,
355 };
356
357 size_t vertexBufferSize = sizeof(Vertex) * _countof(vertices);
358 size_t indexBufferSize = sizeof(uint16_t) * _countof(indices);
359 g_IndexCount = (uint32_t)_countof(indices);
360
361 // Create vertex buffer
362
363 VkBufferCreateInfo vbInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
364 vbInfo.size = vertexBufferSize;
365 vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
366 vbInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200367
Adam Sawicki976f9202017-09-12 20:45:14 +0200368 VmaAllocationCreateInfo vbAllocCreateInfo = {};
369 vbAllocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
Adam Sawicki5268dbb2017-11-08 12:52:05 +0100370 vbAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200371
Adam Sawicki819860e2017-07-04 14:30:38 +0200372 VkBuffer stagingVertexBuffer = VK_NULL_HANDLE;
373 VmaAllocation stagingVertexBufferAlloc = VK_NULL_HANDLE;
374 VmaAllocationInfo stagingVertexBufferAllocInfo = {};
Adam Sawicki976f9202017-09-12 20:45:14 +0200375 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbAllocCreateInfo, &stagingVertexBuffer, &stagingVertexBufferAlloc, &stagingVertexBufferAllocInfo) );
Adam Sawicki819860e2017-07-04 14:30:38 +0200376
377 memcpy(stagingVertexBufferAllocInfo.pMappedData, vertices, vertexBufferSize);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200378
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200379 // No need to flush stagingVertexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
380
Adam Sawickie6e498f2017-06-16 17:21:31 +0200381 vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
Adam Sawicki976f9202017-09-12 20:45:14 +0200382 vbAllocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
383 vbAllocCreateInfo.flags = 0;
384 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbAllocCreateInfo, &g_hVertexBuffer, &g_hVertexBufferAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200385
386 // Create index buffer
387
388 VkBufferCreateInfo ibInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
389 ibInfo.size = indexBufferSize;
390 ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
391 ibInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200392
Adam Sawicki976f9202017-09-12 20:45:14 +0200393 VmaAllocationCreateInfo ibAllocCreateInfo = {};
394 ibAllocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
Adam Sawicki5268dbb2017-11-08 12:52:05 +0100395 ibAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
Adam Sawicki819860e2017-07-04 14:30:38 +0200396
Adam Sawickie6e498f2017-06-16 17:21:31 +0200397 VkBuffer stagingIndexBuffer = VK_NULL_HANDLE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200398 VmaAllocation stagingIndexBufferAlloc = VK_NULL_HANDLE;
399 VmaAllocationInfo stagingIndexBufferAllocInfo = {};
Adam Sawicki976f9202017-09-12 20:45:14 +0200400 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibAllocCreateInfo, &stagingIndexBuffer, &stagingIndexBufferAlloc, &stagingIndexBufferAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200401
Adam Sawicki819860e2017-07-04 14:30:38 +0200402 memcpy(stagingIndexBufferAllocInfo.pMappedData, indices, indexBufferSize);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200403
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200404 // No need to flush stagingIndexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
405
Adam Sawickie6e498f2017-06-16 17:21:31 +0200406 ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
Adam Sawicki976f9202017-09-12 20:45:14 +0200407 ibAllocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
408 ibAllocCreateInfo.flags = 0;
409 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibAllocCreateInfo, &g_hIndexBuffer, &g_hIndexBufferAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200410
411 // Copy buffers
412
413 BeginSingleTimeCommands();
414
415 VkBufferCopy vbCopyRegion = {};
416 vbCopyRegion.srcOffset = 0;
417 vbCopyRegion.dstOffset = 0;
418 vbCopyRegion.size = vbInfo.size;
419 vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingVertexBuffer, g_hVertexBuffer, 1, &vbCopyRegion);
420
421 VkBufferCopy ibCopyRegion = {};
422 ibCopyRegion.srcOffset = 0;
423 ibCopyRegion.dstOffset = 0;
424 ibCopyRegion.size = ibInfo.size;
425 vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingIndexBuffer, g_hIndexBuffer, 1, &ibCopyRegion);
426
427 EndSingleTimeCommands();
428
Adam Sawicki819860e2017-07-04 14:30:38 +0200429 vmaDestroyBuffer(g_hAllocator, stagingIndexBuffer, stagingIndexBufferAlloc);
430 vmaDestroyBuffer(g_hAllocator, stagingVertexBuffer, stagingVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200431}
432
Adam Sawickie6e498f2017-06-16 17:21:31 +0200433static void CreateTexture(uint32_t sizeX, uint32_t sizeY)
434{
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100435 // Create staging buffer.
Adam Sawickie6e498f2017-06-16 17:21:31 +0200436
437 const VkDeviceSize imageSize = sizeX * sizeY * 4;
438
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100439 VkBufferCreateInfo stagingBufInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
440 stagingBufInfo.size = imageSize;
441 stagingBufInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
442
443 VmaAllocationCreateInfo stagingBufAllocCreateInfo = {};
444 stagingBufAllocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
445 stagingBufAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
Adam Sawicki819860e2017-07-04 14:30:38 +0200446
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100447 VkBuffer stagingBuf = VK_NULL_HANDLE;
448 VmaAllocation stagingBufAlloc = VK_NULL_HANDLE;
449 VmaAllocationInfo stagingBufAllocInfo = {};
450 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &stagingBufInfo, &stagingBufAllocCreateInfo, &stagingBuf, &stagingBufAlloc, &stagingBufAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200451
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100452 char* const pImageData = (char*)stagingBufAllocInfo.pMappedData;
453 uint8_t* pRowData = (uint8_t*)pImageData;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200454 for(uint32_t y = 0; y < sizeY; ++y)
455 {
456 uint32_t* pPixelData = (uint32_t*)pRowData;
457 for(uint32_t x = 0; x < sizeY; ++x)
458 {
459 *pPixelData =
460 ((x & 0x18) == 0x08 ? 0x000000FF : 0x00000000) |
461 ((x & 0x18) == 0x10 ? 0x0000FFFF : 0x00000000) |
462 ((y & 0x18) == 0x08 ? 0x0000FF00 : 0x00000000) |
463 ((y & 0x18) == 0x10 ? 0x00FF0000 : 0x00000000);
464 ++pPixelData;
465 }
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100466 pRowData += sizeX * 4;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200467 }
468
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200469 // No need to flush stagingImage memory because CPU_ONLY memory is always HOST_COHERENT.
470
Adam Sawicki10844a82017-08-16 17:32:09 +0200471 // Create g_hTextureImage in GPU memory.
472
Adam Sawickie6e498f2017-06-16 17:21:31 +0200473 VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
474 imageInfo.imageType = VK_IMAGE_TYPE_2D;
475 imageInfo.extent.width = sizeX;
476 imageInfo.extent.height = sizeY;
477 imageInfo.extent.depth = 1;
478 imageInfo.mipLevels = 1;
479 imageInfo.arrayLayers = 1;
480 imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
481 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
482 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
483 imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
484 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
485 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
486 imageInfo.flags = 0;
Adam Sawicki10844a82017-08-16 17:32:09 +0200487
Adam Sawicki976f9202017-09-12 20:45:14 +0200488 VmaAllocationCreateInfo imageAllocCreateInfo = {};
489 imageAllocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki10844a82017-08-16 17:32:09 +0200490
Adam Sawicki976f9202017-09-12 20:45:14 +0200491 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &imageInfo, &imageAllocCreateInfo, &g_hTextureImage, &g_hTextureImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200492
Adam Sawicki10844a82017-08-16 17:32:09 +0200493 // Transition image layouts, copy image.
494
495 BeginSingleTimeCommands();
496
497 VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
Adam Sawicki10844a82017-08-16 17:32:09 +0200498 imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
499 imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
Adam Sawicki10844a82017-08-16 17:32:09 +0200500 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
501 imgMemBarrier.subresourceRange.baseMipLevel = 0;
502 imgMemBarrier.subresourceRange.levelCount = 1;
503 imgMemBarrier.subresourceRange.baseArrayLayer = 0;
504 imgMemBarrier.subresourceRange.layerCount = 1;
Adam Sawicki10844a82017-08-16 17:32:09 +0200505 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
506 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
507 imgMemBarrier.image = g_hTextureImage;
508 imgMemBarrier.srcAccessMask = 0;
509 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
510
511 vkCmdPipelineBarrier(
512 g_hTemporaryCommandBuffer,
513 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
514 VK_PIPELINE_STAGE_TRANSFER_BIT,
515 0,
516 0, nullptr,
517 0, nullptr,
518 1, &imgMemBarrier);
519
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100520 VkBufferImageCopy region = {};
521 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
522 region.imageSubresource.layerCount = 1;
523 region.imageExtent.width = sizeX;
524 region.imageExtent.height = sizeY;
525 region.imageExtent.depth = 1;
526
527 vkCmdCopyBufferToImage(g_hTemporaryCommandBuffer, stagingBuf, g_hTextureImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
Adam Sawicki10844a82017-08-16 17:32:09 +0200528
529 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
530 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
531 imgMemBarrier.image = g_hTextureImage;
532 imgMemBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
533 imgMemBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
534
535 vkCmdPipelineBarrier(
536 g_hTemporaryCommandBuffer,
537 VK_PIPELINE_STAGE_TRANSFER_BIT,
538 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
539 0,
540 0, nullptr,
541 0, nullptr,
542 1, &imgMemBarrier);
543
544 EndSingleTimeCommands();
Adam Sawickie6e498f2017-06-16 17:21:31 +0200545
Adam Sawickif43e9cd2019-02-20 14:55:31 +0100546 vmaDestroyBuffer(g_hAllocator, stagingBuf, stagingBufAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200547
548 // Create ImageView
549
550 VkImageViewCreateInfo textureImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
551 textureImageViewInfo.image = g_hTextureImage;
552 textureImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
553 textureImageViewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
554 textureImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
555 textureImageViewInfo.subresourceRange.baseMipLevel = 0;
556 textureImageViewInfo.subresourceRange.levelCount = 1;
557 textureImageViewInfo.subresourceRange.baseArrayLayer = 0;
558 textureImageViewInfo.subresourceRange.layerCount = 1;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200559 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &textureImageViewInfo, g_Allocs, &g_hTextureImageView) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200560}
561
562struct UniformBufferObject
563{
Adam Sawicki82c3f332018-06-11 15:27:33 +0200564 mat4 ModelViewProj;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200565};
566
567static void RegisterDebugCallbacks()
568{
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200569 vkCreateDebugUtilsMessengerEXT_Func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
570 g_hVulkanInstance, "vkCreateDebugUtilsMessengerEXT");
571 vkDestroyDebugUtilsMessengerEXT_Func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
572 g_hVulkanInstance, "vkDestroyDebugUtilsMessengerEXT");
573 assert(vkCreateDebugUtilsMessengerEXT_Func);
574 assert(vkDestroyDebugUtilsMessengerEXT_Func);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200575
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200576 VkDebugUtilsMessengerCreateInfoEXT messengerCreateInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
577 messengerCreateInfo.messageSeverity = DEBUG_UTILS_MESSENGER_MESSAGE_SEVERITY;
578 messengerCreateInfo.messageType = DEBUG_UTILS_MESSENGER_MESSAGE_TYPE;
579 messengerCreateInfo.pfnUserCallback = MyDebugReportCallback;
580 ERR_GUARD_VULKAN( vkCreateDebugUtilsMessengerEXT_Func(g_hVulkanInstance, &messengerCreateInfo, g_Allocs, &g_DebugUtilsMessenger) );
581}
Adam Sawickie6e498f2017-06-16 17:21:31 +0200582
Adam Sawicki8caf0bd2020-07-15 16:56:30 +0200583static void UnregisterDebugCallbacks()
584{
585 if(g_DebugUtilsMessenger)
586 {
587 vkDestroyDebugUtilsMessengerEXT_Func(g_hVulkanInstance, g_DebugUtilsMessenger, g_Allocs);
588 }
Adam Sawickie6e498f2017-06-16 17:21:31 +0200589}
590
591static bool IsLayerSupported(const VkLayerProperties* pProps, size_t propCount, const char* pLayerName)
592{
593 const VkLayerProperties* propsEnd = pProps + propCount;
594 return std::find_if(
595 pProps,
596 propsEnd,
597 [pLayerName](const VkLayerProperties& prop) -> bool {
598 return strcmp(pLayerName, prop.layerName) == 0;
599 }) != propsEnd;
600}
601
602static VkFormat FindSupportedFormat(
603 const std::vector<VkFormat>& candidates,
604 VkImageTiling tiling,
605 VkFormatFeatureFlags features)
606{
607 for (VkFormat format : candidates)
608 {
609 VkFormatProperties props;
610 vkGetPhysicalDeviceFormatProperties(g_hPhysicalDevice, format, &props);
611
612 if ((tiling == VK_IMAGE_TILING_LINEAR) &&
613 ((props.linearTilingFeatures & features) == features))
614 {
615 return format;
616 }
617 else if ((tiling == VK_IMAGE_TILING_OPTIMAL) &&
618 ((props.optimalTilingFeatures & features) == features))
619 {
620 return format;
621 }
622 }
623 return VK_FORMAT_UNDEFINED;
624}
625
626static VkFormat FindDepthFormat()
627{
628 std::vector<VkFormat> formats;
629 formats.push_back(VK_FORMAT_D32_SFLOAT);
630 formats.push_back(VK_FORMAT_D32_SFLOAT_S8_UINT);
631 formats.push_back(VK_FORMAT_D24_UNORM_S8_UINT);
632
633 return FindSupportedFormat(
634 formats,
635 VK_IMAGE_TILING_OPTIMAL,
636 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
637}
638
639static void CreateSwapchain()
640{
641 // Query surface formats.
642
643 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_hPhysicalDevice, g_hSurface, &g_SurfaceCapabilities) );
644
645 uint32_t formatCount = 0;
646 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, nullptr) );
647 g_SurfaceFormats.resize(formatCount);
648 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, g_SurfaceFormats.data()) );
649
650 uint32_t presentModeCount = 0;
651 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, nullptr) );
652 g_PresentModes.resize(presentModeCount);
653 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, g_PresentModes.data()) );
654
655 // Create swap chain
656
657 g_SurfaceFormat = ChooseSurfaceFormat();
658 VkPresentModeKHR presentMode = ChooseSwapPresentMode();
659 g_Extent = ChooseSwapExtent();
660
661 uint32_t imageCount = g_SurfaceCapabilities.minImageCount + 1;
662 if((g_SurfaceCapabilities.maxImageCount > 0) &&
663 (imageCount > g_SurfaceCapabilities.maxImageCount))
664 {
665 imageCount = g_SurfaceCapabilities.maxImageCount;
666 }
667
668 VkSwapchainCreateInfoKHR swapChainInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
669 swapChainInfo.surface = g_hSurface;
670 swapChainInfo.minImageCount = imageCount;
671 swapChainInfo.imageFormat = g_SurfaceFormat.format;
672 swapChainInfo.imageColorSpace = g_SurfaceFormat.colorSpace;
673 swapChainInfo.imageExtent = g_Extent;
674 swapChainInfo.imageArrayLayers = 1;
675 swapChainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
676 swapChainInfo.preTransform = g_SurfaceCapabilities.currentTransform;
677 swapChainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
678 swapChainInfo.presentMode = presentMode;
679 swapChainInfo.clipped = VK_TRUE;
680 swapChainInfo.oldSwapchain = g_hSwapchain;
681
682 uint32_t queueFamilyIndices[] = { g_GraphicsQueueFamilyIndex, g_PresentQueueFamilyIndex };
683 if(g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex)
684 {
685 swapChainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
686 swapChainInfo.queueFamilyIndexCount = 2;
687 swapChainInfo.pQueueFamilyIndices = queueFamilyIndices;
688 }
689 else
690 {
691 swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
692 }
693
694 VkSwapchainKHR hNewSwapchain = VK_NULL_HANDLE;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200695 ERR_GUARD_VULKAN( vkCreateSwapchainKHR(g_hDevice, &swapChainInfo, g_Allocs, &hNewSwapchain) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200696 if(g_hSwapchain != VK_NULL_HANDLE)
Adam Sawicki1f84f622019-07-02 13:40:01 +0200697 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200698 g_hSwapchain = hNewSwapchain;
699
700 // Retrieve swapchain images.
701
702 uint32_t swapchainImageCount = 0;
703 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, nullptr) );
704 g_SwapchainImages.resize(swapchainImageCount);
705 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, g_SwapchainImages.data()) );
706
707 // Create swapchain image views.
708
709 for(size_t i = g_SwapchainImageViews.size(); i--; )
Adam Sawicki1f84f622019-07-02 13:40:01 +0200710 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200711 g_SwapchainImageViews.clear();
712
713 VkImageViewCreateInfo swapchainImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
714 g_SwapchainImageViews.resize(swapchainImageCount);
715 for(uint32_t i = 0; i < swapchainImageCount; ++i)
716 {
717 swapchainImageViewInfo.image = g_SwapchainImages[i];
718 swapchainImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
719 swapchainImageViewInfo.format = g_SurfaceFormat.format;
720 swapchainImageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
721 swapchainImageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
722 swapchainImageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
723 swapchainImageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
724 swapchainImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
725 swapchainImageViewInfo.subresourceRange.baseMipLevel = 0;
726 swapchainImageViewInfo.subresourceRange.levelCount = 1;
727 swapchainImageViewInfo.subresourceRange.baseArrayLayer = 0;
728 swapchainImageViewInfo.subresourceRange.layerCount = 1;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200729 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &swapchainImageViewInfo, g_Allocs, &g_SwapchainImageViews[i]) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200730 }
731
732 // Create depth buffer
733
734 g_DepthFormat = FindDepthFormat();
735 assert(g_DepthFormat != VK_FORMAT_UNDEFINED);
736
737 VkImageCreateInfo depthImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
738 depthImageInfo.imageType = VK_IMAGE_TYPE_2D;
739 depthImageInfo.extent.width = g_Extent.width;
740 depthImageInfo.extent.height = g_Extent.height;
741 depthImageInfo.extent.depth = 1;
742 depthImageInfo.mipLevels = 1;
743 depthImageInfo.arrayLayers = 1;
744 depthImageInfo.format = g_DepthFormat;
745 depthImageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
746 depthImageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
747 depthImageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
748 depthImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
749 depthImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
750 depthImageInfo.flags = 0;
751
Adam Sawicki976f9202017-09-12 20:45:14 +0200752 VmaAllocationCreateInfo depthImageAllocCreateInfo = {};
753 depthImageAllocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200754
Adam Sawicki976f9202017-09-12 20:45:14 +0200755 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &depthImageInfo, &depthImageAllocCreateInfo, &g_hDepthImage, &g_hDepthImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200756
757 VkImageViewCreateInfo depthImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
758 depthImageViewInfo.image = g_hDepthImage;
759 depthImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
760 depthImageViewInfo.format = g_DepthFormat;
761 depthImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
762 depthImageViewInfo.subresourceRange.baseMipLevel = 0;
763 depthImageViewInfo.subresourceRange.levelCount = 1;
764 depthImageViewInfo.subresourceRange.baseArrayLayer = 0;
765 depthImageViewInfo.subresourceRange.layerCount = 1;
766
Adam Sawicki1f84f622019-07-02 13:40:01 +0200767 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &depthImageViewInfo, g_Allocs, &g_hDepthImageView) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200768
Adam Sawickie6e498f2017-06-16 17:21:31 +0200769 // Create pipeline layout
770 {
771 if(g_hPipelineLayout != VK_NULL_HANDLE)
772 {
Adam Sawicki1f84f622019-07-02 13:40:01 +0200773 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200774 g_hPipelineLayout = VK_NULL_HANDLE;
775 }
776
777 VkPushConstantRange pushConstantRanges[1];
778 ZeroMemory(&pushConstantRanges, sizeof pushConstantRanges);
779 pushConstantRanges[0].offset = 0;
780 pushConstantRanges[0].size = sizeof(UniformBufferObject);
781 pushConstantRanges[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
782
783 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
784 VkPipelineLayoutCreateInfo pipelineLayoutInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
785 pipelineLayoutInfo.setLayoutCount = 1;
786 pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts;
787 pipelineLayoutInfo.pushConstantRangeCount = 1;
788 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200789 ERR_GUARD_VULKAN( vkCreatePipelineLayout(g_hDevice, &pipelineLayoutInfo, g_Allocs, &g_hPipelineLayout) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200790 }
791
792 // Create render pass
793 {
794 if(g_hRenderPass != VK_NULL_HANDLE)
795 {
Adam Sawicki1f84f622019-07-02 13:40:01 +0200796 vkDestroyRenderPass(g_hDevice, g_hRenderPass, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200797 g_hRenderPass = VK_NULL_HANDLE;
798 }
799
800 VkAttachmentDescription attachments[2];
801 ZeroMemory(attachments, sizeof(attachments));
802
803 attachments[0].format = g_SurfaceFormat.format;
804 attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
805 attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
806 attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
807 attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
808 attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
Adam Sawicki8eb9d8e2017-11-13 16:30:14 +0100809 attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200810 attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
811
812 attachments[1].format = g_DepthFormat;
813 attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
814 attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
815 attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
816 attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
817 attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
Adam Sawicki8eb9d8e2017-11-13 16:30:14 +0100818 attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200819 attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
820
821 VkAttachmentReference colorAttachmentRef = {};
822 colorAttachmentRef.attachment = 0;
823 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
824
825 VkAttachmentReference depthStencilAttachmentRef = {};
826 depthStencilAttachmentRef.attachment = 1;
827 depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
828
829 VkSubpassDescription subpassDesc = {};
830 subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
831 subpassDesc.colorAttachmentCount = 1;
832 subpassDesc.pColorAttachments = &colorAttachmentRef;
833 subpassDesc.pDepthStencilAttachment = &depthStencilAttachmentRef;
834
Adam Sawickie6e498f2017-06-16 17:21:31 +0200835 VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
836 renderPassInfo.attachmentCount = (uint32_t)_countof(attachments);
837 renderPassInfo.pAttachments = attachments;
838 renderPassInfo.subpassCount = 1;
839 renderPassInfo.pSubpasses = &subpassDesc;
Adam Sawicki14137d12017-10-16 18:06:05 +0200840 renderPassInfo.dependencyCount = 0;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200841 ERR_GUARD_VULKAN( vkCreateRenderPass(g_hDevice, &renderPassInfo, g_Allocs, &g_hRenderPass) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200842 }
843
844 // Create pipeline
845 {
846 std::vector<char> vertShaderCode;
847 LoadShader(vertShaderCode, "Shader.vert.spv");
848 VkShaderModuleCreateInfo shaderModuleInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
849 shaderModuleInfo.codeSize = vertShaderCode.size();
850 shaderModuleInfo.pCode = (const uint32_t*)vertShaderCode.data();
851 VkShaderModule hVertShaderModule = VK_NULL_HANDLE;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200852 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, g_Allocs, &hVertShaderModule) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200853
854 std::vector<char> hFragShaderCode;
855 LoadShader(hFragShaderCode, "Shader.frag.spv");
856 shaderModuleInfo.codeSize = hFragShaderCode.size();
857 shaderModuleInfo.pCode = (const uint32_t*)hFragShaderCode.data();
858 VkShaderModule fragShaderModule = VK_NULL_HANDLE;
Adam Sawicki1f84f622019-07-02 13:40:01 +0200859 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, g_Allocs, &fragShaderModule) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200860
861 VkPipelineShaderStageCreateInfo vertPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
862 vertPipelineShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
863 vertPipelineShaderStageInfo.module = hVertShaderModule;
864 vertPipelineShaderStageInfo.pName = "main";
865
866 VkPipelineShaderStageCreateInfo fragPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
867 fragPipelineShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
868 fragPipelineShaderStageInfo.module = fragShaderModule;
869 fragPipelineShaderStageInfo.pName = "main";
870
871 VkPipelineShaderStageCreateInfo pipelineShaderStageInfos[] = {
872 vertPipelineShaderStageInfo,
873 fragPipelineShaderStageInfo
874 };
875
876 VkVertexInputBindingDescription bindingDescription = {};
877 bindingDescription.binding = 0;
878 bindingDescription.stride = sizeof(Vertex);
879 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
880
881 VkVertexInputAttributeDescription attributeDescriptions[3];
882 ZeroMemory(attributeDescriptions, sizeof(attributeDescriptions));
883
884 attributeDescriptions[0].binding = 0;
885 attributeDescriptions[0].location = 0;
886 attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
887 attributeDescriptions[0].offset = offsetof(Vertex, pos);
888
889 attributeDescriptions[1].binding = 0;
890 attributeDescriptions[1].location = 1;
891 attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
892 attributeDescriptions[1].offset = offsetof(Vertex, color);
893
894 attributeDescriptions[2].binding = 0;
895 attributeDescriptions[2].location = 2;
896 attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
897 attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
898
899 VkPipelineVertexInputStateCreateInfo pipelineVertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
900 pipelineVertexInputStateInfo.vertexBindingDescriptionCount = 1;
901 pipelineVertexInputStateInfo.pVertexBindingDescriptions = &bindingDescription;
902 pipelineVertexInputStateInfo.vertexAttributeDescriptionCount = _countof(attributeDescriptions);
903 pipelineVertexInputStateInfo.pVertexAttributeDescriptions = attributeDescriptions;
904
905 VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
906 pipelineInputAssemblyStateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
907 pipelineInputAssemblyStateInfo.primitiveRestartEnable = VK_TRUE;
908
909 VkViewport viewport = {};
910 viewport.x = 0.f;
911 viewport.y = 0.f;
912 viewport.width = (float)g_Extent.width;
913 viewport.height = (float)g_Extent.height;
914 viewport.minDepth = 0.f;
915 viewport.maxDepth = 1.f;
916
917 VkRect2D scissor = {};
918 scissor.offset.x = 0;
919 scissor.offset.y = 0;
920 scissor.extent = g_Extent;
921
922 VkPipelineViewportStateCreateInfo pipelineViewportStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
923 pipelineViewportStateInfo.viewportCount = 1;
924 pipelineViewportStateInfo.pViewports = &viewport;
925 pipelineViewportStateInfo.scissorCount = 1;
926 pipelineViewportStateInfo.pScissors = &scissor;
927
928 VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
929 pipelineRasterizationStateInfo.depthClampEnable = VK_FALSE;
930 pipelineRasterizationStateInfo.rasterizerDiscardEnable = VK_FALSE;
931 pipelineRasterizationStateInfo.polygonMode = VK_POLYGON_MODE_FILL;
932 pipelineRasterizationStateInfo.lineWidth = 1.f;
933 pipelineRasterizationStateInfo.cullMode = VK_CULL_MODE_BACK_BIT;
934 pipelineRasterizationStateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
935 pipelineRasterizationStateInfo.depthBiasEnable = VK_FALSE;
936 pipelineRasterizationStateInfo.depthBiasConstantFactor = 0.f;
937 pipelineRasterizationStateInfo.depthBiasClamp = 0.f;
938 pipelineRasterizationStateInfo.depthBiasSlopeFactor = 0.f;
939
940 VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
941 pipelineMultisampleStateInfo.sampleShadingEnable = VK_FALSE;
942 pipelineMultisampleStateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
943 pipelineMultisampleStateInfo.minSampleShading = 1.f;
944 pipelineMultisampleStateInfo.pSampleMask = nullptr;
945 pipelineMultisampleStateInfo.alphaToCoverageEnable = VK_FALSE;
946 pipelineMultisampleStateInfo.alphaToOneEnable = VK_FALSE;
947
948 VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState = {};
949 pipelineColorBlendAttachmentState.colorWriteMask =
950 VK_COLOR_COMPONENT_R_BIT |
951 VK_COLOR_COMPONENT_G_BIT |
952 VK_COLOR_COMPONENT_B_BIT |
953 VK_COLOR_COMPONENT_A_BIT;
954 pipelineColorBlendAttachmentState.blendEnable = VK_FALSE;
955 pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
956 pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
957 pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; // Optional
958 pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
959 pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
960 pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
961
962 VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
963 pipelineColorBlendStateInfo.logicOpEnable = VK_FALSE;
964 pipelineColorBlendStateInfo.logicOp = VK_LOGIC_OP_COPY;
965 pipelineColorBlendStateInfo.attachmentCount = 1;
966 pipelineColorBlendStateInfo.pAttachments = &pipelineColorBlendAttachmentState;
967
968 VkPipelineDepthStencilStateCreateInfo depthStencilStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
969 depthStencilStateInfo.depthTestEnable = VK_TRUE;
970 depthStencilStateInfo.depthWriteEnable = VK_TRUE;
971 depthStencilStateInfo.depthCompareOp = VK_COMPARE_OP_LESS;
972 depthStencilStateInfo.depthBoundsTestEnable = VK_FALSE;
973 depthStencilStateInfo.stencilTestEnable = VK_FALSE;
974
975 VkGraphicsPipelineCreateInfo pipelineInfo = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
976 pipelineInfo.stageCount = 2;
977 pipelineInfo.pStages = pipelineShaderStageInfos;
978 pipelineInfo.pVertexInputState = &pipelineVertexInputStateInfo;
979 pipelineInfo.pInputAssemblyState = &pipelineInputAssemblyStateInfo;
980 pipelineInfo.pViewportState = &pipelineViewportStateInfo;
981 pipelineInfo.pRasterizationState = &pipelineRasterizationStateInfo;
982 pipelineInfo.pMultisampleState = &pipelineMultisampleStateInfo;
983 pipelineInfo.pDepthStencilState = &depthStencilStateInfo;
984 pipelineInfo.pColorBlendState = &pipelineColorBlendStateInfo;
985 pipelineInfo.pDynamicState = nullptr;
986 pipelineInfo.layout = g_hPipelineLayout;
987 pipelineInfo.renderPass = g_hRenderPass;
988 pipelineInfo.subpass = 0;
989 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
990 pipelineInfo.basePipelineIndex = -1;
991 ERR_GUARD_VULKAN( vkCreateGraphicsPipelines(
992 g_hDevice,
993 VK_NULL_HANDLE,
994 1,
Adam Sawicki1f84f622019-07-02 13:40:01 +0200995 &pipelineInfo,
996 g_Allocs,
Adam Sawickie6e498f2017-06-16 17:21:31 +0200997 &g_hPipeline) );
998
Adam Sawicki1f84f622019-07-02 13:40:01 +0200999 vkDestroyShaderModule(g_hDevice, fragShaderModule, g_Allocs);
1000 vkDestroyShaderModule(g_hDevice, hVertShaderModule, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001001 }
1002
1003 // Create frambuffers
1004
1005 for(size_t i = g_Framebuffers.size(); i--; )
Adam Sawicki1f84f622019-07-02 13:40:01 +02001006 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001007 g_Framebuffers.clear();
1008
1009 g_Framebuffers.resize(g_SwapchainImageViews.size());
1010 for(size_t i = 0; i < g_SwapchainImages.size(); ++i)
1011 {
1012 VkImageView attachments[] = { g_SwapchainImageViews[i], g_hDepthImageView };
1013
1014 VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
1015 framebufferInfo.renderPass = g_hRenderPass;
1016 framebufferInfo.attachmentCount = (uint32_t)_countof(attachments);
1017 framebufferInfo.pAttachments = attachments;
1018 framebufferInfo.width = g_Extent.width;
1019 framebufferInfo.height = g_Extent.height;
1020 framebufferInfo.layers = 1;
Adam Sawicki1f84f622019-07-02 13:40:01 +02001021 ERR_GUARD_VULKAN( vkCreateFramebuffer(g_hDevice, &framebufferInfo, g_Allocs, &g_Framebuffers[i]) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001022 }
1023
1024 // Create semaphores
1025
1026 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1027 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001028 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001029 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1030 }
1031 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1032 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001033 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001034 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1035 }
1036
1037 VkSemaphoreCreateInfo semaphoreInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
Adam Sawicki1f84f622019-07-02 13:40:01 +02001038 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, g_Allocs, &g_hImageAvailableSemaphore) );
1039 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, g_Allocs, &g_hRenderFinishedSemaphore) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001040}
1041
1042static void DestroySwapchain(bool destroyActualSwapchain)
1043{
1044 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1045 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001046 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001047 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1048 }
1049 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1050 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001051 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001052 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1053 }
1054
1055 for(size_t i = g_Framebuffers.size(); i--; )
Adam Sawicki1f84f622019-07-02 13:40:01 +02001056 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001057 g_Framebuffers.clear();
1058
1059 if(g_hDepthImageView != VK_NULL_HANDLE)
1060 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001061 vkDestroyImageView(g_hDevice, g_hDepthImageView, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001062 g_hDepthImageView = VK_NULL_HANDLE;
1063 }
1064 if(g_hDepthImage != VK_NULL_HANDLE)
1065 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001066 vmaDestroyImage(g_hAllocator, g_hDepthImage, g_hDepthImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001067 g_hDepthImage = VK_NULL_HANDLE;
1068 }
1069
1070 if(g_hPipeline != VK_NULL_HANDLE)
1071 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001072 vkDestroyPipeline(g_hDevice, g_hPipeline, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001073 g_hPipeline = VK_NULL_HANDLE;
1074 }
1075
1076 if(g_hRenderPass != VK_NULL_HANDLE)
1077 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001078 vkDestroyRenderPass(g_hDevice, g_hRenderPass, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001079 g_hRenderPass = VK_NULL_HANDLE;
1080 }
1081
1082 if(g_hPipelineLayout != VK_NULL_HANDLE)
1083 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001084 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001085 g_hPipelineLayout = VK_NULL_HANDLE;
1086 }
1087
1088 for(size_t i = g_SwapchainImageViews.size(); i--; )
Adam Sawicki1f84f622019-07-02 13:40:01 +02001089 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001090 g_SwapchainImageViews.clear();
1091
1092 if(destroyActualSwapchain && (g_hSwapchain != VK_NULL_HANDLE))
1093 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001094 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001095 g_hSwapchain = VK_NULL_HANDLE;
1096 }
1097}
1098
Adam Sawicki50882502020-02-07 16:51:31 +01001099static constexpr uint32_t GetVulkanApiVersion()
1100{
Adam Sawicki8ef0d202020-03-02 15:43:47 +01001101#if VMA_VULKAN_VERSION == 1002000
1102 return VK_API_VERSION_1_2;
1103#elif VMA_VULKAN_VERSION == 1001000
1104 return VK_API_VERSION_1_1;
1105#elif VMA_VULKAN_VERSION == 1000000
1106 return VK_API_VERSION_1_0;
1107#else
1108 #error Invalid VMA_VULKAN_VERSION.
1109 return UINT32_MAX;
1110#endif
Adam Sawicki50882502020-02-07 16:51:31 +01001111}
1112
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001113static void PrintEnabledFeatures()
1114{
Adam Sawickiafd50562021-02-26 11:59:58 +01001115 wprintf(L"Enabled extensions and features:\n");
Adam Sawickie8a85442020-03-06 14:48:30 +01001116 wprintf(L"Validation layer: %d\n", g_EnableValidationLayer ? 1 : 0);
1117 wprintf(L"Sparse binding: %d\n", g_SparseBindingEnabled ? 1 : 0);
Adam Sawickie73e9882020-03-20 18:05:42 +01001118 wprintf(L"Buffer device address: %d\n", g_BufferDeviceAddressEnabled ? 1 : 0);
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001119 if(GetVulkanApiVersion() == VK_API_VERSION_1_0)
1120 {
Adam Sawickie8a85442020-03-06 14:48:30 +01001121 wprintf(L"VK_KHR_get_memory_requirements2: %d\n", VK_KHR_get_memory_requirements2_enabled ? 1 : 0);
1122 wprintf(L"VK_KHR_get_physical_device_properties2: %d\n", VK_KHR_get_physical_device_properties2_enabled ? 1 : 0);
1123 wprintf(L"VK_KHR_dedicated_allocation: %d\n", VK_KHR_dedicated_allocation_enabled ? 1 : 0);
1124 wprintf(L"VK_KHR_bind_memory2: %d\n", VK_KHR_bind_memory2_enabled ? 1 : 0);
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001125 }
Adam Sawickie8a85442020-03-06 14:48:30 +01001126 wprintf(L"VK_EXT_memory_budget: %d\n", VK_EXT_memory_budget_enabled ? 1 : 0);
1127 wprintf(L"VK_AMD_device_coherent_memory: %d\n", VK_AMD_device_coherent_memory_enabled ? 1 : 0);
Adam Sawickie73e9882020-03-20 18:05:42 +01001128 wprintf(L"VK_KHR_buffer_device_address: %d\n", VK_KHR_buffer_device_address_enabled ? 1 : 0);
1129 wprintf(L"VK_EXT_buffer_device_address: %d\n", VK_EXT_buffer_device_address_enabled ? 1 : 0);
Adam Sawickif2012052021-01-11 18:04:42 +01001130 wprintf(L"VK_EXT_memory_priority: %d\n", VK_EXT_memory_priority ? 1 : 0);
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001131}
1132
Adam Sawicki50882502020-02-07 16:51:31 +01001133void SetAllocatorCreateInfo(VmaAllocatorCreateInfo& outInfo)
1134{
1135 outInfo = {};
1136
1137 outInfo.physicalDevice = g_hPhysicalDevice;
1138 outInfo.device = g_hDevice;
1139 outInfo.instance = g_hVulkanInstance;
1140 outInfo.vulkanApiVersion = GetVulkanApiVersion();
1141
1142 if(VK_KHR_dedicated_allocation_enabled)
1143 {
1144 outInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
1145 }
1146 if(VK_KHR_bind_memory2_enabled)
1147 {
1148 outInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT;
1149 }
1150#if !defined(VMA_MEMORY_BUDGET) || VMA_MEMORY_BUDGET == 1
Adam Sawicki6a93b8a2020-03-09 16:58:18 +01001151 if(VK_EXT_memory_budget_enabled && (
1152 GetVulkanApiVersion() >= VK_API_VERSION_1_1 || VK_KHR_get_physical_device_properties2_enabled))
Adam Sawicki50882502020-02-07 16:51:31 +01001153 {
1154 outInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
1155 }
1156#endif
1157 if(VK_AMD_device_coherent_memory_enabled)
1158 {
1159 outInfo.flags |= VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT;
1160 }
Adam Sawickie73e9882020-03-20 18:05:42 +01001161 if(g_BufferDeviceAddressEnabled)
1162 {
1163 outInfo.flags |= VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT;
1164 }
Adam Sawickif2012052021-01-11 18:04:42 +01001165#if !defined(VMA_MEMORY_PRIORITY) || VMA_MEMORY_PRIORITY == 1
1166 if(VK_EXT_memory_priority_enabled)
1167 {
1168 outInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT;
1169 }
1170#endif
Adam Sawicki50882502020-02-07 16:51:31 +01001171
1172 if(USE_CUSTOM_CPU_ALLOCATION_CALLBACKS)
1173 {
1174 outInfo.pAllocationCallbacks = &g_CpuAllocationCallbacks;
1175 }
1176
1177 // Uncomment to enable recording to CSV file.
1178 /*
1179 static VmaRecordSettings recordSettings = {};
1180 recordSettings.pFilePath = "VulkanSample.csv";
1181 outInfo.pRecordSettings = &recordSettings;
1182 */
1183
1184 // Uncomment to enable HeapSizeLimit.
1185 /*
1186 static std::array<VkDeviceSize, VK_MAX_MEMORY_HEAPS> heapSizeLimit;
1187 std::fill(heapSizeLimit.begin(), heapSizeLimit.end(), VK_WHOLE_SIZE);
1188 heapSizeLimit[0] = 512ull * 1024 * 1024;
1189 outInfo.pHeapSizeLimit = heapSizeLimit.data();
1190 */
1191}
1192
Adam Sawickie8a85442020-03-06 14:48:30 +01001193static void PrintPhysicalDeviceProperties(const VkPhysicalDeviceProperties& properties)
1194{
Adam Sawickiafd50562021-02-26 11:59:58 +01001195 wprintf(L"physicalDeviceProperties:\n");
1196 wprintf(L" driverVersion: 0x%X\n", properties.driverVersion);
1197 wprintf(L" vendorID: 0x%X (%s)\n", properties.vendorID, VendorIDToStr(properties.vendorID));
1198 wprintf(L" deviceID: 0x%X\n", properties.deviceID);
1199 wprintf(L" deviceType: %u (%s)\n", properties.deviceType, PhysicalDeviceTypeToStr(properties.deviceType));
1200 wprintf(L" deviceName: %hs\n", properties.deviceName);
1201 wprintf(L" limits:\n");
1202 wprintf(L" maxMemoryAllocationCount: %u\n", properties.limits.maxMemoryAllocationCount);
1203 wprintf(L" bufferImageGranularity: %llu B\n", properties.limits.bufferImageGranularity);
1204 wprintf(L" nonCoherentAtomSize: %llu B\n", properties.limits.nonCoherentAtomSize);
1205}
1206
1207#if VMA_VULKAN_VERSION >= 1002000
1208static void PrintPhysicalDeviceVulkan11Properties(const VkPhysicalDeviceVulkan11Properties& properties)
1209{
1210 wprintf(L"physicalDeviceVulkan11Properties:\n");
1211 std::wstring sizeStr = SizeToStr(properties.maxMemoryAllocationSize);
1212 wprintf(L" maxMemoryAllocationSize: %llu B (%s)\n", properties.maxMemoryAllocationSize, sizeStr.c_str());
1213}
1214static void PrintPhysicalDeviceVulkan12Properties(const VkPhysicalDeviceVulkan12Properties& properties)
1215{
1216 wprintf(L"physicalDeviceVulkan12Properties:\n");
1217 std::wstring str = DriverIDToStr(properties.driverID);
1218 wprintf(L" driverID: %u (%s)\n", properties.driverID, str.c_str());
1219 wprintf(L" driverName: %hs\n", properties.driverName);
1220 wprintf(L" driverInfo: %hs\n", properties.driverInfo);
1221}
1222#endif // #if VMA_VULKAN_VERSION > 1002000
1223
1224static void AddFlagToStr(std::wstring& inout, const wchar_t* flagStr)
1225{
1226 if(!inout.empty())
1227 inout += L", ";
1228 inout += flagStr;
1229}
1230
1231static std::wstring HeapFlagsToStr(VkMemoryHeapFlags flags)
1232{
1233 std::wstring result;
1234 if(flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT)
1235 AddFlagToStr(result, L"DEVICE_LOCAL");
1236 if(flags & VK_MEMORY_HEAP_MULTI_INSTANCE_BIT)
1237 AddFlagToStr(result, L"MULTI_INSTANCE");
1238 return result;
1239}
1240
1241static std::wstring PropertyFlagsToStr(VkMemoryPropertyFlags flags)
1242{
1243 std::wstring result;
1244 if(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
1245 AddFlagToStr(result, L"DEVICE_LOCAL");
1246 if(flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1247 AddFlagToStr(result, L"HOST_VISIBLE");
1248 if(flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
1249 AddFlagToStr(result, L"HOST_COHERENT");
1250 if(flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT)
1251 AddFlagToStr(result, L"HOST_CACHED");
1252 if(flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT)
1253 AddFlagToStr(result, L"LAZILY_ALLOCATED");
1254
1255#if VMA_VULKAN_VERSION >= 1001000
1256 if(flags & VK_MEMORY_PROPERTY_PROTECTED_BIT)
1257 AddFlagToStr(result, L"PROTECTED");
1258#endif
1259
1260#if VK_AMD_device_coherent_memory
1261 if(flags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD)
1262 AddFlagToStr(result, L"DEVICE_COHERENT (AMD)");
1263 if(flags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD)
1264 AddFlagToStr(result, L"DEVICE_UNCACHED (AMD)");
1265#endif
1266
1267 return result;
1268}
1269
1270static void PrintMemoryTypes()
1271{
1272 wprintf(L"MEMORY HEAPS:\n");
1273 const VkPhysicalDeviceMemoryProperties* memProps = nullptr;
1274 vmaGetMemoryProperties(g_hAllocator, &memProps);
1275
1276 wprintf(L"heapCount=%u, typeCount=%u\n", memProps->memoryHeapCount, memProps->memoryTypeCount);
1277
1278 std::wstring sizeStr, flagsStr;
1279 for(uint32_t heapIndex = 0; heapIndex < memProps->memoryHeapCount; ++heapIndex)
1280 {
1281 const VkMemoryHeap& heap = memProps->memoryHeaps[heapIndex];
1282 sizeStr = SizeToStr(heap.size);
1283 flagsStr = HeapFlagsToStr(heap.flags);
1284 wprintf(L"Heap %u: %llu B (%s) %s\n", heapIndex, heap.size, sizeStr.c_str(), flagsStr.c_str());
1285
1286 for(uint32_t typeIndex = 0; typeIndex < memProps->memoryTypeCount; ++typeIndex)
1287 {
1288 const VkMemoryType& type = memProps->memoryTypes[typeIndex];
1289 if(type.heapIndex == heapIndex)
1290 {
1291 flagsStr = PropertyFlagsToStr(type.propertyFlags);
1292 wprintf(L" Type %u: %s\n", typeIndex, flagsStr.c_str());
1293 }
1294 }
1295 }
1296}
1297
1298#if 0
1299template<typename It, typename MapFunc>
1300inline VkDeviceSize MapSum(It beg, It end, MapFunc mapFunc)
1301{
1302 VkDeviceSize result = 0;
1303 for(It it = beg; it != end; ++it)
1304 result += mapFunc(*it);
1305 return result;
1306}
1307#endif
1308
1309static bool CanCreateVertexBuffer(uint32_t allowedMemoryTypeBits)
1310{
1311 VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
1312 bufCreateInfo.size = 0x10000;
1313 bufCreateInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
1314
1315 VkBuffer buf = VK_NULL_HANDLE;
1316 VkResult res = vkCreateBuffer(g_hDevice, &bufCreateInfo, g_Allocs, &buf);
1317 assert(res == VK_SUCCESS);
1318
1319 VkMemoryRequirements memReq = {};
1320 vkGetBufferMemoryRequirements(g_hDevice, buf, &memReq);
1321
1322 vkDestroyBuffer(g_hDevice, buf, g_Allocs);
1323
1324 return (memReq.memoryTypeBits & allowedMemoryTypeBits) != 0;
1325}
1326
1327static bool CanCreateOptimalSampledImage(uint32_t allowedMemoryTypeBits)
1328{
1329 VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
1330 imgCreateInfo.imageType = VK_IMAGE_TYPE_2D;
1331 imgCreateInfo.extent.width = 256;
1332 imgCreateInfo.extent.height = 256;
1333 imgCreateInfo.extent.depth = 1;
1334 imgCreateInfo.mipLevels = 1;
1335 imgCreateInfo.arrayLayers = 1;
1336 imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
1337 imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
1338 imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
1339 imgCreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
1340 imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
1341
1342 VkImage img = VK_NULL_HANDLE;
1343 VkResult res = vkCreateImage(g_hDevice, &imgCreateInfo, g_Allocs, &img);
1344 assert(res == VK_SUCCESS);
1345
1346 VkMemoryRequirements memReq = {};
1347 vkGetImageMemoryRequirements(g_hDevice, img, &memReq);
1348
1349 vkDestroyImage(g_hDevice, img, g_Allocs);
1350
1351 return (memReq.memoryTypeBits & allowedMemoryTypeBits) != 0;
1352}
1353
1354static void PrintMemoryConclusions()
1355{
1356 wprintf(L"Conclusions:\n");
1357
1358 const VkPhysicalDeviceProperties* props = nullptr;
1359 const VkPhysicalDeviceMemoryProperties* memProps = nullptr;
1360 vmaGetPhysicalDeviceProperties(g_hAllocator, &props);
1361 vmaGetMemoryProperties(g_hAllocator, &memProps);
1362
1363 const uint32_t heapCount = memProps->memoryHeapCount;
1364
1365 uint32_t deviceLocalHeapCount = 0;
1366 uint32_t hostVisibleHeapCount = 0;
1367 uint32_t deviceLocalAndHostVisibleHeapCount = 0;
1368 VkDeviceSize deviceLocalHeapSumSize = 0;
1369 VkDeviceSize hostVisibleHeapSumSize = 0;
1370 VkDeviceSize deviceLocalAndHostVisibleHeapSumSize = 0;
1371
1372 for(uint32_t heapIndex = 0; heapIndex < heapCount; ++heapIndex)
1373 {
1374 const VkMemoryHeap& heap = memProps->memoryHeaps[heapIndex];
1375 const bool isDeviceLocal = (heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0;
1376 bool isHostVisible = false;
1377 for(uint32_t typeIndex = 0; typeIndex < memProps->memoryTypeCount; ++typeIndex)
1378 {
1379 const VkMemoryType& type = memProps->memoryTypes[typeIndex];
1380 if(type.heapIndex == heapIndex && (type.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT))
1381 {
1382 isHostVisible = true;
1383 break;
1384 }
1385 }
1386 if(isDeviceLocal)
1387 {
1388 ++deviceLocalHeapCount;
1389 deviceLocalHeapSumSize += heap.size;
1390 }
1391 if(isHostVisible)
1392 {
1393 ++hostVisibleHeapCount;
1394 hostVisibleHeapSumSize += heap.size;
1395 if(isDeviceLocal)
1396 {
1397 ++deviceLocalAndHostVisibleHeapCount;
1398 deviceLocalAndHostVisibleHeapSumSize += heap.size;
1399 }
1400 }
1401 }
1402
1403 uint32_t hostVisibleNotHostCoherentTypeCount = 0;
1404 uint32_t notDeviceLocalNotHostVisibleTypeCount = 0;
1405 uint32_t amdSpecificTypeCount = 0;
1406 uint32_t lazilyAllocatedTypeCount = 0;
1407 uint32_t allTypeBits = 0;
1408 uint32_t deviceLocalTypeBits = 0;
1409 for(uint32_t typeIndex = 0; typeIndex < memProps->memoryTypeCount; ++typeIndex)
1410 {
1411 const VkMemoryType& type = memProps->memoryTypes[typeIndex];
1412 allTypeBits |= 1u << typeIndex;
1413 if(type.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
1414 {
1415 deviceLocalTypeBits |= 1u << typeIndex;
1416 }
1417 if((type.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) &&
1418 (type.propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
1419 {
1420 ++hostVisibleNotHostCoherentTypeCount;
1421 }
1422 if((type.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0 &&
1423 (type.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
1424 {
1425 ++notDeviceLocalNotHostVisibleTypeCount;
1426 }
1427 if(type.propertyFlags & (VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD))
1428 {
1429 ++amdSpecificTypeCount;
1430 }
1431 if(type.propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT)
1432 {
1433 ++lazilyAllocatedTypeCount;
1434 }
1435 }
1436
1437 assert(deviceLocalHeapCount > 0);
1438 if(deviceLocalHeapCount == heapCount)
1439 wprintf(L"- All heaps are DEVICE_LOCAL.\n");
1440 else
1441 wprintf(L"- %u heaps are DEVICE_LOCAL, total %s.\n", deviceLocalHeapCount, SizeToStr(deviceLocalHeapSumSize).c_str());
1442
1443 assert(hostVisibleHeapCount > 0);
1444 if(hostVisibleHeapCount == heapCount)
1445 wprintf(L"- All heaps are HOST_VISIBLE.\n");
1446 else
1447 wprintf(L"- %u heaps are HOST_VISIBLE, total %s.\n", deviceLocalHeapCount, SizeToStr(hostVisibleHeapSumSize).c_str());
1448
1449 if(deviceLocalHeapCount < heapCount && hostVisibleHeapCount < heapCount)
1450 {
1451 if(deviceLocalAndHostVisibleHeapCount == 0)
1452 wprintf(L"- No heaps are DEVICE_LOCAL and HOST_VISIBLE.\n");
1453 if(deviceLocalAndHostVisibleHeapCount == heapCount)
1454 wprintf(L"- All heaps are DEVICE_LOCAL and HOST_VISIBLE.\n");
1455 else
1456 wprintf(L"- %u heaps are DEVICE_LOCAL and HOST_VISIBLE, total %s.\n", deviceLocalHeapCount, SizeToStr(deviceLocalAndHostVisibleHeapSumSize).c_str());
1457 }
1458
1459 if(hostVisibleNotHostCoherentTypeCount == 0)
1460 wprintf(L"- No types are HOST_VISIBLE but not HOST_COHERENT.\n");
1461 else
1462 wprintf(L"- %u types are HOST_VISIBLE but not HOST_COHERENT.\n", hostVisibleNotHostCoherentTypeCount);
1463
1464 if(notDeviceLocalNotHostVisibleTypeCount == 0)
1465 wprintf(L"- No types are not DEVICE_LOCAL and not HOST_VISIBLE.\n");
1466 else
1467 wprintf(L"- %u types are not DEVICE_LOCAL and not HOST_VISIBLE.\n", notDeviceLocalNotHostVisibleTypeCount);
1468
1469 if(amdSpecificTypeCount == 0)
1470 wprintf(L"- No types are AMD-specific DEVICE_COHERENT or DEVICE_UNCACHED.\n");
1471 else
1472 wprintf(L"- %u types are AMD-specific DEVICE_COHERENT or DEVICE_UNCACHED.\n", amdSpecificTypeCount);
1473
1474 if(lazilyAllocatedTypeCount == 0)
1475 wprintf(L"- No types are LAZILY_ALLOCATED.\n");
1476 else
1477 wprintf(L"- %u types are LAZILY_ALLOCATED.\n", lazilyAllocatedTypeCount);
1478
1479 if(props->vendorID == VENDOR_ID_AMD &&
1480 props->deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU &&
1481 deviceLocalAndHostVisibleHeapSumSize > 256llu * 1024 * 1024)
1482 {
1483 wprintf(L"- AMD Smart Access Memory (SAM) is enabled!\n");
1484 }
1485
1486 if(deviceLocalHeapCount < heapCount)
1487 {
1488 const uint32_t nonDeviceLocalTypeBits = ~deviceLocalTypeBits & allTypeBits;
1489
1490 if(CanCreateVertexBuffer(nonDeviceLocalTypeBits))
1491 wprintf(L"- A buffer with VERTEX_BUFFER usage can be created in some non-DEVICE_LOCAL type.\n");
1492 else
1493 wprintf(L"- A buffer with VERTEX_BUFFER usage cannot be created in some non-DEVICE_LOCAL type.\n");
1494
1495 if(CanCreateOptimalSampledImage(nonDeviceLocalTypeBits))
1496 wprintf(L"- An image with OPTIMAL tiling and SAMPLED usage can be created in some non-DEVICE_LOCAL type.\n");
1497 else
1498 wprintf(L"- An image with OPTIMAL tiling and SAMPLED usage cannot be created in some non-DEVICE_LOCAL type.\n");
1499 }
1500
1501 //wprintf(L"\n");
Adam Sawickie8a85442020-03-06 14:48:30 +01001502}
1503
Adam Sawickie6e498f2017-06-16 17:21:31 +02001504static void InitializeApplication()
1505{
Adam Sawicki1f84f622019-07-02 13:40:01 +02001506 if(USE_CUSTOM_CPU_ALLOCATION_CALLBACKS)
1507 {
1508 g_Allocs = &g_CpuAllocationCallbacks;
1509 }
1510
Adam Sawickie6e498f2017-06-16 17:21:31 +02001511 uint32_t instanceLayerPropCount = 0;
1512 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, nullptr) );
1513 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerPropCount);
1514 if(instanceLayerPropCount > 0)
1515 {
1516 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, instanceLayerProps.data()) );
1517 }
1518
Adam Sawicki8caf0bd2020-07-15 16:56:30 +02001519 if(g_EnableValidationLayer)
Adam Sawickie6e498f2017-06-16 17:21:31 +02001520 {
1521 if(IsLayerSupported(instanceLayerProps.data(), instanceLayerProps.size(), VALIDATION_LAYER_NAME) == false)
1522 {
Adam Sawickie8a85442020-03-06 14:48:30 +01001523 wprintf(L"Layer \"%hs\" not supported.", VALIDATION_LAYER_NAME);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001524 g_EnableValidationLayer = false;
1525 }
1526 }
1527
Adam Sawicki353e3672019-11-02 14:12:05 +01001528 uint32_t availableInstanceExtensionCount = 0;
1529 ERR_GUARD_VULKAN( vkEnumerateInstanceExtensionProperties(nullptr, &availableInstanceExtensionCount, nullptr) );
1530 std::vector<VkExtensionProperties> availableInstanceExtensions(availableInstanceExtensionCount);
1531 if(availableInstanceExtensionCount > 0)
1532 {
1533 ERR_GUARD_VULKAN( vkEnumerateInstanceExtensionProperties(nullptr, &availableInstanceExtensionCount, availableInstanceExtensions.data()) );
1534 }
1535
1536 std::vector<const char*> enabledInstanceExtensions;
1537 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
1538 enabledInstanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001539
1540 std::vector<const char*> instanceLayers;
Adam Sawicki8caf0bd2020-07-15 16:56:30 +02001541 if(g_EnableValidationLayer)
Adam Sawickie6e498f2017-06-16 17:21:31 +02001542 {
1543 instanceLayers.push_back(VALIDATION_LAYER_NAME);
Adam Sawicki353e3672019-11-02 14:12:05 +01001544 }
1545
1546 for(const auto& extensionProperties : availableInstanceExtensions)
1547 {
1548 if(strcmp(extensionProperties.extensionName, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == 0)
1549 {
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001550 if(GetVulkanApiVersion() == VK_API_VERSION_1_0)
1551 {
1552 enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
1553 VK_KHR_get_physical_device_properties2_enabled = true;
1554 }
Adam Sawicki353e3672019-11-02 14:12:05 +01001555 }
Adam Sawicki8caf0bd2020-07-15 16:56:30 +02001556 else if(strcmp(extensionProperties.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0)
1557 {
1558 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
1559 VK_EXT_debug_utils_enabled = true;
1560 }
Adam Sawickie6e498f2017-06-16 17:21:31 +02001561 }
1562
1563 VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
1564 appInfo.pApplicationName = APP_TITLE_A;
1565 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
1566 appInfo.pEngineName = "Adam Sawicki Engine";
1567 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
Adam Sawicki50882502020-02-07 16:51:31 +01001568 appInfo.apiVersion = GetVulkanApiVersion();
Adam Sawickie6e498f2017-06-16 17:21:31 +02001569
1570 VkInstanceCreateInfo instInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
1571 instInfo.pApplicationInfo = &appInfo;
Adam Sawicki353e3672019-11-02 14:12:05 +01001572 instInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
1573 instInfo.ppEnabledExtensionNames = enabledInstanceExtensions.data();
Adam Sawickie6e498f2017-06-16 17:21:31 +02001574 instInfo.enabledLayerCount = static_cast<uint32_t>(instanceLayers.size());
1575 instInfo.ppEnabledLayerNames = instanceLayers.data();
1576
Adam Sawickiafd50562021-02-26 11:59:58 +01001577 wprintf(L"Vulkan API version used: ");
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001578 switch(appInfo.apiVersion)
1579 {
Adam Sawickie8a85442020-03-06 14:48:30 +01001580 case VK_API_VERSION_1_0: wprintf(L"1.0\n"); break;
1581 case VK_API_VERSION_1_1: wprintf(L"1.1\n"); break;
1582 case VK_API_VERSION_1_2: wprintf(L"1.2\n"); break;
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001583 default: assert(0);
1584 }
1585
Adam Sawicki1f84f622019-07-02 13:40:01 +02001586 ERR_GUARD_VULKAN( vkCreateInstance(&instInfo, g_Allocs, &g_hVulkanInstance) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001587
Adam Sawicki8caf0bd2020-07-15 16:56:30 +02001588 if(VK_EXT_debug_utils_enabled)
1589 {
1590 RegisterDebugCallbacks();
1591 }
1592
Adam Sawickie6e498f2017-06-16 17:21:31 +02001593 // Create VkSurfaceKHR.
1594 VkWin32SurfaceCreateInfoKHR surfaceInfo = { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR };
1595 surfaceInfo.hinstance = g_hAppInstance;
1596 surfaceInfo.hwnd = g_hWnd;
Adam Sawicki1f84f622019-07-02 13:40:01 +02001597 VkResult result = vkCreateWin32SurfaceKHR(g_hVulkanInstance, &surfaceInfo, g_Allocs, &g_hSurface);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001598 assert(result == VK_SUCCESS);
1599
Adam Sawickie6e498f2017-06-16 17:21:31 +02001600 // Find physical device
1601
1602 uint32_t deviceCount = 0;
1603 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, nullptr) );
1604 assert(deviceCount > 0);
1605
1606 std::vector<VkPhysicalDevice> physicalDevices(deviceCount);
1607 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, physicalDevices.data()) );
1608
1609 g_hPhysicalDevice = physicalDevices[0];
1610
Adam Sawickie73e9882020-03-20 18:05:42 +01001611 // Query for device extensions
Adam Sawicki50882502020-02-07 16:51:31 +01001612
1613 uint32_t physicalDeviceExtensionPropertyCount = 0;
1614 ERR_GUARD_VULKAN( vkEnumerateDeviceExtensionProperties(g_hPhysicalDevice, nullptr, &physicalDeviceExtensionPropertyCount, nullptr) );
1615 std::vector<VkExtensionProperties> physicalDeviceExtensionProperties{physicalDeviceExtensionPropertyCount};
1616 if(physicalDeviceExtensionPropertyCount)
1617 {
1618 ERR_GUARD_VULKAN( vkEnumerateDeviceExtensionProperties(
1619 g_hPhysicalDevice,
1620 nullptr,
1621 &physicalDeviceExtensionPropertyCount,
1622 physicalDeviceExtensionProperties.data()) );
1623 }
1624
1625 for(uint32_t i = 0; i < physicalDeviceExtensionPropertyCount; ++i)
1626 {
1627 if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME) == 0)
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001628 {
1629 if(GetVulkanApiVersion() == VK_API_VERSION_1_0)
1630 {
1631 VK_KHR_get_memory_requirements2_enabled = true;
1632 }
1633 }
Adam Sawicki50882502020-02-07 16:51:31 +01001634 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME) == 0)
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001635 {
1636 if(GetVulkanApiVersion() == VK_API_VERSION_1_0)
1637 {
1638 VK_KHR_dedicated_allocation_enabled = true;
1639 }
1640 }
Adam Sawicki50882502020-02-07 16:51:31 +01001641 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME) == 0)
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001642 {
1643 if(GetVulkanApiVersion() == VK_API_VERSION_1_0)
1644 {
1645 VK_KHR_bind_memory2_enabled = true;
1646 }
1647 }
Adam Sawicki50882502020-02-07 16:51:31 +01001648 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME) == 0)
1649 VK_EXT_memory_budget_enabled = true;
1650 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_AMD_DEVICE_COHERENT_MEMORY_EXTENSION_NAME) == 0)
1651 VK_AMD_device_coherent_memory_enabled = true;
Adam Sawickie73e9882020-03-20 18:05:42 +01001652 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME) == 0)
1653 {
1654 if(GetVulkanApiVersion() < VK_API_VERSION_1_2)
1655 {
1656 VK_KHR_buffer_device_address_enabled = true;
1657 }
1658 }
1659 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_EXT_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME) == 0)
1660 {
1661 if(GetVulkanApiVersion() < VK_API_VERSION_1_2)
1662 {
1663 VK_EXT_buffer_device_address_enabled = true;
1664 }
1665 }
Adam Sawickif2012052021-01-11 18:04:42 +01001666 else if(strcmp(physicalDeviceExtensionProperties[i].extensionName, VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME) == 0)
1667 VK_EXT_memory_priority_enabled = true;
Adam Sawicki50882502020-02-07 16:51:31 +01001668 }
1669
Adam Sawickie73e9882020-03-20 18:05:42 +01001670 if(VK_EXT_buffer_device_address_enabled && VK_KHR_buffer_device_address_enabled)
1671 VK_EXT_buffer_device_address_enabled = false;
1672
Adam Sawickie6e498f2017-06-16 17:21:31 +02001673 // Query for features
1674
Adam Sawickiafd50562021-02-26 11:59:58 +01001675#if VMA_VULKAN_VERSION >= 1001000
1676 VkPhysicalDeviceProperties2 physicalDeviceProperties2 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 };
1677
1678#if VMA_VULKAN_VERSION >= 1002000
1679 // Vulkan spec says structure VkPhysicalDeviceVulkan11Properties is "Provided by VK_VERSION_1_2" - is this a mistake? Assuming not...
1680 VkPhysicalDeviceVulkan11Properties physicalDeviceVulkan11Properties = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES };
1681 VkPhysicalDeviceVulkan12Properties physicalDeviceVulkan12Properties = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES };
1682 PnextChainPushFront(&physicalDeviceProperties2, &physicalDeviceVulkan11Properties);
1683 PnextChainPushFront(&physicalDeviceProperties2, &physicalDeviceVulkan12Properties);
1684#endif
1685
1686 vkGetPhysicalDeviceProperties2(g_hPhysicalDevice, &physicalDeviceProperties2);
1687
1688 PrintPhysicalDeviceProperties(physicalDeviceProperties2.properties);
1689#if VMA_VULKAN_VERSION >= 1002000
1690 PrintPhysicalDeviceVulkan11Properties(physicalDeviceVulkan11Properties);
1691 PrintPhysicalDeviceVulkan12Properties(physicalDeviceVulkan12Properties);
1692#endif
1693
1694#else // #if VMA_VULKAN_VERSION >= 1001000
Adam Sawickie6e498f2017-06-16 17:21:31 +02001695 VkPhysicalDeviceProperties physicalDeviceProperties = {};
1696 vkGetPhysicalDeviceProperties(g_hPhysicalDevice, &physicalDeviceProperties);
Adam Sawickie8a85442020-03-06 14:48:30 +01001697 PrintPhysicalDeviceProperties(physicalDeviceProperties);
1698
Adam Sawickiafd50562021-02-26 11:59:58 +01001699#endif // #if VMA_VULKAN_VERSION >= 1001000
1700
1701 wprintf(L"\n");
1702
Adam Sawicki50882502020-02-07 16:51:31 +01001703 VkPhysicalDeviceFeatures2 physicalDeviceFeatures = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 };
Adam Sawickie73e9882020-03-20 18:05:42 +01001704
Adam Sawicki50882502020-02-07 16:51:31 +01001705 VkPhysicalDeviceCoherentMemoryFeaturesAMD physicalDeviceCoherentMemoryFeatures = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COHERENT_MEMORY_FEATURES_AMD };
1706 if(VK_AMD_device_coherent_memory_enabled)
1707 {
Adam Sawickie73e9882020-03-20 18:05:42 +01001708 PnextChainPushFront(&physicalDeviceFeatures, &physicalDeviceCoherentMemoryFeatures);
Adam Sawicki50882502020-02-07 16:51:31 +01001709 }
Adam Sawickie73e9882020-03-20 18:05:42 +01001710
1711 VkPhysicalDeviceBufferDeviceAddressFeaturesEXT physicalDeviceBufferDeviceAddressFeatures = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT };
1712 if(VK_KHR_buffer_device_address_enabled || VK_EXT_buffer_device_address_enabled || GetVulkanApiVersion() >= VK_API_VERSION_1_2)
1713 {
1714 PnextChainPushFront(&physicalDeviceFeatures, &physicalDeviceBufferDeviceAddressFeatures);
1715 }
1716
Adam Sawickif2012052021-01-11 18:04:42 +01001717 VkPhysicalDeviceMemoryPriorityFeaturesEXT physicalDeviceMemoryPriorityFeatures = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT };
1718 if(VK_EXT_memory_priority_enabled)
1719 {
1720 PnextChainPushFront(&physicalDeviceFeatures, &physicalDeviceMemoryPriorityFeatures);
1721 }
1722
Adam Sawicki50882502020-02-07 16:51:31 +01001723 vkGetPhysicalDeviceFeatures2(g_hPhysicalDevice, &physicalDeviceFeatures);
Adam Sawicki51fa9662018-10-03 13:44:29 +02001724
Adam Sawicki50882502020-02-07 16:51:31 +01001725 g_SparseBindingEnabled = physicalDeviceFeatures.features.sparseBinding != 0;
1726
1727 // The extension is supported as fake with no real support for this feature? Don't use it.
1728 if(VK_AMD_device_coherent_memory_enabled && !physicalDeviceCoherentMemoryFeatures.deviceCoherentMemory)
1729 VK_AMD_device_coherent_memory_enabled = false;
Adam Sawickie73e9882020-03-20 18:05:42 +01001730 if(VK_KHR_buffer_device_address_enabled || VK_EXT_buffer_device_address_enabled || GetVulkanApiVersion() >= VK_API_VERSION_1_2)
1731 g_BufferDeviceAddressEnabled = physicalDeviceBufferDeviceAddressFeatures.bufferDeviceAddress != VK_FALSE;
Adam Sawickif2012052021-01-11 18:04:42 +01001732 if(VK_EXT_memory_priority_enabled && !physicalDeviceMemoryPriorityFeatures.memoryPriority)
1733 VK_EXT_memory_priority_enabled = false;
Adam Sawickie6e498f2017-06-16 17:21:31 +02001734
1735 // Find queue family index
1736
1737 uint32_t queueFamilyCount = 0;
1738 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, nullptr);
1739 assert(queueFamilyCount > 0);
1740 std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1741 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, queueFamilies.data());
1742 for(uint32_t i = 0;
1743 (i < queueFamilyCount) &&
Adam Sawicki51fa9662018-10-03 13:44:29 +02001744 (g_GraphicsQueueFamilyIndex == UINT_MAX ||
1745 g_PresentQueueFamilyIndex == UINT_MAX ||
1746 (g_SparseBindingEnabled && g_SparseBindingQueueFamilyIndex == UINT_MAX));
Adam Sawickie6e498f2017-06-16 17:21:31 +02001747 ++i)
1748 {
1749 if(queueFamilies[i].queueCount > 0)
1750 {
Adam Sawickida6c1942018-12-05 17:34:34 +01001751 const uint32_t flagsForGraphicsQueue = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Adam Sawickie6e498f2017-06-16 17:21:31 +02001752 if((g_GraphicsQueueFamilyIndex != 0) &&
Adam Sawickida6c1942018-12-05 17:34:34 +01001753 ((queueFamilies[i].queueFlags & flagsForGraphicsQueue) == flagsForGraphicsQueue))
Adam Sawickie6e498f2017-06-16 17:21:31 +02001754 {
1755 g_GraphicsQueueFamilyIndex = i;
1756 }
1757
1758 VkBool32 surfaceSupported = 0;
1759 VkResult res = vkGetPhysicalDeviceSurfaceSupportKHR(g_hPhysicalDevice, i, g_hSurface, &surfaceSupported);
1760 if((res >= 0) && (surfaceSupported == VK_TRUE))
1761 {
1762 g_PresentQueueFamilyIndex = i;
1763 }
Adam Sawicki51fa9662018-10-03 13:44:29 +02001764
1765 if(g_SparseBindingEnabled &&
1766 g_SparseBindingQueueFamilyIndex == UINT32_MAX &&
1767 (queueFamilies[i].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) != 0)
1768 {
1769 g_SparseBindingQueueFamilyIndex = i;
1770 }
Adam Sawickie6e498f2017-06-16 17:21:31 +02001771 }
1772 }
1773 assert(g_GraphicsQueueFamilyIndex != UINT_MAX);
1774
Adam Sawicki51fa9662018-10-03 13:44:29 +02001775 g_SparseBindingEnabled = g_SparseBindingEnabled && g_SparseBindingQueueFamilyIndex != UINT32_MAX;
1776
Adam Sawickie6e498f2017-06-16 17:21:31 +02001777 // Create logical device
1778
1779 const float queuePriority = 1.f;
1780
Adam Sawicki51fa9662018-10-03 13:44:29 +02001781 VkDeviceQueueCreateInfo queueCreateInfo[3] = {};
1782 uint32_t queueCount = 1;
1783 queueCreateInfo[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
1784 queueCreateInfo[0].queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1785 queueCreateInfo[0].queueCount = 1;
1786 queueCreateInfo[0].pQueuePriorities = &queuePriority;
1787
1788 if(g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex)
1789 {
1790
1791 queueCreateInfo[queueCount].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
1792 queueCreateInfo[queueCount].queueFamilyIndex = g_PresentQueueFamilyIndex;
1793 queueCreateInfo[queueCount].queueCount = 1;
1794 queueCreateInfo[queueCount].pQueuePriorities = &queuePriority;
1795 ++queueCount;
1796 }
1797
1798 if(g_SparseBindingEnabled &&
1799 g_SparseBindingQueueFamilyIndex != g_GraphicsQueueFamilyIndex &&
1800 g_SparseBindingQueueFamilyIndex != g_PresentQueueFamilyIndex)
1801 {
1802
1803 queueCreateInfo[queueCount].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
1804 queueCreateInfo[queueCount].queueFamilyIndex = g_SparseBindingQueueFamilyIndex;
1805 queueCreateInfo[queueCount].queueCount = 1;
1806 queueCreateInfo[queueCount].pQueuePriorities = &queuePriority;
1807 ++queueCount;
1808 }
Adam Sawickie6e498f2017-06-16 17:21:31 +02001809
Adam Sawickie6e498f2017-06-16 17:21:31 +02001810 std::vector<const char*> enabledDeviceExtensions;
1811 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
Adam Sawicki50882502020-02-07 16:51:31 +01001812 if(VK_KHR_get_memory_requirements2_enabled)
1813 enabledDeviceExtensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
1814 if(VK_KHR_dedicated_allocation_enabled)
1815 enabledDeviceExtensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
1816 if(VK_KHR_bind_memory2_enabled)
1817 enabledDeviceExtensions.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
1818 if(VK_EXT_memory_budget_enabled)
1819 enabledDeviceExtensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
1820 if(VK_AMD_device_coherent_memory_enabled)
1821 enabledDeviceExtensions.push_back(VK_AMD_DEVICE_COHERENT_MEMORY_EXTENSION_NAME);
Adam Sawickie73e9882020-03-20 18:05:42 +01001822 if(VK_KHR_buffer_device_address_enabled)
1823 enabledDeviceExtensions.push_back(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
1824 if(VK_EXT_buffer_device_address_enabled)
1825 enabledDeviceExtensions.push_back(VK_EXT_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
Adam Sawickif2012052021-01-11 18:04:42 +01001826 if(VK_EXT_memory_priority_enabled)
1827 enabledDeviceExtensions.push_back(VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME);
Adam Sawicki50882502020-02-07 16:51:31 +01001828
1829 VkPhysicalDeviceFeatures2 deviceFeatures = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 };
1830 deviceFeatures.features.samplerAnisotropy = VK_TRUE;
1831 deviceFeatures.features.sparseBinding = g_SparseBindingEnabled ? VK_TRUE : VK_FALSE;
1832
1833 if(VK_AMD_device_coherent_memory_enabled)
Adam Sawicki6cc5e852018-03-13 16:37:54 +01001834 {
Adam Sawicki50882502020-02-07 16:51:31 +01001835 physicalDeviceCoherentMemoryFeatures.deviceCoherentMemory = VK_TRUE;
Adam Sawickie73e9882020-03-20 18:05:42 +01001836 PnextChainPushBack(&deviceFeatures, &physicalDeviceCoherentMemoryFeatures);
1837 }
1838 if(g_BufferDeviceAddressEnabled)
1839 {
1840 physicalDeviceBufferDeviceAddressFeatures = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT };
1841 physicalDeviceBufferDeviceAddressFeatures.bufferDeviceAddress = VK_TRUE;
1842 PnextChainPushBack(&deviceFeatures, &physicalDeviceBufferDeviceAddressFeatures);
Adam Sawicki6cc5e852018-03-13 16:37:54 +01001843 }
Adam Sawickif2012052021-01-11 18:04:42 +01001844 if(VK_EXT_memory_priority_enabled)
1845 {
1846 PnextChainPushBack(&deviceFeatures, &physicalDeviceMemoryPriorityFeatures);
1847 }
Adam Sawickie6e498f2017-06-16 17:21:31 +02001848
1849 VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
Adam Sawicki50882502020-02-07 16:51:31 +01001850 deviceCreateInfo.pNext = &deviceFeatures;
Adam Sawickie6e498f2017-06-16 17:21:31 +02001851 deviceCreateInfo.enabledLayerCount = 0;
1852 deviceCreateInfo.ppEnabledLayerNames = nullptr;
1853 deviceCreateInfo.enabledExtensionCount = (uint32_t)enabledDeviceExtensions.size();
Adam Sawicki6cc5e852018-03-13 16:37:54 +01001854 deviceCreateInfo.ppEnabledExtensionNames = !enabledDeviceExtensions.empty() ? enabledDeviceExtensions.data() : nullptr;
Adam Sawicki51fa9662018-10-03 13:44:29 +02001855 deviceCreateInfo.queueCreateInfoCount = queueCount;
1856 deviceCreateInfo.pQueueCreateInfos = queueCreateInfo;
Adam Sawickie6e498f2017-06-16 17:21:31 +02001857
Adam Sawicki1f84f622019-07-02 13:40:01 +02001858 ERR_GUARD_VULKAN( vkCreateDevice(g_hPhysicalDevice, &deviceCreateInfo, g_Allocs, &g_hDevice) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001859
Adam Sawickie73e9882020-03-20 18:05:42 +01001860 // Fetch pointers to extension functions
1861 if(g_BufferDeviceAddressEnabled)
1862 {
1863 if(GetVulkanApiVersion() >= VK_API_VERSION_1_2)
1864 {
1865 g_vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)vkGetDeviceProcAddr(g_hDevice, "vkGetBufferDeviceAddress");
1866 //assert(g_vkGetBufferDeviceAddressEXT != nullptr);
1867 /*
1868 For some reason this doesn't work, the pointer is NULL :( None of the below methods help.
1869
1870 Validation layers also report following error:
1871 [ VUID-VkMemoryAllocateInfo-flags-03331 ] Object: VK_NULL_HANDLE (Type = 0) | If VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR is set, bufferDeviceAddress must be enabled. The Vulkan spec states: If VkMemoryAllocateFlagsInfo::flags includes VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, the bufferDeviceAddress feature must be enabled (https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#VUID-VkMemoryAllocateInfo-flags-03331)
1872 Despite I'm posting VkPhysicalDeviceBufferDeviceAddressFeaturesEXT::bufferDeviceAddress = VK_TRUE in VkDeviceCreateInfo::pNext chain.
1873
1874 if(g_vkGetBufferDeviceAddressEXT == nullptr)
1875 {
1876 g_vkGetBufferDeviceAddressEXT = &vkGetBufferDeviceAddress; // Doesn't run, cannot find entry point...
1877 }
1878
1879 if(g_vkGetBufferDeviceAddressEXT == nullptr)
1880 {
1881 g_vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)vkGetInstanceProcAddr(g_hVulkanInstance, "vkGetBufferDeviceAddress");
1882 }
1883 if(g_vkGetBufferDeviceAddressEXT == nullptr)
1884 {
1885 g_vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)vkGetDeviceProcAddr(g_hDevice, "vkGetBufferDeviceAddressKHR");
1886 }
1887 if(g_vkGetBufferDeviceAddressEXT == nullptr)
1888 {
1889 g_vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)vkGetDeviceProcAddr(g_hDevice, "vkGetBufferDeviceAddressEXT");
1890 }
1891 */
1892 }
1893 else if(VK_KHR_buffer_device_address_enabled)
1894 {
1895 g_vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)vkGetDeviceProcAddr(g_hDevice, "vkGetBufferDeviceAddressKHR");
1896 assert(g_vkGetBufferDeviceAddressEXT != nullptr);
1897 }
1898 else if(VK_EXT_buffer_device_address_enabled)
1899 {
1900 g_vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)vkGetDeviceProcAddr(g_hDevice, "vkGetBufferDeviceAddressEXT");
1901 assert(g_vkGetBufferDeviceAddressEXT != nullptr);
1902 }
1903 }
1904
Adam Sawickie6e498f2017-06-16 17:21:31 +02001905 // Create memory allocator
1906
1907 VmaAllocatorCreateInfo allocatorInfo = {};
Adam Sawicki50882502020-02-07 16:51:31 +01001908 SetAllocatorCreateInfo(allocatorInfo);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001909 ERR_GUARD_VULKAN( vmaCreateAllocator(&allocatorInfo, &g_hAllocator) );
1910
Adam Sawickiafd50562021-02-26 11:59:58 +01001911 PrintMemoryTypes();
1912 wprintf(L"\n");
1913 PrintMemoryConclusions();
1914 wprintf(L"\n");
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001915 PrintEnabledFeatures();
Adam Sawickiafd50562021-02-26 11:59:58 +01001916 wprintf(L"\n");
Adam Sawickia4f2eb92020-03-06 14:39:42 +01001917
Adam Sawicki51fa9662018-10-03 13:44:29 +02001918 // Retrieve queues (don't need to be destroyed).
Adam Sawickie6e498f2017-06-16 17:21:31 +02001919
1920 vkGetDeviceQueue(g_hDevice, g_GraphicsQueueFamilyIndex, 0, &g_hGraphicsQueue);
1921 vkGetDeviceQueue(g_hDevice, g_PresentQueueFamilyIndex, 0, &g_hPresentQueue);
1922 assert(g_hGraphicsQueue);
1923 assert(g_hPresentQueue);
1924
Adam Sawicki51fa9662018-10-03 13:44:29 +02001925 if(g_SparseBindingEnabled)
1926 {
1927 vkGetDeviceQueue(g_hDevice, g_SparseBindingQueueFamilyIndex, 0, &g_hSparseBindingQueue);
1928 assert(g_hSparseBindingQueue);
1929 }
1930
Adam Sawickie6e498f2017-06-16 17:21:31 +02001931 // Create command pool
1932
1933 VkCommandPoolCreateInfo commandPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
1934 commandPoolInfo.queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1935 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
Adam Sawicki1f84f622019-07-02 13:40:01 +02001936 ERR_GUARD_VULKAN( vkCreateCommandPool(g_hDevice, &commandPoolInfo, g_Allocs, &g_hCommandPool) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001937
1938 VkCommandBufferAllocateInfo commandBufferInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
1939 commandBufferInfo.commandPool = g_hCommandPool;
1940 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1941 commandBufferInfo.commandBufferCount = COMMAND_BUFFER_COUNT;
1942 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, g_MainCommandBuffers) );
1943
1944 VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
1945 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1946 for(size_t i = 0; i < COMMAND_BUFFER_COUNT; ++i)
1947 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02001948 ERR_GUARD_VULKAN( vkCreateFence(g_hDevice, &fenceInfo, g_Allocs, &g_MainCommandBufferExecutedFances[i]) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001949 }
1950
Adam Sawicki1f84f622019-07-02 13:40:01 +02001951 ERR_GUARD_VULKAN( vkCreateFence(g_hDevice, &fenceInfo, g_Allocs, &g_ImmediateFence) );
Adam Sawicki51fa9662018-10-03 13:44:29 +02001952
Adam Sawickie6e498f2017-06-16 17:21:31 +02001953 commandBufferInfo.commandBufferCount = 1;
1954 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, &g_hTemporaryCommandBuffer) );
1955
1956 // Create texture sampler
1957
1958 VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
1959 samplerInfo.magFilter = VK_FILTER_LINEAR;
1960 samplerInfo.minFilter = VK_FILTER_LINEAR;
1961 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1962 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1963 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1964 samplerInfo.anisotropyEnable = VK_TRUE;
1965 samplerInfo.maxAnisotropy = 16;
1966 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
1967 samplerInfo.unnormalizedCoordinates = VK_FALSE;
1968 samplerInfo.compareEnable = VK_FALSE;
1969 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
1970 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1971 samplerInfo.mipLodBias = 0.f;
1972 samplerInfo.minLod = 0.f;
1973 samplerInfo.maxLod = FLT_MAX;
Adam Sawicki1f84f622019-07-02 13:40:01 +02001974 ERR_GUARD_VULKAN( vkCreateSampler(g_hDevice, &samplerInfo, g_Allocs, &g_hSampler) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001975
1976 CreateTexture(128, 128);
1977 CreateMesh();
1978
1979 VkDescriptorSetLayoutBinding samplerLayoutBinding = {};
1980 samplerLayoutBinding.binding = 1;
1981 samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1982 samplerLayoutBinding.descriptorCount = 1;
1983 samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1984
1985 VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
1986 descriptorSetLayoutInfo.bindingCount = 1;
1987 descriptorSetLayoutInfo.pBindings = &samplerLayoutBinding;
Adam Sawicki1f84f622019-07-02 13:40:01 +02001988 ERR_GUARD_VULKAN( vkCreateDescriptorSetLayout(g_hDevice, &descriptorSetLayoutInfo, g_Allocs, &g_hDescriptorSetLayout) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02001989
1990 // Create descriptor pool
1991
1992 VkDescriptorPoolSize descriptorPoolSizes[2];
1993 ZeroMemory(descriptorPoolSizes, sizeof(descriptorPoolSizes));
1994 descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
1995 descriptorPoolSizes[0].descriptorCount = 1;
1996 descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1997 descriptorPoolSizes[1].descriptorCount = 1;
1998
1999 VkDescriptorPoolCreateInfo descriptorPoolInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
2000 descriptorPoolInfo.poolSizeCount = (uint32_t)_countof(descriptorPoolSizes);
2001 descriptorPoolInfo.pPoolSizes = descriptorPoolSizes;
2002 descriptorPoolInfo.maxSets = 1;
Adam Sawicki1f84f622019-07-02 13:40:01 +02002003 ERR_GUARD_VULKAN( vkCreateDescriptorPool(g_hDevice, &descriptorPoolInfo, g_Allocs, &g_hDescriptorPool) );
Adam Sawickie6e498f2017-06-16 17:21:31 +02002004
2005 // Create descriptor set layout
2006
2007 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
2008 VkDescriptorSetAllocateInfo descriptorSetInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
2009 descriptorSetInfo.descriptorPool = g_hDescriptorPool;
2010 descriptorSetInfo.descriptorSetCount = 1;
2011 descriptorSetInfo.pSetLayouts = descriptorSetLayouts;
2012 ERR_GUARD_VULKAN( vkAllocateDescriptorSets(g_hDevice, &descriptorSetInfo, &g_hDescriptorSet) );
2013
2014 VkDescriptorImageInfo descriptorImageInfo = {};
2015 descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
2016 descriptorImageInfo.imageView = g_hTextureImageView;
2017 descriptorImageInfo.sampler = g_hSampler;
2018
2019 VkWriteDescriptorSet writeDescriptorSet = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
2020 writeDescriptorSet.dstSet = g_hDescriptorSet;
2021 writeDescriptorSet.dstBinding = 1;
2022 writeDescriptorSet.dstArrayElement = 0;
2023 writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
2024 writeDescriptorSet.descriptorCount = 1;
2025 writeDescriptorSet.pImageInfo = &descriptorImageInfo;
2026
2027 vkUpdateDescriptorSets(g_hDevice, 1, &writeDescriptorSet, 0, nullptr);
2028
2029 CreateSwapchain();
2030}
2031
2032static void FinalizeApplication()
2033{
2034 vkDeviceWaitIdle(g_hDevice);
2035
2036 DestroySwapchain(true);
2037
2038 if(g_hDescriptorPool != VK_NULL_HANDLE)
2039 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002040 vkDestroyDescriptorPool(g_hDevice, g_hDescriptorPool, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002041 g_hDescriptorPool = VK_NULL_HANDLE;
2042 }
2043
2044 if(g_hDescriptorSetLayout != VK_NULL_HANDLE)
2045 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002046 vkDestroyDescriptorSetLayout(g_hDevice, g_hDescriptorSetLayout, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002047 g_hDescriptorSetLayout = VK_NULL_HANDLE;
2048 }
2049
2050 if(g_hTextureImageView != VK_NULL_HANDLE)
2051 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002052 vkDestroyImageView(g_hDevice, g_hTextureImageView, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002053 g_hTextureImageView = VK_NULL_HANDLE;
2054 }
2055 if(g_hTextureImage != VK_NULL_HANDLE)
2056 {
Adam Sawicki819860e2017-07-04 14:30:38 +02002057 vmaDestroyImage(g_hAllocator, g_hTextureImage, g_hTextureImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002058 g_hTextureImage = VK_NULL_HANDLE;
2059 }
2060
2061 if(g_hIndexBuffer != VK_NULL_HANDLE)
2062 {
Adam Sawicki819860e2017-07-04 14:30:38 +02002063 vmaDestroyBuffer(g_hAllocator, g_hIndexBuffer, g_hIndexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002064 g_hIndexBuffer = VK_NULL_HANDLE;
2065 }
2066 if(g_hVertexBuffer != VK_NULL_HANDLE)
2067 {
Adam Sawicki819860e2017-07-04 14:30:38 +02002068 vmaDestroyBuffer(g_hAllocator, g_hVertexBuffer, g_hVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002069 g_hVertexBuffer = VK_NULL_HANDLE;
2070 }
2071
2072 if(g_hSampler != VK_NULL_HANDLE)
2073 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002074 vkDestroySampler(g_hDevice, g_hSampler, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002075 g_hSampler = VK_NULL_HANDLE;
2076 }
2077
Adam Sawicki51fa9662018-10-03 13:44:29 +02002078 if(g_ImmediateFence)
2079 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002080 vkDestroyFence(g_hDevice, g_ImmediateFence, g_Allocs);
Adam Sawicki51fa9662018-10-03 13:44:29 +02002081 g_ImmediateFence = VK_NULL_HANDLE;
2082 }
2083
Adam Sawickie6e498f2017-06-16 17:21:31 +02002084 for(size_t i = COMMAND_BUFFER_COUNT; i--; )
2085 {
2086 if(g_MainCommandBufferExecutedFances[i] != VK_NULL_HANDLE)
2087 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002088 vkDestroyFence(g_hDevice, g_MainCommandBufferExecutedFances[i], g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002089 g_MainCommandBufferExecutedFances[i] = VK_NULL_HANDLE;
2090 }
2091 }
2092 if(g_MainCommandBuffers[0] != VK_NULL_HANDLE)
2093 {
2094 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, COMMAND_BUFFER_COUNT, g_MainCommandBuffers);
2095 ZeroMemory(g_MainCommandBuffers, sizeof(g_MainCommandBuffers));
2096 }
2097 if(g_hTemporaryCommandBuffer != VK_NULL_HANDLE)
2098 {
2099 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, 1, &g_hTemporaryCommandBuffer);
2100 g_hTemporaryCommandBuffer = VK_NULL_HANDLE;
2101 }
2102
2103 if(g_hCommandPool != VK_NULL_HANDLE)
2104 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002105 vkDestroyCommandPool(g_hDevice, g_hCommandPool, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002106 g_hCommandPool = VK_NULL_HANDLE;
2107 }
2108
2109 if(g_hAllocator != VK_NULL_HANDLE)
2110 {
2111 vmaDestroyAllocator(g_hAllocator);
2112 g_hAllocator = nullptr;
2113 }
2114
2115 if(g_hDevice != VK_NULL_HANDLE)
2116 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002117 vkDestroyDevice(g_hDevice, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002118 g_hDevice = nullptr;
2119 }
2120
Adam Sawickie6e498f2017-06-16 17:21:31 +02002121 if(g_hSurface != VK_NULL_HANDLE)
2122 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002123 vkDestroySurfaceKHR(g_hVulkanInstance, g_hSurface, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002124 g_hSurface = VK_NULL_HANDLE;
2125 }
2126
Adam Sawickid594faa2020-07-15 17:12:28 +02002127 UnregisterDebugCallbacks();
Adam Sawicki8caf0bd2020-07-15 16:56:30 +02002128
Adam Sawickie6e498f2017-06-16 17:21:31 +02002129 if(g_hVulkanInstance != VK_NULL_HANDLE)
2130 {
Adam Sawicki1f84f622019-07-02 13:40:01 +02002131 vkDestroyInstance(g_hVulkanInstance, g_Allocs);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002132 g_hVulkanInstance = VK_NULL_HANDLE;
2133 }
2134}
2135
2136static void PrintAllocatorStats()
2137{
2138#if VMA_STATS_STRING_ENABLED
2139 char* statsString = nullptr;
2140 vmaBuildStatsString(g_hAllocator, &statsString, true);
2141 printf("%s\n", statsString);
2142 vmaFreeStatsString(g_hAllocator, statsString);
2143#endif
2144}
2145
2146static void RecreateSwapChain()
2147{
2148 vkDeviceWaitIdle(g_hDevice);
2149 DestroySwapchain(false);
2150 CreateSwapchain();
2151}
2152
2153static void DrawFrame()
2154{
2155 // Begin main command buffer
2156 size_t cmdBufIndex = (g_NextCommandBufferIndex++) % COMMAND_BUFFER_COUNT;
2157 VkCommandBuffer hCommandBuffer = g_MainCommandBuffers[cmdBufIndex];
2158 VkFence hCommandBufferExecutedFence = g_MainCommandBufferExecutedFances[cmdBufIndex];
2159
2160 ERR_GUARD_VULKAN( vkWaitForFences(g_hDevice, 1, &hCommandBufferExecutedFence, VK_TRUE, UINT64_MAX) );
2161 ERR_GUARD_VULKAN( vkResetFences(g_hDevice, 1, &hCommandBufferExecutedFence) );
2162
2163 VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
2164 commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
2165 ERR_GUARD_VULKAN( vkBeginCommandBuffer(hCommandBuffer, &commandBufferBeginInfo) );
2166
2167 // Acquire swapchain image
2168 uint32_t imageIndex = 0;
2169 VkResult res = vkAcquireNextImageKHR(g_hDevice, g_hSwapchain, UINT64_MAX, g_hImageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
2170 if(res == VK_ERROR_OUT_OF_DATE_KHR)
2171 {
2172 RecreateSwapChain();
2173 return;
2174 }
2175 else if(res < 0)
2176 {
2177 ERR_GUARD_VULKAN(res);
2178 }
2179
2180 // Record geometry pass
2181
2182 VkClearValue clearValues[2];
2183 ZeroMemory(clearValues, sizeof(clearValues));
2184 clearValues[0].color.float32[0] = 0.25f;
2185 clearValues[0].color.float32[1] = 0.25f;
2186 clearValues[0].color.float32[2] = 0.5f;
2187 clearValues[0].color.float32[3] = 1.0f;
2188 clearValues[1].depthStencil.depth = 1.0f;
2189
2190 VkRenderPassBeginInfo renderPassBeginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
2191 renderPassBeginInfo.renderPass = g_hRenderPass;
2192 renderPassBeginInfo.framebuffer = g_Framebuffers[imageIndex];
2193 renderPassBeginInfo.renderArea.offset.x = 0;
2194 renderPassBeginInfo.renderArea.offset.y = 0;
2195 renderPassBeginInfo.renderArea.extent = g_Extent;
2196 renderPassBeginInfo.clearValueCount = (uint32_t)_countof(clearValues);
2197 renderPassBeginInfo.pClearValues = clearValues;
2198 vkCmdBeginRenderPass(hCommandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
2199
2200 vkCmdBindPipeline(
2201 hCommandBuffer,
2202 VK_PIPELINE_BIND_POINT_GRAPHICS,
2203 g_hPipeline);
2204
Adam Sawicki82c3f332018-06-11 15:27:33 +02002205 mat4 view = mat4::LookAt(
2206 vec3(0.f, 0.f, 0.f),
2207 vec3(0.f, -2.f, 4.f),
2208 vec3(0.f, 1.f, 0.f));
2209 mat4 proj = mat4::Perspective(
Adam Sawickie6e498f2017-06-16 17:21:31 +02002210 1.0471975511966f, // 60 degrees
2211 (float)g_Extent.width / (float)g_Extent.height,
2212 0.1f,
Adam Sawicki82c3f332018-06-11 15:27:33 +02002213 1000.f);
2214 mat4 viewProj = view * proj;
Adam Sawickie6e498f2017-06-16 17:21:31 +02002215
2216 vkCmdBindDescriptorSets(
2217 hCommandBuffer,
2218 VK_PIPELINE_BIND_POINT_GRAPHICS,
2219 g_hPipelineLayout,
2220 0,
2221 1,
2222 &g_hDescriptorSet,
2223 0,
2224 nullptr);
2225
Adam Sawicki82c3f332018-06-11 15:27:33 +02002226 float rotationAngle = (float)GetTickCount() * 0.001f * (float)PI * 0.2f;
2227 mat4 model = mat4::RotationY(rotationAngle);
Adam Sawickie6e498f2017-06-16 17:21:31 +02002228
2229 UniformBufferObject ubo = {};
Adam Sawicki82c3f332018-06-11 15:27:33 +02002230 ubo.ModelViewProj = model * viewProj;
Adam Sawickie6e498f2017-06-16 17:21:31 +02002231 vkCmdPushConstants(hCommandBuffer, g_hPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(UniformBufferObject), &ubo);
2232
2233 VkBuffer vertexBuffers[] = { g_hVertexBuffer };
2234 VkDeviceSize offsets[] = { 0 };
2235 vkCmdBindVertexBuffers(hCommandBuffer, 0, 1, vertexBuffers, offsets);
2236
2237 vkCmdBindIndexBuffer(hCommandBuffer, g_hIndexBuffer, 0, VK_INDEX_TYPE_UINT16);
2238
2239 vkCmdDrawIndexed(hCommandBuffer, g_IndexCount, 1, 0, 0, 0);
2240
2241 vkCmdEndRenderPass(hCommandBuffer);
2242
2243 vkEndCommandBuffer(hCommandBuffer);
2244
2245 // Submit command buffer
2246
2247 VkSemaphore submitWaitSemaphores[] = { g_hImageAvailableSemaphore };
2248 VkPipelineStageFlags submitWaitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
2249 VkSemaphore submitSignalSemaphores[] = { g_hRenderFinishedSemaphore };
2250 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
2251 submitInfo.waitSemaphoreCount = 1;
2252 submitInfo.pWaitSemaphores = submitWaitSemaphores;
2253 submitInfo.pWaitDstStageMask = submitWaitStages;
2254 submitInfo.commandBufferCount = 1;
2255 submitInfo.pCommandBuffers = &hCommandBuffer;
2256 submitInfo.signalSemaphoreCount = _countof(submitSignalSemaphores);
2257 submitInfo.pSignalSemaphores = submitSignalSemaphores;
2258 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, hCommandBufferExecutedFence) );
2259
2260 VkSemaphore presentWaitSemaphores[] = { g_hRenderFinishedSemaphore };
2261
2262 VkSwapchainKHR swapchains[] = { g_hSwapchain };
2263 VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
2264 presentInfo.waitSemaphoreCount = _countof(presentWaitSemaphores);
2265 presentInfo.pWaitSemaphores = presentWaitSemaphores;
2266 presentInfo.swapchainCount = 1;
2267 presentInfo.pSwapchains = swapchains;
2268 presentInfo.pImageIndices = &imageIndex;
2269 presentInfo.pResults = nullptr;
2270 res = vkQueuePresentKHR(g_hPresentQueue, &presentInfo);
2271 if(res == VK_ERROR_OUT_OF_DATE_KHR)
2272 {
2273 RecreateSwapChain();
2274 }
2275 else
2276 ERR_GUARD_VULKAN(res);
2277}
2278
2279static void HandlePossibleSizeChange()
2280{
2281 RECT clientRect;
2282 GetClientRect(g_hWnd, &clientRect);
2283 LONG newSizeX = clientRect.right - clientRect.left;
2284 LONG newSizeY = clientRect.bottom - clientRect.top;
2285 if((newSizeX > 0) &&
2286 (newSizeY > 0) &&
2287 ((newSizeX != g_SizeX) || (newSizeY != g_SizeY)))
2288 {
2289 g_SizeX = newSizeX;
2290 g_SizeY = newSizeY;
2291
2292 RecreateSwapChain();
2293 }
2294}
2295
2296static LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2297{
2298 switch(msg)
2299 {
2300 case WM_CREATE:
2301 // This is intentionally assigned here because we are now inside CreateWindow, before it returns.
2302 g_hWnd = hWnd;
2303 InitializeApplication();
Adam Sawickiafd50562021-02-26 11:59:58 +01002304 //PrintAllocatorStats();
Adam Sawickie6e498f2017-06-16 17:21:31 +02002305 return 0;
2306
2307 case WM_DESTROY:
2308 FinalizeApplication();
2309 PostQuitMessage(0);
2310 return 0;
2311
2312 // This prevents app from freezing when left Alt is pressed
2313 // (which normally enters modal menu loop).
2314 case WM_SYSKEYDOWN:
2315 case WM_SYSKEYUP:
2316 return 0;
2317
2318 case WM_SIZE:
2319 if((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED))
2320 HandlePossibleSizeChange();
2321 return 0;
2322
2323 case WM_EXITSIZEMOVE:
2324 HandlePossibleSizeChange();
2325 return 0;
2326
2327 case WM_KEYDOWN:
Adam Sawickib8333fb2018-03-13 16:15:53 +01002328 switch(wParam)
2329 {
2330 case VK_ESCAPE:
Adam Sawickie6e498f2017-06-16 17:21:31 +02002331 PostMessage(hWnd, WM_CLOSE, 0, 0);
Adam Sawickib8333fb2018-03-13 16:15:53 +01002332 break;
2333 case 'T':
Adam Sawickia7d77692018-10-03 16:15:27 +02002334 try
2335 {
2336 Test();
2337 }
2338 catch(const std::exception& ex)
2339 {
2340 printf("ERROR: %s\n", ex.what());
2341 }
Adam Sawickib8333fb2018-03-13 16:15:53 +01002342 break;
Adam Sawickida6c1942018-12-05 17:34:34 +01002343 case 'S':
2344 try
2345 {
2346 if(g_SparseBindingEnabled)
2347 {
2348 TestSparseBinding();
2349 }
2350 else
2351 {
2352 printf("Sparse binding not supported.\n");
2353 }
2354 }
2355 catch(const std::exception& ex)
2356 {
2357 printf("ERROR: %s\n", ex.what());
2358 }
2359 break;
Adam Sawickib8333fb2018-03-13 16:15:53 +01002360 }
Adam Sawickie6e498f2017-06-16 17:21:31 +02002361 return 0;
2362
2363 default:
2364 break;
2365 }
2366
2367 return DefWindowProc(hWnd, msg, wParam, lParam);
2368}
2369
2370int main()
2371{
2372 g_hAppInstance = (HINSTANCE)GetModuleHandle(NULL);
2373
2374 WNDCLASSEX wndClassDesc = { sizeof(WNDCLASSEX) };
2375 wndClassDesc.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
2376 wndClassDesc.hbrBackground = NULL;
2377 wndClassDesc.hCursor = LoadCursor(NULL, IDC_CROSS);
2378 wndClassDesc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
2379 wndClassDesc.hInstance = g_hAppInstance;
2380 wndClassDesc.lpfnWndProc = WndProc;
2381 wndClassDesc.lpszClassName = WINDOW_CLASS_NAME;
2382
2383 const ATOM hWndClass = RegisterClassEx(&wndClassDesc);
2384 assert(hWndClass);
2385
2386 const DWORD style = WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME;
2387 const DWORD exStyle = 0;
2388
2389 RECT rect = { 0, 0, g_SizeX, g_SizeY };
2390 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
2391
Adam Sawicki86ccd632017-07-04 14:57:53 +02002392 CreateWindowEx(
Adam Sawickie6e498f2017-06-16 17:21:31 +02002393 exStyle, WINDOW_CLASS_NAME, APP_TITLE_W, style,
2394 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2395 NULL, NULL, g_hAppInstance, NULL);
2396
2397 MSG msg;
2398 for(;;)
2399 {
2400 if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
2401 {
2402 if(msg.message == WM_QUIT)
2403 break;
2404 TranslateMessage(&msg);
2405 DispatchMessage(&msg);
2406 }
2407 if(g_hDevice != VK_NULL_HANDLE)
2408 DrawFrame();
2409 }
2410
Adam Sawicki8317ba92019-11-18 13:14:11 +01002411 TEST(g_CpuAllocCount.load() == 0);
2412
Adam Sawickie6e498f2017-06-16 17:21:31 +02002413 return 0;
2414}
Adam Sawicki59a3e7e2017-08-21 15:47:30 +02002415
Adam Sawickif1a793c2018-03-13 15:42:22 +01002416#else // #ifdef _WIN32
Adam Sawicki59a3e7e2017-08-21 15:47:30 +02002417
Adam Sawickif1a793c2018-03-13 15:42:22 +01002418#include "VmaUsage.h"
Adam Sawicki59a3e7e2017-08-21 15:47:30 +02002419
2420int main()
2421{
2422}
2423
Adam Sawickif1a793c2018-03-13 15:42:22 +01002424#endif // #ifdef _WIN32