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