cube: Port Wayland impl from wl-shell to xdg-shell
[platform/upstream/Vulkan-Tools.git] / cube / cube.cpp
1 /*
2  * Copyright (c) 2015-2019 The Khronos Group Inc.
3  * Copyright (c) 2015-2019 Valve Corporation
4  * Copyright (c) 2015-2019 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: Jeremy Hayes <jeremy@lunarg.com>
19  */
20
21 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
22 #include <X11/Xutil.h>
23 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
24 #include <linux/input.h>
25 #include "xdg-shell-client-header.h"
26 #include "xdg-decoration-client-header.h"
27 #endif
28
29 #include <cassert>
30 #include <cinttypes>
31 #include <cstdio>
32 #include <cstdlib>
33 #include <cstring>
34 #include <csignal>
35 #include <iostream>
36 #include <sstream>
37 #include <memory>
38
39 #define VULKAN_HPP_NO_SMART_HANDLE
40 #define VULKAN_HPP_NO_EXCEPTIONS
41 #define VULKAN_HPP_TYPESAFE_CONVERSION
42 #include <vulkan/vulkan.hpp>
43 #include <vulkan/vk_sdk_platform.h>
44
45 #include "linmath.h"
46
47 #ifndef NDEBUG
48 #define VERIFY(x) assert(x)
49 #else
50 #define VERIFY(x) ((void)(x))
51 #endif
52
53 #define APP_SHORT_NAME "vkcube"
54 #ifdef _WIN32
55 #define APP_NAME_STR_LEN 80
56 #endif
57
58 // Allow a maximum of two outstanding presentation operations.
59 #define FRAME_LAG 2
60
61 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
62
63 #ifdef _WIN32
64 #define ERR_EXIT(err_msg, err_class)                                          \
65     do {                                                                      \
66         if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
67         exit(1);                                                              \
68     } while (0)
69 #else
70 #define ERR_EXIT(err_msg, err_class) \
71     do {                             \
72         printf("%s\n", err_msg);     \
73         fflush(stdout);              \
74         exit(1);                     \
75     } while (0)
76 #endif
77
78 struct texture_object {
79     vk::Sampler sampler;
80
81     vk::Image image;
82     vk::Buffer buffer;
83     vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
84
85     vk::MemoryAllocateInfo mem_alloc;
86     vk::DeviceMemory mem;
87     vk::ImageView view;
88
89     int32_t tex_width{0};
90     int32_t tex_height{0};
91 };
92
93 static char const *const tex_files[] = {"lunarg.ppm"};
94
95 static int validation_error = 0;
96
97 struct vkcube_vs_uniform {
98     // Must start with MVP
99     float mvp[4][4];
100     float position[12 * 3][4];
101     float color[12 * 3][4];
102 };
103
104 struct vktexcube_vs_uniform {
105     // Must start with MVP
106     float mvp[4][4];
107     float position[12 * 3][4];
108     float attr[12 * 3][4];
109 };
110
111 //--------------------------------------------------------------------------------------
112 // Mesh and VertexFormat Data
113 //--------------------------------------------------------------------------------------
114 // clang-format off
115 static const float g_vertex_buffer_data[] = {
116     -1.0f,-1.0f,-1.0f,  // -X side
117     -1.0f,-1.0f, 1.0f,
118     -1.0f, 1.0f, 1.0f,
119     -1.0f, 1.0f, 1.0f,
120     -1.0f, 1.0f,-1.0f,
121     -1.0f,-1.0f,-1.0f,
122
123     -1.0f,-1.0f,-1.0f,  // -Z side
124      1.0f, 1.0f,-1.0f,
125      1.0f,-1.0f,-1.0f,
126     -1.0f,-1.0f,-1.0f,
127     -1.0f, 1.0f,-1.0f,
128      1.0f, 1.0f,-1.0f,
129
130     -1.0f,-1.0f,-1.0f,  // -Y side
131      1.0f,-1.0f,-1.0f,
132      1.0f,-1.0f, 1.0f,
133     -1.0f,-1.0f,-1.0f,
134      1.0f,-1.0f, 1.0f,
135     -1.0f,-1.0f, 1.0f,
136
137     -1.0f, 1.0f,-1.0f,  // +Y side
138     -1.0f, 1.0f, 1.0f,
139      1.0f, 1.0f, 1.0f,
140     -1.0f, 1.0f,-1.0f,
141      1.0f, 1.0f, 1.0f,
142      1.0f, 1.0f,-1.0f,
143
144      1.0f, 1.0f,-1.0f,  // +X side
145      1.0f, 1.0f, 1.0f,
146      1.0f,-1.0f, 1.0f,
147      1.0f,-1.0f, 1.0f,
148      1.0f,-1.0f,-1.0f,
149      1.0f, 1.0f,-1.0f,
150
151     -1.0f, 1.0f, 1.0f,  // +Z side
152     -1.0f,-1.0f, 1.0f,
153      1.0f, 1.0f, 1.0f,
154     -1.0f,-1.0f, 1.0f,
155      1.0f,-1.0f, 1.0f,
156      1.0f, 1.0f, 1.0f,
157 };
158
159 static const float g_uv_buffer_data[] = {
160     0.0f, 1.0f,  // -X side
161     1.0f, 1.0f,
162     1.0f, 0.0f,
163     1.0f, 0.0f,
164     0.0f, 0.0f,
165     0.0f, 1.0f,
166
167     1.0f, 1.0f,  // -Z side
168     0.0f, 0.0f,
169     0.0f, 1.0f,
170     1.0f, 1.0f,
171     1.0f, 0.0f,
172     0.0f, 0.0f,
173
174     1.0f, 0.0f,  // -Y side
175     1.0f, 1.0f,
176     0.0f, 1.0f,
177     1.0f, 0.0f,
178     0.0f, 1.0f,
179     0.0f, 0.0f,
180
181     1.0f, 0.0f,  // +Y side
182     0.0f, 0.0f,
183     0.0f, 1.0f,
184     1.0f, 0.0f,
185     0.0f, 1.0f,
186     1.0f, 1.0f,
187
188     1.0f, 0.0f,  // +X side
189     0.0f, 0.0f,
190     0.0f, 1.0f,
191     0.0f, 1.0f,
192     1.0f, 1.0f,
193     1.0f, 0.0f,
194
195     0.0f, 0.0f,  // +Z side
196     0.0f, 1.0f,
197     1.0f, 0.0f,
198     0.0f, 1.0f,
199     1.0f, 1.0f,
200     1.0f, 0.0f,
201 };
202 // clang-format on
203
204 typedef struct {
205     vk::Image image;
206     vk::CommandBuffer cmd;
207     vk::CommandBuffer graphics_to_present_cmd;
208     vk::ImageView view;
209     vk::Buffer uniform_buffer;
210     vk::DeviceMemory uniform_memory;
211     vk::Framebuffer framebuffer;
212     vk::DescriptorSet descriptor_set;
213 } SwapchainImageResources;
214
215 struct Demo {
216     Demo();
217     void build_image_ownership_cmd(uint32_t const &);
218     vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
219     void cleanup();
220     void create_device();
221     void destroy_texture(texture_object *);
222     void draw();
223     void draw_build_cmd(vk::CommandBuffer);
224     void flush_init_cmd();
225     void init(int, char **);
226     void init_connection();
227     void init_vk();
228     void init_vk_swapchain();
229     void prepare();
230     void prepare_buffers();
231     void prepare_cube_data_buffers();
232     void prepare_depth();
233     void prepare_descriptor_layout();
234     void prepare_descriptor_pool();
235     void prepare_descriptor_set();
236     void prepare_framebuffers();
237     vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
238     vk::ShaderModule prepare_vs();
239     vk::ShaderModule prepare_fs();
240     void prepare_pipeline();
241     void prepare_render_pass();
242     void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
243     void prepare_texture_buffer(const char *, texture_object *);
244     void prepare_textures();
245
246     void resize();
247     void create_surface();
248     void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
249                           vk::PipelineStageFlags, vk::PipelineStageFlags);
250     void update_data_buffer();
251     bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
252     bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
253
254 #if defined(VK_USE_PLATFORM_WIN32_KHR)
255     void run();
256     void create_window();
257 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
258     void create_xlib_window();
259     void handle_xlib_event(const XEvent *);
260     void run_xlib();
261 #elif defined(VK_USE_PLATFORM_XCB_KHR)
262     void handle_xcb_event(const xcb_generic_event_t *);
263     void run_xcb();
264     void create_xcb_window();
265 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
266     void run();
267     void create_window();
268 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
269     void run();
270 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
271     vk::Result create_display_surface();
272     void run_display();
273 #endif
274
275 #if defined(VK_USE_PLATFORM_WIN32_KHR)
276     HINSTANCE connection;         // hInstance - Windows Instance
277     HWND window;                  // hWnd - window handle
278     POINT minsize;                // minimum window size
279     char name[APP_NAME_STR_LEN];  // Name to put on the window/icon
280 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
281     Window xlib_window;
282     Atom xlib_wm_delete_window;
283     Display *display;
284 #elif defined(VK_USE_PLATFORM_XCB_KHR)
285     xcb_window_t xcb_window;
286     xcb_screen_t *screen;
287     xcb_connection_t *connection;
288     xcb_intern_atom_reply_t *atom_wm_delete_window;
289 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
290     wl_display *display;
291     wl_registry *registry;
292     wl_compositor *compositor;
293     wl_surface *window;
294     xdg_wm_base *wm_base;
295     zxdg_decoration_manager_v1 *xdg_decoration_mgr;
296     zxdg_toplevel_decoration_v1 *toplevel_decoration;
297     xdg_surface *window_surface;
298     bool xdg_surface_has_been_configured;
299     xdg_toplevel *window_toplevel;
300     wl_seat *seat;
301     wl_pointer *pointer;
302     wl_keyboard *keyboard;
303 #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
304     void *window;
305 #endif
306
307     vk::SurfaceKHR surface;
308     bool prepared;
309     bool use_staging_buffer;
310     bool use_xlib;
311     bool separate_present_queue;
312
313     vk::Instance inst;
314     vk::PhysicalDevice gpu;
315     vk::Device device;
316     vk::Queue graphics_queue;
317     vk::Queue present_queue;
318     uint32_t graphics_queue_family_index;
319     uint32_t present_queue_family_index;
320     vk::Semaphore image_acquired_semaphores[FRAME_LAG];
321     vk::Semaphore draw_complete_semaphores[FRAME_LAG];
322     vk::Semaphore image_ownership_semaphores[FRAME_LAG];
323     vk::PhysicalDeviceProperties gpu_props;
324     std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
325     vk::PhysicalDeviceMemoryProperties memory_properties;
326
327     uint32_t enabled_extension_count;
328     uint32_t enabled_layer_count;
329     char const *extension_names[64];
330     char const *enabled_layers[64];
331
332     uint32_t width;
333     uint32_t height;
334     vk::Format format;
335     vk::ColorSpaceKHR color_space;
336
337     uint32_t swapchainImageCount;
338     vk::SwapchainKHR swapchain;
339     std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
340     vk::PresentModeKHR presentMode;
341     vk::Fence fences[FRAME_LAG];
342     uint32_t frame_index;
343
344     vk::CommandPool cmd_pool;
345     vk::CommandPool present_cmd_pool;
346
347     struct {
348         vk::Format format;
349         vk::Image image;
350         vk::MemoryAllocateInfo mem_alloc;
351         vk::DeviceMemory mem;
352         vk::ImageView view;
353     } depth;
354
355     static int32_t const texture_count = 1;
356     texture_object textures[texture_count];
357     texture_object staging_texture;
358
359     struct {
360         vk::Buffer buf;
361         vk::MemoryAllocateInfo mem_alloc;
362         vk::DeviceMemory mem;
363         vk::DescriptorBufferInfo buffer_info;
364     } uniform_data;
365
366     vk::CommandBuffer cmd;  // Buffer for initialization commands
367     vk::PipelineLayout pipeline_layout;
368     vk::DescriptorSetLayout desc_layout;
369     vk::PipelineCache pipelineCache;
370     vk::RenderPass render_pass;
371     vk::Pipeline pipeline;
372
373     mat4x4 projection_matrix;
374     mat4x4 view_matrix;
375     mat4x4 model_matrix;
376
377     float spin_angle;
378     float spin_increment;
379     bool pause;
380
381     vk::ShaderModule vert_shader_module;
382     vk::ShaderModule frag_shader_module;
383
384     vk::DescriptorPool desc_pool;
385     vk::DescriptorSet desc_set;
386
387     std::unique_ptr<vk::Framebuffer[]> framebuffers;
388
389     bool quit;
390     uint32_t curFrame;
391     uint32_t frameCount;
392     bool validate;
393     bool use_break;
394     bool suppress_popups;
395
396     uint32_t current_buffer;
397     uint32_t queue_family_count;
398 };
399
400 #ifdef _WIN32
401 // MS-Windows event handling function:
402 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
403 #endif
404
405 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
406 static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
407     wl_shell_surface_pong(shell_surface, serial);
408 }
409
410 static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
411
412 static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
413
414 static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
415
416 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
417                                  wl_fixed_t sy) {}
418
419 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
420
421 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
422
423 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
424                                   uint32_t state) {
425     Demo *demo = (Demo *)data;
426     if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
427         xdg_toplevel_move(demo->window_toplevel, demo->seat, serial);
428     }
429 }
430
431 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
432
433 static const struct wl_pointer_listener pointer_listener = {
434     pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
435 };
436
437 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
438
439 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
440                                   struct wl_array *keys) {}
441
442 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
443
444 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
445                                 uint32_t state) {
446     if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
447     Demo *demo = (Demo *)data;
448     switch (key) {
449         case KEY_ESC:  // Escape
450             demo->quit = true;
451             break;
452         case KEY_LEFT:  // left arrow key
453             demo->spin_angle -= demo->spin_increment;
454             break;
455         case KEY_RIGHT:  // right arrow key
456             demo->spin_angle += demo->spin_increment;
457             break;
458         case KEY_SPACE:  // space bar
459             demo->pause = !demo->pause;
460             break;
461     }
462 }
463
464 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
465                                       uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
466
467 static const struct wl_keyboard_listener keyboard_listener = {
468     keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
469 };
470
471 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
472     // Subscribe to pointer events
473     Demo *demo = (Demo *)data;
474     if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
475         demo->pointer = wl_seat_get_pointer(seat);
476         wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
477     } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
478         wl_pointer_destroy(demo->pointer);
479         demo->pointer = NULL;
480     }
481     // Subscribe to keyboard events
482     if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
483         demo->keyboard = wl_seat_get_keyboard(seat);
484         wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
485     } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
486         wl_keyboard_destroy(demo->keyboard);
487         demo->keyboard = NULL;
488     }
489 }
490
491 static const wl_seat_listener seat_listener = {
492     seat_handle_capabilities,
493 };
494
495 static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
496
497 static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
498
499 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
500     Demo *demo = (Demo *)data;
501     // pickup wayland objects when they appear
502     if (strcmp(interface, wl_compositor_interface.name) == 0) {
503         demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
504     } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
505         demo->wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
506         xdg_wm_base_add_listener(demo->wm_base, &wm_base_listener, nullptr);
507     } else if (strcmp(interface, wl_seat_interface.name) == 0) {
508         demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
509         wl_seat_add_listener(demo->seat, &seat_listener, demo);
510     } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
511         demo->xdg_decoration_mgr =
512             (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
513     }
514 }
515
516 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
517
518 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
519 #endif
520
521 Demo::Demo()
522     :
523 #if defined(VK_USE_PLATFORM_WIN32_KHR)
524       connection{nullptr},
525       window{nullptr},
526       minsize(POINT{0, 0}),  // Use explicit construction to avoid MSVC error C2797.
527 #endif
528
529 #if defined(VK_USE_PLATFORM_XLIB_KHR)
530       xlib_window{0},
531       xlib_wm_delete_window{0},
532       display{nullptr},
533 #elif defined(VK_USE_PLATFORM_XCB_KHR)
534       xcb_window{0},
535       screen{nullptr},
536       connection{nullptr},
537 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
538       display{nullptr},
539       registry{nullptr},
540       compositor{nullptr},
541       window{nullptr},
542       wm_base{nullptr},
543       xdg_decoration_mgr{nullptr},
544       toplevel_decoration{nullptr},
545       window_surface{nullptr},
546       xdg_surface_has_been_configured{false},
547       window_toplevel{nullptr},
548       seat{nullptr},
549       pointer{nullptr},
550       keyboard{nullptr},
551 #endif
552       prepared{false},
553       use_staging_buffer{false},
554       use_xlib{false},
555       graphics_queue_family_index{0},
556       present_queue_family_index{0},
557       enabled_extension_count{0},
558       enabled_layer_count{0},
559       width{0},
560       height{0},
561       swapchainImageCount{0},
562       presentMode{vk::PresentModeKHR::eFifo},
563       frame_index{0},
564       spin_angle{0.0f},
565       spin_increment{0.0f},
566       pause{false},
567       quit{false},
568       curFrame{0},
569       frameCount{0},
570       validate{false},
571       use_break{false},
572       suppress_popups{false},
573       current_buffer{0},
574       queue_family_count{0} {
575 #if defined(VK_USE_PLATFORM_WIN32_KHR)
576     memset(name, '\0', APP_NAME_STR_LEN);
577 #endif
578     memset(projection_matrix, 0, sizeof(projection_matrix));
579     memset(view_matrix, 0, sizeof(view_matrix));
580     memset(model_matrix, 0, sizeof(model_matrix));
581 }
582
583 void Demo::build_image_ownership_cmd(uint32_t const &i) {
584     auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
585     auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
586     VERIFY(result == vk::Result::eSuccess);
587
588     auto const image_ownership_barrier =
589         vk::ImageMemoryBarrier()
590             .setSrcAccessMask(vk::AccessFlags())
591             .setDstAccessMask(vk::AccessFlags())
592             .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
593             .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
594             .setSrcQueueFamilyIndex(graphics_queue_family_index)
595             .setDstQueueFamilyIndex(present_queue_family_index)
596             .setImage(swapchain_image_resources[i].image)
597             .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
598
599     swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
600         vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
601         nullptr, 1, &image_ownership_barrier);
602
603     result = swapchain_image_resources[i].graphics_to_present_cmd.end();
604     VERIFY(result == vk::Result::eSuccess);
605 }
606
607 vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
608                               vk::LayerProperties *layers) {
609     for (uint32_t i = 0; i < check_count; i++) {
610         vk::Bool32 found = VK_FALSE;
611         for (uint32_t j = 0; j < layer_count; j++) {
612             if (!strcmp(check_names[i], layers[j].layerName)) {
613                 found = VK_TRUE;
614                 break;
615             }
616         }
617         if (!found) {
618             fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
619             return 0;
620         }
621     }
622     return VK_TRUE;
623 }
624
625 void Demo::cleanup() {
626     prepared = false;
627     device.waitIdle();
628
629     // Wait for fences from present operations
630     for (uint32_t i = 0; i < FRAME_LAG; i++) {
631         device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
632         device.destroyFence(fences[i], nullptr);
633         device.destroySemaphore(image_acquired_semaphores[i], nullptr);
634         device.destroySemaphore(draw_complete_semaphores[i], nullptr);
635         if (separate_present_queue) {
636             device.destroySemaphore(image_ownership_semaphores[i], nullptr);
637         }
638     }
639
640     for (uint32_t i = 0; i < swapchainImageCount; i++) {
641         device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
642     }
643     device.destroyDescriptorPool(desc_pool, nullptr);
644
645     device.destroyPipeline(pipeline, nullptr);
646     device.destroyPipelineCache(pipelineCache, nullptr);
647     device.destroyRenderPass(render_pass, nullptr);
648     device.destroyPipelineLayout(pipeline_layout, nullptr);
649     device.destroyDescriptorSetLayout(desc_layout, nullptr);
650
651     for (uint32_t i = 0; i < texture_count; i++) {
652         device.destroyImageView(textures[i].view, nullptr);
653         device.destroyImage(textures[i].image, nullptr);
654         device.freeMemory(textures[i].mem, nullptr);
655         device.destroySampler(textures[i].sampler, nullptr);
656     }
657     device.destroySwapchainKHR(swapchain, nullptr);
658
659     device.destroyImageView(depth.view, nullptr);
660     device.destroyImage(depth.image, nullptr);
661     device.freeMemory(depth.mem, nullptr);
662
663     for (uint32_t i = 0; i < swapchainImageCount; i++) {
664         device.destroyImageView(swapchain_image_resources[i].view, nullptr);
665         device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
666         device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
667         device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
668     }
669
670     device.destroyCommandPool(cmd_pool, nullptr);
671
672     if (separate_present_queue) {
673         device.destroyCommandPool(present_cmd_pool, nullptr);
674     }
675     device.waitIdle();
676     device.destroy(nullptr);
677     inst.destroySurfaceKHR(surface, nullptr);
678
679 #if defined(VK_USE_PLATFORM_XLIB_KHR)
680     XDestroyWindow(display, xlib_window);
681     XCloseDisplay(display);
682 #elif defined(VK_USE_PLATFORM_XCB_KHR)
683     xcb_destroy_window(connection, xcb_window);
684     xcb_disconnect(connection);
685     free(atom_wm_delete_window);
686 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
687     wl_keyboard_destroy(keyboard);
688     wl_pointer_destroy(pointer);
689     wl_seat_destroy(seat);
690     xdg_toplevel_destroy(window_toplevel);
691     xdg_surface_destroy(window_surface);
692     wl_surface_destroy(window);
693     xdg_wm_base_destroy(wm_base);
694     if (xdg_decoration_mgr) {
695         zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
696         zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
697     }
698     wl_compositor_destroy(compositor);
699     wl_registry_destroy(registry);
700     wl_display_disconnect(display);
701 #endif
702
703     inst.destroy(nullptr);
704 }
705
706 void Demo::create_device() {
707     float const priorities[1] = {0.0};
708
709     vk::DeviceQueueCreateInfo queues[2];
710     queues[0].setQueueFamilyIndex(graphics_queue_family_index);
711     queues[0].setQueueCount(1);
712     queues[0].setPQueuePriorities(priorities);
713
714     auto deviceInfo = vk::DeviceCreateInfo()
715                           .setQueueCreateInfoCount(1)
716                           .setPQueueCreateInfos(queues)
717                           .setEnabledLayerCount(0)
718                           .setPpEnabledLayerNames(nullptr)
719                           .setEnabledExtensionCount(enabled_extension_count)
720                           .setPpEnabledExtensionNames((const char *const *)extension_names)
721                           .setPEnabledFeatures(nullptr);
722
723     if (separate_present_queue) {
724         queues[1].setQueueFamilyIndex(present_queue_family_index);
725         queues[1].setQueueCount(1);
726         queues[1].setPQueuePriorities(priorities);
727         deviceInfo.setQueueCreateInfoCount(2);
728     }
729
730     auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
731     VERIFY(result == vk::Result::eSuccess);
732 }
733
734 void Demo::destroy_texture(texture_object *tex_objs) {
735     // clean up staging resources
736     device.freeMemory(tex_objs->mem, nullptr);
737     if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
738     if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
739 }
740
741 void Demo::draw() {
742     // Ensure no more than FRAME_LAG renderings are outstanding
743     device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
744     device.resetFences(1, &fences[frame_index]);
745
746     vk::Result result;
747     do {
748         result =
749             device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
750         if (result == vk::Result::eErrorOutOfDateKHR) {
751             // demo->swapchain is out of date (e.g. the window was resized) and
752             // must be recreated:
753             resize();
754         } else if (result == vk::Result::eSuboptimalKHR) {
755             // swapchain is not as optimal as it could be, but the platform's
756             // presentation engine will still present the image correctly.
757             break;
758         } else if (result == vk::Result::eErrorSurfaceLostKHR) {
759             inst.destroySurfaceKHR(surface, nullptr);
760             create_surface();
761             resize();
762         } else {
763             VERIFY(result == vk::Result::eSuccess);
764         }
765     } while (result != vk::Result::eSuccess);
766
767     update_data_buffer();
768
769     // Wait for the image acquired semaphore to be signaled to ensure
770     // that the image won't be rendered to until the presentation
771     // engine has fully released ownership to the application, and it is
772     // okay to render to the image.
773     vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
774     auto const submit_info = vk::SubmitInfo()
775                                  .setPWaitDstStageMask(&pipe_stage_flags)
776                                  .setWaitSemaphoreCount(1)
777                                  .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
778                                  .setCommandBufferCount(1)
779                                  .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
780                                  .setSignalSemaphoreCount(1)
781                                  .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
782
783     result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
784     VERIFY(result == vk::Result::eSuccess);
785
786     if (separate_present_queue) {
787         // If we are using separate queues, change image ownership to the
788         // present queue before presenting, waiting for the draw complete
789         // semaphore and signalling the ownership released semaphore when
790         // finished
791         auto const present_submit_info = vk::SubmitInfo()
792                                              .setPWaitDstStageMask(&pipe_stage_flags)
793                                              .setWaitSemaphoreCount(1)
794                                              .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
795                                              .setCommandBufferCount(1)
796                                              .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
797                                              .setSignalSemaphoreCount(1)
798                                              .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
799
800         result = present_queue.submit(1, &present_submit_info, vk::Fence());
801         VERIFY(result == vk::Result::eSuccess);
802     }
803
804     // If we are using separate queues we have to wait for image ownership,
805     // otherwise wait for draw complete
806     auto const presentInfo = vk::PresentInfoKHR()
807                                  .setWaitSemaphoreCount(1)
808                                  .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
809                                                                             : &draw_complete_semaphores[frame_index])
810                                  .setSwapchainCount(1)
811                                  .setPSwapchains(&swapchain)
812                                  .setPImageIndices(&current_buffer);
813
814     result = present_queue.presentKHR(&presentInfo);
815     frame_index += 1;
816     frame_index %= FRAME_LAG;
817     if (result == vk::Result::eErrorOutOfDateKHR) {
818         // swapchain is out of date (e.g. the window was resized) and
819         // must be recreated:
820         resize();
821     } else if (result == vk::Result::eSuboptimalKHR) {
822         // swapchain is not as optimal as it could be, but the platform's
823         // presentation engine will still present the image correctly.
824     } else if (result == vk::Result::eErrorSurfaceLostKHR) {
825         inst.destroySurfaceKHR(surface, nullptr);
826         create_surface();
827         resize();
828     } else {
829         VERIFY(result == vk::Result::eSuccess);
830     }
831 }
832
833 void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
834     auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
835
836     vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
837                                            vk::ClearDepthStencilValue(1.0f, 0u)};
838
839     auto const passInfo = vk::RenderPassBeginInfo()
840                               .setRenderPass(render_pass)
841                               .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
842                               .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
843                               .setClearValueCount(2)
844                               .setPClearValues(clearValues);
845
846     auto result = commandBuffer.begin(&commandInfo);
847     VERIFY(result == vk::Result::eSuccess);
848
849     commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
850     commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
851     commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
852                                      &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
853
854     auto const viewport =
855         vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
856     commandBuffer.setViewport(0, 1, &viewport);
857
858     vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
859     commandBuffer.setScissor(0, 1, &scissor);
860     commandBuffer.draw(12 * 3, 1, 0, 0);
861     // Note that ending the renderpass changes the image's layout from
862     // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
863     commandBuffer.endRenderPass();
864
865     if (separate_present_queue) {
866         // We have to transfer ownership from the graphics queue family to
867         // the
868         // present queue family to be able to present.  Note that we don't
869         // have
870         // to transfer from present queue family back to graphics queue
871         // family at
872         // the start of the next frame because we don't care about the
873         // image's
874         // contents at that point.
875         auto const image_ownership_barrier =
876             vk::ImageMemoryBarrier()
877                 .setSrcAccessMask(vk::AccessFlags())
878                 .setDstAccessMask(vk::AccessFlags())
879                 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
880                 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
881                 .setSrcQueueFamilyIndex(graphics_queue_family_index)
882                 .setDstQueueFamilyIndex(present_queue_family_index)
883                 .setImage(swapchain_image_resources[current_buffer].image)
884                 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
885
886         commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
887                                       vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
888     }
889
890     result = commandBuffer.end();
891     VERIFY(result == vk::Result::eSuccess);
892 }
893
894 void Demo::flush_init_cmd() {
895     // TODO: hmm.
896     // This function could get called twice if the texture uses a staging
897     // buffer
898     // In that case the second call should be ignored
899     if (!cmd) {
900         return;
901     }
902
903     auto result = cmd.end();
904     VERIFY(result == vk::Result::eSuccess);
905
906     auto const fenceInfo = vk::FenceCreateInfo();
907     vk::Fence fence;
908     result = device.createFence(&fenceInfo, nullptr, &fence);
909     VERIFY(result == vk::Result::eSuccess);
910
911     vk::CommandBuffer const commandBuffers[] = {cmd};
912     auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
913
914     result = graphics_queue.submit(1, &submitInfo, fence);
915     VERIFY(result == vk::Result::eSuccess);
916
917     result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
918     VERIFY(result == vk::Result::eSuccess);
919
920     device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
921     device.destroyFence(fence, nullptr);
922
923     cmd = vk::CommandBuffer();
924 }
925
926 void Demo::init(int argc, char **argv) {
927     vec3 eye = {0.0f, 3.0f, 5.0f};
928     vec3 origin = {0, 0, 0};
929     vec3 up = {0.0f, 1.0f, 0.0};
930
931     presentMode = vk::PresentModeKHR::eFifo;
932     frameCount = UINT32_MAX;
933     use_xlib = false;
934
935     for (int i = 1; i < argc; i++) {
936         if (strcmp(argv[i], "--use_staging") == 0) {
937             use_staging_buffer = true;
938             continue;
939         }
940         if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
941             presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
942             i++;
943             continue;
944         }
945         if (strcmp(argv[i], "--break") == 0) {
946             use_break = true;
947             continue;
948         }
949         if (strcmp(argv[i], "--validate") == 0) {
950             validate = true;
951             continue;
952         }
953         if (strcmp(argv[i], "--xlib") == 0) {
954             fprintf(stderr, "--xlib is deprecated and no longer does anything");
955             continue;
956         }
957         if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
958             sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
959             i++;
960             continue;
961         }
962         if (strcmp(argv[i], "--suppress_popups") == 0) {
963             suppress_popups = true;
964             continue;
965         }
966
967         std::stringstream usage;
968         usage << "Usage:\n  " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
969               << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
970               << "\t[--present_mode <present mode enum>]\n"
971               << "\t<present_mode_enum>\n"
972               << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
973               << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
974               << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
975               << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
976
977 #if defined(_WIN32)
978         if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
979 #else
980         std::cerr << usage.str();
981         std::cerr.flush();
982 #endif
983         exit(1);
984     }
985
986     if (!use_xlib) {
987         init_connection();
988     }
989
990     init_vk();
991
992     width = 500;
993     height = 500;
994
995     spin_angle = 4.0f;
996     spin_increment = 0.2f;
997     pause = false;
998
999     mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1000     mat4x4_look_at(view_matrix, eye, origin, up);
1001     mat4x4_identity(model_matrix);
1002
1003     projection_matrix[1][1] *= -1;  // Flip projection matrix from GL to Vulkan orientation.
1004 }
1005
1006 void Demo::init_connection() {
1007 #if defined(VK_USE_PLATFORM_XCB_KHR)
1008     const xcb_setup_t *setup;
1009     xcb_screen_iterator_t iter;
1010     int scr;
1011
1012     const char *display_envar = getenv("DISPLAY");
1013     if (display_envar == nullptr || display_envar[0] == '\0') {
1014         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1015         fflush(stdout);
1016         exit(1);
1017     }
1018
1019     connection = xcb_connect(nullptr, &scr);
1020     if (xcb_connection_has_error(connection) > 0) {
1021         printf(
1022             "Cannot find a compatible Vulkan installable client driver "
1023             "(ICD).\nExiting ...\n");
1024         fflush(stdout);
1025         exit(1);
1026     }
1027
1028     setup = xcb_get_setup(connection);
1029     iter = xcb_setup_roots_iterator(setup);
1030     while (scr-- > 0) xcb_screen_next(&iter);
1031
1032     screen = iter.data;
1033 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1034     display = wl_display_connect(nullptr);
1035
1036     if (display == nullptr) {
1037         printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1038         fflush(stdout);
1039         exit(1);
1040     }
1041
1042     registry = wl_display_get_registry(display);
1043     wl_registry_add_listener(registry, &registry_listener, this);
1044     wl_display_dispatch(display);
1045 #endif
1046 }
1047
1048 void Demo::init_vk() {
1049     uint32_t instance_extension_count = 0;
1050     uint32_t instance_layer_count = 0;
1051     char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
1052     enabled_extension_count = 0;
1053     enabled_layer_count = 0;
1054
1055     // Look for validation layers
1056     vk::Bool32 validation_found = VK_FALSE;
1057     if (validate) {
1058         auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
1059         VERIFY(result == vk::Result::eSuccess);
1060
1061         if (instance_layer_count > 0) {
1062             std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1063             result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
1064             VERIFY(result == vk::Result::eSuccess);
1065
1066             validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
1067                                             instance_layer_count, instance_layers.get());
1068             if (validation_found) {
1069                 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1070                 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
1071             }
1072         }
1073
1074         if (!validation_found) {
1075             ERR_EXIT(
1076                 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1077                 "Please look at the Getting Started guide for additional information.\n",
1078                 "vkCreateInstance Failure");
1079         }
1080     }
1081
1082     /* Look for instance extensions */
1083     vk::Bool32 surfaceExtFound = VK_FALSE;
1084     vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1085     memset(extension_names, 0, sizeof(extension_names));
1086
1087     auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1088                                                            static_cast<vk::ExtensionProperties *>(nullptr));
1089     VERIFY(result == vk::Result::eSuccess);
1090
1091     if (instance_extension_count > 0) {
1092         std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1093         result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1094         VERIFY(result == vk::Result::eSuccess);
1095
1096         for (uint32_t i = 0; i < instance_extension_count; i++) {
1097             if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1098                 surfaceExtFound = 1;
1099                 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1100             }
1101 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1102             if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1103                 platformSurfaceExtFound = 1;
1104                 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1105             }
1106 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1107             if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1108                 platformSurfaceExtFound = 1;
1109                 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1110             }
1111 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1112             if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1113                 platformSurfaceExtFound = 1;
1114                 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1115             }
1116 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1117             if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1118                 platformSurfaceExtFound = 1;
1119                 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1120             }
1121 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1122             if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1123                 platformSurfaceExtFound = 1;
1124                 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1125             }
1126 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1127             if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1128                 platformSurfaceExtFound = 1;
1129                 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1130             }
1131 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1132             if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1133                 platformSurfaceExtFound = 1;
1134                 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1135             }
1136
1137 #endif
1138             assert(enabled_extension_count < 64);
1139         }
1140     }
1141
1142     if (!surfaceExtFound) {
1143         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1144                  " extension.\n\n"
1145                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1146                  "Please look at the Getting Started guide for additional information.\n",
1147                  "vkCreateInstance Failure");
1148     }
1149
1150     if (!platformSurfaceExtFound) {
1151 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1152         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1153                  " extension.\n\n"
1154                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1155                  "Please look at the Getting Started guide for additional information.\n",
1156                  "vkCreateInstance Failure");
1157 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1158         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1159                  " extension.\n\n"
1160                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1161                  "Please look at the Getting Started guide for additional information.\n",
1162                  "vkCreateInstance Failure");
1163 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1164         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1165                  " extension.\n\n"
1166                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1167                  "Please look at the Getting Started guide for additional information.\n",
1168                  "vkCreateInstance Failure");
1169 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1170         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1171                  " extension.\n\n"
1172                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1173                  "Please look at the Getting Started guide for additional information.\n",
1174                  "vkCreateInstance Failure");
1175 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1176         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1177                  " extension.\n\n"
1178                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1179                  "Please look at the Getting Started guide for additional information.\n",
1180                  "vkCreateInstance Failure");
1181 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1182         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1183                  " extension.\n\nDo you have a compatible "
1184                  "Vulkan installable client driver (ICD) installed?\nPlease "
1185                  "look at the Getting Started guide for additional "
1186                  "information.\n",
1187                  "vkCreateInstance Failure");
1188 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1189         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1190                  " extension.\n\nDo you have a compatible "
1191                  "Vulkan installable client driver (ICD) installed?\nPlease "
1192                  "look at the Getting Started guide for additional "
1193                  "information.\n",
1194                  "vkCreateInstance Failure");
1195 #endif
1196     }
1197     auto const app = vk::ApplicationInfo()
1198                          .setPApplicationName(APP_SHORT_NAME)
1199                          .setApplicationVersion(0)
1200                          .setPEngineName(APP_SHORT_NAME)
1201                          .setEngineVersion(0)
1202                          .setApiVersion(VK_API_VERSION_1_0);
1203     auto const inst_info = vk::InstanceCreateInfo()
1204                                .setPApplicationInfo(&app)
1205                                .setEnabledLayerCount(enabled_layer_count)
1206                                .setPpEnabledLayerNames(instance_validation_layers)
1207                                .setEnabledExtensionCount(enabled_extension_count)
1208                                .setPpEnabledExtensionNames(extension_names);
1209
1210     result = vk::createInstance(&inst_info, nullptr, &inst);
1211     if (result == vk::Result::eErrorIncompatibleDriver) {
1212         ERR_EXIT(
1213             "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1214             "Please look at the Getting Started guide for additional information.\n",
1215             "vkCreateInstance Failure");
1216     } else if (result == vk::Result::eErrorExtensionNotPresent) {
1217         ERR_EXIT(
1218             "Cannot find a specified extension library.\n"
1219             "Make sure your layers path is set appropriately.\n",
1220             "vkCreateInstance Failure");
1221     } else if (result != vk::Result::eSuccess) {
1222         ERR_EXIT(
1223             "vkCreateInstance failed.\n\n"
1224             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1225             "Please look at the Getting Started guide for additional information.\n",
1226             "vkCreateInstance Failure");
1227     }
1228
1229     /* Make initial call to query gpu_count, then second call for gpu info*/
1230     uint32_t gpu_count;
1231     result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
1232     VERIFY(result == vk::Result::eSuccess);
1233
1234     if (gpu_count > 0) {
1235         std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1236         result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1237         VERIFY(result == vk::Result::eSuccess);
1238         /* For cube demo we just grab the first physical device */
1239         gpu = physical_devices[0];
1240     } else {
1241         ERR_EXIT(
1242             "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1243             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1244             "Please look at the Getting Started guide for additional information.\n",
1245             "vkEnumeratePhysicalDevices Failure");
1246     }
1247
1248     /* Look for device extensions */
1249     uint32_t device_extension_count = 0;
1250     vk::Bool32 swapchainExtFound = VK_FALSE;
1251     enabled_extension_count = 0;
1252     memset(extension_names, 0, sizeof(extension_names));
1253
1254     result =
1255         gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
1256     VERIFY(result == vk::Result::eSuccess);
1257
1258     if (device_extension_count > 0) {
1259         std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1260         result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1261         VERIFY(result == vk::Result::eSuccess);
1262
1263         for (uint32_t i = 0; i < device_extension_count; i++) {
1264             if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1265                 swapchainExtFound = 1;
1266                 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1267             }
1268             assert(enabled_extension_count < 64);
1269         }
1270     }
1271
1272     if (!swapchainExtFound) {
1273         ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1274                  " extension.\n\n"
1275                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1276                  "Please look at the Getting Started guide for additional information.\n",
1277                  "vkCreateInstance Failure");
1278     }
1279
1280     gpu.getProperties(&gpu_props);
1281
1282     /* Call with nullptr data to get count */
1283     gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
1284     assert(queue_family_count >= 1);
1285
1286     queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1287     gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1288
1289     // Query fine-grained feature support for this device.
1290     //  If app has specific feature requirements it should check supported
1291     //  features based on this query
1292     vk::PhysicalDeviceFeatures physDevFeatures;
1293     gpu.getFeatures(&physDevFeatures);
1294 }
1295
1296 void Demo::create_surface() {
1297 // Create a WSI surface for the window:
1298 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1299     {
1300         auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1301
1302         auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1303         VERIFY(result == vk::Result::eSuccess);
1304     }
1305 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1306     {
1307         auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1308
1309         auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1310         VERIFY(result == vk::Result::eSuccess);
1311     }
1312 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1313     {
1314         auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1315
1316         auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1317         VERIFY(result == vk::Result::eSuccess);
1318     }
1319 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1320     {
1321         auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1322
1323         auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1324         VERIFY(result == vk::Result::eSuccess);
1325     }
1326 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1327     {
1328         auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1329
1330         auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1331         VERIFY(result == vk::Result::eSuccess);
1332     }
1333 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1334     {
1335         auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1336
1337         auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1338         VERIFY(result == vk::Result::eSuccess);
1339     }
1340 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1341     {
1342         auto result = create_display_surface();
1343         VERIFY(result == vk::Result::eSuccess);
1344     }
1345 #endif
1346 }
1347
1348 void Demo::init_vk_swapchain() {
1349     create_surface();
1350     // Iterate over each queue to learn whether it supports presenting:
1351     std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1352     for (uint32_t i = 0; i < queue_family_count; i++) {
1353         gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1354     }
1355
1356     uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1357     uint32_t presentQueueFamilyIndex = UINT32_MAX;
1358     for (uint32_t i = 0; i < queue_family_count; i++) {
1359         if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1360             if (graphicsQueueFamilyIndex == UINT32_MAX) {
1361                 graphicsQueueFamilyIndex = i;
1362             }
1363
1364             if (supportsPresent[i] == VK_TRUE) {
1365                 graphicsQueueFamilyIndex = i;
1366                 presentQueueFamilyIndex = i;
1367                 break;
1368             }
1369         }
1370     }
1371
1372     if (presentQueueFamilyIndex == UINT32_MAX) {
1373         // If didn't find a queue that supports both graphics and present,
1374         // then
1375         // find a separate present queue.
1376         for (uint32_t i = 0; i < queue_family_count; ++i) {
1377             if (supportsPresent[i] == VK_TRUE) {
1378                 presentQueueFamilyIndex = i;
1379                 break;
1380             }
1381         }
1382     }
1383
1384     // Generate error if could not find both a graphics and a present queue
1385     if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1386         ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1387     }
1388
1389     graphics_queue_family_index = graphicsQueueFamilyIndex;
1390     present_queue_family_index = presentQueueFamilyIndex;
1391     separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1392
1393     create_device();
1394
1395     device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1396     if (!separate_present_queue) {
1397         present_queue = graphics_queue;
1398     } else {
1399         device.getQueue(present_queue_family_index, 0, &present_queue);
1400     }
1401
1402     // Get the list of VkFormat's that are supported:
1403     uint32_t formatCount;
1404     auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
1405     VERIFY(result == vk::Result::eSuccess);
1406
1407     std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1408     result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1409     VERIFY(result == vk::Result::eSuccess);
1410
1411     // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1412     // the surface has no preferred format.  Otherwise, at least one
1413     // supported format will be returned.
1414     if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1415         format = vk::Format::eB8G8R8A8Unorm;
1416     } else {
1417         assert(formatCount >= 1);
1418         format = surfFormats[0].format;
1419     }
1420     color_space = surfFormats[0].colorSpace;
1421
1422     quit = false;
1423     curFrame = 0;
1424
1425     // Create semaphores to synchronize acquiring presentable buffers before
1426     // rendering and waiting for drawing to be complete before presenting
1427     auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1428
1429     // Create fences that we can use to throttle if we get too far
1430     // ahead of the image presents
1431     auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1432     for (uint32_t i = 0; i < FRAME_LAG; i++) {
1433         result = device.createFence(&fence_ci, nullptr, &fences[i]);
1434         VERIFY(result == vk::Result::eSuccess);
1435
1436         result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1437         VERIFY(result == vk::Result::eSuccess);
1438
1439         result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1440         VERIFY(result == vk::Result::eSuccess);
1441
1442         if (separate_present_queue) {
1443             result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1444             VERIFY(result == vk::Result::eSuccess);
1445         }
1446     }
1447     frame_index = 0;
1448
1449     // Get Memory information and properties
1450     gpu.getMemoryProperties(&memory_properties);
1451 }
1452
1453 void Demo::prepare() {
1454     auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1455     auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1456     VERIFY(result == vk::Result::eSuccess);
1457
1458     auto const cmd = vk::CommandBufferAllocateInfo()
1459                          .setCommandPool(cmd_pool)
1460                          .setLevel(vk::CommandBufferLevel::ePrimary)
1461                          .setCommandBufferCount(1);
1462
1463     result = device.allocateCommandBuffers(&cmd, &this->cmd);
1464     VERIFY(result == vk::Result::eSuccess);
1465
1466     auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1467
1468     result = this->cmd.begin(&cmd_buf_info);
1469     VERIFY(result == vk::Result::eSuccess);
1470
1471     prepare_buffers();
1472     prepare_depth();
1473     prepare_textures();
1474     prepare_cube_data_buffers();
1475
1476     prepare_descriptor_layout();
1477     prepare_render_pass();
1478     prepare_pipeline();
1479
1480     for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1481         result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1482         VERIFY(result == vk::Result::eSuccess);
1483     }
1484
1485     if (separate_present_queue) {
1486         auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1487
1488         result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1489         VERIFY(result == vk::Result::eSuccess);
1490
1491         auto const present_cmd = vk::CommandBufferAllocateInfo()
1492                                      .setCommandPool(present_cmd_pool)
1493                                      .setLevel(vk::CommandBufferLevel::ePrimary)
1494                                      .setCommandBufferCount(1);
1495
1496         for (uint32_t i = 0; i < swapchainImageCount; i++) {
1497             result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1498             VERIFY(result == vk::Result::eSuccess);
1499
1500             build_image_ownership_cmd(i);
1501         }
1502     }
1503
1504     prepare_descriptor_pool();
1505     prepare_descriptor_set();
1506
1507     prepare_framebuffers();
1508
1509     for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1510         current_buffer = i;
1511         draw_build_cmd(swapchain_image_resources[i].cmd);
1512     }
1513
1514     /*
1515      * Prepare functions above may generate pipeline commands
1516      * that need to be flushed before beginning the render loop.
1517      */
1518     flush_init_cmd();
1519     if (staging_texture.buffer) {
1520         destroy_texture(&staging_texture);
1521     }
1522
1523     current_buffer = 0;
1524     prepared = true;
1525 }
1526
1527 void Demo::prepare_buffers() {
1528     vk::SwapchainKHR oldSwapchain = swapchain;
1529
1530     // Check the surface capabilities and formats
1531     vk::SurfaceCapabilitiesKHR surfCapabilities;
1532     auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1533     VERIFY(result == vk::Result::eSuccess);
1534
1535     uint32_t presentModeCount;
1536     result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
1537     VERIFY(result == vk::Result::eSuccess);
1538
1539     std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1540     result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1541     VERIFY(result == vk::Result::eSuccess);
1542
1543     vk::Extent2D swapchainExtent;
1544     // width and height are either both -1, or both not -1.
1545     if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1546         // If the surface size is undefined, the size is set to
1547         // the size of the images requested.
1548         swapchainExtent.width = width;
1549         swapchainExtent.height = height;
1550     } else {
1551         // If the surface size is defined, the swap chain size must match
1552         swapchainExtent = surfCapabilities.currentExtent;
1553         width = surfCapabilities.currentExtent.width;
1554         height = surfCapabilities.currentExtent.height;
1555     }
1556
1557     // The FIFO present mode is guaranteed by the spec to be supported
1558     // and to have no tearing.  It's a great default present mode to use.
1559     vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1560
1561     //  There are times when you may wish to use another present mode.  The
1562     //  following code shows how to select them, and the comments provide some
1563     //  reasons you may wish to use them.
1564     //
1565     // It should be noted that Vulkan 1.0 doesn't provide a method for
1566     // synchronizing rendering with the presentation engine's display.  There
1567     // is a method provided for throttling rendering with the display, but
1568     // there are some presentation engines for which this method will not work.
1569     // If an application doesn't throttle its rendering, and if it renders much
1570     // faster than the refresh rate of the display, this can waste power on
1571     // mobile devices.  That is because power is being spent rendering images
1572     // that may never be seen.
1573
1574     // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1575     // about
1576     // tearing, or have some way of synchronizing their rendering with the
1577     // display.
1578     // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1579     // generally render a new presentable image every refresh cycle, but are
1580     // occasionally early.  In this case, the application wants the new
1581     // image
1582     // to be displayed instead of the previously-queued-for-presentation
1583     // image
1584     // that has not yet been displayed.
1585     // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1586     // render a new presentable image every refresh cycle, but are
1587     // occasionally
1588     // late.  In this case (perhaps because of stuttering/latency concerns),
1589     // the application wants the late image to be immediately displayed,
1590     // even
1591     // though that may mean some tearing.
1592
1593     if (presentMode != swapchainPresentMode) {
1594         for (size_t i = 0; i < presentModeCount; ++i) {
1595             if (presentModes[i] == presentMode) {
1596                 swapchainPresentMode = presentMode;
1597                 break;
1598             }
1599         }
1600     }
1601
1602     if (swapchainPresentMode != presentMode) {
1603         ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1604     }
1605
1606     // Determine the number of VkImages to use in the swap chain.
1607     // Application desires to acquire 3 images at a time for triple
1608     // buffering
1609     uint32_t desiredNumOfSwapchainImages = 3;
1610     if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1611         desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1612     }
1613
1614     // If maxImageCount is 0, we can ask for as many images as we want,
1615     // otherwise
1616     // we're limited to maxImageCount
1617     if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1618         // Application must settle for fewer images than desired:
1619         desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1620     }
1621
1622     vk::SurfaceTransformFlagBitsKHR preTransform;
1623     if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1624         preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1625     } else {
1626         preTransform = surfCapabilities.currentTransform;
1627     }
1628
1629     // Find a supported composite alpha mode - one of these is guaranteed to be set
1630     vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1631     vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1632         vk::CompositeAlphaFlagBitsKHR::eOpaque,
1633         vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1634         vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1635         vk::CompositeAlphaFlagBitsKHR::eInherit,
1636     };
1637     for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1638         if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1639             compositeAlpha = compositeAlphaFlags[i];
1640             break;
1641         }
1642     }
1643
1644     auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1645                                   .setSurface(surface)
1646                                   .setMinImageCount(desiredNumOfSwapchainImages)
1647                                   .setImageFormat(format)
1648                                   .setImageColorSpace(color_space)
1649                                   .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1650                                   .setImageArrayLayers(1)
1651                                   .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1652                                   .setImageSharingMode(vk::SharingMode::eExclusive)
1653                                   .setQueueFamilyIndexCount(0)
1654                                   .setPQueueFamilyIndices(nullptr)
1655                                   .setPreTransform(preTransform)
1656                                   .setCompositeAlpha(compositeAlpha)
1657                                   .setPresentMode(swapchainPresentMode)
1658                                   .setClipped(true)
1659                                   .setOldSwapchain(oldSwapchain);
1660
1661     result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1662     VERIFY(result == vk::Result::eSuccess);
1663
1664     // If we just re-created an existing swapchain, we should destroy the
1665     // old
1666     // swapchain at this point.
1667     // Note: destroying the swapchain also cleans up all its associated
1668     // presentable images once the platform is done with them.
1669     if (oldSwapchain) {
1670         device.destroySwapchainKHR(oldSwapchain, nullptr);
1671     }
1672
1673     result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
1674     VERIFY(result == vk::Result::eSuccess);
1675
1676     std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1677     result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1678     VERIFY(result == vk::Result::eSuccess);
1679
1680     swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1681
1682     for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1683         auto color_image_view = vk::ImageViewCreateInfo()
1684                                     .setViewType(vk::ImageViewType::e2D)
1685                                     .setFormat(format)
1686                                     .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1687
1688         swapchain_image_resources[i].image = swapchainImages[i];
1689
1690         color_image_view.image = swapchain_image_resources[i].image;
1691
1692         result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1693         VERIFY(result == vk::Result::eSuccess);
1694     }
1695 }
1696
1697 void Demo::prepare_cube_data_buffers() {
1698     mat4x4 VP;
1699     mat4x4_mul(VP, projection_matrix, view_matrix);
1700
1701     mat4x4 MVP;
1702     mat4x4_mul(MVP, VP, model_matrix);
1703
1704     vktexcube_vs_uniform data;
1705     memcpy(data.mvp, MVP, sizeof(MVP));
1706     //    dumpMatrix("MVP", MVP)
1707
1708     for (int32_t i = 0; i < 12 * 3; i++) {
1709         data.position[i][0] = g_vertex_buffer_data[i * 3];
1710         data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1711         data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1712         data.position[i][3] = 1.0f;
1713         data.attr[i][0] = g_uv_buffer_data[2 * i];
1714         data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1715         data.attr[i][2] = 0;
1716         data.attr[i][3] = 0;
1717     }
1718
1719     auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1720
1721     for (unsigned int i = 0; i < swapchainImageCount; i++) {
1722         auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
1723         VERIFY(result == vk::Result::eSuccess);
1724
1725         vk::MemoryRequirements mem_reqs;
1726         device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1727
1728         auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1729
1730         bool const pass = memory_type_from_properties(
1731             mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1732             &mem_alloc.memoryTypeIndex);
1733         VERIFY(pass);
1734
1735         result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
1736         VERIFY(result == vk::Result::eSuccess);
1737
1738         auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1739         VERIFY(pData.result == vk::Result::eSuccess);
1740
1741         memcpy(pData.value, &data, sizeof data);
1742
1743         device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1744
1745         result =
1746             device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
1747         VERIFY(result == vk::Result::eSuccess);
1748     }
1749 }
1750
1751 void Demo::prepare_depth() {
1752     depth.format = vk::Format::eD16Unorm;
1753
1754     auto const image = vk::ImageCreateInfo()
1755                            .setImageType(vk::ImageType::e2D)
1756                            .setFormat(depth.format)
1757                            .setExtent({(uint32_t)width, (uint32_t)height, 1})
1758                            .setMipLevels(1)
1759                            .setArrayLayers(1)
1760                            .setSamples(vk::SampleCountFlagBits::e1)
1761                            .setTiling(vk::ImageTiling::eOptimal)
1762                            .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1763                            .setSharingMode(vk::SharingMode::eExclusive)
1764                            .setQueueFamilyIndexCount(0)
1765                            .setPQueueFamilyIndices(nullptr)
1766                            .setInitialLayout(vk::ImageLayout::eUndefined);
1767
1768     auto result = device.createImage(&image, nullptr, &depth.image);
1769     VERIFY(result == vk::Result::eSuccess);
1770
1771     vk::MemoryRequirements mem_reqs;
1772     device.getImageMemoryRequirements(depth.image, &mem_reqs);
1773
1774     depth.mem_alloc.setAllocationSize(mem_reqs.size);
1775     depth.mem_alloc.setMemoryTypeIndex(0);
1776
1777     auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1778                                                   &depth.mem_alloc.memoryTypeIndex);
1779     VERIFY(pass);
1780
1781     result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1782     VERIFY(result == vk::Result::eSuccess);
1783
1784     result = device.bindImageMemory(depth.image, depth.mem, 0);
1785     VERIFY(result == vk::Result::eSuccess);
1786
1787     auto const view = vk::ImageViewCreateInfo()
1788                           .setImage(depth.image)
1789                           .setViewType(vk::ImageViewType::e2D)
1790                           .setFormat(depth.format)
1791                           .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1792     result = device.createImageView(&view, nullptr, &depth.view);
1793     VERIFY(result == vk::Result::eSuccess);
1794 }
1795
1796 void Demo::prepare_descriptor_layout() {
1797     vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1798                                                                    .setBinding(0)
1799                                                                    .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1800                                                                    .setDescriptorCount(1)
1801                                                                    .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1802                                                                    .setPImmutableSamplers(nullptr),
1803                                                                vk::DescriptorSetLayoutBinding()
1804                                                                    .setBinding(1)
1805                                                                    .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1806                                                                    .setDescriptorCount(texture_count)
1807                                                                    .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1808                                                                    .setPImmutableSamplers(nullptr)};
1809
1810     auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1811
1812     auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1813     VERIFY(result == vk::Result::eSuccess);
1814
1815     auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1816
1817     result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1818     VERIFY(result == vk::Result::eSuccess);
1819 }
1820
1821 void Demo::prepare_descriptor_pool() {
1822     vk::DescriptorPoolSize const poolSizes[2] = {
1823         vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1824         vk::DescriptorPoolSize()
1825             .setType(vk::DescriptorType::eCombinedImageSampler)
1826             .setDescriptorCount(swapchainImageCount * texture_count)};
1827
1828     auto const descriptor_pool =
1829         vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1830
1831     auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1832     VERIFY(result == vk::Result::eSuccess);
1833 }
1834
1835 void Demo::prepare_descriptor_set() {
1836     auto const alloc_info =
1837         vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1838
1839     auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1840
1841     vk::DescriptorImageInfo tex_descs[texture_count];
1842     for (uint32_t i = 0; i < texture_count; i++) {
1843         tex_descs[i].setSampler(textures[i].sampler);
1844         tex_descs[i].setImageView(textures[i].view);
1845         tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1846     }
1847
1848     vk::WriteDescriptorSet writes[2];
1849
1850     writes[0].setDescriptorCount(1);
1851     writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1852     writes[0].setPBufferInfo(&buffer_info);
1853
1854     writes[1].setDstBinding(1);
1855     writes[1].setDescriptorCount(texture_count);
1856     writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1857     writes[1].setPImageInfo(tex_descs);
1858
1859     for (unsigned int i = 0; i < swapchainImageCount; i++) {
1860         auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
1861         VERIFY(result == vk::Result::eSuccess);
1862
1863         buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1864         writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1865         writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1866         device.updateDescriptorSets(2, writes, 0, nullptr);
1867     }
1868 }
1869
1870 void Demo::prepare_framebuffers() {
1871     vk::ImageView attachments[2];
1872     attachments[1] = depth.view;
1873
1874     auto const fb_info = vk::FramebufferCreateInfo()
1875                              .setRenderPass(render_pass)
1876                              .setAttachmentCount(2)
1877                              .setPAttachments(attachments)
1878                              .setWidth((uint32_t)width)
1879                              .setHeight((uint32_t)height)
1880                              .setLayers(1);
1881
1882     for (uint32_t i = 0; i < swapchainImageCount; i++) {
1883         attachments[0] = swapchain_image_resources[i].view;
1884         auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
1885         VERIFY(result == vk::Result::eSuccess);
1886     }
1887 }
1888
1889 vk::ShaderModule Demo::prepare_fs() {
1890     const uint32_t fragShaderCode[] = {
1891 #include "cube.frag.inc"
1892     };
1893
1894     frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
1895
1896     return frag_shader_module;
1897 }
1898
1899 void Demo::prepare_pipeline() {
1900     vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1901     auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1902     VERIFY(result == vk::Result::eSuccess);
1903
1904     vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1905         vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1906         vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1907
1908     vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1909
1910     auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1911
1912     // TODO: Where are pViewports and pScissors set?
1913     auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1914
1915     auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1916                                        .setDepthClampEnable(VK_FALSE)
1917                                        .setRasterizerDiscardEnable(VK_FALSE)
1918                                        .setPolygonMode(vk::PolygonMode::eFill)
1919                                        .setCullMode(vk::CullModeFlagBits::eBack)
1920                                        .setFrontFace(vk::FrontFace::eCounterClockwise)
1921                                        .setDepthBiasEnable(VK_FALSE)
1922                                        .setLineWidth(1.0f);
1923
1924     auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1925
1926     auto const stencilOp =
1927         vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1928
1929     auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1930                                       .setDepthTestEnable(VK_TRUE)
1931                                       .setDepthWriteEnable(VK_TRUE)
1932                                       .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1933                                       .setDepthBoundsTestEnable(VK_FALSE)
1934                                       .setStencilTestEnable(VK_FALSE)
1935                                       .setFront(stencilOp)
1936                                       .setBack(stencilOp);
1937
1938     vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1939         vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1940                                                                   vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1941
1942     auto const colorBlendInfo =
1943         vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1944
1945     vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1946
1947     auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1948
1949     auto const pipeline = vk::GraphicsPipelineCreateInfo()
1950                               .setStageCount(2)
1951                               .setPStages(shaderStageInfo)
1952                               .setPVertexInputState(&vertexInputInfo)
1953                               .setPInputAssemblyState(&inputAssemblyInfo)
1954                               .setPViewportState(&viewportInfo)
1955                               .setPRasterizationState(&rasterizationInfo)
1956                               .setPMultisampleState(&multisampleInfo)
1957                               .setPDepthStencilState(&depthStencilInfo)
1958                               .setPColorBlendState(&colorBlendInfo)
1959                               .setPDynamicState(&dynamicStateInfo)
1960                               .setLayout(pipeline_layout)
1961                               .setRenderPass(render_pass);
1962
1963     result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1964     VERIFY(result == vk::Result::eSuccess);
1965
1966     device.destroyShaderModule(frag_shader_module, nullptr);
1967     device.destroyShaderModule(vert_shader_module, nullptr);
1968 }
1969
1970 void Demo::prepare_render_pass() {
1971     // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1972     // because at the start of the renderpass, we don't care about their contents.
1973     // At the start of the subpass, the color attachment's layout will be transitioned
1974     // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1975     // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL.  At the end of
1976     // the renderpass, the color attachment's layout will be transitioned to
1977     // LAYOUT_PRESENT_SRC_KHR to be ready to present.  This is all done as part of
1978     // the renderpass, no barriers are necessary.
1979     const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1980                                                           .setFormat(format)
1981                                                           .setSamples(vk::SampleCountFlagBits::e1)
1982                                                           .setLoadOp(vk::AttachmentLoadOp::eClear)
1983                                                           .setStoreOp(vk::AttachmentStoreOp::eStore)
1984                                                           .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1985                                                           .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1986                                                           .setInitialLayout(vk::ImageLayout::eUndefined)
1987                                                           .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1988                                                       vk::AttachmentDescription()
1989                                                           .setFormat(depth.format)
1990                                                           .setSamples(vk::SampleCountFlagBits::e1)
1991                                                           .setLoadOp(vk::AttachmentLoadOp::eClear)
1992                                                           .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1993                                                           .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1994                                                           .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1995                                                           .setInitialLayout(vk::ImageLayout::eUndefined)
1996                                                           .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1997
1998     auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1999
2000     auto const depth_reference =
2001         vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2002
2003     auto const subpass = vk::SubpassDescription()
2004                              .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2005                              .setInputAttachmentCount(0)
2006                              .setPInputAttachments(nullptr)
2007                              .setColorAttachmentCount(1)
2008                              .setPColorAttachments(&color_reference)
2009                              .setPResolveAttachments(nullptr)
2010                              .setPDepthStencilAttachment(&depth_reference)
2011                              .setPreserveAttachmentCount(0)
2012                              .setPPreserveAttachments(nullptr);
2013
2014     vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2015     vk::SubpassDependency const dependencies[2] = {
2016         vk::SubpassDependency()  // Depth buffer is shared between swapchain images
2017             .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2018             .setDstSubpass(0)
2019             .setSrcStageMask(stages)
2020             .setDstStageMask(stages)
2021             .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2022             .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2023             .setDependencyFlags(vk::DependencyFlags()),
2024         vk::SubpassDependency()  // Image layout transition
2025             .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2026             .setDstSubpass(0)
2027             .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2028             .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2029             .setSrcAccessMask(vk::AccessFlagBits())
2030             .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2031             .setDependencyFlags(vk::DependencyFlags()),
2032     };
2033
2034     auto const rp_info = vk::RenderPassCreateInfo()
2035                              .setAttachmentCount(2)
2036                              .setPAttachments(attachments)
2037                              .setSubpassCount(1)
2038                              .setPSubpasses(&subpass)
2039                              .setDependencyCount(2)
2040                              .setPDependencies(dependencies);
2041
2042     auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2043     VERIFY(result == vk::Result::eSuccess);
2044 }
2045
2046 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2047     const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2048
2049     vk::ShaderModule module;
2050     auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2051     VERIFY(result == vk::Result::eSuccess);
2052
2053     return module;
2054 }
2055
2056 void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2057     int32_t tex_width;
2058     int32_t tex_height;
2059
2060     if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2061         ERR_EXIT("Failed to load textures", "Load Texture Failure");
2062     }
2063
2064     tex_obj->tex_width = tex_width;
2065     tex_obj->tex_height = tex_height;
2066
2067     auto const buffer_create_info = vk::BufferCreateInfo()
2068                                         .setSize(tex_width * tex_height * 4)
2069                                         .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2070                                         .setSharingMode(vk::SharingMode::eExclusive)
2071                                         .setQueueFamilyIndexCount(0)
2072                                         .setPQueueFamilyIndices(nullptr);
2073
2074     auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2075     VERIFY(result == vk::Result::eSuccess);
2076
2077     vk::MemoryRequirements mem_reqs;
2078     device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2079
2080     tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2081     tex_obj->mem_alloc.setMemoryTypeIndex(0);
2082
2083     vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2084     auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2085     VERIFY(pass == true);
2086
2087     result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2088     VERIFY(result == vk::Result::eSuccess);
2089
2090     result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2091     VERIFY(result == vk::Result::eSuccess);
2092
2093     vk::SubresourceLayout layout;
2094     memset(&layout, 0, sizeof(layout));
2095     layout.rowPitch = tex_width * 4;
2096     auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2097     VERIFY(data.result == vk::Result::eSuccess);
2098
2099     if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2100         fprintf(stderr, "Error loading texture: %s\n", filename);
2101     }
2102
2103     device.unmapMemory(tex_obj->mem);
2104 }
2105
2106 void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2107                                  vk::MemoryPropertyFlags required_props) {
2108     int32_t tex_width;
2109     int32_t tex_height;
2110     if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2111         ERR_EXIT("Failed to load textures", "Load Texture Failure");
2112     }
2113
2114     tex_obj->tex_width = tex_width;
2115     tex_obj->tex_height = tex_height;
2116
2117     auto const image_create_info = vk::ImageCreateInfo()
2118                                        .setImageType(vk::ImageType::e2D)
2119                                        .setFormat(vk::Format::eR8G8B8A8Unorm)
2120                                        .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2121                                        .setMipLevels(1)
2122                                        .setArrayLayers(1)
2123                                        .setSamples(vk::SampleCountFlagBits::e1)
2124                                        .setTiling(tiling)
2125                                        .setUsage(usage)
2126                                        .setSharingMode(vk::SharingMode::eExclusive)
2127                                        .setQueueFamilyIndexCount(0)
2128                                        .setPQueueFamilyIndices(nullptr)
2129                                        .setInitialLayout(vk::ImageLayout::ePreinitialized);
2130
2131     auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2132     VERIFY(result == vk::Result::eSuccess);
2133
2134     vk::MemoryRequirements mem_reqs;
2135     device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
2136
2137     tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2138     tex_obj->mem_alloc.setMemoryTypeIndex(0);
2139
2140     auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2141     VERIFY(pass == true);
2142
2143     result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2144     VERIFY(result == vk::Result::eSuccess);
2145
2146     result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2147     VERIFY(result == vk::Result::eSuccess);
2148
2149     if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2150         auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2151         vk::SubresourceLayout layout;
2152         device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
2153
2154         auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2155         VERIFY(data.result == vk::Result::eSuccess);
2156
2157         if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2158             fprintf(stderr, "Error loading texture: %s\n", filename);
2159         }
2160
2161         device.unmapMemory(tex_obj->mem);
2162     }
2163
2164     tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2165 }
2166
2167 void Demo::prepare_textures() {
2168     vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2169     vk::FormatProperties props;
2170     gpu.getFormatProperties(tex_format, &props);
2171
2172     for (uint32_t i = 0; i < texture_count; i++) {
2173         if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2174             /* Device can texture using linear textures */
2175             prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2176                                   vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2177             // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2178             // shader to run until layout transition completes
2179             set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2180                              textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2181                              vk::PipelineStageFlagBits::eFragmentShader);
2182             staging_texture.image = vk::Image();
2183         } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2184             /* Must use staging buffer to copy linear texture to optimized */
2185
2186             prepare_texture_buffer(tex_files[i], &staging_texture);
2187
2188             prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2189                                   vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2190                                   vk::MemoryPropertyFlagBits::eDeviceLocal);
2191
2192             set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2193                              vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2194                              vk::PipelineStageFlagBits::eTransfer);
2195
2196             auto const subresource = vk::ImageSubresourceLayers()
2197                                          .setAspectMask(vk::ImageAspectFlagBits::eColor)
2198                                          .setMipLevel(0)
2199                                          .setBaseArrayLayer(0)
2200                                          .setLayerCount(1);
2201
2202             auto const copy_region =
2203                 vk::BufferImageCopy()
2204                     .setBufferOffset(0)
2205                     .setBufferRowLength(staging_texture.tex_width)
2206                     .setBufferImageHeight(staging_texture.tex_height)
2207                     .setImageSubresource(subresource)
2208                     .setImageOffset({0, 0, 0})
2209                     .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2210
2211             cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
2212
2213             set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2214                              textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2215                              vk::PipelineStageFlagBits::eFragmentShader);
2216         } else {
2217             assert(!"No support for R8G8B8A8_UNORM as texture image format");
2218         }
2219
2220         auto const samplerInfo = vk::SamplerCreateInfo()
2221                                      .setMagFilter(vk::Filter::eNearest)
2222                                      .setMinFilter(vk::Filter::eNearest)
2223                                      .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2224                                      .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2225                                      .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2226                                      .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2227                                      .setMipLodBias(0.0f)
2228                                      .setAnisotropyEnable(VK_FALSE)
2229                                      .setMaxAnisotropy(1)
2230                                      .setCompareEnable(VK_FALSE)
2231                                      .setCompareOp(vk::CompareOp::eNever)
2232                                      .setMinLod(0.0f)
2233                                      .setMaxLod(0.0f)
2234                                      .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2235                                      .setUnnormalizedCoordinates(VK_FALSE);
2236
2237         auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2238         VERIFY(result == vk::Result::eSuccess);
2239
2240         auto const viewInfo = vk::ImageViewCreateInfo()
2241                                   .setImage(textures[i].image)
2242                                   .setViewType(vk::ImageViewType::e2D)
2243                                   .setFormat(tex_format)
2244                                   .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2245
2246         result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2247         VERIFY(result == vk::Result::eSuccess);
2248     }
2249 }
2250
2251 vk::ShaderModule Demo::prepare_vs() {
2252     const uint32_t vertShaderCode[] = {
2253 #include "cube.vert.inc"
2254     };
2255
2256     vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2257
2258     return vert_shader_module;
2259 }
2260
2261 void Demo::resize() {
2262     uint32_t i;
2263
2264     // Don't react to resize until after first initialization.
2265     if (!prepared) {
2266         return;
2267     }
2268
2269     // In order to properly resize the window, we must re-create the
2270     // swapchain
2271     // AND redo the command buffers, etc.
2272     //
2273     // First, perform part of the cleanup() function:
2274     prepared = false;
2275     auto result = device.waitIdle();
2276     VERIFY(result == vk::Result::eSuccess);
2277
2278     for (i = 0; i < swapchainImageCount; i++) {
2279         device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2280     }
2281
2282     device.destroyDescriptorPool(desc_pool, nullptr);
2283
2284     device.destroyPipeline(pipeline, nullptr);
2285     device.destroyPipelineCache(pipelineCache, nullptr);
2286     device.destroyRenderPass(render_pass, nullptr);
2287     device.destroyPipelineLayout(pipeline_layout, nullptr);
2288     device.destroyDescriptorSetLayout(desc_layout, nullptr);
2289
2290     for (i = 0; i < texture_count; i++) {
2291         device.destroyImageView(textures[i].view, nullptr);
2292         device.destroyImage(textures[i].image, nullptr);
2293         device.freeMemory(textures[i].mem, nullptr);
2294         device.destroySampler(textures[i].sampler, nullptr);
2295     }
2296
2297     device.destroyImageView(depth.view, nullptr);
2298     device.destroyImage(depth.image, nullptr);
2299     device.freeMemory(depth.mem, nullptr);
2300
2301     for (i = 0; i < swapchainImageCount; i++) {
2302         device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2303         device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2304         device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2305         device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2306     }
2307
2308     device.destroyCommandPool(cmd_pool, nullptr);
2309     if (separate_present_queue) {
2310         device.destroyCommandPool(present_cmd_pool, nullptr);
2311     }
2312
2313     // Second, re-perform the prepare() function, which will re-create the
2314     // swapchain.
2315     prepare();
2316 }
2317
2318 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2319                             vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2320     assert(cmd);
2321
2322     auto DstAccessMask = [](vk::ImageLayout const &layout) {
2323         vk::AccessFlags flags;
2324
2325         switch (layout) {
2326             case vk::ImageLayout::eTransferDstOptimal:
2327                 // Make sure anything that was copying from this image has
2328                 // completed
2329                 flags = vk::AccessFlagBits::eTransferWrite;
2330                 break;
2331             case vk::ImageLayout::eColorAttachmentOptimal:
2332                 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2333                 break;
2334             case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2335                 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2336                 break;
2337             case vk::ImageLayout::eShaderReadOnlyOptimal:
2338                 // Make sure any Copy or CPU writes to image are flushed
2339                 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2340                 break;
2341             case vk::ImageLayout::eTransferSrcOptimal:
2342                 flags = vk::AccessFlagBits::eTransferRead;
2343                 break;
2344             case vk::ImageLayout::ePresentSrcKHR:
2345                 flags = vk::AccessFlagBits::eMemoryRead;
2346                 break;
2347             default:
2348                 break;
2349         }
2350
2351         return flags;
2352     };
2353
2354     auto const barrier = vk::ImageMemoryBarrier()
2355                              .setSrcAccessMask(srcAccessMask)
2356                              .setDstAccessMask(DstAccessMask(newLayout))
2357                              .setOldLayout(oldLayout)
2358                              .setNewLayout(newLayout)
2359                              .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2360                              .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2361                              .setImage(image)
2362                              .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2363
2364     cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2365 }
2366
2367 void Demo::update_data_buffer() {
2368     mat4x4 VP;
2369     mat4x4_mul(VP, projection_matrix, view_matrix);
2370
2371     // Rotate around the Y axis
2372     mat4x4 Model;
2373     mat4x4_dup(Model, model_matrix);
2374     mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2375
2376     mat4x4 MVP;
2377     mat4x4_mul(MVP, VP, model_matrix);
2378
2379     auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2380     VERIFY(data.result == vk::Result::eSuccess);
2381
2382     memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2383
2384     device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2385 }
2386
2387 /* Convert ppm image data from header file into RGBA texture image */
2388 #include "lunarg.ppm.h"
2389 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
2390     (void)filename;
2391     char *cPtr;
2392     cPtr = (char *)lunarg_ppm;
2393     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2394         return false;
2395     }
2396     while (strncmp(cPtr++, "\n", 1))
2397         ;
2398     sscanf(cPtr, "%u %u", width, height);
2399     if (rgba_data == NULL) {
2400         return true;
2401     }
2402     while (strncmp(cPtr++, "\n", 1))
2403         ;
2404     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2405         return false;
2406     }
2407     while (strncmp(cPtr++, "\n", 1))
2408         ;
2409     for (int y = 0; y < *height; y++) {
2410         uint8_t *rowPtr = rgba_data;
2411         for (int x = 0; x < *width; x++) {
2412             memcpy(rowPtr, cPtr, 3);
2413             rowPtr[3] = 255; /* Alpha of 1 */
2414             rowPtr += 4;
2415             cPtr += 3;
2416         }
2417         rgba_data += layout->rowPitch;
2418     }
2419     return true;
2420 }
2421
2422 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2423     // Search memtypes to find first index with those properties
2424     for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2425         if ((typeBits & 1) == 1) {
2426             // Type is available, does it match user properties?
2427             if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2428                 *typeIndex = i;
2429                 return true;
2430             }
2431         }
2432         typeBits >>= 1;
2433     }
2434
2435     // No memory types matched, return failure
2436     return false;
2437 }
2438
2439 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2440 void Demo::run() {
2441     if (!prepared) {
2442         return;
2443     }
2444
2445     draw();
2446     curFrame++;
2447
2448     if (frameCount != UINT32_MAX && curFrame == frameCount) {
2449         PostQuitMessage(validation_error);
2450     }
2451 }
2452
2453 void Demo::create_window() {
2454     WNDCLASSEX win_class;
2455
2456     // Initialize the window class structure:
2457     win_class.cbSize = sizeof(WNDCLASSEX);
2458     win_class.style = CS_HREDRAW | CS_VREDRAW;
2459     win_class.lpfnWndProc = WndProc;
2460     win_class.cbClsExtra = 0;
2461     win_class.cbWndExtra = 0;
2462     win_class.hInstance = connection;  // hInstance
2463     win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2464     win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2465     win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2466     win_class.lpszMenuName = nullptr;
2467     win_class.lpszClassName = name;
2468     win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2469
2470     // Register window class:
2471     if (!RegisterClassEx(&win_class)) {
2472         // It didn't work, so try to give a useful error:
2473         printf("Unexpected error trying to start the application!\n");
2474         fflush(stdout);
2475         exit(1);
2476     }
2477
2478     // Create window with the registered class:
2479     RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2480     AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2481     window = CreateWindowEx(0,
2482                             name,                  // class name
2483                             name,                  // app name
2484                             WS_OVERLAPPEDWINDOW |  // window style
2485                                 WS_VISIBLE | WS_SYSMENU,
2486                             100, 100,            // x/y coords
2487                             wr.right - wr.left,  // width
2488                             wr.bottom - wr.top,  // height
2489                             nullptr,             // handle to parent
2490                             nullptr,             // handle to menu
2491                             connection,          // hInstance
2492                             nullptr);            // no extra parameters
2493
2494     if (!window) {
2495         // It didn't work, so try to give a useful error:
2496         printf("Cannot create a window in which to draw!\n");
2497         fflush(stdout);
2498         exit(1);
2499     }
2500
2501     // Window client area size must be at least 1 pixel high, to prevent
2502     // crash.
2503     minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2504     minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2505 }
2506 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2507
2508 void Demo::create_xlib_window() {
2509     const char *display_envar = getenv("DISPLAY");
2510     if (display_envar == nullptr || display_envar[0] == '\0') {
2511         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2512         fflush(stdout);
2513         exit(1);
2514     }
2515
2516     XInitThreads();
2517     display = XOpenDisplay(nullptr);
2518     long visualMask = VisualScreenMask;
2519     int numberOfVisuals;
2520     XVisualInfo vInfoTemplate = {};
2521     vInfoTemplate.screen = DefaultScreen(display);
2522     XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2523
2524     Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2525
2526     XSetWindowAttributes windowAttributes = {};
2527     windowAttributes.colormap = colormap;
2528     windowAttributes.background_pixel = 0xFFFFFFFF;
2529     windowAttributes.border_pixel = 0;
2530     windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2531
2532     xlib_window =
2533         XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2534                       visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2535
2536     XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2537     XMapWindow(display, xlib_window);
2538     XFlush(display);
2539     xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2540 }
2541
2542 void Demo::handle_xlib_event(const XEvent *event) {
2543     switch (event->type) {
2544         case ClientMessage:
2545             if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2546                 quit = true;
2547             }
2548             break;
2549         case KeyPress:
2550             switch (event->xkey.keycode) {
2551                 case 0x9:  // Escape
2552                     quit = true;
2553                     break;
2554                 case 0x71:  // left arrow key
2555                     spin_angle -= spin_increment;
2556                     break;
2557                 case 0x72:  // right arrow key
2558                     spin_angle += spin_increment;
2559                     break;
2560                 case 0x41:  // space bar
2561                     pause = !pause;
2562                     break;
2563             }
2564             break;
2565         case ConfigureNotify:
2566             if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2567                 width = event->xconfigure.width;
2568                 height = event->xconfigure.height;
2569                 resize();
2570             }
2571             break;
2572         default:
2573             break;
2574     }
2575 }
2576
2577 void Demo::run_xlib() {
2578     while (!quit) {
2579         XEvent event;
2580
2581         if (pause) {
2582             XNextEvent(display, &event);
2583             handle_xlib_event(&event);
2584         }
2585         while (XPending(display) > 0) {
2586             XNextEvent(display, &event);
2587             handle_xlib_event(&event);
2588         }
2589
2590         draw();
2591         curFrame++;
2592
2593         if (frameCount != UINT32_MAX && curFrame == frameCount) {
2594             quit = true;
2595         }
2596     }
2597 }
2598 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2599
2600 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2601     uint8_t event_code = event->response_type & 0x7f;
2602     switch (event_code) {
2603         case XCB_EXPOSE:
2604             // TODO: Resize window
2605             break;
2606         case XCB_CLIENT_MESSAGE:
2607             if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2608                 quit = true;
2609             }
2610             break;
2611         case XCB_KEY_RELEASE: {
2612             const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2613
2614             switch (key->detail) {
2615                 case 0x9:  // Escape
2616                     quit = true;
2617                     break;
2618                 case 0x71:  // left arrow key
2619                     spin_angle -= spin_increment;
2620                     break;
2621                 case 0x72:  // right arrow key
2622                     spin_angle += spin_increment;
2623                     break;
2624                 case 0x41:  // space bar
2625                     pause = !pause;
2626                     break;
2627             }
2628         } break;
2629         case XCB_CONFIGURE_NOTIFY: {
2630             const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2631             if ((width != cfg->width) || (height != cfg->height)) {
2632                 width = cfg->width;
2633                 height = cfg->height;
2634                 resize();
2635             }
2636         } break;
2637         default:
2638             break;
2639     }
2640 }
2641
2642 void Demo::run_xcb() {
2643     xcb_flush(connection);
2644
2645     while (!quit) {
2646         xcb_generic_event_t *event;
2647
2648         if (pause) {
2649             event = xcb_wait_for_event(connection);
2650         } else {
2651             event = xcb_poll_for_event(connection);
2652         }
2653         while (event) {
2654             handle_xcb_event(event);
2655             free(event);
2656             event = xcb_poll_for_event(connection);
2657         }
2658
2659         draw();
2660         curFrame++;
2661         if (frameCount != UINT32_MAX && curFrame == frameCount) {
2662             quit = true;
2663         }
2664     }
2665 }
2666
2667 void Demo::create_xcb_window() {
2668     uint32_t value_mask, value_list[32];
2669
2670     xcb_window = xcb_generate_id(connection);
2671
2672     value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2673     value_list[0] = screen->black_pixel;
2674     value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2675
2676     xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2677                       XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2678
2679     /* Magic code that will send notification when window is destroyed */
2680     xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2681     xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2682
2683     xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2684     atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2685
2686     xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2687
2688     free(reply);
2689
2690     xcb_map_window(connection, xcb_window);
2691
2692     // Force the x/y coordinates to 100,100 results are identical in
2693     // consecutive
2694     // runs
2695     const uint32_t coords[] = {100, 100};
2696     xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2697 }
2698 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2699
2700 void Demo::run() {
2701     while (!quit) {
2702         if (pause) {
2703             wl_display_dispatch(display);
2704         } else {
2705             wl_display_dispatch_pending(display);
2706             update_data_buffer();
2707             draw();
2708             curFrame++;
2709             if (frameCount != UINT32_MAX && curFrame == frameCount) {
2710                 quit = true;
2711             }
2712         }
2713     }
2714 }
2715
2716 static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2717     Demo *demo = (Demo *)data;
2718     xdg_surface_ack_configure(xdg_surface, serial);
2719     if (demo->xdg_surface_has_been_configured) {
2720         demo->resize();
2721     }
2722     demo->xdg_surface_has_been_configured = true;
2723 }
2724
2725 static const xdg_surface_listener surface_listener = {handle_surface_configure};
2726
2727 static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2728                                       struct wl_array *states) {
2729     Demo *demo = (Demo *)data;
2730     demo->width = width;
2731     demo->height = height;
2732     // This will be followed by a surface configure
2733 }
2734
2735 static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2736     Demo *demo = (Demo *)data;
2737     demo->quit = true;
2738 }
2739
2740 static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2741
2742 void Demo::create_window() {
2743     if (!wm_base) {
2744         printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2745         fflush(stdout);
2746         exit(1);
2747     }
2748
2749     window = wl_compositor_create_surface(compositor);
2750     if (!window) {
2751         printf("Can not create wayland_surface from compositor!\n");
2752         fflush(stdout);
2753         exit(1);
2754     }
2755
2756     window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2757     if (!window_surface) {
2758         printf("Can not get xdg_surface from wayland_surface!\n");
2759         fflush(stdout);
2760         exit(1);
2761     }
2762     window_toplevel = xdg_surface_get_toplevel(window_surface);
2763     if (!window_toplevel) {
2764         printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2765         fflush(stdout);
2766         exit(1);
2767     }
2768     xdg_surface_add_listener(window_surface, &surface_listener, this);
2769     xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2770     xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2771     if (xdg_decoration_mgr) {
2772         // if supported, let the compositor render titlebars for us
2773         toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2774         zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2775     }
2776
2777     wl_surface_commit(window);
2778 }
2779 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
2780 void Demo::run() {
2781     draw();
2782     curFrame++;
2783     if (frameCount != UINT32_MAX && curFrame == frameCount) {
2784         quit = true;
2785     }
2786 }
2787 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2788
2789 vk::Result Demo::create_display_surface() {
2790     vk::Result result;
2791     uint32_t display_count;
2792     uint32_t mode_count;
2793     uint32_t plane_count;
2794     vk::DisplayPropertiesKHR display_props;
2795     vk::DisplayKHR display;
2796     vk::DisplayModePropertiesKHR mode_props;
2797     vk::DisplayPlanePropertiesKHR *plane_props;
2798     vk::Bool32 found_plane = VK_FALSE;
2799     uint32_t plane_index;
2800     vk::Extent2D image_extent;
2801
2802     // Get the first display
2803     result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2804     VERIFY(result == vk::Result::eSuccess);
2805
2806     if (display_count == 0) {
2807         printf("Cannot find any display!\n");
2808         fflush(stdout);
2809         exit(1);
2810     }
2811
2812     display_count = 1;
2813     result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2814     VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2815
2816     display = display_props.display;
2817
2818     // Get the first mode of the display
2819     result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2820     VERIFY(result == vk::Result::eSuccess);
2821
2822     if (mode_count == 0) {
2823         printf("Cannot find any mode for the display!\n");
2824         fflush(stdout);
2825         exit(1);
2826     }
2827
2828     mode_count = 1;
2829     result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2830     VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2831
2832     // Get the list of planes
2833     result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2834     VERIFY(result == vk::Result::eSuccess);
2835
2836     if (plane_count == 0) {
2837         printf("Cannot find any plane!\n");
2838         fflush(stdout);
2839         exit(1);
2840     }
2841
2842     plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2843     VERIFY(plane_props != nullptr);
2844
2845     result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2846     VERIFY(result == vk::Result::eSuccess);
2847
2848     // Find a plane compatible with the display
2849     for (plane_index = 0; plane_index < plane_count; plane_index++) {
2850         uint32_t supported_count;
2851         vk::DisplayKHR *supported_displays;
2852
2853         // Disqualify planes that are bound to a different display
2854         if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2855             continue;
2856         }
2857
2858         result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
2859         VERIFY(result == vk::Result::eSuccess);
2860
2861         if (supported_count == 0) {
2862             continue;
2863         }
2864
2865         supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2866         VERIFY(supported_displays != nullptr);
2867
2868         result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
2869         VERIFY(result == vk::Result::eSuccess);
2870
2871         for (uint32_t i = 0; i < supported_count; i++) {
2872             if (supported_displays[i] == display) {
2873                 found_plane = VK_TRUE;
2874                 break;
2875             }
2876         }
2877
2878         free(supported_displays);
2879
2880         if (found_plane) {
2881             break;
2882         }
2883     }
2884
2885     if (!found_plane) {
2886         printf("Cannot find a plane compatible with the display!\n");
2887         fflush(stdout);
2888         exit(1);
2889     }
2890
2891     free(plane_props);
2892
2893     vk::DisplayPlaneCapabilitiesKHR planeCaps;
2894     gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2895     // Find a supported alpha mode
2896     vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2897     vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2898         vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2899         vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2900         vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2901         vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2902     };
2903     for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2904         if (planeCaps.supportedAlpha & alphaModes[i]) {
2905             alphaMode = alphaModes[i];
2906             break;
2907         }
2908     }
2909
2910     image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2911     image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2912
2913     auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2914                                 .setDisplayMode(mode_props.displayMode)
2915                                 .setPlaneIndex(plane_index)
2916                                 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2917                                 .setGlobalAlpha(1.0f)
2918                                 .setAlphaMode(alphaMode)
2919                                 .setImageExtent(image_extent);
2920
2921     return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2922 }
2923
2924 void Demo::run_display() {
2925     while (!quit) {
2926         draw();
2927         curFrame++;
2928
2929         if (frameCount != UINT32_MAX && curFrame == frameCount) {
2930             quit = true;
2931         }
2932     }
2933 }
2934 #endif
2935
2936 #if _WIN32
2937 // Include header required for parsing the command line options.
2938 #include <shellapi.h>
2939
2940 Demo demo;
2941
2942 // MS-Windows event handling function:
2943 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2944     switch (uMsg) {
2945         case WM_CLOSE:
2946             PostQuitMessage(validation_error);
2947             break;
2948         case WM_PAINT:
2949             demo.run();
2950             break;
2951         case WM_GETMINMAXINFO:  // set window's minimum size
2952             ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2953             return 0;
2954         case WM_ERASEBKGND:
2955             return 1;
2956         case WM_SIZE:
2957             // Resize the application to the new window size, except when
2958             // it was minimized. Vulkan doesn't support images or swapchains
2959             // with width=0 and height=0.
2960             if (wParam != SIZE_MINIMIZED) {
2961                 demo.width = lParam & 0xffff;
2962                 demo.height = (lParam & 0xffff0000) >> 16;
2963                 demo.resize();
2964             }
2965             break;
2966         case WM_KEYDOWN:
2967             switch (wParam) {
2968                 case VK_ESCAPE:
2969                     PostQuitMessage(validation_error);
2970                     break;
2971                 case VK_LEFT:
2972                     demo.spin_angle -= demo.spin_increment;
2973                     break;
2974                 case VK_RIGHT:
2975                     demo.spin_angle += demo.spin_increment;
2976                     break;
2977                 case VK_SPACE:
2978                     demo.pause = !demo.pause;
2979                     break;
2980             }
2981             return 0;
2982         default:
2983             break;
2984     }
2985
2986     return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2987 }
2988
2989 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
2990     // TODO: Gah.. refactor. This isn't 1989.
2991     MSG msg;    // message
2992     bool done;  // flag saying when app is complete
2993     int argc;
2994     char **argv;
2995
2996     // Ensure wParam is initialized.
2997     msg.wParam = 0;
2998
2999     // Use the CommandLine functions to get the command line arguments.
3000     // Unfortunately, Microsoft outputs
3001     // this information as wide characters for Unicode, and we simply want the
3002     // Ascii version to be compatible
3003     // with the non-Windows side.  So, we have to convert the information to
3004     // Ascii character strings.
3005     LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3006     if (nullptr == commandLineArgs) {
3007         argc = 0;
3008     }
3009
3010     if (argc > 0) {
3011         argv = (char **)malloc(sizeof(char *) * argc);
3012         if (argv == nullptr) {
3013             argc = 0;
3014         } else {
3015             for (int iii = 0; iii < argc; iii++) {
3016                 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3017                 size_t numConverted = 0;
3018
3019                 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3020                 if (argv[iii] != nullptr) {
3021                     wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3022                 }
3023             }
3024         }
3025     } else {
3026         argv = nullptr;
3027     }
3028
3029     demo.init(argc, argv);
3030
3031     // Free up the items we had to allocate for the command line arguments.
3032     if (argc > 0 && argv != nullptr) {
3033         for (int iii = 0; iii < argc; iii++) {
3034             if (argv[iii] != nullptr) {
3035                 free(argv[iii]);
3036             }
3037         }
3038         free(argv);
3039     }
3040
3041     demo.connection = hInstance;
3042     strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
3043     demo.create_window();
3044     demo.init_vk_swapchain();
3045
3046     demo.prepare();
3047
3048     done = false;  // initialize loop condition variable
3049
3050     // main message loop
3051     while (!done) {
3052         if (demo.pause) {
3053             const BOOL succ = WaitMessage();
3054
3055             if (!succ) {
3056                 const auto &suppress_popups = demo.suppress_popups;
3057                 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3058             }
3059         }
3060
3061         PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
3062         if (msg.message == WM_QUIT)  // check for a quit message
3063         {
3064             done = true;  // if found, quit app
3065         } else {
3066             /* Translate and dispatch to event queue*/
3067             TranslateMessage(&msg);
3068             DispatchMessage(&msg);
3069         }
3070         RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3071     }
3072
3073     demo.cleanup();
3074
3075     return (int)msg.wParam;
3076 }
3077
3078 #elif __linux__
3079
3080 int main(int argc, char **argv) {
3081     Demo demo;
3082
3083     demo.init(argc, argv);
3084
3085 #if defined(VK_USE_PLATFORM_XCB_KHR)
3086     demo.create_xcb_window();
3087 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3088     demo.use_xlib = true;
3089     demo.create_xlib_window();
3090 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3091     demo.create_window();
3092 #endif
3093
3094     demo.init_vk_swapchain();
3095
3096     demo.prepare();
3097
3098 #if defined(VK_USE_PLATFORM_XCB_KHR)
3099     demo.run_xcb();
3100 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3101     demo.run_xlib();
3102 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3103     demo.run();
3104 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3105     demo.run_display();
3106 #endif
3107
3108     demo.cleanup();
3109
3110     return validation_error;
3111 }
3112
3113 #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3114
3115 // Global function invoked from NS or UI views and controllers to create demo
3116 static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
3117     demo.init(argc, (char **)argv);
3118     demo.window = view;
3119     demo.init_vk_swapchain();
3120     demo.prepare();
3121     demo.spin_angle = 0.4f;
3122 }
3123
3124 #else
3125 #error "Platform not supported"
3126 #endif