blob: 9973fa0c61316ee9735da8d0eeb8a7ad024f8211 [file] [log] [blame]
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001/*
Dave Houlton5fa47912018-02-16 11:02:26 -07002 * Copyright (c) 2015-2016 The Khronos Group Inc.
3 * Copyright (c) 2015-2016 Valve Corporation
4 * Copyright (c) 2015-2016 LunarG, Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Jeremy Hayes <jeremy@lunarg.com>
19 */
Jeremy Hayesf56427a2016-09-07 15:55:11 -060020
21#if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
22#include <X11/Xutil.h>
Joey Bzdek15eb0702017-06-07 09:40:36 -060023#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
24#include <linux/input.h>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060025#endif
26
27#include <cassert>
Petr Krausbc0ab752017-12-09 00:22:39 +010028#include <cinttypes>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060029#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <csignal>
33#include <memory>
34
Tony Barbourefd0c5a2016-12-07 14:45:12 -070035#if defined(VK_USE_PLATFORM_MIR_KHR)
36#warning "Cubepp does not have code for Mir at this time"
37#endif
38
Mark Lobodzinskidefadcf2017-10-23 09:23:06 -060039#define VULKAN_HPP_NO_SMART_HANDLE
Jeremy Hayesf56427a2016-09-07 15:55:11 -060040#define VULKAN_HPP_NO_EXCEPTIONS
41#include <vulkan/vulkan.hpp>
42#include <vulkan/vk_sdk_platform.h>
43
44#include "linmath.h"
45
46#ifndef NDEBUG
47#define VERIFY(x) assert(x)
48#else
49#define VERIFY(x) ((void)(x))
50#endif
51
52#define APP_SHORT_NAME "cube"
53#ifdef _WIN32
54#define APP_NAME_STR_LEN 80
55#endif
56
57// Allow a maximum of two outstanding presentation operations.
58#define FRAME_LAG 2
59
60#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
61
62#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070063#define ERR_EXIT(err_msg, err_class) \
64 do { \
65 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
66 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060067 } while (0)
68#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070069#define ERR_EXIT(err_msg, err_class) \
70 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080071 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070072 fflush(stdout); \
73 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060074 } while (0)
75#endif
76
Jeremy Hayes9d304782016-10-09 11:48:12 -060077struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060078 vk::Sampler sampler;
79
80 vk::Image image;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070081 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060082
83 vk::MemoryAllocateInfo mem_alloc;
84 vk::DeviceMemory mem;
85 vk::ImageView view;
86
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070087 int32_t tex_width{0};
88 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060089};
90
Jeremy Hayes9d304782016-10-09 11:48:12 -060091static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060092
93static int validation_error = 0;
94
95struct vkcube_vs_uniform {
96 // Must start with MVP
97 float mvp[4][4];
98 float position[12 * 3][4];
99 float color[12 * 3][4];
100};
101
102struct vktexcube_vs_uniform {
103 // Must start with MVP
104 float mvp[4][4];
105 float position[12 * 3][4];
106 float attr[12 * 3][4];
107};
108
109//--------------------------------------------------------------------------------------
110// Mesh and VertexFormat Data
111//--------------------------------------------------------------------------------------
112// clang-format off
113static const float g_vertex_buffer_data[] = {
114 -1.0f,-1.0f,-1.0f, // -X side
115 -1.0f,-1.0f, 1.0f,
116 -1.0f, 1.0f, 1.0f,
117 -1.0f, 1.0f, 1.0f,
118 -1.0f, 1.0f,-1.0f,
119 -1.0f,-1.0f,-1.0f,
120
121 -1.0f,-1.0f,-1.0f, // -Z side
122 1.0f, 1.0f,-1.0f,
123 1.0f,-1.0f,-1.0f,
124 -1.0f,-1.0f,-1.0f,
125 -1.0f, 1.0f,-1.0f,
126 1.0f, 1.0f,-1.0f,
127
128 -1.0f,-1.0f,-1.0f, // -Y side
129 1.0f,-1.0f,-1.0f,
130 1.0f,-1.0f, 1.0f,
131 -1.0f,-1.0f,-1.0f,
132 1.0f,-1.0f, 1.0f,
133 -1.0f,-1.0f, 1.0f,
134
135 -1.0f, 1.0f,-1.0f, // +Y side
136 -1.0f, 1.0f, 1.0f,
137 1.0f, 1.0f, 1.0f,
138 -1.0f, 1.0f,-1.0f,
139 1.0f, 1.0f, 1.0f,
140 1.0f, 1.0f,-1.0f,
141
142 1.0f, 1.0f,-1.0f, // +X side
143 1.0f, 1.0f, 1.0f,
144 1.0f,-1.0f, 1.0f,
145 1.0f,-1.0f, 1.0f,
146 1.0f,-1.0f,-1.0f,
147 1.0f, 1.0f,-1.0f,
148
149 -1.0f, 1.0f, 1.0f, // +Z side
150 -1.0f,-1.0f, 1.0f,
151 1.0f, 1.0f, 1.0f,
152 -1.0f,-1.0f, 1.0f,
153 1.0f,-1.0f, 1.0f,
154 1.0f, 1.0f, 1.0f,
155};
156
157static const float g_uv_buffer_data[] = {
158 0.0f, 1.0f, // -X side
159 1.0f, 1.0f,
160 1.0f, 0.0f,
161 1.0f, 0.0f,
162 0.0f, 0.0f,
163 0.0f, 1.0f,
164
165 1.0f, 1.0f, // -Z side
166 0.0f, 0.0f,
167 0.0f, 1.0f,
168 1.0f, 1.0f,
169 1.0f, 0.0f,
170 0.0f, 0.0f,
171
172 1.0f, 0.0f, // -Y side
173 1.0f, 1.0f,
174 0.0f, 1.0f,
175 1.0f, 0.0f,
176 0.0f, 1.0f,
177 0.0f, 0.0f,
178
179 1.0f, 0.0f, // +Y side
180 0.0f, 0.0f,
181 0.0f, 1.0f,
182 1.0f, 0.0f,
183 0.0f, 1.0f,
184 1.0f, 1.0f,
185
186 1.0f, 0.0f, // +X side
187 0.0f, 0.0f,
188 0.0f, 1.0f,
189 0.0f, 1.0f,
190 1.0f, 1.0f,
191 1.0f, 0.0f,
192
193 0.0f, 0.0f, // +Z side
194 0.0f, 1.0f,
195 1.0f, 0.0f,
196 0.0f, 1.0f,
197 1.0f, 1.0f,
198 1.0f, 0.0f,
199};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600200// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600201
Jeremy Hayes9d304782016-10-09 11:48:12 -0600202typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600203 vk::Image image;
204 vk::CommandBuffer cmd;
205 vk::CommandBuffer graphics_to_present_cmd;
206 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600207 vk::Buffer uniform_buffer;
208 vk::DeviceMemory uniform_memory;
209 vk::Framebuffer framebuffer;
210 vk::DescriptorSet descriptor_set;
211} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600212
Joey Bzdekbaf66472017-06-07 09:37:37 -0600213struct Demo {
214 Demo();
215 void build_image_ownership_cmd(uint32_t const &);
216 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
217 void cleanup();
218 void create_device();
219 void destroy_texture_image(texture_object *);
220 void draw();
221 void draw_build_cmd(vk::CommandBuffer);
222 void flush_init_cmd();
223 void init(int, char **);
224 void init_connection();
225 void init_vk();
226 void init_vk_swapchain();
227 void prepare();
228 void prepare_buffers();
229 void prepare_cube_data_buffers();
230 void prepare_depth();
231 void prepare_descriptor_layout();
232 void prepare_descriptor_pool();
233 void prepare_descriptor_set();
234 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100235 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
236 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600237 vk::ShaderModule prepare_fs();
238 void prepare_pipeline();
239 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600240 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
241 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100242
Joey Bzdekbaf66472017-06-07 09:37:37 -0600243 void resize();
244 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
245 vk::PipelineStageFlags, vk::PipelineStageFlags);
246 void update_data_buffer();
247 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
248 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
249
250#if defined(VK_USE_PLATFORM_WIN32_KHR)
251 void run();
252 void create_window();
253#elif defined(VK_USE_PLATFORM_XLIB_KHR)
254 void create_xlib_window();
255 void handle_xlib_event(const XEvent *);
256 void run_xlib();
257#elif defined(VK_USE_PLATFORM_XCB_KHR)
258 void handle_xcb_event(const xcb_generic_event_t *);
259 void run_xcb();
260 void create_xcb_window();
261#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
262 void run();
263 void create_window();
Karl Schultz206b1c52018-04-13 18:02:07 -0600264#elif defined(VK_USE_PLATFORM_MACOS_MVK)
265 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600266#elif defined(VK_USE_PLATFORM_MIR_KHR)
267#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
268 vk::Result create_display_surface();
269 void run_display();
270#endif
271
272#if defined(VK_USE_PLATFORM_WIN32_KHR)
273 HINSTANCE connection; // hInstance - Windows Instance
274 HWND window; // hWnd - window handle
275 POINT minsize; // minimum window size
276 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
277#elif defined(VK_USE_PLATFORM_XLIB_KHR)
278 Window xlib_window;
279 Atom xlib_wm_delete_window;
280 Display *display;
281#elif defined(VK_USE_PLATFORM_XCB_KHR)
282 xcb_window_t xcb_window;
283 xcb_screen_t *screen;
284 xcb_connection_t *connection;
285 xcb_intern_atom_reply_t *atom_wm_delete_window;
286#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
287 wl_display *display;
288 wl_registry *registry;
289 wl_compositor *compositor;
290 wl_surface *window;
291 wl_shell *shell;
292 wl_shell_surface *shell_surface;
293 wl_seat *seat;
294 wl_pointer *pointer;
295 wl_keyboard *keyboard;
296#elif defined(VK_USE_PLATFORM_MIR_KHR)
Karl Schultz9ceac062017-12-12 10:33:01 -0500297#elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
298 void *window;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600299#endif
300
301 vk::SurfaceKHR surface;
302 bool prepared;
303 bool use_staging_buffer;
304 bool use_xlib;
305 bool separate_present_queue;
306
307 vk::Instance inst;
308 vk::PhysicalDevice gpu;
309 vk::Device device;
310 vk::Queue graphics_queue;
311 vk::Queue present_queue;
312 uint32_t graphics_queue_family_index;
313 uint32_t present_queue_family_index;
314 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
315 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
316 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
317 vk::PhysicalDeviceProperties gpu_props;
318 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
319 vk::PhysicalDeviceMemoryProperties memory_properties;
320
321 uint32_t enabled_extension_count;
322 uint32_t enabled_layer_count;
323 char const *extension_names[64];
324 char const *enabled_layers[64];
325
326 uint32_t width;
327 uint32_t height;
328 vk::Format format;
329 vk::ColorSpaceKHR color_space;
330
331 uint32_t swapchainImageCount;
332 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600333 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600334 vk::PresentModeKHR presentMode;
335 vk::Fence fences[FRAME_LAG];
336 uint32_t frame_index;
337
338 vk::CommandPool cmd_pool;
339 vk::CommandPool present_cmd_pool;
340
341 struct {
342 vk::Format format;
343 vk::Image image;
344 vk::MemoryAllocateInfo mem_alloc;
345 vk::DeviceMemory mem;
346 vk::ImageView view;
347 } depth;
348
349 static int32_t const texture_count = 1;
350 texture_object textures[texture_count];
351 texture_object staging_texture;
352
353 struct {
354 vk::Buffer buf;
355 vk::MemoryAllocateInfo mem_alloc;
356 vk::DeviceMemory mem;
357 vk::DescriptorBufferInfo buffer_info;
358 } uniform_data;
359
360 vk::CommandBuffer cmd; // Buffer for initialization commands
361 vk::PipelineLayout pipeline_layout;
362 vk::DescriptorSetLayout desc_layout;
363 vk::PipelineCache pipelineCache;
364 vk::RenderPass render_pass;
365 vk::Pipeline pipeline;
366
367 mat4x4 projection_matrix;
368 mat4x4 view_matrix;
369 mat4x4 model_matrix;
370
371 float spin_angle;
372 float spin_increment;
373 bool pause;
374
375 vk::ShaderModule vert_shader_module;
376 vk::ShaderModule frag_shader_module;
377
378 vk::DescriptorPool desc_pool;
379 vk::DescriptorSet desc_set;
380
381 std::unique_ptr<vk::Framebuffer[]> framebuffers;
382
383 bool quit;
384 uint32_t curFrame;
385 uint32_t frameCount;
386 bool validate;
387 bool use_break;
388 bool suppress_popups;
389
390 uint32_t current_buffer;
391 uint32_t queue_family_count;
392};
393
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600394#ifdef _WIN32
395// MS-Windows event handling function:
396LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
397#endif
398
Karl Schultz23cc2182016-11-23 17:15:17 -0700399#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700400static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700401 wl_shell_surface_pong(shell_surface, serial);
402}
403
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700404static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700405
406static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
407
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700408static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700409
Joey Bzdek15eb0702017-06-07 09:40:36 -0600410static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
411 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700412
Joey Bzdek15eb0702017-06-07 09:40:36 -0600413static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700414
Joey Bzdek15eb0702017-06-07 09:40:36 -0600415static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
416
417static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
418 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600419 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600420 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
421 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
422 }
423}
424
425static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
426
427static const struct wl_pointer_listener pointer_listener = {
428 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
429};
430
431static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
432
433static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
434 struct wl_array *keys) {}
435
436static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
437
438static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
439 uint32_t state) {
440 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
441 Demo *demo = (Demo *)data;
442 switch (key) {
443 case KEY_ESC: // Escape
444 demo->quit = true;
445 break;
446 case KEY_LEFT: // left arrow key
447 demo->spin_angle -= demo->spin_increment;
448 break;
449 case KEY_RIGHT: // right arrow key
450 demo->spin_angle += demo->spin_increment;
451 break;
452 case KEY_SPACE: // space bar
453 demo->pause = !demo->pause;
454 break;
455 }
456}
457
458static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
459 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
460
461static const struct wl_keyboard_listener keyboard_listener = {
462 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
463};
464
465static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
466 // Subscribe to pointer events
467 Demo *demo = (Demo *)data;
468 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
469 demo->pointer = wl_seat_get_pointer(seat);
470 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
471 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
472 wl_pointer_destroy(demo->pointer);
473 demo->pointer = NULL;
474 }
475 // Subscribe to keyboard events
476 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
477 demo->keyboard = wl_seat_get_keyboard(seat);
478 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
479 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
480 wl_keyboard_destroy(demo->keyboard);
481 demo->keyboard = NULL;
482 }
483}
484
485static const wl_seat_listener seat_listener = {
486 seat_handle_capabilities,
487};
488
489static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
490 Demo *demo = (Demo *)data;
491 // pickup wayland objects when they appear
492 if (strcmp(interface, "wl_compositor") == 0) {
493 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
494 } else if (strcmp(interface, "wl_shell") == 0) {
495 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
496 } else if (strcmp(interface, "wl_seat") == 0) {
497 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
498 wl_seat_add_listener(demo->seat, &seat_listener, demo);
499 }
500}
501
502static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
503
504static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Tony Barbourefd0c5a2016-12-07 14:45:12 -0700505#elif defined(VK_USE_PLATFORM_MIR_KHR)
Karl Schultz23cc2182016-11-23 17:15:17 -0700506#endif
507
Joey Bzdekbaf66472017-06-07 09:37:37 -0600508Demo::Demo()
509 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600510#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600511 connection{nullptr},
512 window{nullptr},
513 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600514#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700515
Tony Barbour78d6b572016-11-14 14:46:33 -0700516#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600517 xlib_window{0},
518 xlib_wm_delete_window{0},
519 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700520#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521 xcb_window{0},
522 screen{nullptr},
523 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700524#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600525 display{nullptr},
526 registry{nullptr},
527 compositor{nullptr},
528 window{nullptr},
529 shell{nullptr},
530 shell_surface{nullptr},
531 seat{nullptr},
532 pointer{nullptr},
533 keyboard{nullptr},
Tony Barbourefd0c5a2016-12-07 14:45:12 -0700534#elif defined(VK_USE_PLATFORM_MIR_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -0700535#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600536 prepared{false},
537 use_staging_buffer{false},
538 use_xlib{false},
539 graphics_queue_family_index{0},
540 present_queue_family_index{0},
541 enabled_extension_count{0},
542 enabled_layer_count{0},
543 width{0},
544 height{0},
545 swapchainImageCount{0},
546 frame_index{0},
547 spin_angle{0.0f},
548 spin_increment{0.0f},
549 pause{false},
550 quit{false},
551 curFrame{0},
552 frameCount{0},
553 validate{false},
554 use_break{false},
555 suppress_popups{false},
556 current_buffer{0},
557 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600558#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700559 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600560#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700561 memset(projection_matrix, 0, sizeof(projection_matrix));
562 memset(view_matrix, 0, sizeof(view_matrix));
563 memset(model_matrix, 0, sizeof(model_matrix));
564}
565
566void Demo::build_image_ownership_cmd(uint32_t const &i) {
567 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
568 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
569 VERIFY(result == vk::Result::eSuccess);
570
571 auto const image_ownership_barrier =
572 vk::ImageMemoryBarrier()
573 .setSrcAccessMask(vk::AccessFlags())
574 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
575 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
577 .setSrcQueueFamilyIndex(graphics_queue_family_index)
578 .setDstQueueFamilyIndex(present_queue_family_index)
579 .setImage(swapchain_image_resources[i].image)
580 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
581
582 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
583 vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput,
584 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
585
586 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
587 VERIFY(result == vk::Result::eSuccess);
588}
589
590vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
591 vk::LayerProperties *layers) {
592 for (uint32_t i = 0; i < check_count; i++) {
593 vk::Bool32 found = VK_FALSE;
594 for (uint32_t j = 0; j < layer_count; j++) {
595 if (!strcmp(check_names[i], layers[j].layerName)) {
596 found = VK_TRUE;
597 break;
598 }
599 }
600 if (!found) {
601 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
602 return 0;
603 }
604 }
605 return VK_TRUE;
606}
607
608void Demo::cleanup() {
609 prepared = false;
610 device.waitIdle();
611
612 // Wait for fences from present operations
613 for (uint32_t i = 0; i < FRAME_LAG; i++) {
614 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
615 device.destroyFence(fences[i], nullptr);
616 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
617 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
618 if (separate_present_queue) {
619 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
620 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600621 }
622
Dave Houlton5fa47912018-02-16 11:02:26 -0700623 for (uint32_t i = 0; i < swapchainImageCount; i++) {
624 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
625 }
626 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600627
Dave Houlton5fa47912018-02-16 11:02:26 -0700628 device.destroyPipeline(pipeline, nullptr);
629 device.destroyPipelineCache(pipelineCache, nullptr);
630 device.destroyRenderPass(render_pass, nullptr);
631 device.destroyPipelineLayout(pipeline_layout, nullptr);
632 device.destroyDescriptorSetLayout(desc_layout, nullptr);
633
634 for (uint32_t i = 0; i < texture_count; i++) {
635 device.destroyImageView(textures[i].view, nullptr);
636 device.destroyImage(textures[i].image, nullptr);
637 device.freeMemory(textures[i].mem, nullptr);
638 device.destroySampler(textures[i].sampler, nullptr);
639 }
640 device.destroySwapchainKHR(swapchain, nullptr);
641
642 device.destroyImageView(depth.view, nullptr);
643 device.destroyImage(depth.image, nullptr);
644 device.freeMemory(depth.mem, nullptr);
645
646 for (uint32_t i = 0; i < swapchainImageCount; i++) {
647 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
648 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
649 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
650 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
651 }
652
653 device.destroyCommandPool(cmd_pool, nullptr);
654
655 if (separate_present_queue) {
656 device.destroyCommandPool(present_cmd_pool, nullptr);
657 }
658 device.waitIdle();
659 device.destroy(nullptr);
660 inst.destroySurfaceKHR(surface, nullptr);
661
662#if defined(VK_USE_PLATFORM_XLIB_KHR)
663 XDestroyWindow(display, xlib_window);
664 XCloseDisplay(display);
665#elif defined(VK_USE_PLATFORM_XCB_KHR)
666 xcb_destroy_window(connection, xcb_window);
667 xcb_disconnect(connection);
668 free(atom_wm_delete_window);
669#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
670 wl_keyboard_destroy(keyboard);
671 wl_pointer_destroy(pointer);
672 wl_seat_destroy(seat);
673 wl_shell_surface_destroy(shell_surface);
674 wl_surface_destroy(window);
675 wl_shell_destroy(shell);
676 wl_compositor_destroy(compositor);
677 wl_registry_destroy(registry);
678 wl_display_disconnect(display);
679#elif defined(VK_USE_PLATFORM_MIR_KHR)
680#endif
681
682 inst.destroy(nullptr);
683}
684
685void Demo::create_device() {
686 float const priorities[1] = {0.0};
687
688 vk::DeviceQueueCreateInfo queues[2];
689 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
690 queues[0].setQueueCount(1);
691 queues[0].setPQueuePriorities(priorities);
692
693 auto deviceInfo = vk::DeviceCreateInfo()
694 .setQueueCreateInfoCount(1)
695 .setPQueueCreateInfos(queues)
696 .setEnabledLayerCount(0)
697 .setPpEnabledLayerNames(nullptr)
698 .setEnabledExtensionCount(enabled_extension_count)
699 .setPpEnabledExtensionNames((const char *const *)extension_names)
700 .setPEnabledFeatures(nullptr);
701
702 if (separate_present_queue) {
703 queues[1].setQueueFamilyIndex(present_queue_family_index);
704 queues[1].setQueueCount(1);
705 queues[1].setPQueuePriorities(priorities);
706 deviceInfo.setQueueCreateInfoCount(2);
707 }
708
709 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
710 VERIFY(result == vk::Result::eSuccess);
711}
712
713void Demo::destroy_texture_image(texture_object *tex_objs) {
714 // clean up staging resources
715 device.freeMemory(tex_objs->mem, nullptr);
716 device.destroyImage(tex_objs->image, nullptr);
717}
718
719void Demo::draw() {
720 // Ensure no more than FRAME_LAG renderings are outstanding
721 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
722 device.resetFences(1, &fences[frame_index]);
723
724 vk::Result result;
725 do {
726 result =
727 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
728 if (result == vk::Result::eErrorOutOfDateKHR) {
729 // demo->swapchain is out of date (e.g. the window was resized) and
730 // must be recreated:
731 resize();
732 } else if (result == vk::Result::eSuboptimalKHR) {
733 // swapchain is not as optimal as it could be, but the platform's
734 // presentation engine will still present the image correctly.
735 break;
736 } else {
737 VERIFY(result == vk::Result::eSuccess);
738 }
739 } while (result != vk::Result::eSuccess);
740
741 update_data_buffer();
742
743 // Wait for the image acquired semaphore to be signaled to ensure
744 // that the image won't be rendered to until the presentation
745 // engine has fully released ownership to the application, and it is
746 // okay to render to the image.
747 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
748 auto const submit_info = vk::SubmitInfo()
749 .setPWaitDstStageMask(&pipe_stage_flags)
750 .setWaitSemaphoreCount(1)
751 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
752 .setCommandBufferCount(1)
753 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
754 .setSignalSemaphoreCount(1)
755 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
756
757 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
758 VERIFY(result == vk::Result::eSuccess);
759
760 if (separate_present_queue) {
761 // If we are using separate queues, change image ownership to the
762 // present queue before presenting, waiting for the draw complete
763 // semaphore and signalling the ownership released semaphore when
764 // finished
765 auto const present_submit_info = vk::SubmitInfo()
766 .setPWaitDstStageMask(&pipe_stage_flags)
767 .setWaitSemaphoreCount(1)
768 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
769 .setCommandBufferCount(1)
770 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
771 .setSignalSemaphoreCount(1)
772 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
773
774 result = present_queue.submit(1, &present_submit_info, vk::Fence());
775 VERIFY(result == vk::Result::eSuccess);
776 }
777
778 // If we are using separate queues we have to wait for image ownership,
779 // otherwise wait for draw complete
780 auto const presentInfo = vk::PresentInfoKHR()
781 .setWaitSemaphoreCount(1)
782 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
783 : &draw_complete_semaphores[frame_index])
784 .setSwapchainCount(1)
785 .setPSwapchains(&swapchain)
786 .setPImageIndices(&current_buffer);
787
788 result = present_queue.presentKHR(&presentInfo);
789 frame_index += 1;
790 frame_index %= FRAME_LAG;
791 if (result == vk::Result::eErrorOutOfDateKHR) {
792 // swapchain is out of date (e.g. the window was resized) and
793 // must be recreated:
794 resize();
795 } else if (result == vk::Result::eSuboptimalKHR) {
796 // swapchain is not as optimal as it could be, but the platform's
797 // presentation engine will still present the image correctly.
798 } else {
799 VERIFY(result == vk::Result::eSuccess);
800 }
801}
802
803void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
804 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
805
806 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
807 vk::ClearDepthStencilValue(1.0f, 0u)};
808
809 auto const passInfo = vk::RenderPassBeginInfo()
810 .setRenderPass(render_pass)
811 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
812 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
813 .setClearValueCount(2)
814 .setPClearValues(clearValues);
815
816 auto result = commandBuffer.begin(&commandInfo);
817 VERIFY(result == vk::Result::eSuccess);
818
819 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
820 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
821 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
822 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
823
824 auto const viewport =
825 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
826 commandBuffer.setViewport(0, 1, &viewport);
827
828 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
829 commandBuffer.setScissor(0, 1, &scissor);
830 commandBuffer.draw(12 * 3, 1, 0, 0);
831 // Note that ending the renderpass changes the image's layout from
832 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
833 commandBuffer.endRenderPass();
834
835 if (separate_present_queue) {
836 // We have to transfer ownership from the graphics queue family to
837 // the
838 // present queue family to be able to present. Note that we don't
839 // have
840 // to transfer from present queue family back to graphics queue
841 // family at
842 // the start of the next frame because we don't care about the
843 // image's
844 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600845 auto const image_ownership_barrier =
846 vk::ImageMemoryBarrier()
847 .setSrcAccessMask(vk::AccessFlags())
848 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
849 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
850 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
851 .setSrcQueueFamilyIndex(graphics_queue_family_index)
852 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700853 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700854 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600855
Dave Houlton5fa47912018-02-16 11:02:26 -0700856 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eBottomOfPipe,
857 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600858 }
859
Dave Houlton5fa47912018-02-16 11:02:26 -0700860 result = commandBuffer.end();
861 VERIFY(result == vk::Result::eSuccess);
862}
863
864void Demo::flush_init_cmd() {
865 // TODO: hmm.
866 // This function could get called twice if the texture uses a staging
867 // buffer
868 // In that case the second call should be ignored
869 if (!cmd) {
870 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600871 }
872
Dave Houlton5fa47912018-02-16 11:02:26 -0700873 auto result = cmd.end();
874 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600875
Dave Houlton5fa47912018-02-16 11:02:26 -0700876 auto const fenceInfo = vk::FenceCreateInfo();
877 vk::Fence fence;
878 result = device.createFence(&fenceInfo, nullptr, &fence);
879 VERIFY(result == vk::Result::eSuccess);
880
881 vk::CommandBuffer const commandBuffers[] = {cmd};
882 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
883
884 result = graphics_queue.submit(1, &submitInfo, fence);
885 VERIFY(result == vk::Result::eSuccess);
886
887 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
888 VERIFY(result == vk::Result::eSuccess);
889
890 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
891 device.destroyFence(fence, nullptr);
892
893 cmd = vk::CommandBuffer();
894}
895
896void Demo::init(int argc, char **argv) {
897 vec3 eye = {0.0f, 3.0f, 5.0f};
898 vec3 origin = {0, 0, 0};
899 vec3 up = {0.0f, 1.0f, 0.0};
900
901 presentMode = vk::PresentModeKHR::eFifo;
902 frameCount = UINT32_MAX;
903 use_xlib = false;
904
905 for (int i = 1; i < argc; i++) {
906 if (strcmp(argv[i], "--use_staging") == 0) {
907 use_staging_buffer = true;
908 continue;
909 }
910 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
911 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
912 i++;
913 continue;
914 }
915 if (strcmp(argv[i], "--break") == 0) {
916 use_break = true;
917 continue;
918 }
919 if (strcmp(argv[i], "--validate") == 0) {
920 validate = true;
921 continue;
922 }
923 if (strcmp(argv[i], "--xlib") == 0) {
924 fprintf(stderr, "--xlib is deprecated and no longer does anything");
925 continue;
926 }
927 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
928 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
929 i++;
930 continue;
931 }
932 if (strcmp(argv[i], "--suppress_popups") == 0) {
933 suppress_popups = true;
934 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600935 }
936
Dave Houlton5fa47912018-02-16 11:02:26 -0700937 fprintf(stderr,
938 "Usage:\n %s [--use_staging] [--validate] [--break] [--c <framecount>] \n"
939 " [--suppress_popups] [--present_mode {0,1,2,3}]\n"
940 "\n"
941 "Options for --present_mode:\n"
942 " %d: VK_PRESENT_MODE_IMMEDIATE_KHR\n"
943 " %d: VK_PRESENT_MODE_MAILBOX_KHR\n"
944 " %d: VK_PRESENT_MODE_FIFO_KHR (default)\n"
945 " %d: VK_PRESENT_MODE_FIFO_RELAXED_KHR\n",
946 APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
947 VK_PRESENT_MODE_FIFO_RELAXED_KHR);
948 fflush(stderr);
949 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600950 }
951
Dave Houlton5fa47912018-02-16 11:02:26 -0700952 if (!use_xlib) {
953 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600954 }
955
Dave Houlton5fa47912018-02-16 11:02:26 -0700956 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600957
Dave Houlton5fa47912018-02-16 11:02:26 -0700958 width = 500;
959 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600960
Dave Houlton5fa47912018-02-16 11:02:26 -0700961 spin_angle = 4.0f;
962 spin_increment = 0.2f;
963 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600964
Dave Houlton5fa47912018-02-16 11:02:26 -0700965 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
966 mat4x4_look_at(view_matrix, eye, origin, up);
967 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600968
Dave Houlton5fa47912018-02-16 11:02:26 -0700969 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
970}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600971
Dave Houlton5fa47912018-02-16 11:02:26 -0700972void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600973#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700974 const xcb_setup_t *setup;
975 xcb_screen_iterator_t iter;
976 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600977
Dave Houlton5fa47912018-02-16 11:02:26 -0700978 const char *display_envar = getenv("DISPLAY");
979 if (display_envar == nullptr || display_envar[0] == '\0') {
980 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
981 fflush(stdout);
982 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600983 }
984
Dave Houlton5fa47912018-02-16 11:02:26 -0700985 connection = xcb_connect(nullptr, &scr);
986 if (xcb_connection_has_error(connection) > 0) {
987 printf(
988 "Cannot find a compatible Vulkan installable client driver "
989 "(ICD).\nExiting ...\n");
990 fflush(stdout);
991 exit(1);
992 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600993
Dave Houlton5fa47912018-02-16 11:02:26 -0700994 setup = xcb_get_setup(connection);
995 iter = xcb_setup_roots_iterator(setup);
996 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600997
Dave Houlton5fa47912018-02-16 11:02:26 -0700998 screen = iter.data;
999#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1000 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001001
Dave Houlton5fa47912018-02-16 11:02:26 -07001002 if (display == nullptr) {
1003 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1004 fflush(stdout);
1005 exit(1);
1006 }
1007
1008 registry = wl_display_get_registry(display);
1009 wl_registry_add_listener(registry, &registry_listener, this);
1010 wl_display_dispatch(display);
1011#elif defined(VK_USE_PLATFORM_MIR_KHR)
1012#endif
1013}
1014
1015void Demo::init_vk() {
1016 uint32_t instance_extension_count = 0;
1017 uint32_t instance_layer_count = 0;
1018 uint32_t validation_layer_count = 0;
1019 char const *const *instance_validation_layers = nullptr;
1020 enabled_extension_count = 0;
1021 enabled_layer_count = 0;
1022
1023 char const *const instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"};
1024
1025 char const *const instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
1026 "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation",
1027 "VK_LAYER_GOOGLE_unique_objects"};
1028
1029 // Look for validation layers
1030 vk::Bool32 validation_found = VK_FALSE;
1031 if (validate) {
1032 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, nullptr);
1033 VERIFY(result == vk::Result::eSuccess);
1034
1035 instance_validation_layers = instance_validation_layers_alt1;
1036 if (instance_layer_count > 0) {
1037 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1038 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001039 VERIFY(result == vk::Result::eSuccess);
1040
Dave Houlton5fa47912018-02-16 11:02:26 -07001041 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers,
1042 instance_layer_count, instance_layers.get());
1043 if (validation_found) {
1044 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
1045 enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
1046 validation_layer_count = 1;
1047 } else {
1048 // use alternative set of validation layers
1049 instance_validation_layers = instance_validation_layers_alt2;
1050 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
1051 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers,
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07001052 instance_layer_count, instance_layers.get());
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
1054 for (uint32_t i = 0; i < validation_layer_count; i++) {
1055 enabled_layers[i] = instance_validation_layers[i];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001056 }
1057 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001058 }
1059
Dave Houlton5fa47912018-02-16 11:02:26 -07001060 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001061 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001062 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1063 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001064 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001065 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001066 }
1067
Dave Houlton5fa47912018-02-16 11:02:26 -07001068 /* Look for instance extensions */
1069 vk::Bool32 surfaceExtFound = VK_FALSE;
1070 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1071 memset(extension_names, 0, sizeof(extension_names));
1072
1073 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
1074 VERIFY(result == vk::Result::eSuccess);
1075
1076 if (instance_extension_count > 0) {
1077 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1078 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1079 VERIFY(result == vk::Result::eSuccess);
1080
1081 for (uint32_t i = 0; i < instance_extension_count; i++) {
1082 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1083 surfaceExtFound = 1;
1084 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1085 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001086#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001087 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1088 platformSurfaceExtFound = 1;
1089 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1090 }
1091#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1092 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1093 platformSurfaceExtFound = 1;
1094 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1095 }
1096#elif defined(VK_USE_PLATFORM_XCB_KHR)
1097 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1098 platformSurfaceExtFound = 1;
1099 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1100 }
Tony Barbour153cb062016-12-07 13:43:36 -07001101#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001102 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1103 platformSurfaceExtFound = 1;
1104 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1105 }
1106#elif defined(VK_USE_PLATFORM_MIR_KHR)
1107#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1108 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1109 platformSurfaceExtFound = 1;
1110 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1111 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001112#elif defined(VK_USE_PLATFORM_IOS_MVK)
1113 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1114 platformSurfaceExtFound = 1;
1115 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1116 }
1117#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1118 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1119 platformSurfaceExtFound = 1;
1120 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1121 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001122
Dave Houlton5fa47912018-02-16 11:02:26 -07001123#endif
1124 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001125 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001126 }
1127
1128 if (!surfaceExtFound) {
1129 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1130 " extension.\n\n"
1131 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1132 "Please look at the Getting Started guide for additional information.\n",
1133 "vkCreateInstance Failure");
1134 }
1135
1136 if (!platformSurfaceExtFound) {
1137#if defined(VK_USE_PLATFORM_WIN32_KHR)
1138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1139 " extension.\n\n"
1140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1141 "Please look at the Getting Started guide for additional information.\n",
1142 "vkCreateInstance Failure");
1143#elif defined(VK_USE_PLATFORM_XCB_KHR)
1144 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1145 " extension.\n\n"
1146 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1147 "Please look at the Getting Started guide for additional information.\n",
1148 "vkCreateInstance Failure");
1149#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1150 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1151 " extension.\n\n"
1152 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1153 "Please look at the Getting Started guide for additional information.\n",
1154 "vkCreateInstance Failure");
Tony Barbourefd0c5a2016-12-07 14:45:12 -07001155#elif defined(VK_USE_PLATFORM_MIR_KHR)
Tony Barbour153cb062016-12-07 13:43:36 -07001156#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001157 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1158 " extension.\n\n"
1159 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1160 "Please look at the Getting Started guide for additional information.\n",
1161 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001162#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001163 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1164 " extension.\n\n"
1165 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1166 "Please look at the Getting Started guide for additional information.\n",
1167 "vkCreateInstance Failure");
Karl Schultz9ceac062017-12-12 10:33:01 -05001168#elif defined(VK_USE_PLATFORM_IOS_MVK)
1169 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1170 " extension.\n\nDo you have a compatible "
1171 "Vulkan installable client driver (ICD) installed?\nPlease "
1172 "look at the Getting Started guide for additional "
1173 "information.\n",
1174 "vkCreateInstance Failure");
1175#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1176 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1177 " extension.\n\nDo you have a compatible "
1178 "Vulkan installable client driver (ICD) installed?\nPlease "
1179 "look at the Getting Started guide for additional "
1180 "information.\n",
1181 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001182#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001183 }
1184 auto const app = vk::ApplicationInfo()
1185 .setPApplicationName(APP_SHORT_NAME)
1186 .setApplicationVersion(0)
1187 .setPEngineName(APP_SHORT_NAME)
1188 .setEngineVersion(0)
1189 .setApiVersion(VK_API_VERSION_1_0);
1190 auto const inst_info = vk::InstanceCreateInfo()
1191 .setPApplicationInfo(&app)
1192 .setEnabledLayerCount(enabled_layer_count)
1193 .setPpEnabledLayerNames(instance_validation_layers)
1194 .setEnabledExtensionCount(enabled_extension_count)
1195 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001196
Dave Houlton5fa47912018-02-16 11:02:26 -07001197 result = vk::createInstance(&inst_info, nullptr, &inst);
1198 if (result == vk::Result::eErrorIncompatibleDriver) {
1199 ERR_EXIT(
1200 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1201 "Please look at the Getting Started guide for additional information.\n",
1202 "vkCreateInstance Failure");
1203 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1204 ERR_EXIT(
1205 "Cannot find a specified extension library.\n"
1206 "Make sure your layers path is set appropriately.\n",
1207 "vkCreateInstance Failure");
1208 } else if (result != vk::Result::eSuccess) {
1209 ERR_EXIT(
1210 "vkCreateInstance failed.\n\n"
1211 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1212 "Please look at the Getting Started guide for additional information.\n",
1213 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001214 }
1215
Dave Houlton5fa47912018-02-16 11:02:26 -07001216 /* Make initial call to query gpu_count, then second call for gpu info*/
1217 uint32_t gpu_count;
1218 result = inst.enumeratePhysicalDevices(&gpu_count, nullptr);
1219 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001220
1221 if (gpu_count > 0) {
1222 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1223 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001224 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001225 /* For cube demo we just grab the first physical device */
1226 gpu = physical_devices[0];
1227 } else {
1228 ERR_EXIT(
1229 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1230 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1231 "Please look at the Getting Started guide for additional information.\n",
1232 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001233 }
1234
Dave Houlton5fa47912018-02-16 11:02:26 -07001235 /* Look for device extensions */
1236 uint32_t device_extension_count = 0;
1237 vk::Bool32 swapchainExtFound = VK_FALSE;
1238 enabled_extension_count = 0;
1239 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001240
Dave Houlton5fa47912018-02-16 11:02:26 -07001241 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, nullptr);
1242 VERIFY(result == vk::Result::eSuccess);
1243
1244 if (device_extension_count > 0) {
1245 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1246 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001247 VERIFY(result == vk::Result::eSuccess);
1248
Dave Houlton5fa47912018-02-16 11:02:26 -07001249 for (uint32_t i = 0; i < device_extension_count; i++) {
1250 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1251 swapchainExtFound = 1;
1252 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001253 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001254 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001255 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001256 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001257
Dave Houlton5fa47912018-02-16 11:02:26 -07001258 if (!swapchainExtFound) {
1259 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1260 " extension.\n\n"
1261 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1262 "Please look at the Getting Started guide for additional information.\n",
1263 "vkCreateInstance Failure");
1264 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001265
Dave Houlton5fa47912018-02-16 11:02:26 -07001266 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001267
Dave Houlton5fa47912018-02-16 11:02:26 -07001268 /* Call with nullptr data to get count */
1269 gpu.getQueueFamilyProperties(&queue_family_count, nullptr);
1270 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001271
Dave Houlton5fa47912018-02-16 11:02:26 -07001272 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1273 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001274
Dave Houlton5fa47912018-02-16 11:02:26 -07001275 // Query fine-grained feature support for this device.
1276 // If app has specific feature requirements it should check supported
1277 // features based on this query
1278 vk::PhysicalDeviceFeatures physDevFeatures;
1279 gpu.getFeatures(&physDevFeatures);
1280}
1281
1282void Demo::init_vk_swapchain() {
1283// Create a WSI surface for the window:
1284#if defined(VK_USE_PLATFORM_WIN32_KHR)
1285 {
1286 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1287
1288 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1289 VERIFY(result == vk::Result::eSuccess);
1290 }
1291#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1292 {
1293 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1294
1295 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1296 VERIFY(result == vk::Result::eSuccess);
1297 }
1298#elif defined(VK_USE_PLATFORM_MIR_KHR)
1299#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1300 {
1301 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1302
1303 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1304 VERIFY(result == vk::Result::eSuccess);
1305 }
1306#elif defined(VK_USE_PLATFORM_XCB_KHR)
1307 {
1308 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1309
1310 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1311 VERIFY(result == vk::Result::eSuccess);
1312 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001313#elif defined(VK_USE_PLATFORM_IOS_MVK)
1314 {
1315 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1316
1317 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1318 VERIFY(result == vk::Result::eSuccess);
1319 }
1320#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1321 {
1322 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1323
1324 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1325 VERIFY(result == vk::Result::eSuccess);
1326 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001327#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1328 {
1329 auto result = create_display_surface();
1330 VERIFY(result == vk::Result::eSuccess);
1331 }
1332#endif
1333 // Iterate over each queue to learn whether it supports presenting:
1334 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1335 for (uint32_t i = 0; i < queue_family_count; i++) {
1336 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1337 }
1338
1339 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1340 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1341 for (uint32_t i = 0; i < queue_family_count; i++) {
1342 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1343 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1344 graphicsQueueFamilyIndex = i;
1345 }
1346
1347 if (supportsPresent[i] == VK_TRUE) {
1348 graphicsQueueFamilyIndex = i;
1349 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001350 break;
1351 }
1352 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001353 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001354
Dave Houlton5fa47912018-02-16 11:02:26 -07001355 if (presentQueueFamilyIndex == UINT32_MAX) {
1356 // If didn't find a queue that supports both graphics and present,
1357 // then
1358 // find a separate present queue.
1359 for (uint32_t i = 0; i < queue_family_count; ++i) {
1360 if (supportsPresent[i] == VK_TRUE) {
1361 presentQueueFamilyIndex = i;
1362 break;
1363 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001364 }
1365 }
1366
Dave Houlton5fa47912018-02-16 11:02:26 -07001367 // Generate error if could not find both a graphics and a present queue
1368 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1369 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1370 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001371
Dave Houlton5fa47912018-02-16 11:02:26 -07001372 graphics_queue_family_index = graphicsQueueFamilyIndex;
1373 present_queue_family_index = presentQueueFamilyIndex;
1374 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001375
Dave Houlton5fa47912018-02-16 11:02:26 -07001376 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001377
Dave Houlton5fa47912018-02-16 11:02:26 -07001378 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1379 if (!separate_present_queue) {
1380 present_queue = graphics_queue;
1381 } else {
1382 device.getQueue(present_queue_family_index, 0, &present_queue);
1383 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001384
Dave Houlton5fa47912018-02-16 11:02:26 -07001385 // Get the list of VkFormat's that are supported:
1386 uint32_t formatCount;
1387 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, nullptr);
1388 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001389
Dave Houlton5fa47912018-02-16 11:02:26 -07001390 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1391 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1392 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001393
Dave Houlton5fa47912018-02-16 11:02:26 -07001394 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1395 // the surface has no preferred format. Otherwise, at least one
1396 // supported format will be returned.
1397 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1398 format = vk::Format::eB8G8R8A8Unorm;
1399 } else {
1400 assert(formatCount >= 1);
1401 format = surfFormats[0].format;
1402 }
1403 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001404
Dave Houlton5fa47912018-02-16 11:02:26 -07001405 quit = false;
1406 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001407
Dave Houlton5fa47912018-02-16 11:02:26 -07001408 // Create semaphores to synchronize acquiring presentable buffers before
1409 // rendering and waiting for drawing to be complete before presenting
1410 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001411
Dave Houlton5fa47912018-02-16 11:02:26 -07001412 // Create fences that we can use to throttle if we get too far
1413 // ahead of the image presents
1414 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1415 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1416 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1417 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001418
Dave Houlton5fa47912018-02-16 11:02:26 -07001419 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1420 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001421
Dave Houlton5fa47912018-02-16 11:02:26 -07001422 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1423 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001424
Dave Houlton5fa47912018-02-16 11:02:26 -07001425 if (separate_present_queue) {
1426 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001427 VERIFY(result == vk::Result::eSuccess);
1428 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001429 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001430 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001431
Dave Houlton5fa47912018-02-16 11:02:26 -07001432 // Get Memory information and properties
1433 gpu.getMemoryProperties(&memory_properties);
1434}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001435
Dave Houlton5fa47912018-02-16 11:02:26 -07001436void Demo::prepare() {
1437 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1438 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1439 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001440
Dave Houlton5fa47912018-02-16 11:02:26 -07001441 auto const cmd = vk::CommandBufferAllocateInfo()
1442 .setCommandPool(cmd_pool)
1443 .setLevel(vk::CommandBufferLevel::ePrimary)
1444 .setCommandBufferCount(1);
1445
1446 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1447 VERIFY(result == vk::Result::eSuccess);
1448
1449 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1450
1451 result = this->cmd.begin(&cmd_buf_info);
1452 VERIFY(result == vk::Result::eSuccess);
1453
1454 prepare_buffers();
1455 prepare_depth();
1456 prepare_textures();
1457 prepare_cube_data_buffers();
1458
1459 prepare_descriptor_layout();
1460 prepare_render_pass();
1461 prepare_pipeline();
1462
1463 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1464 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1465 VERIFY(result == vk::Result::eSuccess);
1466 }
1467
1468 if (separate_present_queue) {
1469 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1470
1471 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1472 VERIFY(result == vk::Result::eSuccess);
1473
1474 auto const present_cmd = vk::CommandBufferAllocateInfo()
1475 .setCommandPool(present_cmd_pool)
1476 .setLevel(vk::CommandBufferLevel::ePrimary)
1477 .setCommandBufferCount(1);
1478
1479 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1480 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1481 VERIFY(result == vk::Result::eSuccess);
1482
1483 build_image_ownership_cmd(i);
1484 }
1485 }
1486
1487 prepare_descriptor_pool();
1488 prepare_descriptor_set();
1489
1490 prepare_framebuffers();
1491
1492 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1493 current_buffer = i;
1494 draw_build_cmd(swapchain_image_resources[i].cmd);
1495 }
1496
1497 /*
1498 * Prepare functions above may generate pipeline commands
1499 * that need to be flushed before beginning the render loop.
1500 */
1501 flush_init_cmd();
1502 if (staging_texture.image) {
1503 destroy_texture_image(&staging_texture);
1504 }
1505
1506 current_buffer = 0;
1507 prepared = true;
1508}
1509
1510void Demo::prepare_buffers() {
1511 vk::SwapchainKHR oldSwapchain = swapchain;
1512
1513 // Check the surface capabilities and formats
1514 vk::SurfaceCapabilitiesKHR surfCapabilities;
1515 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1516 VERIFY(result == vk::Result::eSuccess);
1517
1518 uint32_t presentModeCount;
1519 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, nullptr);
1520 VERIFY(result == vk::Result::eSuccess);
1521
1522 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1523 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1524 VERIFY(result == vk::Result::eSuccess);
1525
1526 vk::Extent2D swapchainExtent;
1527 // width and height are either both -1, or both not -1.
1528 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1529 // If the surface size is undefined, the size is set to
1530 // the size of the images requested.
1531 swapchainExtent.width = width;
1532 swapchainExtent.height = height;
1533 } else {
1534 // If the surface size is defined, the swap chain size must match
1535 swapchainExtent = surfCapabilities.currentExtent;
1536 width = surfCapabilities.currentExtent.width;
1537 height = surfCapabilities.currentExtent.height;
1538 }
1539
1540 // The FIFO present mode is guaranteed by the spec to be supported
1541 // and to have no tearing. It's a great default present mode to use.
1542 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1543
1544 // There are times when you may wish to use another present mode. The
1545 // following code shows how to select them, and the comments provide some
1546 // reasons you may wish to use them.
1547 //
1548 // It should be noted that Vulkan 1.0 doesn't provide a method for
1549 // synchronizing rendering with the presentation engine's display. There
1550 // is a method provided for throttling rendering with the display, but
1551 // there are some presentation engines for which this method will not work.
1552 // If an application doesn't throttle its rendering, and if it renders much
1553 // faster than the refresh rate of the display, this can waste power on
1554 // mobile devices. That is because power is being spent rendering images
1555 // that may never be seen.
1556
1557 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1558 // about
1559 // tearing, or have some way of synchronizing their rendering with the
1560 // display.
1561 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1562 // generally render a new presentable image every refresh cycle, but are
1563 // occasionally early. In this case, the application wants the new
1564 // image
1565 // to be displayed instead of the previously-queued-for-presentation
1566 // image
1567 // that has not yet been displayed.
1568 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1569 // render a new presentable image every refresh cycle, but are
1570 // occasionally
1571 // late. In this case (perhaps because of stuttering/latency concerns),
1572 // the application wants the late image to be immediately displayed,
1573 // even
1574 // though that may mean some tearing.
1575
1576 if (presentMode != swapchainPresentMode) {
1577 for (size_t i = 0; i < presentModeCount; ++i) {
1578 if (presentModes[i] == presentMode) {
1579 swapchainPresentMode = presentMode;
1580 break;
1581 }
1582 }
1583 }
1584
1585 if (swapchainPresentMode != presentMode) {
1586 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1587 }
1588
1589 // Determine the number of VkImages to use in the swap chain.
1590 // Application desires to acquire 3 images at a time for triple
1591 // buffering
1592 uint32_t desiredNumOfSwapchainImages = 3;
1593 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1594 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1595 }
1596
1597 // If maxImageCount is 0, we can ask for as many images as we want,
1598 // otherwise
1599 // we're limited to maxImageCount
1600 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1601 // Application must settle for fewer images than desired:
1602 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1603 }
1604
1605 vk::SurfaceTransformFlagBitsKHR preTransform;
1606 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1607 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1608 } else {
1609 preTransform = surfCapabilities.currentTransform;
1610 }
1611
1612 // Find a supported composite alpha mode - one of these is guaranteed to be set
1613 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1614 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1615 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1616 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1617 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1618 vk::CompositeAlphaFlagBitsKHR::eInherit,
1619 };
1620 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1621 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1622 compositeAlpha = compositeAlphaFlags[i];
1623 break;
1624 }
1625 }
1626
1627 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1628 .setSurface(surface)
1629 .setMinImageCount(desiredNumOfSwapchainImages)
1630 .setImageFormat(format)
1631 .setImageColorSpace(color_space)
1632 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1633 .setImageArrayLayers(1)
1634 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1635 .setImageSharingMode(vk::SharingMode::eExclusive)
1636 .setQueueFamilyIndexCount(0)
1637 .setPQueueFamilyIndices(nullptr)
1638 .setPreTransform(preTransform)
1639 .setCompositeAlpha(compositeAlpha)
1640 .setPresentMode(swapchainPresentMode)
1641 .setClipped(true)
1642 .setOldSwapchain(oldSwapchain);
1643
1644 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1645 VERIFY(result == vk::Result::eSuccess);
1646
1647 // If we just re-created an existing swapchain, we should destroy the
1648 // old
1649 // swapchain at this point.
1650 // Note: destroying the swapchain also cleans up all its associated
1651 // presentable images once the platform is done with them.
1652 if (oldSwapchain) {
1653 device.destroySwapchainKHR(oldSwapchain, nullptr);
1654 }
1655
1656 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, nullptr);
1657 VERIFY(result == vk::Result::eSuccess);
1658
1659 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1660 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1661 VERIFY(result == vk::Result::eSuccess);
1662
1663 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1664
1665 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1666 auto color_image_view = vk::ImageViewCreateInfo()
1667 .setViewType(vk::ImageViewType::e2D)
1668 .setFormat(format)
1669 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1670
1671 swapchain_image_resources[i].image = swapchainImages[i];
1672
1673 color_image_view.image = swapchain_image_resources[i].image;
1674
1675 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1676 VERIFY(result == vk::Result::eSuccess);
1677 }
1678}
1679
1680void Demo::prepare_cube_data_buffers() {
1681 mat4x4 VP;
1682 mat4x4_mul(VP, projection_matrix, view_matrix);
1683
1684 mat4x4 MVP;
1685 mat4x4_mul(MVP, VP, model_matrix);
1686
1687 vktexcube_vs_uniform data;
1688 memcpy(data.mvp, MVP, sizeof(MVP));
1689 // dumpMatrix("MVP", MVP)
1690
1691 for (int32_t i = 0; i < 12 * 3; i++) {
1692 data.position[i][0] = g_vertex_buffer_data[i * 3];
1693 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1694 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1695 data.position[i][3] = 1.0f;
1696 data.attr[i][0] = g_uv_buffer_data[2 * i];
1697 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1698 data.attr[i][2] = 0;
1699 data.attr[i][3] = 0;
1700 }
1701
1702 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1703
1704 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1705 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001706 VERIFY(result == vk::Result::eSuccess);
1707
1708 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001709 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001710
Dave Houlton5fa47912018-02-16 11:02:26 -07001711 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001712
Dave Houlton5fa47912018-02-16 11:02:26 -07001713 bool const pass = memory_type_from_properties(
1714 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1715 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001716 VERIFY(pass);
1717
Dave Houlton5fa47912018-02-16 11:02:26 -07001718 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001719 VERIFY(result == vk::Result::eSuccess);
1720
Dave Houlton5fa47912018-02-16 11:02:26 -07001721 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1722 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001723
Dave Houlton5fa47912018-02-16 11:02:26 -07001724 memcpy(pData.value, &data, sizeof data);
1725
1726 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1727
1728 result =
1729 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001730 VERIFY(result == vk::Result::eSuccess);
1731 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001732}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001733
Dave Houlton5fa47912018-02-16 11:02:26 -07001734void Demo::prepare_depth() {
1735 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001736
Dave Houlton5fa47912018-02-16 11:02:26 -07001737 auto const image = vk::ImageCreateInfo()
1738 .setImageType(vk::ImageType::e2D)
1739 .setFormat(depth.format)
1740 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1741 .setMipLevels(1)
1742 .setArrayLayers(1)
1743 .setSamples(vk::SampleCountFlagBits::e1)
1744 .setTiling(vk::ImageTiling::eOptimal)
1745 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1746 .setSharingMode(vk::SharingMode::eExclusive)
1747 .setQueueFamilyIndexCount(0)
1748 .setPQueueFamilyIndices(nullptr)
1749 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001750
Dave Houlton5fa47912018-02-16 11:02:26 -07001751 auto result = device.createImage(&image, nullptr, &depth.image);
1752 VERIFY(result == vk::Result::eSuccess);
1753
1754 vk::MemoryRequirements mem_reqs;
1755 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1756
1757 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1758 depth.mem_alloc.setMemoryTypeIndex(0);
1759
1760 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1761 &depth.mem_alloc.memoryTypeIndex);
1762 VERIFY(pass);
1763
1764 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1765 VERIFY(result == vk::Result::eSuccess);
1766
1767 result = device.bindImageMemory(depth.image, depth.mem, 0);
1768 VERIFY(result == vk::Result::eSuccess);
1769
1770 auto const view = vk::ImageViewCreateInfo()
1771 .setImage(depth.image)
1772 .setViewType(vk::ImageViewType::e2D)
1773 .setFormat(depth.format)
1774 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1775 result = device.createImageView(&view, nullptr, &depth.view);
1776 VERIFY(result == vk::Result::eSuccess);
1777}
1778
1779void Demo::prepare_descriptor_layout() {
1780 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1781 .setBinding(0)
1782 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1783 .setDescriptorCount(1)
1784 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1785 .setPImmutableSamplers(nullptr),
1786 vk::DescriptorSetLayoutBinding()
1787 .setBinding(1)
1788 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1789 .setDescriptorCount(texture_count)
1790 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1791 .setPImmutableSamplers(nullptr)};
1792
1793 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1794
1795 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1796 VERIFY(result == vk::Result::eSuccess);
1797
1798 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1799
1800 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1801 VERIFY(result == vk::Result::eSuccess);
1802}
1803
1804void Demo::prepare_descriptor_pool() {
1805 vk::DescriptorPoolSize const poolSizes[2] = {
1806 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1807 vk::DescriptorPoolSize()
1808 .setType(vk::DescriptorType::eCombinedImageSampler)
1809 .setDescriptorCount(swapchainImageCount * texture_count)};
1810
1811 auto const descriptor_pool =
1812 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1813
1814 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1815 VERIFY(result == vk::Result::eSuccess);
1816}
1817
1818void Demo::prepare_descriptor_set() {
1819 auto const alloc_info =
1820 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1821
1822 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1823
1824 vk::DescriptorImageInfo tex_descs[texture_count];
1825 for (uint32_t i = 0; i < texture_count; i++) {
1826 tex_descs[i].setSampler(textures[i].sampler);
1827 tex_descs[i].setImageView(textures[i].view);
1828 tex_descs[i].setImageLayout(vk::ImageLayout::eGeneral);
1829 }
1830
1831 vk::WriteDescriptorSet writes[2];
1832
1833 writes[0].setDescriptorCount(1);
1834 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1835 writes[0].setPBufferInfo(&buffer_info);
1836
1837 writes[1].setDstBinding(1);
1838 writes[1].setDescriptorCount(texture_count);
1839 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1840 writes[1].setPImageInfo(tex_descs);
1841
1842 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1843 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001844 VERIFY(result == vk::Result::eSuccess);
1845
Dave Houlton5fa47912018-02-16 11:02:26 -07001846 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1847 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1848 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1849 device.updateDescriptorSets(2, writes, 0, nullptr);
1850 }
1851}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001852
Dave Houlton5fa47912018-02-16 11:02:26 -07001853void Demo::prepare_framebuffers() {
1854 vk::ImageView attachments[2];
1855 attachments[1] = depth.view;
1856
1857 auto const fb_info = vk::FramebufferCreateInfo()
1858 .setRenderPass(render_pass)
1859 .setAttachmentCount(2)
1860 .setPAttachments(attachments)
1861 .setWidth((uint32_t)width)
1862 .setHeight((uint32_t)height)
1863 .setLayers(1);
1864
1865 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1866 attachments[0] = swapchain_image_resources[i].view;
1867 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001868 VERIFY(result == vk::Result::eSuccess);
1869 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001870}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001871
Dave Houlton5fa47912018-02-16 11:02:26 -07001872vk::ShaderModule Demo::prepare_fs() {
1873 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001874#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001875 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001876
Dave Houlton5fa47912018-02-16 11:02:26 -07001877 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001878
Dave Houlton5fa47912018-02-16 11:02:26 -07001879 return frag_shader_module;
1880}
1881
1882void Demo::prepare_pipeline() {
1883 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1884 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1885 VERIFY(result == vk::Result::eSuccess);
1886
1887 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1888 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1889 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1890
1891 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1892
1893 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1894
1895 // TODO: Where are pViewports and pScissors set?
1896 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1897
1898 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1899 .setDepthClampEnable(VK_FALSE)
1900 .setRasterizerDiscardEnable(VK_FALSE)
1901 .setPolygonMode(vk::PolygonMode::eFill)
1902 .setCullMode(vk::CullModeFlagBits::eBack)
1903 .setFrontFace(vk::FrontFace::eCounterClockwise)
1904 .setDepthBiasEnable(VK_FALSE)
1905 .setLineWidth(1.0f);
1906
1907 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1908
1909 auto const stencilOp =
1910 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1911
1912 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1913 .setDepthTestEnable(VK_TRUE)
1914 .setDepthWriteEnable(VK_TRUE)
1915 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1916 .setDepthBoundsTestEnable(VK_FALSE)
1917 .setStencilTestEnable(VK_FALSE)
1918 .setFront(stencilOp)
1919 .setBack(stencilOp);
1920
1921 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1922 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1923 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1924
1925 auto const colorBlendInfo =
1926 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1927
1928 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1929
1930 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1931
1932 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1933 .setStageCount(2)
1934 .setPStages(shaderStageInfo)
1935 .setPVertexInputState(&vertexInputInfo)
1936 .setPInputAssemblyState(&inputAssemblyInfo)
1937 .setPViewportState(&viewportInfo)
1938 .setPRasterizationState(&rasterizationInfo)
1939 .setPMultisampleState(&multisampleInfo)
1940 .setPDepthStencilState(&depthStencilInfo)
1941 .setPColorBlendState(&colorBlendInfo)
1942 .setPDynamicState(&dynamicStateInfo)
1943 .setLayout(pipeline_layout)
1944 .setRenderPass(render_pass);
1945
1946 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1947 VERIFY(result == vk::Result::eSuccess);
1948
1949 device.destroyShaderModule(frag_shader_module, nullptr);
1950 device.destroyShaderModule(vert_shader_module, nullptr);
1951}
1952
1953void Demo::prepare_render_pass() {
1954 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1955 // because at the start of the renderpass, we don't care about their contents.
1956 // At the start of the subpass, the color attachment's layout will be transitioned
1957 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1958 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1959 // the renderpass, the color attachment's layout will be transitioned to
1960 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1961 // the renderpass, no barriers are necessary.
1962 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1963 .setFormat(format)
1964 .setSamples(vk::SampleCountFlagBits::e1)
1965 .setLoadOp(vk::AttachmentLoadOp::eClear)
1966 .setStoreOp(vk::AttachmentStoreOp::eStore)
1967 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1968 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1969 .setInitialLayout(vk::ImageLayout::eUndefined)
1970 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1971 vk::AttachmentDescription()
1972 .setFormat(depth.format)
1973 .setSamples(vk::SampleCountFlagBits::e1)
1974 .setLoadOp(vk::AttachmentLoadOp::eClear)
1975 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1976 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1977 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1978 .setInitialLayout(vk::ImageLayout::eUndefined)
1979 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1980
1981 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1982
1983 auto const depth_reference =
1984 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1985
1986 auto const subpass = vk::SubpassDescription()
1987 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1988 .setInputAttachmentCount(0)
1989 .setPInputAttachments(nullptr)
1990 .setColorAttachmentCount(1)
1991 .setPColorAttachments(&color_reference)
1992 .setPResolveAttachments(nullptr)
1993 .setPDepthStencilAttachment(&depth_reference)
1994 .setPreserveAttachmentCount(0)
1995 .setPPreserveAttachments(nullptr);
1996
1997 auto const rp_info = vk::RenderPassCreateInfo()
1998 .setAttachmentCount(2)
1999 .setPAttachments(attachments)
2000 .setSubpassCount(1)
2001 .setPSubpasses(&subpass)
2002 .setDependencyCount(0)
2003 .setPDependencies(nullptr);
2004
2005 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2006 VERIFY(result == vk::Result::eSuccess);
2007}
2008
2009vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2010 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2011
2012 vk::ShaderModule module;
2013 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2014 VERIFY(result == vk::Result::eSuccess);
2015
2016 return module;
2017}
2018
2019void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2020 vk::MemoryPropertyFlags required_props) {
2021 int32_t tex_width;
2022 int32_t tex_height;
2023 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2024 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002025 }
2026
Dave Houlton5fa47912018-02-16 11:02:26 -07002027 tex_obj->tex_width = tex_width;
2028 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002029
Dave Houlton5fa47912018-02-16 11:02:26 -07002030 auto const image_create_info = vk::ImageCreateInfo()
2031 .setImageType(vk::ImageType::e2D)
2032 .setFormat(vk::Format::eR8G8B8A8Unorm)
2033 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2034 .setMipLevels(1)
2035 .setArrayLayers(1)
2036 .setSamples(vk::SampleCountFlagBits::e1)
2037 .setTiling(tiling)
2038 .setUsage(usage)
2039 .setSharingMode(vk::SharingMode::eExclusive)
2040 .setQueueFamilyIndexCount(0)
2041 .setPQueueFamilyIndices(nullptr)
2042 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002043
Dave Houlton5fa47912018-02-16 11:02:26 -07002044 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2045 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002046
Dave Houlton5fa47912018-02-16 11:02:26 -07002047 vk::MemoryRequirements mem_reqs;
2048 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002049
Dave Houlton5fa47912018-02-16 11:02:26 -07002050 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2051 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002052
Dave Houlton5fa47912018-02-16 11:02:26 -07002053 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2054 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002055
Dave Houlton5fa47912018-02-16 11:02:26 -07002056 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2057 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002058
Dave Houlton5fa47912018-02-16 11:02:26 -07002059 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2060 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002061
Dave Houlton5fa47912018-02-16 11:02:26 -07002062 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2063 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2064 vk::SubresourceLayout layout;
2065 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002066
Dave Houlton5fa47912018-02-16 11:02:26 -07002067 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002068 VERIFY(data.result == vk::Result::eSuccess);
2069
Dave Houlton5fa47912018-02-16 11:02:26 -07002070 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2071 fprintf(stderr, "Error loading texture: %s\n", filename);
2072 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002073
Dave Houlton5fa47912018-02-16 11:02:26 -07002074 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002075 }
2076
Dave Houlton5fa47912018-02-16 11:02:26 -07002077 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2078}
2079
2080void Demo::prepare_textures() {
2081 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2082 vk::FormatProperties props;
2083 gpu.getFormatProperties(tex_format, &props);
2084
2085 for (uint32_t i = 0; i < texture_count; i++) {
2086 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2087 /* Device can texture using linear textures */
2088 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2089 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2090 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2091 // shader to run until layout transition completes
2092 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2093 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2094 vk::PipelineStageFlagBits::eFragmentShader);
2095 staging_texture.image = vk::Image();
2096 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2097 /* Must use staging buffer to copy linear texture to optimized */
2098
2099 prepare_texture_image(tex_files[i], &staging_texture, vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eTransferSrc,
2100 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2101
2102 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2103 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2104 vk::MemoryPropertyFlagBits::eDeviceLocal);
2105
2106 set_image_layout(staging_texture.image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2107 vk::ImageLayout::eTransferSrcOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2108 vk::PipelineStageFlagBits::eTransfer);
2109
2110 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2111 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2112 vk::PipelineStageFlagBits::eTransfer);
2113
2114 auto const subresource = vk::ImageSubresourceLayers()
2115 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2116 .setMipLevel(0)
2117 .setBaseArrayLayer(0)
2118 .setLayerCount(1);
2119
2120 auto const copy_region = vk::ImageCopy()
2121 .setSrcSubresource(subresource)
2122 .setSrcOffset({0, 0, 0})
2123 .setDstSubresource(subresource)
2124 .setDstOffset({0, 0, 0})
2125 .setExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2126
2127 cmd.copyImage(staging_texture.image, vk::ImageLayout::eTransferSrcOptimal, textures[i].image,
2128 vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
2129
2130 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2131 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2132 vk::PipelineStageFlagBits::eFragmentShader);
2133 } else {
2134 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002135 }
2136
Dave Houlton5fa47912018-02-16 11:02:26 -07002137 auto const samplerInfo = vk::SamplerCreateInfo()
2138 .setMagFilter(vk::Filter::eNearest)
2139 .setMinFilter(vk::Filter::eNearest)
2140 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2141 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2142 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2143 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2144 .setMipLodBias(0.0f)
2145 .setAnisotropyEnable(VK_FALSE)
2146 .setMaxAnisotropy(1)
2147 .setCompareEnable(VK_FALSE)
2148 .setCompareOp(vk::CompareOp::eNever)
2149 .setMinLod(0.0f)
2150 .setMaxLod(0.0f)
2151 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2152 .setUnnormalizedCoordinates(VK_FALSE);
2153
2154 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2155 VERIFY(result == vk::Result::eSuccess);
2156
2157 auto const viewInfo = vk::ImageViewCreateInfo()
2158 .setImage(textures[i].image)
2159 .setViewType(vk::ImageViewType::e2D)
2160 .setFormat(tex_format)
2161 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2162
2163 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2164 VERIFY(result == vk::Result::eSuccess);
2165 }
2166}
2167
2168vk::ShaderModule Demo::prepare_vs() {
2169 const uint32_t vertShaderCode[] = {
2170#include "cube.vert.inc"
2171 };
2172
2173 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2174
2175 return vert_shader_module;
2176}
2177
2178void Demo::resize() {
2179 uint32_t i;
2180
2181 // Don't react to resize until after first initialization.
2182 if (!prepared) {
2183 return;
2184 }
2185
2186 // In order to properly resize the window, we must re-create the
2187 // swapchain
2188 // AND redo the command buffers, etc.
2189 //
2190 // First, perform part of the cleanup() function:
2191 prepared = false;
2192 auto result = device.waitIdle();
2193 VERIFY(result == vk::Result::eSuccess);
2194
2195 for (i = 0; i < swapchainImageCount; i++) {
2196 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2197 }
2198
2199 device.destroyDescriptorPool(desc_pool, nullptr);
2200
2201 device.destroyPipeline(pipeline, nullptr);
2202 device.destroyPipelineCache(pipelineCache, nullptr);
2203 device.destroyRenderPass(render_pass, nullptr);
2204 device.destroyPipelineLayout(pipeline_layout, nullptr);
2205 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2206
2207 for (i = 0; i < texture_count; i++) {
2208 device.destroyImageView(textures[i].view, nullptr);
2209 device.destroyImage(textures[i].image, nullptr);
2210 device.freeMemory(textures[i].mem, nullptr);
2211 device.destroySampler(textures[i].sampler, nullptr);
2212 }
2213
2214 device.destroyImageView(depth.view, nullptr);
2215 device.destroyImage(depth.image, nullptr);
2216 device.freeMemory(depth.mem, nullptr);
2217
2218 for (i = 0; i < swapchainImageCount; i++) {
2219 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2220 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2221 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2222 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2223 }
2224
2225 device.destroyCommandPool(cmd_pool, nullptr);
2226 if (separate_present_queue) {
2227 device.destroyCommandPool(present_cmd_pool, nullptr);
2228 }
2229
2230 // Second, re-perform the prepare() function, which will re-create the
2231 // swapchain.
2232 prepare();
2233}
2234
2235void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2236 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2237 assert(cmd);
2238
2239 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2240 vk::AccessFlags flags;
2241
2242 switch (layout) {
2243 case vk::ImageLayout::eTransferDstOptimal:
2244 // Make sure anything that was copying from this image has
2245 // completed
2246 flags = vk::AccessFlagBits::eTransferWrite;
2247 break;
2248 case vk::ImageLayout::eColorAttachmentOptimal:
2249 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2250 break;
2251 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2252 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2253 break;
2254 case vk::ImageLayout::eShaderReadOnlyOptimal:
2255 // Make sure any Copy or CPU writes to image are flushed
2256 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2257 break;
2258 case vk::ImageLayout::eTransferSrcOptimal:
2259 flags = vk::AccessFlagBits::eTransferRead;
2260 break;
2261 case vk::ImageLayout::ePresentSrcKHR:
2262 flags = vk::AccessFlagBits::eMemoryRead;
2263 break;
2264 default:
2265 break;
2266 }
2267
2268 return flags;
2269 };
2270
2271 auto const barrier = vk::ImageMemoryBarrier()
2272 .setSrcAccessMask(srcAccessMask)
2273 .setDstAccessMask(DstAccessMask(newLayout))
2274 .setOldLayout(oldLayout)
2275 .setNewLayout(newLayout)
2276 .setSrcQueueFamilyIndex(0)
2277 .setDstQueueFamilyIndex(0)
2278 .setImage(image)
2279 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2280
2281 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2282}
2283
2284void Demo::update_data_buffer() {
2285 mat4x4 VP;
2286 mat4x4_mul(VP, projection_matrix, view_matrix);
2287
2288 // Rotate around the Y axis
2289 mat4x4 Model;
2290 mat4x4_dup(Model, model_matrix);
2291 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2292
2293 mat4x4 MVP;
2294 mat4x4_mul(MVP, VP, model_matrix);
2295
2296 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2297 VERIFY(data.result == vk::Result::eSuccess);
2298
2299 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2300
2301 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2302}
2303
Karl Schultzb7940402018-05-29 13:09:22 -06002304/* Convert ppm image data from header file into RGBA texture image */
2305#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002306bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
Karl Schultzb7940402018-05-29 13:09:22 -06002307 (void)filename;
2308 char *cPtr;
2309 cPtr = (char *)lunarg_ppm;
2310 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002311 return false;
2312 }
Karl Schultzb7940402018-05-29 13:09:22 -06002313 while (strncmp(cPtr++, "\n", 1))
2314 ;
2315 sscanf(cPtr, "%u %u", width, height);
2316 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002317 return true;
2318 }
Karl Schultzb7940402018-05-29 13:09:22 -06002319 while (strncmp(cPtr++, "\n", 1))
2320 ;
2321 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002322 return false;
2323 }
Karl Schultzb7940402018-05-29 13:09:22 -06002324 while (strncmp(cPtr++, "\n", 1))
2325 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002326 for (int y = 0; y < *height; y++) {
2327 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002328 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002329 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002330 rowPtr[3] = 255; /* Alpha of 1 */
2331 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002332 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002333 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002334 rgba_data += layout->rowPitch;
2335 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002336 return true;
2337}
2338
2339bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2340 // Search memtypes to find first index with those properties
2341 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2342 if ((typeBits & 1) == 1) {
2343 // Type is available, does it match user properties?
2344 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2345 *typeIndex = i;
2346 return true;
2347 }
2348 }
2349 typeBits >>= 1;
2350 }
2351
2352 // No memory types matched, return failure
2353 return false;
2354}
2355
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002356#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002357void Demo::run() {
2358 if (!prepared) {
2359 return;
2360 }
2361
2362 draw();
2363 curFrame++;
2364
2365 if (frameCount != INT_MAX && curFrame == frameCount) {
2366 PostQuitMessage(validation_error);
2367 }
2368}
2369
2370void Demo::create_window() {
2371 WNDCLASSEX win_class;
2372
2373 // Initialize the window class structure:
2374 win_class.cbSize = sizeof(WNDCLASSEX);
2375 win_class.style = CS_HREDRAW | CS_VREDRAW;
2376 win_class.lpfnWndProc = WndProc;
2377 win_class.cbClsExtra = 0;
2378 win_class.cbWndExtra = 0;
2379 win_class.hInstance = connection; // hInstance
2380 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2381 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2382 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2383 win_class.lpszMenuName = nullptr;
2384 win_class.lpszClassName = name;
2385 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2386
2387 // Register window class:
2388 if (!RegisterClassEx(&win_class)) {
2389 // It didn't work, so try to give a useful error:
2390 printf("Unexpected error trying to start the application!\n");
2391 fflush(stdout);
2392 exit(1);
2393 }
2394
2395 // Create window with the registered class:
2396 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2397 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2398 window = CreateWindowEx(0,
2399 name, // class name
2400 name, // app name
2401 WS_OVERLAPPEDWINDOW | // window style
2402 WS_VISIBLE | WS_SYSMENU,
2403 100, 100, // x/y coords
2404 wr.right - wr.left, // width
2405 wr.bottom - wr.top, // height
2406 nullptr, // handle to parent
2407 nullptr, // handle to menu
2408 connection, // hInstance
2409 nullptr); // no extra parameters
2410
2411 if (!window) {
2412 // It didn't work, so try to give a useful error:
2413 printf("Cannot create a window in which to draw!\n");
2414 fflush(stdout);
2415 exit(1);
2416 }
2417
2418 // Window client area size must be at least 1 pixel high, to prevent
2419 // crash.
2420 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2421 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2422}
2423#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2424
2425void Demo::create_xlib_window() {
2426 const char *display_envar = getenv("DISPLAY");
2427 if (display_envar == nullptr || display_envar[0] == '\0') {
2428 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2429 fflush(stdout);
2430 exit(1);
2431 }
2432
2433 XInitThreads();
2434 display = XOpenDisplay(nullptr);
2435 long visualMask = VisualScreenMask;
2436 int numberOfVisuals;
2437 XVisualInfo vInfoTemplate = {};
2438 vInfoTemplate.screen = DefaultScreen(display);
2439 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2440
2441 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2442
2443 XSetWindowAttributes windowAttributes = {};
2444 windowAttributes.colormap = colormap;
2445 windowAttributes.background_pixel = 0xFFFFFFFF;
2446 windowAttributes.border_pixel = 0;
2447 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2448
2449 xlib_window =
2450 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2451 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2452
2453 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2454 XMapWindow(display, xlib_window);
2455 XFlush(display);
2456 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2457}
2458
2459void Demo::handle_xlib_event(const XEvent *event) {
2460 switch (event->type) {
2461 case ClientMessage:
2462 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2463 quit = true;
2464 }
2465 break;
2466 case KeyPress:
2467 switch (event->xkey.keycode) {
2468 case 0x9: // Escape
2469 quit = true;
2470 break;
2471 case 0x71: // left arrow key
2472 spin_angle -= spin_increment;
2473 break;
2474 case 0x72: // right arrow key
2475 spin_angle += spin_increment;
2476 break;
2477 case 0x41: // space bar
2478 pause = !pause;
2479 break;
2480 }
2481 break;
2482 case ConfigureNotify:
2483 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2484 width = event->xconfigure.width;
2485 height = event->xconfigure.height;
2486 resize();
2487 }
2488 break;
2489 default:
2490 break;
2491 }
2492}
2493
2494void Demo::run_xlib() {
2495 while (!quit) {
2496 XEvent event;
2497
2498 if (pause) {
2499 XNextEvent(display, &event);
2500 handle_xlib_event(&event);
2501 }
2502 while (XPending(display) > 0) {
2503 XNextEvent(display, &event);
2504 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002505 }
2506
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002507 draw();
2508 curFrame++;
2509
Dave Houlton5fa47912018-02-16 11:02:26 -07002510 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2511 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002512 }
2513 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002514}
Tony Barbour153cb062016-12-07 13:43:36 -07002515#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002516
Dave Houlton5fa47912018-02-16 11:02:26 -07002517void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2518 uint8_t event_code = event->response_type & 0x7f;
2519 switch (event_code) {
2520 case XCB_EXPOSE:
2521 // TODO: Resize window
2522 break;
2523 case XCB_CLIENT_MESSAGE:
2524 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2525 quit = true;
2526 }
2527 break;
2528 case XCB_KEY_RELEASE: {
2529 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002530
Dave Houlton5fa47912018-02-16 11:02:26 -07002531 switch (key->detail) {
2532 case 0x9: // Escape
2533 quit = true;
2534 break;
2535 case 0x71: // left arrow key
2536 spin_angle -= spin_increment;
2537 break;
2538 case 0x72: // right arrow key
2539 spin_angle += spin_increment;
2540 break;
2541 case 0x41: // space bar
2542 pause = !pause;
2543 break;
2544 }
2545 } break;
2546 case XCB_CONFIGURE_NOTIFY: {
2547 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2548 if ((width != cfg->width) || (height != cfg->height)) {
2549 width = cfg->width;
2550 height = cfg->height;
2551 resize();
2552 }
2553 } break;
2554 default:
2555 break;
2556 }
2557}
2558
2559void Demo::run_xcb() {
2560 xcb_flush(connection);
2561
2562 while (!quit) {
2563 xcb_generic_event_t *event;
2564
2565 if (pause) {
2566 event = xcb_wait_for_event(connection);
2567 } else {
2568 event = xcb_poll_for_event(connection);
2569 }
2570 while (event) {
2571 handle_xcb_event(event);
2572 free(event);
2573 event = xcb_poll_for_event(connection);
2574 }
2575
2576 draw();
2577 curFrame++;
2578 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2579 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002580 }
2581 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002582}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002583
Dave Houlton5fa47912018-02-16 11:02:26 -07002584void Demo::create_xcb_window() {
2585 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002586
Dave Houlton5fa47912018-02-16 11:02:26 -07002587 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002588
Dave Houlton5fa47912018-02-16 11:02:26 -07002589 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2590 value_list[0] = screen->black_pixel;
2591 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002592
Dave Houlton5fa47912018-02-16 11:02:26 -07002593 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2594 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2595
2596 /* Magic code that will send notification when window is destroyed */
2597 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2598 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2599
2600 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2601 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2602
2603 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2604
2605 free(reply);
2606
2607 xcb_map_window(connection, xcb_window);
2608
2609 // Force the x/y coordinates to 100,100 results are identical in
2610 // consecutive
2611 // runs
2612 const uint32_t coords[] = {100, 100};
2613 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2614}
2615#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2616
2617void Demo::run() {
2618 while (!quit) {
2619 if (pause) {
2620 wl_display_dispatch(display);
2621 } else {
2622 wl_display_dispatch_pending(display);
2623 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002624 draw();
2625 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002626 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002627 quit = true;
2628 }
2629 }
2630 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002631}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002632
Dave Houlton5fa47912018-02-16 11:02:26 -07002633void Demo::create_window() {
2634 window = wl_compositor_create_surface(compositor);
2635 if (!window) {
2636 printf("Can not create wayland_surface from compositor!\n");
2637 fflush(stdout);
2638 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002639 }
2640
Dave Houlton5fa47912018-02-16 11:02:26 -07002641 shell_surface = wl_shell_get_shell_surface(shell, window);
2642 if (!shell_surface) {
2643 printf("Can not get shell_surface from wayland_surface!\n");
2644 fflush(stdout);
2645 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002646 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002647
2648 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2649 wl_shell_surface_set_toplevel(shell_surface);
2650 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2651}
Karl Schultz206b1c52018-04-13 18:02:07 -06002652#elif defined(VK_USE_PLATFORM_MACOS_MVK)
2653void Demo::run() {
2654 draw();
2655 curFrame++;
2656 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2657 quit = true;
2658 }
2659}
Tony Barbourefd0c5a2016-12-07 14:45:12 -07002660#elif defined(VK_USE_PLATFORM_MIR_KHR)
Damien Leone600c3052017-01-31 10:26:07 -07002661#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2662
Dave Houlton5fa47912018-02-16 11:02:26 -07002663vk::Result Demo::create_display_surface() {
2664 vk::Result result;
2665 uint32_t display_count;
2666 uint32_t mode_count;
2667 uint32_t plane_count;
2668 vk::DisplayPropertiesKHR display_props;
2669 vk::DisplayKHR display;
2670 vk::DisplayModePropertiesKHR mode_props;
2671 vk::DisplayPlanePropertiesKHR *plane_props;
2672 vk::Bool32 found_plane = VK_FALSE;
2673 uint32_t plane_index;
2674 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002675
Dave Houlton5fa47912018-02-16 11:02:26 -07002676 // Get the first display
2677 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2678 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002679
Dave Houlton5fa47912018-02-16 11:02:26 -07002680 if (display_count == 0) {
2681 printf("Cannot find any display!\n");
2682 fflush(stdout);
2683 exit(1);
2684 }
2685
2686 display_count = 1;
2687 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2688 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2689
2690 display = display_props.display;
2691
2692 // Get the first mode of the display
2693 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2694 VERIFY(result == vk::Result::eSuccess);
2695
2696 if (mode_count == 0) {
2697 printf("Cannot find any mode for the display!\n");
2698 fflush(stdout);
2699 exit(1);
2700 }
2701
2702 mode_count = 1;
2703 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2704 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2705
2706 // Get the list of planes
2707 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2708 VERIFY(result == vk::Result::eSuccess);
2709
2710 if (plane_count == 0) {
2711 printf("Cannot find any plane!\n");
2712 fflush(stdout);
2713 exit(1);
2714 }
2715
2716 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2717 VERIFY(plane_props != nullptr);
2718
2719 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2720 VERIFY(result == vk::Result::eSuccess);
2721
2722 // Find a plane compatible with the display
2723 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2724 uint32_t supported_count;
2725 vk::DisplayKHR *supported_displays;
2726
2727 // Disqualify planes that are bound to a different display
2728 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2729 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002730 }
2731
Dave Houlton5fa47912018-02-16 11:02:26 -07002732 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002733 VERIFY(result == vk::Result::eSuccess);
2734
Dave Houlton5fa47912018-02-16 11:02:26 -07002735 if (supported_count == 0) {
2736 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002737 }
2738
Dave Houlton5fa47912018-02-16 11:02:26 -07002739 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2740 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002741
Dave Houlton5fa47912018-02-16 11:02:26 -07002742 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002743 VERIFY(result == vk::Result::eSuccess);
2744
Dave Houlton5fa47912018-02-16 11:02:26 -07002745 for (uint32_t i = 0; i < supported_count; i++) {
2746 if (supported_displays[i] == display) {
2747 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002748 break;
2749 }
2750 }
2751
Dave Houlton5fa47912018-02-16 11:02:26 -07002752 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002753
Dave Houlton5fa47912018-02-16 11:02:26 -07002754 if (found_plane) {
2755 break;
Damien Leone600c3052017-01-31 10:26:07 -07002756 }
2757 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002758
2759 if (!found_plane) {
2760 printf("Cannot find a plane compatible with the display!\n");
2761 fflush(stdout);
2762 exit(1);
2763 }
2764
2765 free(plane_props);
2766
2767 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2768 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2769 // Find a supported alpha mode
2770 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2771 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2772 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2773 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2774 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2775 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2776 };
2777 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2778 if (planeCaps.supportedAlpha & alphaModes[i]) {
2779 alphaMode = alphaModes[i];
2780 break;
2781 }
2782 }
2783
2784 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2785 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2786
2787 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2788 .setDisplayMode(mode_props.displayMode)
2789 .setPlaneIndex(plane_index)
2790 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2791 .setGlobalAlpha(1.0f)
2792 .setAlphaMode(alphaMode)
2793 .setImageExtent(image_extent);
2794
2795 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2796}
2797
2798void Demo::run_display() {
2799 while (!quit) {
2800 draw();
2801 curFrame++;
2802
2803 if (frameCount != INT32_MAX && curFrame == frameCount) {
2804 quit = true;
2805 }
2806 }
2807}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002808#endif
2809
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002810#if _WIN32
2811// Include header required for parsing the command line options.
2812#include <shellapi.h>
2813
2814Demo demo;
2815
2816// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002817LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2818 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002819 case WM_CLOSE:
2820 PostQuitMessage(validation_error);
2821 break;
2822 case WM_PAINT:
2823 demo.run();
2824 break;
2825 case WM_GETMINMAXINFO: // set window's minimum size
2826 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2827 return 0;
2828 case WM_SIZE:
2829 // Resize the application to the new window size, except when
2830 // it was minimized. Vulkan doesn't support images or swapchains
2831 // with width=0 and height=0.
2832 if (wParam != SIZE_MINIMIZED) {
2833 demo.width = lParam & 0xffff;
2834 demo.height = (lParam & 0xffff0000) >> 16;
2835 demo.resize();
2836 }
2837 break;
2838 default:
2839 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002840 }
2841
2842 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2843}
2844
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002845int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002846 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002847 MSG msg; // message
2848 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002849 int argc;
2850 char **argv;
2851
Jamie Madillb2ff6502017-03-15 16:17:46 -04002852 // Ensure wParam is initialized.
2853 msg.wParam = 0;
2854
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002855 // Use the CommandLine functions to get the command line arguments.
2856 // Unfortunately, Microsoft outputs
2857 // this information as wide characters for Unicode, and we simply want the
2858 // Ascii version to be compatible
2859 // with the non-Windows side. So, we have to convert the information to
2860 // Ascii character strings.
2861 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002862 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002863 argc = 0;
2864 }
2865
Jeremy Hayes9d304782016-10-09 11:48:12 -06002866 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002867 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002868 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002869 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002870 } else {
2871 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002872 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2873 size_t numConverted = 0;
2874
2875 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002876 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002877 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002878 }
2879 }
2880 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002881 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002882 argv = nullptr;
2883 }
2884
2885 demo.init(argc, argv);
2886
2887 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002888 if (argc > 0 && argv != nullptr) {
2889 for (int iii = 0; iii < argc; iii++) {
2890 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002891 free(argv[iii]);
2892 }
2893 }
2894 free(argv);
2895 }
2896
2897 demo.connection = hInstance;
2898 strncpy(demo.name, "cube", APP_NAME_STR_LEN);
2899 demo.create_window();
2900 demo.init_vk_swapchain();
2901
2902 demo.prepare();
2903
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002904 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002905
2906 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002907 while (!done) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002908 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002909 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002910 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002911 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002912 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002913 /* Translate and dispatch to event queue*/
2914 TranslateMessage(&msg);
2915 DispatchMessage(&msg);
2916 }
2917 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2918 }
2919
2920 demo.cleanup();
2921
2922 return (int)msg.wParam;
2923}
2924
2925#elif __linux__
2926
Jeremy Hayes9d304782016-10-09 11:48:12 -06002927int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002928 Demo demo;
2929
2930 demo.init(argc, argv);
2931
Tony Barbour153cb062016-12-07 13:43:36 -07002932#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06002933 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002934#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07002935 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002936 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002937#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06002938 demo.create_window();
Tony Barbourefd0c5a2016-12-07 14:45:12 -07002939#elif defined(VK_USE_PLATFORM_MIR_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002940#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002941
2942 demo.init_vk_swapchain();
2943
2944 demo.prepare();
2945
Tony Barbour153cb062016-12-07 13:43:36 -07002946#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002947 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002948#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002949 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002950#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002951 demo.run();
Tony Barbourefd0c5a2016-12-07 14:45:12 -07002952#elif defined(VK_USE_PLATFORM_MIR_KHR)
Damien Leone600c3052017-01-31 10:26:07 -07002953#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2954 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002955#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002956
2957 demo.cleanup();
2958
2959 return validation_error;
2960}
2961
Karl Schultz9ceac062017-12-12 10:33:01 -05002962#elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
2963
2964// Global function invoked from NS or UI views and controllers to create demo
Karl Schultz206b1c52018-04-13 18:02:07 -06002965static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05002966
2967 demo.init(argc, (char **)argv);
2968 demo.window = view;
2969 demo.init_vk_swapchain();
2970 demo.prepare();
2971 demo.spin_angle = 0.4f;
2972}
2973
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002974#else
2975#error "Platform not supported"
2976#endif