vkcube: Implement key events in Windows
[platform/upstream/Vulkan-Tools.git] / cube / cube.c
1 /*
2  * Copyright (c) 2015-2016 The Khronos Group Inc.
3  * Copyright (c) 2015-2016 Valve Corporation
4  * Copyright (c) 2015-2016 LunarG, Inc.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * Author: Chia-I Wu <olv@lunarg.com>
19  * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
20  * Author: Ian Elliott <ian@LunarG.com>
21  * Author: Ian Elliott <ianelliott@google.com>
22  * Author: Jon Ashburn <jon@lunarg.com>
23  * Author: Gwan-gyeong Mun <elongbug@gmail.com>
24  * Author: Tony Barbour <tony@LunarG.com>
25  * Author: Bill Hollings <bill.hollings@brenwill.com>
26  */
27
28 #define _GNU_SOURCE
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <stdbool.h>
34 #include <assert.h>
35 #include <signal.h>
36 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
37 #include <X11/Xutil.h>
38 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
39 #include <linux/input.h>
40 #endif
41
42 #ifdef _WIN32
43 #pragma comment(linker, "/subsystem:windows")
44 #define APP_NAME_STR_LEN 80
45 #endif  // _WIN32
46
47 #ifdef ANDROID
48 #include "vulkan_wrapper.h"
49 #else
50 #include <vulkan/vulkan.h>
51 #endif
52
53 #include <vulkan/vk_sdk_platform.h>
54 #include "linmath.h"
55 #include "object_type_string_helper.h"
56
57 #include "gettime.h"
58 #include "inttypes.h"
59 #define MILLION 1000000L
60 #define BILLION 1000000000L
61
62 #define DEMO_TEXTURE_COUNT 1
63 #define APP_SHORT_NAME "vkcube"
64 #define APP_LONG_NAME "Vulkan Cube"
65
66 // Allow a maximum of two outstanding presentation operations.
67 #define FRAME_LAG 2
68
69 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
70
71 #if defined(NDEBUG) && defined(__GNUC__)
72 #define U_ASSERT_ONLY __attribute__((unused))
73 #else
74 #define U_ASSERT_ONLY
75 #endif
76
77 #if defined(__GNUC__)
78 #define UNUSED __attribute__((unused))
79 #else
80 #define UNUSED
81 #endif
82
83 #ifdef _WIN32
84 bool in_callback = false;
85 #define ERR_EXIT(err_msg, err_class)                                             \
86     do {                                                                         \
87         if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
88         exit(1);                                                                 \
89     } while (0)
90 void DbgMsg(char *fmt, ...) {
91     va_list va;
92     va_start(va, fmt);
93     printf(fmt, va);
94     fflush(stdout);
95     va_end(va);
96 }
97
98 #elif defined __ANDROID__
99 #include <android/log.h>
100 #define ERR_EXIT(err_msg, err_class)                                    \
101     do {                                                                \
102         ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", err_msg)); \
103         exit(1);                                                        \
104     } while (0)
105 #ifdef VARARGS_WORKS_ON_ANDROID
106 void DbgMsg(const char *fmt, ...) {
107     va_list va;
108     va_start(va, fmt);
109     __android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, va);
110     va_end(va);
111 }
112 #else  // VARARGS_WORKS_ON_ANDROID
113 #define DbgMsg(fmt, ...)                                                           \
114     do {                                                                           \
115         ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, ##__VA_ARGS__)); \
116     } while (0)
117 #endif  // VARARGS_WORKS_ON_ANDROID
118 #else
119 #define ERR_EXIT(err_msg, err_class) \
120     do {                             \
121         printf("%s\n", err_msg);     \
122         fflush(stdout);              \
123         exit(1);                     \
124     } while (0)
125 void DbgMsg(char *fmt, ...) {
126     va_list va;
127     va_start(va, fmt);
128     printf(fmt, va);
129     fflush(stdout);
130     va_end(va);
131 }
132 #endif
133
134 #define GET_INSTANCE_PROC_ADDR(inst, entrypoint)                                                              \
135     {                                                                                                         \
136         demo->fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint);             \
137         if (demo->fp##entrypoint == NULL) {                                                                   \
138             ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, "vkGetInstanceProcAddr Failure"); \
139         }                                                                                                     \
140     }
141
142 static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
143
144 #define GET_DEVICE_PROC_ADDR(dev, entrypoint)                                                                    \
145     {                                                                                                            \
146         if (!g_gdpa) g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \
147         demo->fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint);                                \
148         if (demo->fp##entrypoint == NULL) {                                                                      \
149             ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, "vkGetDeviceProcAddr Failure");        \
150         }                                                                                                        \
151     }
152
153 /*
154  * structure to track all objects related to a texture.
155  */
156 struct texture_object {
157     VkSampler sampler;
158
159     VkImage image;
160     VkBuffer buffer;
161     VkImageLayout imageLayout;
162
163     VkMemoryAllocateInfo mem_alloc;
164     VkDeviceMemory mem;
165     VkImageView view;
166     int32_t tex_width, tex_height;
167 };
168
169 static char *tex_files[] = {"lunarg.ppm"};
170
171 static int validation_error = 0;
172
173 struct vktexcube_vs_uniform {
174     // Must start with MVP
175     float mvp[4][4];
176     float position[12 * 3][4];
177     float attr[12 * 3][4];
178 };
179
180 //--------------------------------------------------------------------------------------
181 // Mesh and VertexFormat Data
182 //--------------------------------------------------------------------------------------
183 // clang-format off
184 static const float g_vertex_buffer_data[] = {
185     -1.0f,-1.0f,-1.0f,  // -X side
186     -1.0f,-1.0f, 1.0f,
187     -1.0f, 1.0f, 1.0f,
188     -1.0f, 1.0f, 1.0f,
189     -1.0f, 1.0f,-1.0f,
190     -1.0f,-1.0f,-1.0f,
191
192     -1.0f,-1.0f,-1.0f,  // -Z side
193      1.0f, 1.0f,-1.0f,
194      1.0f,-1.0f,-1.0f,
195     -1.0f,-1.0f,-1.0f,
196     -1.0f, 1.0f,-1.0f,
197      1.0f, 1.0f,-1.0f,
198
199     -1.0f,-1.0f,-1.0f,  // -Y side
200      1.0f,-1.0f,-1.0f,
201      1.0f,-1.0f, 1.0f,
202     -1.0f,-1.0f,-1.0f,
203      1.0f,-1.0f, 1.0f,
204     -1.0f,-1.0f, 1.0f,
205
206     -1.0f, 1.0f,-1.0f,  // +Y side
207     -1.0f, 1.0f, 1.0f,
208      1.0f, 1.0f, 1.0f,
209     -1.0f, 1.0f,-1.0f,
210      1.0f, 1.0f, 1.0f,
211      1.0f, 1.0f,-1.0f,
212
213      1.0f, 1.0f,-1.0f,  // +X side
214      1.0f, 1.0f, 1.0f,
215      1.0f,-1.0f, 1.0f,
216      1.0f,-1.0f, 1.0f,
217      1.0f,-1.0f,-1.0f,
218      1.0f, 1.0f,-1.0f,
219
220     -1.0f, 1.0f, 1.0f,  // +Z side
221     -1.0f,-1.0f, 1.0f,
222      1.0f, 1.0f, 1.0f,
223     -1.0f,-1.0f, 1.0f,
224      1.0f,-1.0f, 1.0f,
225      1.0f, 1.0f, 1.0f,
226 };
227
228 static const float g_uv_buffer_data[] = {
229     0.0f, 1.0f,  // -X side
230     1.0f, 1.0f,
231     1.0f, 0.0f,
232     1.0f, 0.0f,
233     0.0f, 0.0f,
234     0.0f, 1.0f,
235
236     1.0f, 1.0f,  // -Z side
237     0.0f, 0.0f,
238     0.0f, 1.0f,
239     1.0f, 1.0f,
240     1.0f, 0.0f,
241     0.0f, 0.0f,
242
243     1.0f, 0.0f,  // -Y side
244     1.0f, 1.0f,
245     0.0f, 1.0f,
246     1.0f, 0.0f,
247     0.0f, 1.0f,
248     0.0f, 0.0f,
249
250     1.0f, 0.0f,  // +Y side
251     0.0f, 0.0f,
252     0.0f, 1.0f,
253     1.0f, 0.0f,
254     0.0f, 1.0f,
255     1.0f, 1.0f,
256
257     1.0f, 0.0f,  // +X side
258     0.0f, 0.0f,
259     0.0f, 1.0f,
260     0.0f, 1.0f,
261     1.0f, 1.0f,
262     1.0f, 0.0f,
263
264     0.0f, 0.0f,  // +Z side
265     0.0f, 1.0f,
266     1.0f, 0.0f,
267     0.0f, 1.0f,
268     1.0f, 1.0f,
269     1.0f, 0.0f,
270 };
271 // clang-format on
272
273 void dumpMatrix(const char *note, mat4x4 MVP) {
274     int i;
275
276     printf("%s: \n", note);
277     for (i = 0; i < 4; i++) {
278         printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
279     }
280     printf("\n");
281     fflush(stdout);
282 }
283
284 void dumpVec4(const char *note, vec4 vector) {
285     printf("%s: \n", note);
286     printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
287     printf("\n");
288     fflush(stdout);
289 }
290
291 typedef struct {
292     VkImage image;
293     VkCommandBuffer cmd;
294     VkCommandBuffer graphics_to_present_cmd;
295     VkImageView view;
296     VkBuffer uniform_buffer;
297     VkDeviceMemory uniform_memory;
298     VkFramebuffer framebuffer;
299     VkDescriptorSet descriptor_set;
300 } SwapchainImageResources;
301
302 struct demo {
303 #if defined(VK_USE_PLATFORM_WIN32_KHR)
304 #define APP_NAME_STR_LEN 80
305     HINSTANCE connection;         // hInstance - Windows Instance
306     char name[APP_NAME_STR_LEN];  // Name to put on the window/icon
307     HWND window;                  // hWnd - window handle
308     POINT minsize;                // minimum window size
309 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
310     Display *display;
311     Window xlib_window;
312     Atom xlib_wm_delete_window;
313 #elif defined(VK_USE_PLATFORM_XCB_KHR)
314     Display *display;
315     xcb_connection_t *connection;
316     xcb_screen_t *screen;
317     xcb_window_t xcb_window;
318     xcb_intern_atom_reply_t *atom_wm_delete_window;
319 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
320     struct wl_display *display;
321     struct wl_registry *registry;
322     struct wl_compositor *compositor;
323     struct wl_surface *window;
324     struct wl_shell *shell;
325     struct wl_shell_surface *shell_surface;
326     struct wl_seat *seat;
327     struct wl_pointer *pointer;
328     struct wl_keyboard *keyboard;
329 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
330     struct ANativeWindow *window;
331 #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
332     void *window;
333 #endif
334     VkSurfaceKHR surface;
335     bool prepared;
336     bool use_staging_buffer;
337     bool separate_present_queue;
338     bool is_minimized;
339
340     bool VK_KHR_incremental_present_enabled;
341
342     bool VK_GOOGLE_display_timing_enabled;
343     bool syncd_with_actual_presents;
344     uint64_t refresh_duration;
345     uint64_t refresh_duration_multiplier;
346     uint64_t target_IPD;  // image present duration (inverse of frame rate)
347     uint64_t prev_desired_present_time;
348     uint32_t next_present_id;
349     uint32_t last_early_id;  // 0 if no early images
350     uint32_t last_late_id;   // 0 if no late images
351
352     VkInstance inst;
353     VkPhysicalDevice gpu;
354     VkDevice device;
355     VkQueue graphics_queue;
356     VkQueue present_queue;
357     uint32_t graphics_queue_family_index;
358     uint32_t present_queue_family_index;
359     VkSemaphore image_acquired_semaphores[FRAME_LAG];
360     VkSemaphore draw_complete_semaphores[FRAME_LAG];
361     VkSemaphore image_ownership_semaphores[FRAME_LAG];
362     VkPhysicalDeviceProperties gpu_props;
363     VkQueueFamilyProperties *queue_props;
364     VkPhysicalDeviceMemoryProperties memory_properties;
365
366     uint32_t enabled_extension_count;
367     uint32_t enabled_layer_count;
368     char *extension_names[64];
369     char *enabled_layers[64];
370
371     int width, height;
372     VkFormat format;
373     VkColorSpaceKHR color_space;
374
375     PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR;
376     PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
377     PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR;
378     PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR;
379     PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
380     PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
381     PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
382     PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
383     PFN_vkQueuePresentKHR fpQueuePresentKHR;
384     PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE;
385     PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE;
386     uint32_t swapchainImageCount;
387     VkSwapchainKHR swapchain;
388     SwapchainImageResources *swapchain_image_resources;
389     VkPresentModeKHR presentMode;
390     VkFence fences[FRAME_LAG];
391     int frame_index;
392
393     VkCommandPool cmd_pool;
394     VkCommandPool present_cmd_pool;
395
396     struct {
397         VkFormat format;
398
399         VkImage image;
400         VkMemoryAllocateInfo mem_alloc;
401         VkDeviceMemory mem;
402         VkImageView view;
403     } depth;
404
405     struct texture_object textures[DEMO_TEXTURE_COUNT];
406     struct texture_object staging_texture;
407
408     VkCommandBuffer cmd;  // Buffer for initialization commands
409     VkPipelineLayout pipeline_layout;
410     VkDescriptorSetLayout desc_layout;
411     VkPipelineCache pipelineCache;
412     VkRenderPass render_pass;
413     VkPipeline pipeline;
414
415     mat4x4 projection_matrix;
416     mat4x4 view_matrix;
417     mat4x4 model_matrix;
418
419     float spin_angle;
420     float spin_increment;
421     bool pause;
422
423     VkShaderModule vert_shader_module;
424     VkShaderModule frag_shader_module;
425
426     VkDescriptorPool desc_pool;
427
428     bool quit;
429     int32_t curFrame;
430     int32_t frameCount;
431     bool validate;
432     bool validate_checks_disabled;
433     bool use_break;
434     bool suppress_popups;
435
436     PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT;
437     PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT;
438     PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT;
439     PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
440     PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
441     PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT;
442     PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
443     VkDebugUtilsMessengerEXT dbg_messenger;
444
445     uint32_t current_buffer;
446     uint32_t queue_family_count;
447 };
448
449 VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
450                                                         VkDebugUtilsMessageTypeFlagsEXT messageType,
451                                                         const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
452                                                         void *pUserData) {
453     char prefix[64] = "";
454     char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
455     assert(message);
456     struct demo *demo = (struct demo *)pUserData;
457
458     if (demo->use_break) {
459 #ifndef WIN32
460         raise(SIGTRAP);
461 #else
462         DebugBreak();
463 #endif
464     }
465
466     if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
467         strcat(prefix, "VERBOSE : ");
468     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
469         strcat(prefix, "INFO : ");
470     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
471         strcat(prefix, "WARNING : ");
472     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
473         strcat(prefix, "ERROR : ");
474     }
475
476     if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
477         strcat(prefix, "GENERAL");
478     } else {
479         if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
480             strcat(prefix, "VALIDATION");
481             validation_error = 1;
482         }
483         if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
484             if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
485                 strcat(prefix, "|");
486             }
487             strcat(prefix, "PERFORMANCE");
488         }
489     }
490
491     sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
492             pCallbackData->pMessageIdName, pCallbackData->pMessage);
493     if (pCallbackData->objectCount > 0) {
494         char tmp_message[500];
495         sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
496         strcat(message, tmp_message);
497         for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
498             if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
499                 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p, Name \"%s\"\n", object,
500                         string_VkObjectType(pCallbackData->pObjects[object].objectType),
501                         (void *)(pCallbackData->pObjects[object].objectHandle), pCallbackData->pObjects[object].pObjectName);
502             } else {
503                 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p\n", object,
504                         string_VkObjectType(pCallbackData->pObjects[object].objectType),
505                         (void *)(pCallbackData->pObjects[object].objectHandle));
506             }
507             strcat(message, tmp_message);
508         }
509     }
510     if (pCallbackData->cmdBufLabelCount > 0) {
511         char tmp_message[500];
512         sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
513         strcat(message, tmp_message);
514         for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
515             sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
516                     pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
517                     pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
518                     pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
519             strcat(message, tmp_message);
520         }
521     }
522
523 #ifdef _WIN32
524
525     in_callback = true;
526     if (!demo->suppress_popups)
527         MessageBox(NULL, message, "Alert", MB_OK);
528     in_callback = false;
529
530 #elif defined(ANDROID)
531
532     if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
533         __android_log_print(ANDROID_LOG_INFO,  APP_SHORT_NAME, "%s", message);
534     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
535         __android_log_print(ANDROID_LOG_WARN,  APP_SHORT_NAME, "%s", message);
536     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
537         __android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message);
538     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
539         __android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message);
540     } else {
541         __android_log_print(ANDROID_LOG_INFO,  APP_SHORT_NAME, "%s", message);
542     }
543
544 #else
545
546     printf("%s\n", message);
547     fflush(stdout);
548
549 #endif
550
551     free(message);
552
553     // Don't bail out, but keep going.
554     return false;
555 }
556
557 bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) {
558     // The desired time was the earliest time that the present should have
559     // occured.  In almost every case, the actual time should be later than the
560     // desired time.  We should only consider the actual time "late" if it is
561     // after "desired + rdur".
562     if (actual <= desired) {
563         // The actual time was before or equal to the desired time.  This will
564         // probably never happen, but in case it does, return false since the
565         // present was obviously NOT late.
566         return false;
567     }
568     uint64_t deadline = desired + rdur;
569     if (actual > deadline) {
570         return true;
571     } else {
572         return false;
573     }
574 }
575 bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) {
576     if (earliest < actual) {
577         // Consider whether this present could have occured earlier.  Make sure
578         // that earliest time was at least 2msec earlier than actual time, and
579         // that the margin was at least 2msec:
580         uint64_t diff = actual - earliest;
581         if ((diff >= (2 * MILLION)) && (margin >= (2 * MILLION))) {
582             // This present could have occured earlier because both: 1) the
583             // earliest time was at least 2 msec before actual time, and 2) the
584             // margin was at least 2msec.
585             return true;
586         }
587     }
588     return false;
589 }
590
591 // Forward declaration:
592 static void demo_resize(struct demo *demo);
593
594 static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
595     // Search memtypes to find first index with those properties
596     for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
597         if ((typeBits & 1) == 1) {
598             // Type is available, does it match user properties?
599             if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
600                 *typeIndex = i;
601                 return true;
602             }
603         }
604         typeBits >>= 1;
605     }
606     // No memory types matched, return failure
607     return false;
608 }
609
610 static void demo_flush_init_cmd(struct demo *demo) {
611     VkResult U_ASSERT_ONLY err;
612
613     // This function could get called twice if the texture uses a staging buffer
614     // In that case the second call should be ignored
615     if (demo->cmd == VK_NULL_HANDLE) return;
616
617     err = vkEndCommandBuffer(demo->cmd);
618     assert(!err);
619
620     VkFence fence;
621     VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
622     err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
623     assert(!err);
624
625     const VkCommandBuffer cmd_bufs[] = {demo->cmd};
626     VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
627                                 .pNext = NULL,
628                                 .waitSemaphoreCount = 0,
629                                 .pWaitSemaphores = NULL,
630                                 .pWaitDstStageMask = NULL,
631                                 .commandBufferCount = 1,
632                                 .pCommandBuffers = cmd_bufs,
633                                 .signalSemaphoreCount = 0,
634                                 .pSignalSemaphores = NULL};
635
636     err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
637     assert(!err);
638
639     err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
640     assert(!err);
641
642     vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
643     vkDestroyFence(demo->device, fence, NULL);
644     demo->cmd = VK_NULL_HANDLE;
645 }
646
647 static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
648                                   VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
649                                   VkPipelineStageFlags dest_stages) {
650     assert(demo->cmd);
651
652     VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
653                                                  .pNext = NULL,
654                                                  .srcAccessMask = srcAccessMask,
655                                                  .dstAccessMask = 0,
656                                                  .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
657                                                  .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
658                                                  .oldLayout = old_image_layout,
659                                                  .newLayout = new_image_layout,
660                                                  .image = image,
661                                                  .subresourceRange = {aspectMask, 0, 1, 0, 1}};
662
663     switch (new_image_layout) {
664         case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
665             /* Make sure anything that was copying from this image has completed */
666             image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
667             break;
668
669         case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
670             image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
671             break;
672
673         case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
674             image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
675             break;
676
677         case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
678             image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
679             break;
680
681         case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
682             image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
683             break;
684
685         case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
686             image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
687             break;
688
689         default:
690             image_memory_barrier.dstAccessMask = 0;
691             break;
692     }
693
694     VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
695
696     vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
697 }
698
699 static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
700     VkDebugUtilsLabelEXT label;
701     memset(&label, 0, sizeof(label));
702     const VkCommandBufferBeginInfo cmd_buf_info = {
703         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
704         .pNext = NULL,
705         .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
706         .pInheritanceInfo = NULL,
707     };
708     const VkClearValue clear_values[2] = {
709         [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
710         [1] = {.depthStencil = {1.0f, 0}},
711     };
712     const VkRenderPassBeginInfo rp_begin = {
713         .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
714         .pNext = NULL,
715         .renderPass = demo->render_pass,
716         .framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
717         .renderArea.offset.x = 0,
718         .renderArea.offset.y = 0,
719         .renderArea.extent.width = demo->width,
720         .renderArea.extent.height = demo->height,
721         .clearValueCount = 2,
722         .pClearValues = clear_values,
723     };
724     VkResult U_ASSERT_ONLY err;
725
726     err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
727
728     if (demo->validate) {
729         // Set a name for the command buffer
730         VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
731             .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
732             .pNext = NULL,
733             .objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
734             .objectHandle = (uint64_t)cmd_buf,
735             .pObjectName = "CubeDrawCommandBuf",
736         };
737         demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
738
739         label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
740         label.pNext = NULL;
741         label.pLabelName = "DrawBegin";
742         label.color[0] = 0.4f;
743         label.color[1] = 0.3f;
744         label.color[2] = 0.2f;
745         label.color[3] = 0.1f;
746         demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
747     }
748
749     assert(!err);
750     vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
751
752     if (demo->validate) {
753         label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
754         label.pNext = NULL;
755         label.pLabelName = "InsideRenderPass";
756         label.color[0] = 8.4f;
757         label.color[1] = 7.3f;
758         label.color[2] = 6.2f;
759         label.color[3] = 7.1f;
760         demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
761     }
762
763     vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
764     vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
765                             &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
766     VkViewport viewport;
767     memset(&viewport, 0, sizeof(viewport));
768     viewport.height = (float)demo->height;
769     viewport.width = (float)demo->width;
770     viewport.minDepth = (float)0.0f;
771     viewport.maxDepth = (float)1.0f;
772     vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
773
774     VkRect2D scissor;
775     memset(&scissor, 0, sizeof(scissor));
776     scissor.extent.width = demo->width;
777     scissor.extent.height = demo->height;
778     scissor.offset.x = 0;
779     scissor.offset.y = 0;
780     vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
781
782     if (demo->validate) {
783         label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
784         label.pNext = NULL;
785         label.pLabelName = "ActualDraw";
786         label.color[0] = -0.4f;
787         label.color[1] = -0.3f;
788         label.color[2] = -0.2f;
789         label.color[3] = -0.1f;
790         demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
791     }
792
793     vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
794     if (demo->validate) {
795         demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
796     }
797
798     // Note that ending the renderpass changes the image's layout from
799     // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
800     vkCmdEndRenderPass(cmd_buf);
801     if (demo->validate) {
802         demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
803     }
804
805     if (demo->separate_present_queue) {
806         // We have to transfer ownership from the graphics queue family to the
807         // present queue family to be able to present.  Note that we don't have
808         // to transfer from present queue family back to graphics queue family at
809         // the start of the next frame because we don't care about the image's
810         // contents at that point.
811         VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
812                                                         .pNext = NULL,
813                                                         .srcAccessMask = 0,
814                                                         .dstAccessMask = 0,
815                                                         .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
816                                                         .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
817                                                         .srcQueueFamilyIndex = demo->graphics_queue_family_index,
818                                                         .dstQueueFamilyIndex = demo->present_queue_family_index,
819                                                         .image = demo->swapchain_image_resources[demo->current_buffer].image,
820                                                         .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
821
822         vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
823                              NULL, 1, &image_ownership_barrier);
824     }
825     if (demo->validate) {
826         demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
827     }
828     err = vkEndCommandBuffer(cmd_buf);
829     assert(!err);
830 }
831
832 void demo_build_image_ownership_cmd(struct demo *demo, int i) {
833     VkResult U_ASSERT_ONLY err;
834
835     const VkCommandBufferBeginInfo cmd_buf_info = {
836         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
837         .pNext = NULL,
838         .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
839         .pInheritanceInfo = NULL,
840     };
841     err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
842     assert(!err);
843
844     VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
845                                                     .pNext = NULL,
846                                                     .srcAccessMask = 0,
847                                                     .dstAccessMask = 0,
848                                                     .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
849                                                     .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
850                                                     .srcQueueFamilyIndex = demo->graphics_queue_family_index,
851                                                     .dstQueueFamilyIndex = demo->present_queue_family_index,
852                                                     .image = demo->swapchain_image_resources[i].image,
853                                                     .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
854
855     vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
856                          VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
857     err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
858     assert(!err);
859 }
860
861 void demo_update_data_buffer(struct demo *demo) {
862     mat4x4 MVP, Model, VP;
863     int matrixSize = sizeof(MVP);
864     uint8_t *pData;
865     VkResult U_ASSERT_ONLY err;
866
867     mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
868
869     // Rotate around the Y axis
870     mat4x4_dup(Model, demo->model_matrix);
871     mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(demo->spin_angle));
872     mat4x4_mul(MVP, VP, demo->model_matrix);
873
874     err = vkMapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, 0,
875                       (void **)&pData);
876     assert(!err);
877
878     memcpy(pData, (const void *)&MVP[0][0], matrixSize);
879
880     vkUnmapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory);
881 }
882
883 void DemoUpdateTargetIPD(struct demo *demo) {
884     // Look at what happened to previous presents, and make appropriate
885     // adjustments in timing:
886     VkResult U_ASSERT_ONLY err;
887     VkPastPresentationTimingGOOGLE *past = NULL;
888     uint32_t count = 0;
889
890     err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
891     assert(!err);
892     if (count) {
893         past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
894         assert(past);
895         err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
896         assert(!err);
897
898         bool early = false;
899         bool late = false;
900         bool calibrate_next = false;
901         for (uint32_t i = 0; i < count; i++) {
902             if (!demo->syncd_with_actual_presents) {
903                 // This is the first time that we've received an
904                 // actualPresentTime for this swapchain.  In order to not
905                 // perceive these early frames as "late", we need to sync-up
906                 // our future desiredPresentTime's with the
907                 // actualPresentTime(s) that we're receiving now.
908                 calibrate_next = true;
909
910                 // So that we don't suspect any pending presents as late,
911                 // record them all as suspected-late presents:
912                 demo->last_late_id = demo->next_present_id - 1;
913                 demo->last_early_id = 0;
914                 demo->syncd_with_actual_presents = true;
915                 break;
916             } else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
917                                          demo->refresh_duration)) {
918                 // This image could have been presented earlier.  We don't want
919                 // to decrease the target_IPD until we've seen early presents
920                 // for at least two seconds.
921                 if (demo->last_early_id == past[i].presentID) {
922                     // We've now seen two seconds worth of early presents.
923                     // Flag it as such, and reset the counter:
924                     early = true;
925                     demo->last_early_id = 0;
926                 } else if (demo->last_early_id == 0) {
927                     // This is the first early present we've seen.
928                     // Calculate the presentID for two seconds from now.
929                     uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
930                     uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
931                     demo->last_early_id = past[i].presentID + howManyPresents;
932                 } else {
933                     // We are in the midst of a set of early images,
934                     // and so we won't do anything.
935                 }
936                 late = false;
937                 demo->last_late_id = 0;
938             } else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
939                 // This image was presented after its desired time.  Since
940                 // there's a delay between calling vkQueuePresentKHR and when
941                 // we get the timing data, several presents may have been late.
942                 // Thus, we need to threat all of the outstanding presents as
943                 // being likely late, so that we only increase the target_IPD
944                 // once for all of those presents.
945                 if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
946                     late = true;
947                     // Record the last suspected-late present:
948                     demo->last_late_id = demo->next_present_id - 1;
949                 } else {
950                     // We are in the midst of a set of likely-late images,
951                     // and so we won't do anything.
952                 }
953                 early = false;
954                 demo->last_early_id = 0;
955             } else {
956                 // Since this image was not presented early or late, reset
957                 // any sets of early or late presentIDs:
958                 early = false;
959                 late = false;
960                 calibrate_next = true;
961                 demo->last_early_id = 0;
962                 demo->last_late_id = 0;
963             }
964         }
965
966         if (early) {
967             // Since we've seen at least two-seconds worth of presnts that
968             // could have occured earlier than desired, let's decrease the
969             // target_IPD (i.e. increase the frame rate):
970             //
971             // TODO(ianelliott): Try to calculate a better target_IPD based
972             // on the most recently-seen present (this is overly-simplistic).
973             demo->refresh_duration_multiplier--;
974             if (demo->refresh_duration_multiplier == 0) {
975                 // This should never happen, but in case it does, don't
976                 // try to go faster.
977                 demo->refresh_duration_multiplier = 1;
978             }
979             demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
980         }
981         if (late) {
982             // Since we found a new instance of a late present, we want to
983             // increase the target_IPD (i.e. decrease the frame rate):
984             //
985             // TODO(ianelliott): Try to calculate a better target_IPD based
986             // on the most recently-seen present (this is overly-simplistic).
987             demo->refresh_duration_multiplier++;
988             demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
989         }
990
991         if (calibrate_next) {
992             int64_t multiple = demo->next_present_id - past[count - 1].presentID;
993             demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD));
994         }
995         free(past);
996     }
997 }
998
999 static void demo_draw(struct demo *demo) {
1000     VkResult U_ASSERT_ONLY err;
1001
1002     // Ensure no more than FRAME_LAG renderings are outstanding
1003     vkWaitForFences(demo->device, 1, &demo->fences[demo->frame_index], VK_TRUE, UINT64_MAX);
1004     vkResetFences(demo->device, 1, &demo->fences[demo->frame_index]);
1005
1006     do {
1007         // Get the index of the next available swapchain image:
1008         err =
1009             demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
1010                                         demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE, &demo->current_buffer);
1011
1012         if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1013             // demo->swapchain is out of date (e.g. the window was resized) and
1014             // must be recreated:
1015             demo_resize(demo);
1016         } else if (err == VK_SUBOPTIMAL_KHR) {
1017             // demo->swapchain is not as optimal as it could be, but the platform's
1018             // presentation engine will still present the image correctly.
1019             break;
1020         } else {
1021             assert(!err);
1022         }
1023     } while (err != VK_SUCCESS);
1024
1025     demo_update_data_buffer(demo);
1026
1027     if (demo->VK_GOOGLE_display_timing_enabled) {
1028         // Look at what happened to previous presents, and make appropriate
1029         // adjustments in timing:
1030         DemoUpdateTargetIPD(demo);
1031
1032         // Note: a real application would position its geometry to that it's in
1033         // the correct locatoin for when the next image is presented.  It might
1034         // also wait, so that there's less latency between any input and when
1035         // the next image is rendered/presented.  This demo program is so
1036         // simple that it doesn't do either of those.
1037     }
1038
1039     // Wait for the image acquired semaphore to be signaled to ensure
1040     // that the image won't be rendered to until the presentation
1041     // engine has fully released ownership to the application, and it is
1042     // okay to render to the image.
1043     VkPipelineStageFlags pipe_stage_flags;
1044     VkSubmitInfo submit_info;
1045     submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1046     submit_info.pNext = NULL;
1047     submit_info.pWaitDstStageMask = &pipe_stage_flags;
1048     pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1049     submit_info.waitSemaphoreCount = 1;
1050     submit_info.pWaitSemaphores = &demo->image_acquired_semaphores[demo->frame_index];
1051     submit_info.commandBufferCount = 1;
1052     submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd;
1053     submit_info.signalSemaphoreCount = 1;
1054     submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
1055     err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]);
1056     assert(!err);
1057
1058     if (demo->separate_present_queue) {
1059         // If we are using separate queues, change image ownership to the
1060         // present queue before presenting, waiting for the draw complete
1061         // semaphore and signalling the ownership released semaphore when finished
1062         VkFence nullFence = VK_NULL_HANDLE;
1063         pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1064         submit_info.waitSemaphoreCount = 1;
1065         submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
1066         submit_info.commandBufferCount = 1;
1067         submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd;
1068         submit_info.signalSemaphoreCount = 1;
1069         submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index];
1070         err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
1071         assert(!err);
1072     }
1073
1074     // If we are using separate queues we have to wait for image ownership,
1075     // otherwise wait for draw complete
1076     VkPresentInfoKHR present = {
1077         .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1078         .pNext = NULL,
1079         .waitSemaphoreCount = 1,
1080         .pWaitSemaphores = (demo->separate_present_queue) ? &demo->image_ownership_semaphores[demo->frame_index]
1081                                                           : &demo->draw_complete_semaphores[demo->frame_index],
1082         .swapchainCount = 1,
1083         .pSwapchains = &demo->swapchain,
1084         .pImageIndices = &demo->current_buffer,
1085     };
1086
1087     if (demo->VK_KHR_incremental_present_enabled) {
1088         // If using VK_KHR_incremental_present, we provide a hint of the region
1089         // that contains changed content relative to the previously-presented
1090         // image.  The implementation can use this hint in order to save
1091         // work/power (by only copying the region in the hint).  The
1092         // implementation is free to ignore the hint though, and so we must
1093         // ensure that the entire image has the correctly-drawn content.
1094         uint32_t eighthOfWidth = demo->width / 8;
1095         uint32_t eighthOfHeight = demo->height / 8;
1096         VkRectLayerKHR rect = {
1097             .offset.x = eighthOfWidth,
1098             .offset.y = eighthOfHeight,
1099             .extent.width = eighthOfWidth * 6,
1100             .extent.height = eighthOfHeight * 6,
1101             .layer = 0,
1102         };
1103         VkPresentRegionKHR region = {
1104             .rectangleCount = 1,
1105             .pRectangles = &rect,
1106         };
1107         VkPresentRegionsKHR regions = {
1108             .sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR,
1109             .pNext = present.pNext,
1110             .swapchainCount = present.swapchainCount,
1111             .pRegions = &region,
1112         };
1113         present.pNext = &regions;
1114     }
1115
1116     if (demo->VK_GOOGLE_display_timing_enabled) {
1117         VkPresentTimeGOOGLE ptime;
1118         if (demo->prev_desired_present_time == 0) {
1119             // This must be the first present for this swapchain.
1120             //
1121             // We don't know where we are relative to the presentation engine's
1122             // display's refresh cycle.  We also don't know how long rendering
1123             // takes.  Let's make a grossly-simplified assumption that the
1124             // desiredPresentTime should be half way between now and
1125             // now+target_IPD.  We will adjust over time.
1126             uint64_t curtime = getTimeInNanoseconds();
1127             if (curtime == 0) {
1128                 // Since we didn't find out the current time, don't give a
1129                 // desiredPresentTime:
1130                 ptime.desiredPresentTime = 0;
1131             } else {
1132                 ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1);
1133             }
1134         } else {
1135             ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD);
1136         }
1137         ptime.presentID = demo->next_present_id++;
1138         demo->prev_desired_present_time = ptime.desiredPresentTime;
1139
1140         VkPresentTimesInfoGOOGLE present_time = {
1141             .sType = VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
1142             .pNext = present.pNext,
1143             .swapchainCount = present.swapchainCount,
1144             .pTimes = &ptime,
1145         };
1146         if (demo->VK_GOOGLE_display_timing_enabled) {
1147             present.pNext = &present_time;
1148         }
1149     }
1150
1151     err = demo->fpQueuePresentKHR(demo->present_queue, &present);
1152     demo->frame_index += 1;
1153     demo->frame_index %= FRAME_LAG;
1154
1155     if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1156         // demo->swapchain is out of date (e.g. the window was resized) and
1157         // must be recreated:
1158         demo_resize(demo);
1159     } else if (err == VK_SUBOPTIMAL_KHR) {
1160         // demo->swapchain is not as optimal as it could be, but the platform's
1161         // presentation engine will still present the image correctly.
1162     } else {
1163         assert(!err);
1164     }
1165 }
1166
1167 static void demo_prepare_buffers(struct demo *demo) {
1168     VkResult U_ASSERT_ONLY err;
1169     VkSwapchainKHR oldSwapchain = demo->swapchain;
1170
1171     // Check the surface capabilities and formats
1172     VkSurfaceCapabilitiesKHR surfCapabilities;
1173     err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
1174     assert(!err);
1175
1176     uint32_t presentModeCount;
1177     err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
1178     assert(!err);
1179     VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
1180     assert(presentModes);
1181     err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
1182     assert(!err);
1183
1184     VkExtent2D swapchainExtent;
1185     // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
1186     if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
1187         // If the surface size is undefined, the size is set to the size
1188         // of the images requested, which must fit within the minimum and
1189         // maximum values.
1190         swapchainExtent.width = demo->width;
1191         swapchainExtent.height = demo->height;
1192
1193         if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
1194             swapchainExtent.width = surfCapabilities.minImageExtent.width;
1195         } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
1196             swapchainExtent.width = surfCapabilities.maxImageExtent.width;
1197         }
1198
1199         if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
1200             swapchainExtent.height = surfCapabilities.minImageExtent.height;
1201         } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
1202             swapchainExtent.height = surfCapabilities.maxImageExtent.height;
1203         }
1204     } else {
1205         // If the surface size is defined, the swap chain size must match
1206         swapchainExtent = surfCapabilities.currentExtent;
1207         demo->width = surfCapabilities.currentExtent.width;
1208         demo->height = surfCapabilities.currentExtent.height;
1209     }
1210
1211     if (demo->width == 0 || demo->height == 0) {
1212         demo->is_minimized = true;
1213         return;
1214     } else {
1215         demo->is_minimized = false;
1216     }
1217
1218     // The FIFO present mode is guaranteed by the spec to be supported
1219     // and to have no tearing.  It's a great default present mode to use.
1220     VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
1221
1222     //  There are times when you may wish to use another present mode.  The
1223     //  following code shows how to select them, and the comments provide some
1224     //  reasons you may wish to use them.
1225     //
1226     // It should be noted that Vulkan 1.0 doesn't provide a method for
1227     // synchronizing rendering with the presentation engine's display.  There
1228     // is a method provided for throttling rendering with the display, but
1229     // there are some presentation engines for which this method will not work.
1230     // If an application doesn't throttle its rendering, and if it renders much
1231     // faster than the refresh rate of the display, this can waste power on
1232     // mobile devices.  That is because power is being spent rendering images
1233     // that may never be seen.
1234
1235     // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
1236     // tearing, or have some way of synchronizing their rendering with the
1237     // display.
1238     // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1239     // generally render a new presentable image every refresh cycle, but are
1240     // occasionally early.  In this case, the application wants the new image
1241     // to be displayed instead of the previously-queued-for-presentation image
1242     // that has not yet been displayed.
1243     // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1244     // render a new presentable image every refresh cycle, but are occasionally
1245     // late.  In this case (perhaps because of stuttering/latency concerns),
1246     // the application wants the late image to be immediately displayed, even
1247     // though that may mean some tearing.
1248
1249     if (demo->presentMode != swapchainPresentMode) {
1250         for (size_t i = 0; i < presentModeCount; ++i) {
1251             if (presentModes[i] == demo->presentMode) {
1252                 swapchainPresentMode = demo->presentMode;
1253                 break;
1254             }
1255         }
1256     }
1257     if (swapchainPresentMode != demo->presentMode) {
1258         ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1259     }
1260
1261     // Determine the number of VkImages to use in the swap chain.
1262     // Application desires to acquire 3 images at a time for triple
1263     // buffering
1264     uint32_t desiredNumOfSwapchainImages = 3;
1265     if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1266         desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1267     }
1268     // If maxImageCount is 0, we can ask for as many images as we want;
1269     // otherwise we're limited to maxImageCount
1270     if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1271         // Application must settle for fewer images than desired:
1272         desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1273     }
1274
1275     VkSurfaceTransformFlagsKHR preTransform;
1276     if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
1277         preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
1278     } else {
1279         preTransform = surfCapabilities.currentTransform;
1280     }
1281
1282     // Find a supported composite alpha mode - one of these is guaranteed to be set
1283     VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
1284     VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1285         VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
1286         VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
1287         VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
1288         VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
1289     };
1290     for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1291         if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1292             compositeAlpha = compositeAlphaFlags[i];
1293             break;
1294         }
1295     }
1296
1297     VkSwapchainCreateInfoKHR swapchain_ci = {
1298         .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
1299         .pNext = NULL,
1300         .surface = demo->surface,
1301         .minImageCount = desiredNumOfSwapchainImages,
1302         .imageFormat = demo->format,
1303         .imageColorSpace = demo->color_space,
1304         .imageExtent =
1305             {
1306                 .width = swapchainExtent.width,
1307                 .height = swapchainExtent.height,
1308             },
1309         .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
1310         .preTransform = preTransform,
1311         .compositeAlpha = compositeAlpha,
1312         .imageArrayLayers = 1,
1313         .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
1314         .queueFamilyIndexCount = 0,
1315         .pQueueFamilyIndices = NULL,
1316         .presentMode = swapchainPresentMode,
1317         .oldSwapchain = oldSwapchain,
1318         .clipped = true,
1319     };
1320     uint32_t i;
1321     err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
1322     assert(!err);
1323
1324     // If we just re-created an existing swapchain, we should destroy the old
1325     // swapchain at this point.
1326     // Note: destroying the swapchain also cleans up all its associated
1327     // presentable images once the platform is done with them.
1328     if (oldSwapchain != VK_NULL_HANDLE) {
1329         demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
1330     }
1331
1332     err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
1333     assert(!err);
1334
1335     VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
1336     assert(swapchainImages);
1337     err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
1338     assert(!err);
1339
1340     demo->swapchain_image_resources =
1341         (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount);
1342     assert(demo->swapchain_image_resources);
1343
1344     for (i = 0; i < demo->swapchainImageCount; i++) {
1345         VkImageViewCreateInfo color_image_view = {
1346             .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1347             .pNext = NULL,
1348             .format = demo->format,
1349             .components =
1350                 {
1351                     .r = VK_COMPONENT_SWIZZLE_R,
1352                     .g = VK_COMPONENT_SWIZZLE_G,
1353                     .b = VK_COMPONENT_SWIZZLE_B,
1354                     .a = VK_COMPONENT_SWIZZLE_A,
1355                 },
1356             .subresourceRange =
1357                 {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
1358             .viewType = VK_IMAGE_VIEW_TYPE_2D,
1359             .flags = 0,
1360         };
1361
1362         demo->swapchain_image_resources[i].image = swapchainImages[i];
1363
1364         color_image_view.image = demo->swapchain_image_resources[i].image;
1365
1366         err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_image_resources[i].view);
1367         assert(!err);
1368     }
1369
1370     if (demo->VK_GOOGLE_display_timing_enabled) {
1371         VkRefreshCycleDurationGOOGLE rc_dur;
1372         err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur);
1373         assert(!err);
1374         demo->refresh_duration = rc_dur.refreshDuration;
1375
1376         demo->syncd_with_actual_presents = false;
1377         // Initially target 1X the refresh duration:
1378         demo->target_IPD = demo->refresh_duration;
1379         demo->refresh_duration_multiplier = 1;
1380         demo->prev_desired_present_time = 0;
1381         demo->next_present_id = 1;
1382     }
1383
1384     if (NULL != presentModes) {
1385         free(presentModes);
1386     }
1387 }
1388
1389 static void demo_prepare_depth(struct demo *demo) {
1390     const VkFormat depth_format = VK_FORMAT_D16_UNORM;
1391     const VkImageCreateInfo image = {
1392         .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1393         .pNext = NULL,
1394         .imageType = VK_IMAGE_TYPE_2D,
1395         .format = depth_format,
1396         .extent = {demo->width, demo->height, 1},
1397         .mipLevels = 1,
1398         .arrayLayers = 1,
1399         .samples = VK_SAMPLE_COUNT_1_BIT,
1400         .tiling = VK_IMAGE_TILING_OPTIMAL,
1401         .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
1402         .flags = 0,
1403     };
1404
1405     VkImageViewCreateInfo view = {
1406         .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1407         .pNext = NULL,
1408         .image = VK_NULL_HANDLE,
1409         .format = depth_format,
1410         .subresourceRange =
1411             {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
1412         .flags = 0,
1413         .viewType = VK_IMAGE_VIEW_TYPE_2D,
1414     };
1415
1416     VkMemoryRequirements mem_reqs;
1417     VkResult U_ASSERT_ONLY err;
1418     bool U_ASSERT_ONLY pass;
1419
1420     demo->depth.format = depth_format;
1421
1422     /* create image */
1423     err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
1424     assert(!err);
1425
1426     vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
1427     assert(!err);
1428
1429     demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1430     demo->depth.mem_alloc.pNext = NULL;
1431     demo->depth.mem_alloc.allocationSize = mem_reqs.size;
1432     demo->depth.mem_alloc.memoryTypeIndex = 0;
1433
1434     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1435                                        &demo->depth.mem_alloc.memoryTypeIndex);
1436     assert(pass);
1437
1438     /* allocate memory */
1439     err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
1440     assert(!err);
1441
1442     /* bind memory */
1443     err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
1444     assert(!err);
1445
1446     /* create image view */
1447     view.image = demo->depth.image;
1448     err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
1449     assert(!err);
1450 }
1451
1452 /* Convert ppm image data from header file into RGBA texture image */
1453 #include "lunarg.ppm.h"
1454 bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
1455     (void)filename;
1456     char *cPtr;
1457     cPtr = (char *)lunarg_ppm;
1458     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
1459         return false;
1460     }
1461     while (strncmp(cPtr++, "\n", 1))
1462         ;
1463     sscanf(cPtr, "%u %u", width, height);
1464     if (rgba_data == NULL) {
1465         return true;
1466     }
1467     while (strncmp(cPtr++, "\n", 1))
1468         ;
1469     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
1470         return false;
1471     }
1472     while (strncmp(cPtr++, "\n", 1))
1473         ;
1474     for (int y = 0; y < *height; y++) {
1475         uint8_t *rowPtr = rgba_data;
1476         for (int x = 0; x < *width; x++) {
1477             memcpy(rowPtr, cPtr, 3);
1478             rowPtr[3] = 255; /* Alpha of 1 */
1479             rowPtr += 4;
1480             cPtr += 3;
1481         }
1482         rgba_data += layout->rowPitch;
1483     }
1484     return true;
1485 }
1486
1487 static void demo_prepare_texture_buffer(struct demo *demo, const char *filename, struct texture_object *tex_obj) {
1488     int32_t tex_width;
1489     int32_t tex_height;
1490     VkResult U_ASSERT_ONLY err;
1491     bool U_ASSERT_ONLY pass;
1492
1493     if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1494         ERR_EXIT("Failed to load textures", "Load Texture Failure");
1495     }
1496
1497     tex_obj->tex_width = tex_width;
1498     tex_obj->tex_height = tex_height;
1499
1500     const VkBufferCreateInfo buffer_create_info = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
1501                                                    .pNext = NULL,
1502                                                    .flags = 0,
1503                                                    .size = tex_width * tex_height * 4,
1504                                                    .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1505                                                    .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1506                                                    .queueFamilyIndexCount = 0,
1507                                                    .pQueueFamilyIndices = NULL};
1508
1509     err = vkCreateBuffer(demo->device, &buffer_create_info, NULL, &tex_obj->buffer);
1510     assert(!err);
1511
1512     VkMemoryRequirements mem_reqs;
1513     vkGetBufferMemoryRequirements(demo->device, tex_obj->buffer, &mem_reqs);
1514
1515     tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1516     tex_obj->mem_alloc.pNext = NULL;
1517     tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1518     tex_obj->mem_alloc.memoryTypeIndex = 0;
1519
1520     VkFlags requirements = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1521     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
1522     assert(pass);
1523
1524     err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1525     assert(!err);
1526
1527     /* bind memory */
1528     err = vkBindBufferMemory(demo->device, tex_obj->buffer, tex_obj->mem, 0);
1529     assert(!err);
1530
1531     VkSubresourceLayout layout;
1532     memset(&layout, 0, sizeof(layout));
1533     layout.rowPitch = tex_width * 4;
1534
1535     void *data;
1536     err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1537     assert(!err);
1538
1539     if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1540         fprintf(stderr, "Error loading texture: %s\n", filename);
1541     }
1542
1543     vkUnmapMemory(demo->device, tex_obj->mem);
1544 }
1545
1546 static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj,
1547                                        VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) {
1548     const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
1549     int32_t tex_width;
1550     int32_t tex_height;
1551     VkResult U_ASSERT_ONLY err;
1552     bool U_ASSERT_ONLY pass;
1553
1554     if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1555         ERR_EXIT("Failed to load textures", "Load Texture Failure");
1556     }
1557
1558     tex_obj->tex_width = tex_width;
1559     tex_obj->tex_height = tex_height;
1560
1561     const VkImageCreateInfo image_create_info = {
1562         .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1563         .pNext = NULL,
1564         .imageType = VK_IMAGE_TYPE_2D,
1565         .format = tex_format,
1566         .extent = {tex_width, tex_height, 1},
1567         .mipLevels = 1,
1568         .arrayLayers = 1,
1569         .samples = VK_SAMPLE_COUNT_1_BIT,
1570         .tiling = tiling,
1571         .usage = usage,
1572         .flags = 0,
1573         .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
1574     };
1575
1576     VkMemoryRequirements mem_reqs;
1577
1578     err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
1579     assert(!err);
1580
1581     vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
1582
1583     tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1584     tex_obj->mem_alloc.pNext = NULL;
1585     tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1586     tex_obj->mem_alloc.memoryTypeIndex = 0;
1587
1588     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
1589     assert(pass);
1590
1591     /* allocate memory */
1592     err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1593     assert(!err);
1594
1595     /* bind memory */
1596     err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
1597     assert(!err);
1598
1599     if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
1600         const VkImageSubresource subres = {
1601             .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1602             .mipLevel = 0,
1603             .arrayLayer = 0,
1604         };
1605         VkSubresourceLayout layout;
1606         void *data;
1607
1608         vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout);
1609
1610         err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1611         assert(!err);
1612
1613         if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1614             fprintf(stderr, "Error loading texture: %s\n", filename);
1615         }
1616
1617         vkUnmapMemory(demo->device, tex_obj->mem);
1618     }
1619
1620     tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1621 }
1622
1623 static void demo_destroy_texture(struct demo *demo, struct texture_object *tex_objs) {
1624     /* clean up staging resources */
1625     vkFreeMemory(demo->device, tex_objs->mem, NULL);
1626     if (tex_objs->image) vkDestroyImage(demo->device, tex_objs->image, NULL);
1627     if (tex_objs->buffer) vkDestroyBuffer(demo->device, tex_objs->buffer, NULL);
1628 }
1629
1630 static void demo_prepare_textures(struct demo *demo) {
1631     const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
1632     VkFormatProperties props;
1633     uint32_t i;
1634
1635     vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
1636
1637     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
1638         VkResult U_ASSERT_ONLY err;
1639
1640         if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) {
1641             /* Device can texture using linear textures */
1642             demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
1643                                        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
1644             // Nothing in the pipeline needs to be complete to start, and don't allow fragment
1645             // shader to run until layout transition completes
1646             demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1647                                   demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1648                                   VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1649             demo->staging_texture.image = 0;
1650         } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
1651             /* Must use staging buffer to copy linear texture to optimized */
1652
1653             memset(&demo->staging_texture, 0, sizeof(demo->staging_texture));
1654             demo_prepare_texture_buffer(demo, tex_files[i], &demo->staging_texture);
1655
1656             demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
1657                                        (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
1658                                        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1659
1660             demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1661                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1662                                   VK_PIPELINE_STAGE_TRANSFER_BIT);
1663
1664             VkBufferImageCopy copy_region = {
1665                 .bufferOffset = 0,
1666                 .bufferRowLength = demo->staging_texture.tex_width,
1667                 .bufferImageHeight = demo->staging_texture.tex_height,
1668                 .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
1669                 .imageOffset = {0, 0, 0},
1670                 .imageExtent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1},
1671             };
1672
1673             vkCmdCopyBufferToImage(demo->cmd, demo->staging_texture.buffer, demo->textures[i].image,
1674                                    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);
1675
1676             demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1677                                   demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1678                                   VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1679
1680         } else {
1681             /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */
1682             assert(!"No support for R8G8B8A8_UNORM as texture image format");
1683         }
1684
1685         const VkSamplerCreateInfo sampler = {
1686             .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
1687             .pNext = NULL,
1688             .magFilter = VK_FILTER_NEAREST,
1689             .minFilter = VK_FILTER_NEAREST,
1690             .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
1691             .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1692             .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1693             .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1694             .mipLodBias = 0.0f,
1695             .anisotropyEnable = VK_FALSE,
1696             .maxAnisotropy = 1,
1697             .compareOp = VK_COMPARE_OP_NEVER,
1698             .minLod = 0.0f,
1699             .maxLod = 0.0f,
1700             .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
1701             .unnormalizedCoordinates = VK_FALSE,
1702         };
1703
1704         VkImageViewCreateInfo view = {
1705             .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1706             .pNext = NULL,
1707             .image = VK_NULL_HANDLE,
1708             .viewType = VK_IMAGE_VIEW_TYPE_2D,
1709             .format = tex_format,
1710             .components =
1711                 {
1712                     VK_COMPONENT_SWIZZLE_R,
1713                     VK_COMPONENT_SWIZZLE_G,
1714                     VK_COMPONENT_SWIZZLE_B,
1715                     VK_COMPONENT_SWIZZLE_A,
1716                 },
1717             .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
1718             .flags = 0,
1719         };
1720
1721         /* create sampler */
1722         err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler);
1723         assert(!err);
1724
1725         /* create image view */
1726         view.image = demo->textures[i].image;
1727         err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view);
1728         assert(!err);
1729     }
1730 }
1731
1732 void demo_prepare_cube_data_buffers(struct demo *demo) {
1733     VkBufferCreateInfo buf_info;
1734     VkMemoryRequirements mem_reqs;
1735     VkMemoryAllocateInfo mem_alloc;
1736     uint8_t *pData;
1737     mat4x4 MVP, VP;
1738     VkResult U_ASSERT_ONLY err;
1739     bool U_ASSERT_ONLY pass;
1740     struct vktexcube_vs_uniform data;
1741
1742     mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
1743     mat4x4_mul(MVP, VP, demo->model_matrix);
1744     memcpy(data.mvp, MVP, sizeof(MVP));
1745     //    dumpMatrix("MVP", MVP);
1746
1747     for (unsigned int i = 0; i < 12 * 3; i++) {
1748         data.position[i][0] = g_vertex_buffer_data[i * 3];
1749         data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1750         data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1751         data.position[i][3] = 1.0f;
1752         data.attr[i][0] = g_uv_buffer_data[2 * i];
1753         data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1754         data.attr[i][2] = 0;
1755         data.attr[i][3] = 0;
1756     }
1757
1758     memset(&buf_info, 0, sizeof(buf_info));
1759     buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1760     buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
1761     buf_info.size = sizeof(data);
1762
1763     for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
1764         err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->swapchain_image_resources[i].uniform_buffer);
1765         assert(!err);
1766
1767         vkGetBufferMemoryRequirements(demo->device, demo->swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1768
1769         mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1770         mem_alloc.pNext = NULL;
1771         mem_alloc.allocationSize = mem_reqs.size;
1772         mem_alloc.memoryTypeIndex = 0;
1773
1774         pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
1775                                            VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1776                                            &mem_alloc.memoryTypeIndex);
1777         assert(pass);
1778
1779         err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->swapchain_image_resources[i].uniform_memory);
1780         assert(!err);
1781
1782         err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0, (void **)&pData);
1783         assert(!err);
1784
1785         memcpy(pData, &data, sizeof data);
1786
1787         vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
1788
1789         err = vkBindBufferMemory(demo->device, demo->swapchain_image_resources[i].uniform_buffer,
1790                                  demo->swapchain_image_resources[i].uniform_memory, 0);
1791         assert(!err);
1792     }
1793 }
1794
1795 static void demo_prepare_descriptor_layout(struct demo *demo) {
1796     const VkDescriptorSetLayoutBinding layout_bindings[2] = {
1797         [0] =
1798             {
1799                 .binding = 0,
1800                 .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1801                 .descriptorCount = 1,
1802                 .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
1803                 .pImmutableSamplers = NULL,
1804             },
1805         [1] =
1806             {
1807                 .binding = 1,
1808                 .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1809                 .descriptorCount = DEMO_TEXTURE_COUNT,
1810                 .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
1811                 .pImmutableSamplers = NULL,
1812             },
1813     };
1814     const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
1815         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
1816         .pNext = NULL,
1817         .bindingCount = 2,
1818         .pBindings = layout_bindings,
1819     };
1820     VkResult U_ASSERT_ONLY err;
1821
1822     err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout);
1823     assert(!err);
1824
1825     const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
1826         .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1827         .pNext = NULL,
1828         .setLayoutCount = 1,
1829         .pSetLayouts = &demo->desc_layout,
1830     };
1831
1832     err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout);
1833     assert(!err);
1834 }
1835
1836 static void demo_prepare_render_pass(struct demo *demo) {
1837     // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1838     // because at the start of the renderpass, we don't care about their contents.
1839     // At the start of the subpass, the color attachment's layout will be transitioned
1840     // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1841     // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL.  At the end of
1842     // the renderpass, the color attachment's layout will be transitioned to
1843     // LAYOUT_PRESENT_SRC_KHR to be ready to present.  This is all done as part of
1844     // the renderpass, no barriers are necessary.
1845     const VkAttachmentDescription attachments[2] = {
1846         [0] =
1847             {
1848                 .format = demo->format,
1849                 .flags = 0,
1850                 .samples = VK_SAMPLE_COUNT_1_BIT,
1851                 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1852                 .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
1853                 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1854                 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1855                 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1856                 .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
1857             },
1858         [1] =
1859             {
1860                 .format = demo->depth.format,
1861                 .flags = 0,
1862                 .samples = VK_SAMPLE_COUNT_1_BIT,
1863                 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1864                 .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1865                 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1866                 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1867                 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1868                 .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1869             },
1870     };
1871     const VkAttachmentReference color_reference = {
1872         .attachment = 0,
1873         .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1874     };
1875     const VkAttachmentReference depth_reference = {
1876         .attachment = 1,
1877         .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1878     };
1879     const VkSubpassDescription subpass = {
1880         .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
1881         .flags = 0,
1882         .inputAttachmentCount = 0,
1883         .pInputAttachments = NULL,
1884         .colorAttachmentCount = 1,
1885         .pColorAttachments = &color_reference,
1886         .pResolveAttachments = NULL,
1887         .pDepthStencilAttachment = &depth_reference,
1888         .preserveAttachmentCount = 0,
1889         .pPreserveAttachments = NULL,
1890     };
1891     const VkRenderPassCreateInfo rp_info = {
1892         .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
1893         .pNext = NULL,
1894         .flags = 0,
1895         .attachmentCount = 2,
1896         .pAttachments = attachments,
1897         .subpassCount = 1,
1898         .pSubpasses = &subpass,
1899         .dependencyCount = 0,
1900         .pDependencies = NULL,
1901     };
1902     VkResult U_ASSERT_ONLY err;
1903
1904     err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
1905     assert(!err);
1906 }
1907
1908 static VkShaderModule demo_prepare_shader_module(struct demo *demo, const uint32_t *code, size_t size) {
1909     VkShaderModule module;
1910     VkShaderModuleCreateInfo moduleCreateInfo;
1911     VkResult U_ASSERT_ONLY err;
1912
1913     moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1914     moduleCreateInfo.pNext = NULL;
1915     moduleCreateInfo.flags = 0;
1916     moduleCreateInfo.codeSize = size;
1917     moduleCreateInfo.pCode = code;
1918
1919     err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
1920     assert(!err);
1921
1922     return module;
1923 }
1924
1925 static void demo_prepare_vs(struct demo *demo) {
1926     const uint32_t vs_code[] = {
1927 #include "cube.vert.inc"
1928     };
1929     demo->vert_shader_module = demo_prepare_shader_module(demo, vs_code, sizeof(vs_code));
1930 }
1931
1932 static void demo_prepare_fs(struct demo *demo) {
1933     const uint32_t fs_code[] = {
1934 #include "cube.frag.inc"
1935     };
1936     demo->frag_shader_module = demo_prepare_shader_module(demo, fs_code, sizeof(fs_code));
1937 }
1938
1939 static void demo_prepare_pipeline(struct demo *demo) {
1940     VkGraphicsPipelineCreateInfo pipeline;
1941     VkPipelineCacheCreateInfo pipelineCache;
1942     VkPipelineVertexInputStateCreateInfo vi;
1943     VkPipelineInputAssemblyStateCreateInfo ia;
1944     VkPipelineRasterizationStateCreateInfo rs;
1945     VkPipelineColorBlendStateCreateInfo cb;
1946     VkPipelineDepthStencilStateCreateInfo ds;
1947     VkPipelineViewportStateCreateInfo vp;
1948     VkPipelineMultisampleStateCreateInfo ms;
1949     VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
1950     VkPipelineDynamicStateCreateInfo dynamicState;
1951     VkResult U_ASSERT_ONLY err;
1952
1953     memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
1954     memset(&dynamicState, 0, sizeof dynamicState);
1955     dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1956     dynamicState.pDynamicStates = dynamicStateEnables;
1957
1958     memset(&pipeline, 0, sizeof(pipeline));
1959     pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1960     pipeline.layout = demo->pipeline_layout;
1961
1962     memset(&vi, 0, sizeof(vi));
1963     vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1964
1965     memset(&ia, 0, sizeof(ia));
1966     ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1967     ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1968
1969     memset(&rs, 0, sizeof(rs));
1970     rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1971     rs.polygonMode = VK_POLYGON_MODE_FILL;
1972     rs.cullMode = VK_CULL_MODE_BACK_BIT;
1973     rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1974     rs.depthClampEnable = VK_FALSE;
1975     rs.rasterizerDiscardEnable = VK_FALSE;
1976     rs.depthBiasEnable = VK_FALSE;
1977     rs.lineWidth = 1.0f;
1978
1979     memset(&cb, 0, sizeof(cb));
1980     cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1981     VkPipelineColorBlendAttachmentState att_state[1];
1982     memset(att_state, 0, sizeof(att_state));
1983     att_state[0].colorWriteMask = 0xf;
1984     att_state[0].blendEnable = VK_FALSE;
1985     cb.attachmentCount = 1;
1986     cb.pAttachments = att_state;
1987
1988     memset(&vp, 0, sizeof(vp));
1989     vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1990     vp.viewportCount = 1;
1991     dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
1992     vp.scissorCount = 1;
1993     dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
1994
1995     memset(&ds, 0, sizeof(ds));
1996     ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1997     ds.depthTestEnable = VK_TRUE;
1998     ds.depthWriteEnable = VK_TRUE;
1999     ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
2000     ds.depthBoundsTestEnable = VK_FALSE;
2001     ds.back.failOp = VK_STENCIL_OP_KEEP;
2002     ds.back.passOp = VK_STENCIL_OP_KEEP;
2003     ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
2004     ds.stencilTestEnable = VK_FALSE;
2005     ds.front = ds.back;
2006
2007     memset(&ms, 0, sizeof(ms));
2008     ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
2009     ms.pSampleMask = NULL;
2010     ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
2011
2012     demo_prepare_vs(demo);
2013     demo_prepare_fs(demo);
2014
2015     // Two stages: vs and fs
2016     VkPipelineShaderStageCreateInfo shaderStages[2];
2017     memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
2018
2019     shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2020     shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
2021     shaderStages[0].module = demo->vert_shader_module;
2022     shaderStages[0].pName = "main";
2023
2024     shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2025     shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
2026     shaderStages[1].module = demo->frag_shader_module;
2027     shaderStages[1].pName = "main";
2028
2029     memset(&pipelineCache, 0, sizeof(pipelineCache));
2030     pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2031
2032     err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache);
2033     assert(!err);
2034
2035     pipeline.pVertexInputState = &vi;
2036     pipeline.pInputAssemblyState = &ia;
2037     pipeline.pRasterizationState = &rs;
2038     pipeline.pColorBlendState = &cb;
2039     pipeline.pMultisampleState = &ms;
2040     pipeline.pViewportState = &vp;
2041     pipeline.pDepthStencilState = &ds;
2042     pipeline.stageCount = ARRAY_SIZE(shaderStages);
2043     pipeline.pStages = shaderStages;
2044     pipeline.renderPass = demo->render_pass;
2045     pipeline.pDynamicState = &dynamicState;
2046
2047     pipeline.renderPass = demo->render_pass;
2048
2049     err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline);
2050     assert(!err);
2051
2052     vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
2053     vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
2054 }
2055
2056 static void demo_prepare_descriptor_pool(struct demo *demo) {
2057     const VkDescriptorPoolSize type_counts[2] = {
2058         [0] =
2059             {
2060                 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
2061                 .descriptorCount = demo->swapchainImageCount,
2062             },
2063         [1] =
2064             {
2065                 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2066                 .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT,
2067             },
2068     };
2069     const VkDescriptorPoolCreateInfo descriptor_pool = {
2070         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
2071         .pNext = NULL,
2072         .maxSets = demo->swapchainImageCount,
2073         .poolSizeCount = 2,
2074         .pPoolSizes = type_counts,
2075     };
2076     VkResult U_ASSERT_ONLY err;
2077
2078     err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool);
2079     assert(!err);
2080 }
2081
2082 static void demo_prepare_descriptor_set(struct demo *demo) {
2083     VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
2084     VkWriteDescriptorSet writes[2];
2085     VkResult U_ASSERT_ONLY err;
2086
2087     VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
2088                                               .pNext = NULL,
2089                                               .descriptorPool = demo->desc_pool,
2090                                               .descriptorSetCount = 1,
2091                                               .pSetLayouts = &demo->desc_layout};
2092
2093     VkDescriptorBufferInfo buffer_info;
2094     buffer_info.offset = 0;
2095     buffer_info.range = sizeof(struct vktexcube_vs_uniform);
2096
2097     memset(&tex_descs, 0, sizeof(tex_descs));
2098     for (unsigned int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2099         tex_descs[i].sampler = demo->textures[i].sampler;
2100         tex_descs[i].imageView = demo->textures[i].view;
2101         tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
2102     }
2103
2104     memset(&writes, 0, sizeof(writes));
2105
2106     writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
2107     writes[0].descriptorCount = 1;
2108     writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
2109     writes[0].pBufferInfo = &buffer_info;
2110
2111     writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
2112     writes[1].dstBinding = 1;
2113     writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
2114     writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
2115     writes[1].pImageInfo = tex_descs;
2116
2117     for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
2118         err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->swapchain_image_resources[i].descriptor_set);
2119         assert(!err);
2120         buffer_info.buffer = demo->swapchain_image_resources[i].uniform_buffer;
2121         writes[0].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2122         writes[1].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2123         vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
2124     }
2125 }
2126
2127 static void demo_prepare_framebuffers(struct demo *demo) {
2128     VkImageView attachments[2];
2129     attachments[1] = demo->depth.view;
2130
2131     const VkFramebufferCreateInfo fb_info = {
2132         .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
2133         .pNext = NULL,
2134         .renderPass = demo->render_pass,
2135         .attachmentCount = 2,
2136         .pAttachments = attachments,
2137         .width = demo->width,
2138         .height = demo->height,
2139         .layers = 1,
2140     };
2141     VkResult U_ASSERT_ONLY err;
2142     uint32_t i;
2143
2144     for (i = 0; i < demo->swapchainImageCount; i++) {
2145         attachments[0] = demo->swapchain_image_resources[i].view;
2146         err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_image_resources[i].framebuffer);
2147         assert(!err);
2148     }
2149 }
2150
2151 static void demo_prepare(struct demo *demo) {
2152     VkResult U_ASSERT_ONLY err;
2153     if (demo->cmd_pool == VK_NULL_HANDLE) {
2154         const VkCommandPoolCreateInfo cmd_pool_info = {
2155             .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2156             .pNext = NULL,
2157             .queueFamilyIndex = demo->graphics_queue_family_index,
2158             .flags = 0,
2159         };
2160         err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool);
2161         assert(!err);
2162     }
2163
2164     const VkCommandBufferAllocateInfo cmd = {
2165         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2166         .pNext = NULL,
2167         .commandPool = demo->cmd_pool,
2168         .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2169         .commandBufferCount = 1,
2170     };
2171     err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
2172     assert(!err);
2173     VkCommandBufferBeginInfo cmd_buf_info = {
2174         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2175         .pNext = NULL,
2176         .flags = 0,
2177         .pInheritanceInfo = NULL,
2178     };
2179     err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
2180     assert(!err);
2181
2182     demo_prepare_buffers(demo);
2183
2184     if (demo->is_minimized) {
2185         demo->prepared = false;
2186         return;
2187     }
2188
2189     demo_prepare_depth(demo);
2190     demo_prepare_textures(demo);
2191     demo_prepare_cube_data_buffers(demo);
2192
2193     demo_prepare_descriptor_layout(demo);
2194     demo_prepare_render_pass(demo);
2195     demo_prepare_pipeline(demo);
2196
2197     for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2198         err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd);
2199         assert(!err);
2200     }
2201
2202     if (demo->separate_present_queue) {
2203         const VkCommandPoolCreateInfo present_cmd_pool_info = {
2204             .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2205             .pNext = NULL,
2206             .queueFamilyIndex = demo->present_queue_family_index,
2207             .flags = 0,
2208         };
2209         err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool);
2210         assert(!err);
2211         const VkCommandBufferAllocateInfo present_cmd_info = {
2212             .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2213             .pNext = NULL,
2214             .commandPool = demo->present_cmd_pool,
2215             .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2216             .commandBufferCount = 1,
2217         };
2218         for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2219             err = vkAllocateCommandBuffers(demo->device, &present_cmd_info,
2220                                            &demo->swapchain_image_resources[i].graphics_to_present_cmd);
2221             assert(!err);
2222             demo_build_image_ownership_cmd(demo, i);
2223         }
2224     }
2225
2226     demo_prepare_descriptor_pool(demo);
2227     demo_prepare_descriptor_set(demo);
2228
2229     demo_prepare_framebuffers(demo);
2230
2231     for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2232         demo->current_buffer = i;
2233         demo_draw_build_cmd(demo, demo->swapchain_image_resources[i].cmd);
2234     }
2235
2236     /*
2237      * Prepare functions above may generate pipeline commands
2238      * that need to be flushed before beginning the render loop.
2239      */
2240     demo_flush_init_cmd(demo);
2241     if (demo->staging_texture.buffer) {
2242         demo_destroy_texture(demo, &demo->staging_texture);
2243     }
2244
2245     demo->current_buffer = 0;
2246     demo->prepared = true;
2247 }
2248
2249 static void demo_cleanup(struct demo *demo) {
2250     uint32_t i;
2251
2252     demo->prepared = false;
2253     vkDeviceWaitIdle(demo->device);
2254
2255     // Wait for fences from present operations
2256     for (i = 0; i < FRAME_LAG; i++) {
2257         vkWaitForFences(demo->device, 1, &demo->fences[i], VK_TRUE, UINT64_MAX);
2258         vkDestroyFence(demo->device, demo->fences[i], NULL);
2259         vkDestroySemaphore(demo->device, demo->image_acquired_semaphores[i], NULL);
2260         vkDestroySemaphore(demo->device, demo->draw_complete_semaphores[i], NULL);
2261         if (demo->separate_present_queue) {
2262             vkDestroySemaphore(demo->device, demo->image_ownership_semaphores[i], NULL);
2263         }
2264     }
2265
2266     // If the window is currently minimized, demo_resize has already done some cleanup for us.
2267     if (!demo->is_minimized) {
2268         for (i = 0; i < demo->swapchainImageCount; i++) {
2269             vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2270         }
2271         vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
2272
2273         vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2274         vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2275         vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2276         vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2277         vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
2278
2279         for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2280             vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2281             vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2282             vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2283             vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2284         }
2285         demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
2286
2287         vkDestroyImageView(demo->device, demo->depth.view, NULL);
2288         vkDestroyImage(demo->device, demo->depth.image, NULL);
2289         vkFreeMemory(demo->device, demo->depth.mem, NULL);
2290
2291         for (i = 0; i < demo->swapchainImageCount; i++) {
2292             vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2293             vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2294             vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
2295             vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2296         }
2297         free(demo->swapchain_image_resources);
2298         free(demo->queue_props);
2299         vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
2300
2301         if (demo->separate_present_queue) {
2302             vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2303         }
2304     }
2305     vkDeviceWaitIdle(demo->device);
2306     vkDestroyDevice(demo->device, NULL);
2307     if (demo->validate) {
2308         demo->DestroyDebugUtilsMessengerEXT(demo->inst, demo->dbg_messenger, NULL);
2309     }
2310     vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
2311
2312 #if defined(VK_USE_PLATFORM_XLIB_KHR)
2313     XDestroyWindow(demo->display, demo->xlib_window);
2314     XCloseDisplay(demo->display);
2315 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2316     xcb_destroy_window(demo->connection, demo->xcb_window);
2317     xcb_disconnect(demo->connection);
2318     free(demo->atom_wm_delete_window);
2319 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2320     wl_keyboard_destroy(demo->keyboard);
2321     wl_pointer_destroy(demo->pointer);
2322     wl_seat_destroy(demo->seat);
2323     wl_shell_surface_destroy(demo->shell_surface);
2324     wl_surface_destroy(demo->window);
2325     wl_shell_destroy(demo->shell);
2326     wl_compositor_destroy(demo->compositor);
2327     wl_registry_destroy(demo->registry);
2328     wl_display_disconnect(demo->display);
2329 #endif
2330
2331     vkDestroyInstance(demo->inst, NULL);
2332 }
2333
2334 static void demo_resize(struct demo *demo) {
2335     uint32_t i;
2336
2337     // Don't react to resize until after first initialization.
2338     if (!demo->prepared) {
2339         if (demo->is_minimized) {
2340             demo_prepare(demo);
2341         }
2342         return;
2343     }
2344     // In order to properly resize the window, we must re-create the swapchain
2345     // AND redo the command buffers, etc.
2346     //
2347     // First, perform part of the demo_cleanup() function:
2348     demo->prepared = false;
2349     vkDeviceWaitIdle(demo->device);
2350
2351     for (i = 0; i < demo->swapchainImageCount; i++) {
2352         vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2353     }
2354     vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
2355
2356     vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2357     vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2358     vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2359     vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2360     vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
2361
2362     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2363         vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2364         vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2365         vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2366         vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2367     }
2368
2369     vkDestroyImageView(demo->device, demo->depth.view, NULL);
2370     vkDestroyImage(demo->device, demo->depth.image, NULL);
2371     vkFreeMemory(demo->device, demo->depth.mem, NULL);
2372
2373     for (i = 0; i < demo->swapchainImageCount; i++) {
2374         vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2375         vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2376         vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
2377         vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2378     }
2379     vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
2380     demo->cmd_pool = VK_NULL_HANDLE;
2381     if (demo->separate_present_queue) {
2382         vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2383     }
2384     free(demo->swapchain_image_resources);
2385
2386     // Second, re-perform the demo_prepare() function, which will re-create the
2387     // swapchain:
2388     demo_prepare(demo);
2389 }
2390
2391 // On MS-Windows, make this a global, so it's available to WndProc()
2392 struct demo demo;
2393
2394 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2395 static void demo_run(struct demo *demo) {
2396     if (!demo->prepared) return;
2397
2398     demo_draw(demo);
2399     demo->curFrame++;
2400     if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2401         PostQuitMessage(validation_error);
2402     }
2403 }
2404
2405 // MS-Windows event handling function:
2406 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2407     switch (uMsg) {
2408         case WM_CLOSE:
2409             PostQuitMessage(validation_error);
2410             break;
2411         case WM_PAINT:
2412             // The validation callback calls MessageBox which can generate paint
2413             // events - don't make more Vulkan calls if we got here from the
2414             // callback
2415             if (!in_callback) {
2416                 demo_run(&demo);
2417             }
2418             break;
2419         case WM_GETMINMAXINFO:  // set window's minimum size
2420             ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2421             return 0;
2422         case WM_ERASEBKGND:
2423             return 1;
2424         case WM_SIZE:
2425             // Resize the application to the new window size, except when
2426             // it was minimized. Vulkan doesn't support images or swapchains
2427             // with width=0 and height=0.
2428             if (wParam != SIZE_MINIMIZED) {
2429                 demo.width = lParam & 0xffff;
2430                 demo.height = (lParam & 0xffff0000) >> 16;
2431                 demo_resize(&demo);
2432             }
2433             break;
2434         case WM_KEYDOWN:
2435             switch (wParam) {
2436                 case VK_ESCAPE:
2437                     PostQuitMessage(validation_error);
2438                     break;
2439                 case VK_LEFT:
2440                     demo.spin_angle -= demo.spin_increment;
2441                     break;
2442                 case VK_RIGHT:
2443                     demo.spin_angle += demo.spin_increment;
2444                     break;
2445                 case VK_SPACE:
2446                     demo.pause = !demo.pause;
2447                     break;
2448             }
2449             return 0;
2450         default:
2451             break;
2452     }
2453     return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2454 }
2455
2456 static void demo_create_window(struct demo *demo) {
2457     WNDCLASSEX win_class;
2458
2459     // Initialize the window class structure:
2460     win_class.cbSize = sizeof(WNDCLASSEX);
2461     win_class.style = CS_HREDRAW | CS_VREDRAW;
2462     win_class.lpfnWndProc = WndProc;
2463     win_class.cbClsExtra = 0;
2464     win_class.cbWndExtra = 0;
2465     win_class.hInstance = demo->connection;  // hInstance
2466     win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
2467     win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
2468     win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2469     win_class.lpszMenuName = NULL;
2470     win_class.lpszClassName = demo->name;
2471     win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
2472     // Register window class:
2473     if (!RegisterClassEx(&win_class)) {
2474         // It didn't work, so try to give a useful error:
2475         printf("Unexpected error trying to start the application!\n");
2476         fflush(stdout);
2477         exit(1);
2478     }
2479     // Create window with the registered class:
2480     RECT wr = {0, 0, demo->width, demo->height};
2481     AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2482     demo->window = CreateWindowEx(0,
2483                                   demo->name,            // class name
2484                                   demo->name,            // app name
2485                                   WS_OVERLAPPEDWINDOW |  // window style
2486                                       WS_VISIBLE | WS_SYSMENU,
2487                                   100, 100,            // x/y coords
2488                                   wr.right - wr.left,  // width
2489                                   wr.bottom - wr.top,  // height
2490                                   NULL,                // handle to parent
2491                                   NULL,                // handle to menu
2492                                   demo->connection,    // hInstance
2493                                   NULL);               // no extra parameters
2494     if (!demo->window) {
2495         // It didn't work, so try to give a useful error:
2496         printf("Cannot create a window in which to draw!\n");
2497         fflush(stdout);
2498         exit(1);
2499     }
2500     // Window client area size must be at least 1 pixel high, to prevent crash.
2501     demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2502     demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2503 }
2504 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2505 static void demo_create_xlib_window(struct demo *demo) {
2506     const char *display_envar = getenv("DISPLAY");
2507     if (display_envar == NULL || display_envar[0] == '\0') {
2508         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2509         fflush(stdout);
2510         exit(1);
2511     }
2512
2513     XInitThreads();
2514     demo->display = XOpenDisplay(NULL);
2515     long visualMask = VisualScreenMask;
2516     int numberOfVisuals;
2517     XVisualInfo vInfoTemplate = {};
2518     vInfoTemplate.screen = DefaultScreen(demo->display);
2519     XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, &vInfoTemplate, &numberOfVisuals);
2520
2521     Colormap colormap =
2522         XCreateColormap(demo->display, RootWindow(demo->display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2523
2524     XSetWindowAttributes windowAttributes = {};
2525     windowAttributes.colormap = colormap;
2526     windowAttributes.background_pixel = 0xFFFFFFFF;
2527     windowAttributes.border_pixel = 0;
2528     windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2529
2530     demo->xlib_window = XCreateWindow(demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, demo->width,
2531                                       demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual,
2532                                       CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2533
2534     XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask);
2535     XMapWindow(demo->display, demo->xlib_window);
2536     XFlush(demo->display);
2537     demo->xlib_wm_delete_window = XInternAtom(demo->display, "WM_DELETE_WINDOW", False);
2538 }
2539 static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
2540     switch (event->type) {
2541         case ClientMessage:
2542             if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true;
2543             break;
2544         case KeyPress:
2545             switch (event->xkey.keycode) {
2546                 case 0x9:  // Escape
2547                     demo->quit = true;
2548                     break;
2549                 case 0x71:  // left arrow key
2550                     demo->spin_angle -= demo->spin_increment;
2551                     break;
2552                 case 0x72:  // right arrow key
2553                     demo->spin_angle += demo->spin_increment;
2554                     break;
2555                 case 0x41:  // space bar
2556                     demo->pause = !demo->pause;
2557                     break;
2558             }
2559             break;
2560         case ConfigureNotify:
2561             if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) {
2562                 demo->width = event->xconfigure.width;
2563                 demo->height = event->xconfigure.height;
2564                 demo_resize(demo);
2565             }
2566             break;
2567         default:
2568             break;
2569     }
2570 }
2571
2572 static void demo_run_xlib(struct demo *demo) {
2573     while (!demo->quit) {
2574         XEvent event;
2575
2576         if (demo->pause) {
2577             XNextEvent(demo->display, &event);
2578             demo_handle_xlib_event(demo, &event);
2579         }
2580         while (XPending(demo->display) > 0) {
2581             XNextEvent(demo->display, &event);
2582             demo_handle_xlib_event(demo, &event);
2583         }
2584
2585         demo_draw(demo);
2586         demo->curFrame++;
2587         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2588     }
2589 }
2590 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2591 static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) {
2592     uint8_t event_code = event->response_type & 0x7f;
2593     switch (event_code) {
2594         case XCB_EXPOSE:
2595             // TODO: Resize window
2596             break;
2597         case XCB_CLIENT_MESSAGE:
2598             if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) {
2599                 demo->quit = true;
2600             }
2601             break;
2602         case XCB_KEY_RELEASE: {
2603             const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2604
2605             switch (key->detail) {
2606                 case 0x9:  // Escape
2607                     demo->quit = true;
2608                     break;
2609                 case 0x71:  // left arrow key
2610                     demo->spin_angle -= demo->spin_increment;
2611                     break;
2612                 case 0x72:  // right arrow key
2613                     demo->spin_angle += demo->spin_increment;
2614                     break;
2615                 case 0x41:  // space bar
2616                     demo->pause = !demo->pause;
2617                     break;
2618             }
2619         } break;
2620         case XCB_CONFIGURE_NOTIFY: {
2621             const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2622             if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
2623                 demo->width = cfg->width;
2624                 demo->height = cfg->height;
2625                 demo_resize(demo);
2626             }
2627         } break;
2628         default:
2629             break;
2630     }
2631 }
2632
2633 static void demo_run_xcb(struct demo *demo) {
2634     xcb_flush(demo->connection);
2635
2636     while (!demo->quit) {
2637         xcb_generic_event_t *event;
2638
2639         if (demo->pause) {
2640             event = xcb_wait_for_event(demo->connection);
2641         } else {
2642             event = xcb_poll_for_event(demo->connection);
2643         }
2644         while (event) {
2645             demo_handle_xcb_event(demo, event);
2646             free(event);
2647             event = xcb_poll_for_event(demo->connection);
2648         }
2649
2650         demo_draw(demo);
2651         demo->curFrame++;
2652         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2653     }
2654 }
2655
2656 static void demo_create_xcb_window(struct demo *demo) {
2657     uint32_t value_mask, value_list[32];
2658
2659     demo->xcb_window = xcb_generate_id(demo->connection);
2660
2661     value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2662     value_list[0] = demo->screen->black_pixel;
2663     value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2664
2665     xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height,
2666                       0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list);
2667
2668     /* Magic code that will send notification when window is destroyed */
2669     xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
2670     xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0);
2671
2672     xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
2673     demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0);
2674
2675     xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1,
2676                         &(*demo->atom_wm_delete_window).atom);
2677     free(reply);
2678
2679     xcb_map_window(demo->connection, demo->xcb_window);
2680
2681     // Force the x/y coordinates to 100,100 results are identical in consecutive
2682     // runs
2683     const uint32_t coords[] = {100, 100};
2684     xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2685 }
2686 // VK_USE_PLATFORM_XCB_KHR
2687 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2688 static void demo_run(struct demo *demo) {
2689     while (!demo->quit) {
2690         if (demo->pause) {
2691             wl_display_dispatch(demo->display);  // block and wait for input
2692         } else {
2693             wl_display_dispatch_pending(demo->display);  // don't block
2694             demo_draw(demo);
2695             demo->curFrame++;
2696             if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2697         }
2698     }
2699 }
2700
2701 static void handle_ping(void *data UNUSED, struct wl_shell_surface *shell_surface, uint32_t serial) {
2702     wl_shell_surface_pong(shell_surface, serial);
2703 }
2704
2705 static void handle_configure(void *data UNUSED, struct wl_shell_surface *shell_surface UNUSED, uint32_t edges UNUSED,
2706                              int32_t width UNUSED, int32_t height UNUSED) {}
2707
2708 static void handle_popup_done(void *data UNUSED, struct wl_shell_surface *shell_surface UNUSED) {}
2709
2710 static const struct wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
2711
2712 static void demo_create_window(struct demo *demo) {
2713     demo->window = wl_compositor_create_surface(demo->compositor);
2714     if (!demo->window) {
2715         printf("Can not create wayland_surface from compositor!\n");
2716         fflush(stdout);
2717         exit(1);
2718     }
2719
2720     demo->shell_surface = wl_shell_get_shell_surface(demo->shell, demo->window);
2721     if (!demo->shell_surface) {
2722         printf("Can not get shell_surface from wayland_surface!\n");
2723         fflush(stdout);
2724         exit(1);
2725     }
2726     wl_shell_surface_add_listener(demo->shell_surface, &shell_surface_listener, demo);
2727     wl_shell_surface_set_toplevel(demo->shell_surface);
2728     wl_shell_surface_set_title(demo->shell_surface, APP_SHORT_NAME);
2729 }
2730 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
2731 static void demo_run(struct demo *demo) {
2732     if (!demo->prepared) return;
2733
2734     demo_draw(demo);
2735     demo->curFrame++;
2736 }
2737 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
2738 static void demo_run(struct demo *demo) {
2739     demo_draw(demo);
2740     demo->curFrame++;
2741     if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2742         demo->quit = TRUE;
2743     }
2744 }
2745 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2746 static VkResult demo_create_display_surface(struct demo *demo) {
2747     VkResult U_ASSERT_ONLY err;
2748     uint32_t display_count;
2749     uint32_t mode_count;
2750     uint32_t plane_count;
2751     VkDisplayPropertiesKHR display_props;
2752     VkDisplayKHR display;
2753     VkDisplayModePropertiesKHR mode_props;
2754     VkDisplayPlanePropertiesKHR *plane_props;
2755     VkBool32 found_plane = VK_FALSE;
2756     uint32_t plane_index;
2757     VkExtent2D image_extent;
2758     VkDisplaySurfaceCreateInfoKHR create_info;
2759
2760     // Get the first display
2761     err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, NULL);
2762     assert(!err);
2763
2764     if (display_count == 0) {
2765         printf("Cannot find any display!\n");
2766         fflush(stdout);
2767         exit(1);
2768     }
2769
2770     display_count = 1;
2771     err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, &display_props);
2772     assert(!err || (err == VK_INCOMPLETE));
2773
2774     display = display_props.display;
2775
2776     // Get the first mode of the display
2777     err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, NULL);
2778     assert(!err);
2779
2780     if (mode_count == 0) {
2781         printf("Cannot find any mode for the display!\n");
2782         fflush(stdout);
2783         exit(1);
2784     }
2785
2786     mode_count = 1;
2787     err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, &mode_props);
2788     assert(!err || (err == VK_INCOMPLETE));
2789
2790     // Get the list of planes
2791     err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, NULL);
2792     assert(!err);
2793
2794     if (plane_count == 0) {
2795         printf("Cannot find any plane!\n");
2796         fflush(stdout);
2797         exit(1);
2798     }
2799
2800     plane_props = malloc(sizeof(VkDisplayPlanePropertiesKHR) * plane_count);
2801     assert(plane_props);
2802
2803     err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, plane_props);
2804     assert(!err);
2805
2806     // Find a plane compatible with the display
2807     for (plane_index = 0; plane_index < plane_count; plane_index++) {
2808         uint32_t supported_count;
2809         VkDisplayKHR *supported_displays;
2810
2811         // Disqualify planes that are bound to a different display
2812         if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) {
2813             continue;
2814         }
2815
2816         err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, NULL);
2817         assert(!err);
2818
2819         if (supported_count == 0) {
2820             continue;
2821         }
2822
2823         supported_displays = malloc(sizeof(VkDisplayKHR) * supported_count);
2824         assert(supported_displays);
2825
2826         err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, supported_displays);
2827         assert(!err);
2828
2829         for (uint32_t i = 0; i < supported_count; i++) {
2830             if (supported_displays[i] == display) {
2831                 found_plane = VK_TRUE;
2832                 break;
2833             }
2834         }
2835
2836         free(supported_displays);
2837
2838         if (found_plane) {
2839             break;
2840         }
2841     }
2842
2843     if (!found_plane) {
2844         printf("Cannot find a plane compatible with the display!\n");
2845         fflush(stdout);
2846         exit(1);
2847     }
2848
2849     free(plane_props);
2850
2851     VkDisplayPlaneCapabilitiesKHR planeCaps;
2852     vkGetDisplayPlaneCapabilitiesKHR(demo->gpu, mode_props.displayMode, plane_index, &planeCaps);
2853     // Find a supported alpha mode
2854     VkCompositeAlphaFlagBitsKHR alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR;
2855     VkCompositeAlphaFlagBitsKHR alphaModes[4] = {
2856         VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
2857         VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR,
2858         VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR,
2859         VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR,
2860     };
2861     for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2862         if (planeCaps.supportedAlpha & alphaModes[i]) {
2863             alphaMode = alphaModes[i];
2864             break;
2865         }
2866     }
2867     image_extent.width = mode_props.parameters.visibleRegion.width;
2868     image_extent.height = mode_props.parameters.visibleRegion.height;
2869
2870     create_info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR;
2871     create_info.pNext = NULL;
2872     create_info.flags = 0;
2873     create_info.displayMode = mode_props.displayMode;
2874     create_info.planeIndex = plane_index;
2875     create_info.planeStackIndex = plane_props[plane_index].currentStackIndex;
2876     create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
2877     create_info.alphaMode = alphaMode;
2878     create_info.globalAlpha = 1.0f;
2879     create_info.imageExtent = image_extent;
2880
2881     return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface);
2882 }
2883
2884 static void demo_run_display(struct demo *demo) {
2885     while (!demo->quit) {
2886         demo_draw(demo);
2887         demo->curFrame++;
2888
2889         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2890             demo->quit = true;
2891         }
2892     }
2893 }
2894 #endif
2895
2896 /*
2897  * Return 1 (true) if all layer names specified in check_names
2898  * can be found in given layer properties.
2899  */
2900 static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
2901     for (uint32_t i = 0; i < check_count; i++) {
2902         VkBool32 found = 0;
2903         for (uint32_t j = 0; j < layer_count; j++) {
2904             if (!strcmp(check_names[i], layers[j].layerName)) {
2905                 found = 1;
2906                 break;
2907             }
2908         }
2909         if (!found) {
2910             fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
2911             return 0;
2912         }
2913     }
2914     return 1;
2915 }
2916
2917 static void demo_init_vk(struct demo *demo) {
2918     VkResult err;
2919     uint32_t instance_extension_count = 0;
2920     uint32_t instance_layer_count = 0;
2921     uint32_t validation_layer_count = 0;
2922     char **instance_validation_layers = NULL;
2923     demo->enabled_extension_count = 0;
2924     demo->enabled_layer_count = 0;
2925     demo->is_minimized = false;
2926     demo->cmd_pool = VK_NULL_HANDLE;
2927
2928     char *instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"};
2929
2930     char *instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
2931                                                "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation",
2932                                                "VK_LAYER_GOOGLE_unique_objects"};
2933
2934     /* Look for validation layers */
2935     VkBool32 validation_found = 0;
2936     if (demo->validate) {
2937         err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
2938         assert(!err);
2939
2940         instance_validation_layers = instance_validation_layers_alt1;
2941         if (instance_layer_count > 0) {
2942             VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count);
2943             err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
2944             assert(!err);
2945
2946             validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers,
2947                                                  instance_layer_count, instance_layers);
2948             if (validation_found) {
2949                 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
2950                 demo->enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
2951                 validation_layer_count = 1;
2952             } else {
2953                 // use alternative set of validation layers
2954                 instance_validation_layers = instance_validation_layers_alt2;
2955                 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
2956                 validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers,
2957                                                      instance_layer_count, instance_layers);
2958                 validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
2959                 for (uint32_t i = 0; i < validation_layer_count; i++) {
2960                     demo->enabled_layers[i] = instance_validation_layers[i];
2961                 }
2962             }
2963             free(instance_layers);
2964         }
2965
2966         if (!validation_found) {
2967             ERR_EXIT(
2968                 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
2969                 "Please look at the Getting Started guide for additional information.\n",
2970                 "vkCreateInstance Failure");
2971         }
2972     }
2973
2974     /* Look for instance extensions */
2975     VkBool32 surfaceExtFound = 0;
2976     VkBool32 platformSurfaceExtFound = 0;
2977     memset(demo->extension_names, 0, sizeof(demo->extension_names));
2978
2979     err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
2980     assert(!err);
2981
2982     if (instance_extension_count > 0) {
2983         VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
2984         err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
2985         assert(!err);
2986         for (uint32_t i = 0; i < instance_extension_count; i++) {
2987             if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2988                 surfaceExtFound = 1;
2989                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
2990             }
2991 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2992             if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2993                 platformSurfaceExtFound = 1;
2994                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
2995             }
2996 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2997             if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2998                 platformSurfaceExtFound = 1;
2999                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
3000             }
3001 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3002             if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3003                 platformSurfaceExtFound = 1;
3004                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
3005             }
3006 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3007             if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3008                 platformSurfaceExtFound = 1;
3009                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
3010             }
3011 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3012             if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3013                 platformSurfaceExtFound = 1;
3014                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
3015             }
3016 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3017             if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3018                 platformSurfaceExtFound = 1;
3019                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
3020             }
3021 #elif defined(VK_USE_PLATFORM_IOS_MVK)
3022             if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3023                 platformSurfaceExtFound = 1;
3024                 demo->extension_names[demo->enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
3025             }
3026 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
3027             if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3028                 platformSurfaceExtFound = 1;
3029                 demo->extension_names[demo->enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
3030             }
3031 #endif
3032             if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3033                 if (demo->validate) {
3034                     demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
3035                 }
3036             }
3037             assert(demo->enabled_extension_count < 64);
3038         }
3039
3040         free(instance_extensions);
3041     }
3042
3043     if (!surfaceExtFound) {
3044         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
3045                  " extension.\n\n"
3046                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3047                  "Please look at the Getting Started guide for additional information.\n",
3048                  "vkCreateInstance Failure");
3049     }
3050     if (!platformSurfaceExtFound) {
3051 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3052         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
3053                  " extension.\n\n"
3054                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3055                  "Please look at the Getting Started guide for additional information.\n",
3056                  "vkCreateInstance Failure");
3057 #elif defined(VK_USE_PLATFORM_IOS_MVK)
3058         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
3059                  " extension.\n\n"
3060                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3061                  "Please look at the Getting Started guide for additional information.\n",
3062                  "vkCreateInstance Failure");
3063 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
3064         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
3065                  " extension.\n\n"
3066                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3067                  "Please look at the Getting Started guide for additional information.\n",
3068                  "vkCreateInstance Failure");
3069 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3070         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
3071                  " extension.\n\n"
3072                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3073                  "Please look at the Getting Started guide for additional information.\n",
3074                  "vkCreateInstance Failure");
3075 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3076         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
3077                  " extension.\n\n"
3078                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3079                  "Please look at the Getting Started guide for additional information.\n",
3080                  "vkCreateInstance Failure");
3081 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3082         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
3083                  " extension.\n\n"
3084                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3085                  "Please look at the Getting Started guide for additional information.\n",
3086                  "vkCreateInstance Failure");
3087 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3088         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
3089                  " extension.\n\n"
3090                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3091                  "Please look at the Getting Started guide for additional information.\n",
3092                  "vkCreateInstance Failure");
3093 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3094         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
3095                  " extension.\n\n"
3096                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3097                  "Please look at the Getting Started guide for additional information.\n",
3098                  "vkCreateInstance Failure");
3099 #endif
3100     }
3101     const VkApplicationInfo app = {
3102         .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
3103         .pNext = NULL,
3104         .pApplicationName = APP_SHORT_NAME,
3105         .applicationVersion = 0,
3106         .pEngineName = APP_SHORT_NAME,
3107         .engineVersion = 0,
3108         .apiVersion = VK_API_VERSION_1_0,
3109     };
3110     VkInstanceCreateInfo inst_info = {
3111         .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
3112         .pNext = NULL,
3113         .pApplicationInfo = &app,
3114         .enabledLayerCount = demo->enabled_layer_count,
3115         .ppEnabledLayerNames = (const char *const *)instance_validation_layers,
3116         .enabledExtensionCount = demo->enabled_extension_count,
3117         .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
3118     };
3119
3120     /*
3121      * This is info for a temp callback to use during CreateInstance.
3122      * After the instance is created, we use the instance-based
3123      * function to register the final callback.
3124      */
3125     VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
3126     if (demo->validate) {
3127         // VK_EXT_debug_utils style
3128         dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
3129         dbg_messenger_create_info.pNext = NULL;
3130         dbg_messenger_create_info.flags = 0;
3131         dbg_messenger_create_info.messageSeverity =
3132             VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
3133         dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
3134                                                 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
3135                                                 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
3136         dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
3137         dbg_messenger_create_info.pUserData = demo;
3138         inst_info.pNext = &dbg_messenger_create_info;
3139     }
3140
3141     uint32_t gpu_count;
3142
3143     err = vkCreateInstance(&inst_info, NULL, &demo->inst);
3144     if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
3145         ERR_EXIT(
3146             "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
3147             "Please look at the Getting Started guide for additional information.\n",
3148             "vkCreateInstance Failure");
3149     } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
3150         ERR_EXIT(
3151             "Cannot find a specified extension library.\n"
3152             "Make sure your layers path is set appropriately.\n",
3153             "vkCreateInstance Failure");
3154     } else if (err) {
3155         ERR_EXIT(
3156             "vkCreateInstance failed.\n\n"
3157             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3158             "Please look at the Getting Started guide for additional information.\n",
3159             "vkCreateInstance Failure");
3160     }
3161
3162     /* Make initial call to query gpu_count, then second call for gpu info*/
3163     err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
3164     assert(!err);
3165
3166     if (gpu_count > 0) {
3167         VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
3168         err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
3169         assert(!err);
3170         /* For cube demo we just grab the first physical device */
3171         demo->gpu = physical_devices[0];
3172         free(physical_devices);
3173     } else {
3174         ERR_EXIT(
3175             "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
3176             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3177             "Please look at the Getting Started guide for additional information.\n",
3178             "vkEnumeratePhysicalDevices Failure");
3179     }
3180
3181     /* Look for device extensions */
3182     uint32_t device_extension_count = 0;
3183     VkBool32 swapchainExtFound = 0;
3184     demo->enabled_extension_count = 0;
3185     memset(demo->extension_names, 0, sizeof(demo->extension_names));
3186
3187     err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL);
3188     assert(!err);
3189
3190     if (device_extension_count > 0) {
3191         VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count);
3192         err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions);
3193         assert(!err);
3194
3195         for (uint32_t i = 0; i < device_extension_count; i++) {
3196             if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
3197                 swapchainExtFound = 1;
3198                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
3199             }
3200             assert(demo->enabled_extension_count < 64);
3201         }
3202
3203         if (demo->VK_KHR_incremental_present_enabled) {
3204             // Even though the user "enabled" the extension via the command
3205             // line, we must make sure that it's enumerated for use with the
3206             // device.  Therefore, disable it here, and re-enable it again if
3207             // enumerated.
3208             demo->VK_KHR_incremental_present_enabled = false;
3209             for (uint32_t i = 0; i < device_extension_count; i++) {
3210                 if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
3211                     demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
3212                     demo->VK_KHR_incremental_present_enabled = true;
3213                     DbgMsg("VK_KHR_incremental_present extension enabled\n");
3214                 }
3215                 assert(demo->enabled_extension_count < 64);
3216             }
3217             if (!demo->VK_KHR_incremental_present_enabled) {
3218                 DbgMsg("VK_KHR_incremental_present extension NOT AVAILABLE\n");
3219             }
3220         }
3221
3222         if (demo->VK_GOOGLE_display_timing_enabled) {
3223             // Even though the user "enabled" the extension via the command
3224             // line, we must make sure that it's enumerated for use with the
3225             // device.  Therefore, disable it here, and re-enable it again if
3226             // enumerated.
3227             demo->VK_GOOGLE_display_timing_enabled = false;
3228             for (uint32_t i = 0; i < device_extension_count; i++) {
3229                 if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
3230                     demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
3231                     demo->VK_GOOGLE_display_timing_enabled = true;
3232                     DbgMsg("VK_GOOGLE_display_timing extension enabled\n");
3233                 }
3234                 assert(demo->enabled_extension_count < 64);
3235             }
3236             if (!demo->VK_GOOGLE_display_timing_enabled) {
3237                 DbgMsg("VK_GOOGLE_display_timing extension NOT AVAILABLE\n");
3238             }
3239         }
3240
3241         free(device_extensions);
3242     }
3243
3244     if (!swapchainExtFound) {
3245         ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
3246                  " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
3247                  "Please look at the Getting Started guide for additional information.\n",
3248                  "vkCreateInstance Failure");
3249     }
3250
3251     if (demo->validate) {
3252         // Setup VK_EXT_debug_utils function pointers always (we use them for
3253         // debug labels and names).
3254         demo->CreateDebugUtilsMessengerEXT =
3255             (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkCreateDebugUtilsMessengerEXT");
3256         demo->DestroyDebugUtilsMessengerEXT =
3257             (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugUtilsMessengerEXT");
3258         demo->SubmitDebugUtilsMessageEXT =
3259             (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(demo->inst, "vkSubmitDebugUtilsMessageEXT");
3260         demo->CmdBeginDebugUtilsLabelEXT =
3261             (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdBeginDebugUtilsLabelEXT");
3262         demo->CmdEndDebugUtilsLabelEXT =
3263             (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdEndDebugUtilsLabelEXT");
3264         demo->CmdInsertDebugUtilsLabelEXT =
3265             (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdInsertDebugUtilsLabelEXT");
3266         demo->SetDebugUtilsObjectNameEXT =
3267             (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(demo->inst, "vkSetDebugUtilsObjectNameEXT");
3268         if (NULL == demo->CreateDebugUtilsMessengerEXT || NULL == demo->DestroyDebugUtilsMessengerEXT ||
3269             NULL == demo->SubmitDebugUtilsMessageEXT || NULL == demo->CmdBeginDebugUtilsLabelEXT ||
3270             NULL == demo->CmdEndDebugUtilsLabelEXT || NULL == demo->CmdInsertDebugUtilsLabelEXT ||
3271             NULL == demo->SetDebugUtilsObjectNameEXT) {
3272             ERR_EXIT("GetProcAddr: Failed to init VK_EXT_debug_utils\n", "GetProcAddr: Failure");
3273         }
3274
3275         err = demo->CreateDebugUtilsMessengerEXT(demo->inst, &dbg_messenger_create_info, NULL, &demo->dbg_messenger);
3276         switch (err) {
3277             case VK_SUCCESS:
3278                 break;
3279             case VK_ERROR_OUT_OF_HOST_MEMORY:
3280                 ERR_EXIT("CreateDebugUtilsMessengerEXT: out of host memory\n", "CreateDebugUtilsMessengerEXT Failure");
3281                 break;
3282             default:
3283                 ERR_EXIT("CreateDebugUtilsMessengerEXT: unknown failure\n", "CreateDebugUtilsMessengerEXT Failure");
3284                 break;
3285         }
3286     }
3287     vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
3288
3289     /* Call with NULL data to get count */
3290     vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL);
3291     assert(demo->queue_family_count >= 1);
3292
3293     demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties));
3294     vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props);
3295
3296     // Query fine-grained feature support for this device.
3297     //  If app has specific feature requirements it should check supported
3298     //  features based on this query
3299     VkPhysicalDeviceFeatures physDevFeatures;
3300     vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
3301
3302     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR);
3303     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
3304     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR);
3305     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR);
3306     GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR);
3307 }
3308
3309 static void demo_create_device(struct demo *demo) {
3310     VkResult U_ASSERT_ONLY err;
3311     float queue_priorities[1] = {0.0};
3312     VkDeviceQueueCreateInfo queues[2];
3313     queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3314     queues[0].pNext = NULL;
3315     queues[0].queueFamilyIndex = demo->graphics_queue_family_index;
3316     queues[0].queueCount = 1;
3317     queues[0].pQueuePriorities = queue_priorities;
3318     queues[0].flags = 0;
3319
3320     VkDeviceCreateInfo device = {
3321         .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
3322         .pNext = NULL,
3323         .queueCreateInfoCount = 1,
3324         .pQueueCreateInfos = queues,
3325         .enabledLayerCount = 0,
3326         .ppEnabledLayerNames = NULL,
3327         .enabledExtensionCount = demo->enabled_extension_count,
3328         .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
3329         .pEnabledFeatures = NULL,  // If specific features are required, pass them in here
3330     };
3331     if (demo->separate_present_queue) {
3332         queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3333         queues[1].pNext = NULL;
3334         queues[1].queueFamilyIndex = demo->present_queue_family_index;
3335         queues[1].queueCount = 1;
3336         queues[1].pQueuePriorities = queue_priorities;
3337         queues[1].flags = 0;
3338         device.queueCreateInfoCount = 2;
3339     }
3340     err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
3341     assert(!err);
3342 }
3343
3344 static void demo_init_vk_swapchain(struct demo *demo) {
3345     VkResult U_ASSERT_ONLY err;
3346
3347 // Create a WSI surface for the window:
3348 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3349     VkWin32SurfaceCreateInfoKHR createInfo;
3350     createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
3351     createInfo.pNext = NULL;
3352     createInfo.flags = 0;
3353     createInfo.hinstance = demo->connection;
3354     createInfo.hwnd = demo->window;
3355
3356     err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3357 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3358     VkWaylandSurfaceCreateInfoKHR createInfo;
3359     createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
3360     createInfo.pNext = NULL;
3361     createInfo.flags = 0;
3362     createInfo.display = demo->display;
3363     createInfo.surface = demo->window;
3364
3365     err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3366 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3367     VkAndroidSurfaceCreateInfoKHR createInfo;
3368     createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
3369     createInfo.pNext = NULL;
3370     createInfo.flags = 0;
3371     createInfo.window = (struct ANativeWindow *)(demo->window);
3372
3373     err = vkCreateAndroidSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3374 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3375     VkXlibSurfaceCreateInfoKHR createInfo;
3376     createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
3377     createInfo.pNext = NULL;
3378     createInfo.flags = 0;
3379     createInfo.dpy = demo->display;
3380     createInfo.window = demo->xlib_window;
3381
3382     err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3383 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3384     VkXcbSurfaceCreateInfoKHR createInfo;
3385     createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
3386     createInfo.pNext = NULL;
3387     createInfo.flags = 0;
3388     createInfo.connection = demo->connection;
3389     createInfo.window = demo->xcb_window;
3390
3391     err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3392 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3393     err = demo_create_display_surface(demo);
3394 #elif defined(VK_USE_PLATFORM_IOS_MVK)
3395     VkIOSSurfaceCreateInfoMVK surface;
3396     surface.sType = VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK;
3397     surface.pNext = NULL;
3398     surface.flags = 0;
3399     surface.pView = demo->window;
3400
3401     err = vkCreateIOSSurfaceMVK(demo->inst, &surface, NULL, &demo->surface);
3402 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
3403     VkMacOSSurfaceCreateInfoMVK surface;
3404     surface.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
3405     surface.pNext = NULL;
3406     surface.flags = 0;
3407     surface.pView = demo->window;
3408
3409     err = vkCreateMacOSSurfaceMVK(demo->inst, &surface, NULL, &demo->surface);
3410 #endif
3411     assert(!err);
3412
3413     // Iterate over each queue to learn whether it supports presenting:
3414     VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32));
3415     for (uint32_t i = 0; i < demo->queue_family_count; i++) {
3416         demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]);
3417     }
3418
3419     // Search for a graphics and a present queue in the array of queue
3420     // families, try to find one that supports both
3421     uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
3422     uint32_t presentQueueFamilyIndex = UINT32_MAX;
3423     for (uint32_t i = 0; i < demo->queue_family_count; i++) {
3424         if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
3425             if (graphicsQueueFamilyIndex == UINT32_MAX) {
3426                 graphicsQueueFamilyIndex = i;
3427             }
3428
3429             if (supportsPresent[i] == VK_TRUE) {
3430                 graphicsQueueFamilyIndex = i;
3431                 presentQueueFamilyIndex = i;
3432                 break;
3433             }
3434         }
3435     }
3436
3437     if (presentQueueFamilyIndex == UINT32_MAX) {
3438         // If didn't find a queue that supports both graphics and present, then
3439         // find a separate present queue.
3440         for (uint32_t i = 0; i < demo->queue_family_count; ++i) {
3441             if (supportsPresent[i] == VK_TRUE) {
3442                 presentQueueFamilyIndex = i;
3443                 break;
3444             }
3445         }
3446     }
3447
3448     // Generate error if could not find both a graphics and a present queue
3449     if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
3450         ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
3451     }
3452
3453     demo->graphics_queue_family_index = graphicsQueueFamilyIndex;
3454     demo->present_queue_family_index = presentQueueFamilyIndex;
3455     demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index);
3456     free(supportsPresent);
3457
3458     demo_create_device(demo);
3459
3460     GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR);
3461     GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR);
3462     GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR);
3463     GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR);
3464     GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR);
3465     if (demo->VK_GOOGLE_display_timing_enabled) {
3466         GET_DEVICE_PROC_ADDR(demo->device, GetRefreshCycleDurationGOOGLE);
3467         GET_DEVICE_PROC_ADDR(demo->device, GetPastPresentationTimingGOOGLE);
3468     }
3469
3470     vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue);
3471
3472     if (!demo->separate_present_queue) {
3473         demo->present_queue = demo->graphics_queue;
3474     } else {
3475         vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue);
3476     }
3477
3478     // Get the list of VkFormat's that are supported:
3479     uint32_t formatCount;
3480     err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL);
3481     assert(!err);
3482     VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
3483     err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats);
3484     assert(!err);
3485     // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
3486     // the surface has no preferred format.  Otherwise, at least one
3487     // supported format will be returned.
3488     if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
3489         demo->format = VK_FORMAT_B8G8R8A8_UNORM;
3490     } else {
3491         assert(formatCount >= 1);
3492         demo->format = surfFormats[0].format;
3493     }
3494     demo->color_space = surfFormats[0].colorSpace;
3495
3496     demo->quit = false;
3497     demo->curFrame = 0;
3498
3499     // Create semaphores to synchronize acquiring presentable buffers before
3500     // rendering and waiting for drawing to be complete before presenting
3501     VkSemaphoreCreateInfo semaphoreCreateInfo = {
3502         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
3503         .pNext = NULL,
3504         .flags = 0,
3505     };
3506
3507     // Create fences that we can use to throttle if we get too far
3508     // ahead of the image presents
3509     VkFenceCreateInfo fence_ci = {
3510         .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT};
3511     for (uint32_t i = 0; i < FRAME_LAG; i++) {
3512         err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->fences[i]);
3513         assert(!err);
3514
3515         err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_acquired_semaphores[i]);
3516         assert(!err);
3517
3518         err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->draw_complete_semaphores[i]);
3519         assert(!err);
3520
3521         if (demo->separate_present_queue) {
3522             err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_ownership_semaphores[i]);
3523             assert(!err);
3524         }
3525     }
3526     demo->frame_index = 0;
3527
3528     // Get Memory information and properties
3529     vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
3530 }
3531
3532 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
3533 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
3534                                  wl_fixed_t sy) {}
3535
3536 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
3537
3538 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
3539
3540 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
3541                                   uint32_t state) {
3542     struct demo *demo = data;
3543     if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
3544         wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
3545     }
3546 }
3547
3548 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
3549
3550 static const struct wl_pointer_listener pointer_listener = {
3551     pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
3552 };
3553
3554 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
3555
3556 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
3557                                   struct wl_array *keys) {}
3558
3559 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
3560
3561 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
3562                                 uint32_t state) {
3563     if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
3564     struct demo *demo = data;
3565     switch (key) {
3566         case KEY_ESC:  // Escape
3567             demo->quit = true;
3568             break;
3569         case KEY_LEFT:  // left arrow key
3570             demo->spin_angle -= demo->spin_increment;
3571             break;
3572         case KEY_RIGHT:  // right arrow key
3573             demo->spin_angle += demo->spin_increment;
3574             break;
3575         case KEY_SPACE:  // space bar
3576             demo->pause = !demo->pause;
3577             break;
3578     }
3579 }
3580
3581 static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
3582                                       uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
3583
3584 static const struct wl_keyboard_listener keyboard_listener = {
3585     keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
3586 };
3587
3588 static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) {
3589     // Subscribe to pointer events
3590     struct demo *demo = data;
3591     if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
3592         demo->pointer = wl_seat_get_pointer(seat);
3593         wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
3594     } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
3595         wl_pointer_destroy(demo->pointer);
3596         demo->pointer = NULL;
3597     }
3598     // Subscribe to keyboard events
3599     if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
3600         demo->keyboard = wl_seat_get_keyboard(seat);
3601         wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
3602     } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
3603         wl_keyboard_destroy(demo->keyboard);
3604         demo->keyboard = NULL;
3605     }
3606 }
3607
3608 static const struct wl_seat_listener seat_listener = {
3609     seat_handle_capabilities,
3610 };
3611
3612 static void registry_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface,
3613                                    uint32_t version UNUSED) {
3614     struct demo *demo = data;
3615     // pickup wayland objects when they appear
3616     if (strcmp(interface, "wl_compositor") == 0) {
3617         demo->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, 1);
3618     } else if (strcmp(interface, "wl_shell") == 0) {
3619         demo->shell = wl_registry_bind(registry, id, &wl_shell_interface, 1);
3620     } else if (strcmp(interface, "wl_seat") == 0) {
3621         demo->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
3622         wl_seat_add_listener(demo->seat, &seat_listener, demo);
3623     }
3624 }
3625
3626 static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {}
3627
3628 static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
3629 #endif
3630
3631 static void demo_init_connection(struct demo *demo) {
3632 #if defined(VK_USE_PLATFORM_XCB_KHR)
3633     const xcb_setup_t *setup;
3634     xcb_screen_iterator_t iter;
3635     int scr;
3636
3637     const char *display_envar = getenv("DISPLAY");
3638     if (display_envar == NULL || display_envar[0] == '\0') {
3639         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
3640         fflush(stdout);
3641         exit(1);
3642     }
3643
3644     demo->connection = xcb_connect(NULL, &scr);
3645     if (xcb_connection_has_error(demo->connection) > 0) {
3646         printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
3647         fflush(stdout);
3648         exit(1);
3649     }
3650
3651     setup = xcb_get_setup(demo->connection);
3652     iter = xcb_setup_roots_iterator(setup);
3653     while (scr-- > 0) xcb_screen_next(&iter);
3654
3655     demo->screen = iter.data;
3656 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3657     demo->display = wl_display_connect(NULL);
3658
3659     if (demo->display == NULL) {
3660         printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
3661         fflush(stdout);
3662         exit(1);
3663     }
3664
3665     demo->registry = wl_display_get_registry(demo->display);
3666     wl_registry_add_listener(demo->registry, &registry_listener, demo);
3667     wl_display_dispatch(demo->display);
3668 #endif
3669 }
3670
3671 static void demo_init(struct demo *demo, int argc, char **argv) {
3672     vec3 eye = {0.0f, 3.0f, 5.0f};
3673     vec3 origin = {0, 0, 0};
3674     vec3 up = {0.0f, 1.0f, 0.0};
3675
3676     memset(demo, 0, sizeof(*demo));
3677     demo->presentMode = VK_PRESENT_MODE_FIFO_KHR;
3678     demo->frameCount = INT32_MAX;
3679
3680     for (int i = 1; i < argc; i++) {
3681         if (strcmp(argv[i], "--use_staging") == 0) {
3682             demo->use_staging_buffer = true;
3683             continue;
3684         }
3685         if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
3686             demo->presentMode = atoi(argv[i + 1]);
3687             i++;
3688             continue;
3689         }
3690         if (strcmp(argv[i], "--break") == 0) {
3691             demo->use_break = true;
3692             continue;
3693         }
3694         if (strcmp(argv[i], "--validate") == 0) {
3695             demo->validate = true;
3696             continue;
3697         }
3698         if (strcmp(argv[i], "--validate-checks-disabled") == 0) {
3699             demo->validate = true;
3700             demo->validate_checks_disabled = true;
3701             continue;
3702         }
3703         if (strcmp(argv[i], "--xlib") == 0) {
3704             fprintf(stderr, "--xlib is deprecated and no longer does anything");
3705             continue;
3706         }
3707         if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 &&
3708             sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) {
3709             i++;
3710             continue;
3711         }
3712         if (strcmp(argv[i], "--suppress_popups") == 0) {
3713             demo->suppress_popups = true;
3714             continue;
3715         }
3716         if (strcmp(argv[i], "--display_timing") == 0) {
3717             demo->VK_GOOGLE_display_timing_enabled = true;
3718             continue;
3719         }
3720         if (strcmp(argv[i], "--incremental_present") == 0) {
3721             demo->VK_KHR_incremental_present_enabled = true;
3722             continue;
3723         }
3724
3725 #if defined(ANDROID)
3726         ERR_EXIT("Usage: vkcube [--validate]\n", "Usage");
3727 #else
3728         fprintf(stderr,
3729                 "Usage:\n  %s\t[--use_staging] [--validate] [--validate-checks-disabled] [--break]\n"
3730                 "\t[--c <framecount>] [--suppress_popups] [--incremental_present] [--display_timing]\n"
3731                 "\t[--present_mode <present mode enum>]\n"
3732                 "\t <present_mode_enum>\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
3733                 "\t\t\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
3734                 "\t\t\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
3735                 "\t\t\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n",
3736                 APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
3737                 VK_PRESENT_MODE_FIFO_RELAXED_KHR);
3738         fflush(stderr);
3739         exit(1);
3740 #endif
3741     }
3742
3743     demo_init_connection(demo);
3744
3745     demo_init_vk(demo);
3746
3747     demo->width = 500;
3748     demo->height = 500;
3749
3750     demo->spin_angle = 4.0f;
3751     demo->spin_increment = 0.2f;
3752     demo->pause = false;
3753
3754     mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
3755     mat4x4_look_at(demo->view_matrix, eye, origin, up);
3756     mat4x4_identity(demo->model_matrix);
3757
3758     demo->projection_matrix[1][1] *= -1;  // Flip projection matrix from GL to Vulkan orientation.
3759 }
3760
3761 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3762 // Include header required for parsing the command line options.
3763 #include <shellapi.h>
3764
3765 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
3766     MSG msg;    // message
3767     bool done;  // flag saying when app is complete
3768     int argc;
3769     char **argv;
3770
3771     // Ensure wParam is initialized.
3772     msg.wParam = 0;
3773
3774     // Use the CommandLine functions to get the command line arguments.
3775     // Unfortunately, Microsoft outputs
3776     // this information as wide characters for Unicode, and we simply want the
3777     // Ascii version to be compatible
3778     // with the non-Windows side.  So, we have to convert the information to
3779     // Ascii character strings.
3780     LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3781     if (NULL == commandLineArgs) {
3782         argc = 0;
3783     }
3784
3785     if (argc > 0) {
3786         argv = (char **)malloc(sizeof(char *) * argc);
3787         if (argv == NULL) {
3788             argc = 0;
3789         } else {
3790             for (int iii = 0; iii < argc; iii++) {
3791                 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3792                 size_t numConverted = 0;
3793
3794                 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3795                 if (argv[iii] != NULL) {
3796                     wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3797                 }
3798             }
3799         }
3800     } else {
3801         argv = NULL;
3802     }
3803
3804     demo_init(&demo, argc, argv);
3805
3806     // Free up the items we had to allocate for the command line arguments.
3807     if (argc > 0 && argv != NULL) {
3808         for (int iii = 0; iii < argc; iii++) {
3809             if (argv[iii] != NULL) {
3810                 free(argv[iii]);
3811             }
3812         }
3813         free(argv);
3814     }
3815
3816     demo.connection = hInstance;
3817     strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
3818     demo_create_window(&demo);
3819     demo_init_vk_swapchain(&demo);
3820
3821     demo_prepare(&demo);
3822
3823     done = false;  // initialize loop condition variable
3824
3825     // main message loop
3826     while (!done) {
3827         if (demo.pause) {
3828             const BOOL succ = WaitMessage();
3829
3830             if (!succ) {
3831                 struct demo *tmp = &demo;
3832                 struct demo *demo = tmp;
3833                 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3834             }
3835         }
3836         PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
3837         if (msg.message == WM_QUIT)  // check for a quit message
3838         {
3839             done = true;  // if found, quit app
3840         } else {
3841             /* Translate and dispatch to event queue*/
3842             TranslateMessage(&msg);
3843             DispatchMessage(&msg);
3844         }
3845         RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
3846     }
3847
3848     demo_cleanup(&demo);
3849
3850     return (int)msg.wParam;
3851 }
3852
3853 #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3854 static void demo_main(struct demo *demo, void *view, int argc, const char *argv[]) {
3855
3856     demo_init(demo, argc, (char **)argv);
3857     demo->window = view;
3858     demo_init_vk_swapchain(demo);
3859     demo_prepare(demo);
3860     demo->spin_angle = 0.4f;
3861 }
3862
3863 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3864 #include <android/log.h>
3865 #include <android_native_app_glue.h>
3866 #include "android_util.h"
3867
3868 static bool initialized = false;
3869 static bool active = false;
3870 struct demo demo;
3871
3872 static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
3873
3874 static void processCommand(struct android_app *app, int32_t cmd) {
3875     switch (cmd) {
3876         case APP_CMD_INIT_WINDOW: {
3877             if (app->window) {
3878                 // We're getting a new window.  If the app is starting up, we
3879                 // need to initialize.  If the app has already been
3880                 // initialized, that means that we lost our previous window,
3881                 // which means that we have a lot of work to do.  At a minimum,
3882                 // we need to destroy the swapchain and surface associated with
3883                 // the old window, and create a new surface and swapchain.
3884                 // However, since there are a lot of other objects/state that
3885                 // is tied to the swapchain, it's easiest to simply cleanup and
3886                 // start over (i.e. use a brute-force approach of re-starting
3887                 // the app)
3888                 if (demo.prepared) {
3889                     demo_cleanup(&demo);
3890                 }
3891
3892                 // Parse Intents into argc, argv
3893                 // Use the following key to send arguments, i.e.
3894                 // --es args "--validate"
3895                 const char key[] = "args";
3896                 char *appTag = (char *)APP_SHORT_NAME;
3897                 int argc = 0;
3898                 char **argv = get_args(app, key, appTag, &argc);
3899
3900                 __android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc);
3901                 for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]);
3902
3903                 demo_init(&demo, argc, argv);
3904
3905                 // Free the argv malloc'd by get_args
3906                 for (int i = 0; i < argc; i++) free(argv[i]);
3907
3908                 demo.window = (void *)app->window;
3909                 demo_init_vk_swapchain(&demo);
3910                 demo_prepare(&demo);
3911                 initialized = true;
3912             }
3913             break;
3914         }
3915         case APP_CMD_GAINED_FOCUS: {
3916             active = true;
3917             break;
3918         }
3919         case APP_CMD_LOST_FOCUS: {
3920             active = false;
3921             break;
3922         }
3923     }
3924 }
3925
3926 void android_main(struct android_app *app) {
3927 #ifdef ANDROID
3928     int vulkanSupport = InitVulkan();
3929     if (vulkanSupport == 0) return;
3930 #endif
3931
3932     demo.prepared = false;
3933
3934     app->onAppCmd = processCommand;
3935     app->onInputEvent = processInput;
3936
3937     while (1) {
3938         int events;
3939         struct android_poll_source *source;
3940         while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
3941             if (source) {
3942                 source->process(app, source);
3943             }
3944
3945             if (app->destroyRequested != 0) {
3946                 demo_cleanup(&demo);
3947                 return;
3948             }
3949         }
3950         if (initialized && active) {
3951             demo_run(&demo);
3952         }
3953     }
3954 }
3955 #else
3956 int main(int argc, char **argv) {
3957     struct demo demo;
3958
3959     demo_init(&demo, argc, argv);
3960 #if defined(VK_USE_PLATFORM_XCB_KHR)
3961     demo_create_xcb_window(&demo);
3962 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3963     demo_create_xlib_window(&demo);
3964 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3965     demo_create_window(&demo);
3966 #endif
3967
3968     demo_init_vk_swapchain(&demo);
3969
3970     demo_prepare(&demo);
3971
3972 #if defined(VK_USE_PLATFORM_XCB_KHR)
3973     demo_run_xcb(&demo);
3974 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3975     demo_run_xlib(&demo);
3976 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3977     demo_run(&demo);
3978 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3979     demo_run_display(&demo);
3980 #endif
3981
3982     demo_cleanup(&demo);
3983
3984     return validation_error;
3985 }
3986 #endif