blob: e30c516d8cd2cf136f6252a948a0ed02bf495d97 [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
Mark Lobodzinskidefadcf2017-10-23 09:23:06 -060035#define VULKAN_HPP_NO_SMART_HANDLE
Jeremy Hayesf56427a2016-09-07 15:55:11 -060036#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060037#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060038#include <vulkan/vulkan.hpp>
39#include <vulkan/vk_sdk_platform.h>
40
41#include "linmath.h"
42
43#ifndef NDEBUG
44#define VERIFY(x) assert(x)
45#else
46#define VERIFY(x) ((void)(x))
47#endif
48
Lenny Komowffe446c2018-11-19 17:08:04 -070049#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060050#ifdef _WIN32
51#define APP_NAME_STR_LEN 80
52#endif
53
54// Allow a maximum of two outstanding presentation operations.
55#define FRAME_LAG 2
56
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
58
59#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070060#define ERR_EXIT(err_msg, err_class) \
61 do { \
62 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
63 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060064 } while (0)
65#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070066#define ERR_EXIT(err_msg, err_class) \
67 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080068 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070069 fflush(stdout); \
70 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060071 } while (0)
72#endif
73
Jeremy Hayes9d304782016-10-09 11:48:12 -060074struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060075 vk::Sampler sampler;
76
77 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060078 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070079 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060080
81 vk::MemoryAllocateInfo mem_alloc;
82 vk::DeviceMemory mem;
83 vk::ImageView view;
84
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070085 int32_t tex_width{0};
86 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060087};
88
Jeremy Hayes9d304782016-10-09 11:48:12 -060089static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060090
91static int validation_error = 0;
92
93struct vkcube_vs_uniform {
94 // Must start with MVP
95 float mvp[4][4];
96 float position[12 * 3][4];
97 float color[12 * 3][4];
98};
99
100struct vktexcube_vs_uniform {
101 // Must start with MVP
102 float mvp[4][4];
103 float position[12 * 3][4];
104 float attr[12 * 3][4];
105};
106
107//--------------------------------------------------------------------------------------
108// Mesh and VertexFormat Data
109//--------------------------------------------------------------------------------------
110// clang-format off
111static const float g_vertex_buffer_data[] = {
112 -1.0f,-1.0f,-1.0f, // -X side
113 -1.0f,-1.0f, 1.0f,
114 -1.0f, 1.0f, 1.0f,
115 -1.0f, 1.0f, 1.0f,
116 -1.0f, 1.0f,-1.0f,
117 -1.0f,-1.0f,-1.0f,
118
119 -1.0f,-1.0f,-1.0f, // -Z side
120 1.0f, 1.0f,-1.0f,
121 1.0f,-1.0f,-1.0f,
122 -1.0f,-1.0f,-1.0f,
123 -1.0f, 1.0f,-1.0f,
124 1.0f, 1.0f,-1.0f,
125
126 -1.0f,-1.0f,-1.0f, // -Y side
127 1.0f,-1.0f,-1.0f,
128 1.0f,-1.0f, 1.0f,
129 -1.0f,-1.0f,-1.0f,
130 1.0f,-1.0f, 1.0f,
131 -1.0f,-1.0f, 1.0f,
132
133 -1.0f, 1.0f,-1.0f, // +Y side
134 -1.0f, 1.0f, 1.0f,
135 1.0f, 1.0f, 1.0f,
136 -1.0f, 1.0f,-1.0f,
137 1.0f, 1.0f, 1.0f,
138 1.0f, 1.0f,-1.0f,
139
140 1.0f, 1.0f,-1.0f, // +X side
141 1.0f, 1.0f, 1.0f,
142 1.0f,-1.0f, 1.0f,
143 1.0f,-1.0f, 1.0f,
144 1.0f,-1.0f,-1.0f,
145 1.0f, 1.0f,-1.0f,
146
147 -1.0f, 1.0f, 1.0f, // +Z side
148 -1.0f,-1.0f, 1.0f,
149 1.0f, 1.0f, 1.0f,
150 -1.0f,-1.0f, 1.0f,
151 1.0f,-1.0f, 1.0f,
152 1.0f, 1.0f, 1.0f,
153};
154
155static const float g_uv_buffer_data[] = {
156 0.0f, 1.0f, // -X side
157 1.0f, 1.0f,
158 1.0f, 0.0f,
159 1.0f, 0.0f,
160 0.0f, 0.0f,
161 0.0f, 1.0f,
162
163 1.0f, 1.0f, // -Z side
164 0.0f, 0.0f,
165 0.0f, 1.0f,
166 1.0f, 1.0f,
167 1.0f, 0.0f,
168 0.0f, 0.0f,
169
170 1.0f, 0.0f, // -Y side
171 1.0f, 1.0f,
172 0.0f, 1.0f,
173 1.0f, 0.0f,
174 0.0f, 1.0f,
175 0.0f, 0.0f,
176
177 1.0f, 0.0f, // +Y side
178 0.0f, 0.0f,
179 0.0f, 1.0f,
180 1.0f, 0.0f,
181 0.0f, 1.0f,
182 1.0f, 1.0f,
183
184 1.0f, 0.0f, // +X side
185 0.0f, 0.0f,
186 0.0f, 1.0f,
187 0.0f, 1.0f,
188 1.0f, 1.0f,
189 1.0f, 0.0f,
190
191 0.0f, 0.0f, // +Z side
192 0.0f, 1.0f,
193 1.0f, 0.0f,
194 0.0f, 1.0f,
195 1.0f, 1.0f,
196 1.0f, 0.0f,
197};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600198// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600199
Jeremy Hayes9d304782016-10-09 11:48:12 -0600200typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600201 vk::Image image;
202 vk::CommandBuffer cmd;
203 vk::CommandBuffer graphics_to_present_cmd;
204 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600205 vk::Buffer uniform_buffer;
206 vk::DeviceMemory uniform_memory;
207 vk::Framebuffer framebuffer;
208 vk::DescriptorSet descriptor_set;
209} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600210
Joey Bzdekbaf66472017-06-07 09:37:37 -0600211struct Demo {
212 Demo();
213 void build_image_ownership_cmd(uint32_t const &);
214 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
215 void cleanup();
216 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600217 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600218 void draw();
219 void draw_build_cmd(vk::CommandBuffer);
220 void flush_init_cmd();
221 void init(int, char **);
222 void init_connection();
223 void init_vk();
224 void init_vk_swapchain();
225 void prepare();
226 void prepare_buffers();
227 void prepare_cube_data_buffers();
228 void prepare_depth();
229 void prepare_descriptor_layout();
230 void prepare_descriptor_pool();
231 void prepare_descriptor_set();
232 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100233 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
234 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600235 vk::ShaderModule prepare_fs();
236 void prepare_pipeline();
237 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600238 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600239 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600240 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100241
Joey Bzdekbaf66472017-06-07 09:37:37 -0600242 void resize();
243 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
244 vk::PipelineStageFlags, vk::PipelineStageFlags);
245 void update_data_buffer();
246 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
247 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
248
249#if defined(VK_USE_PLATFORM_WIN32_KHR)
250 void run();
251 void create_window();
252#elif defined(VK_USE_PLATFORM_XLIB_KHR)
253 void create_xlib_window();
254 void handle_xlib_event(const XEvent *);
255 void run_xlib();
256#elif defined(VK_USE_PLATFORM_XCB_KHR)
257 void handle_xcb_event(const xcb_generic_event_t *);
258 void run_xcb();
259 void create_xcb_window();
260#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
261 void run();
262 void create_window();
Karl Schultz206b1c52018-04-13 18:02:07 -0600263#elif defined(VK_USE_PLATFORM_MACOS_MVK)
264 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600265#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
266 vk::Result create_display_surface();
267 void run_display();
268#endif
269
270#if defined(VK_USE_PLATFORM_WIN32_KHR)
271 HINSTANCE connection; // hInstance - Windows Instance
272 HWND window; // hWnd - window handle
273 POINT minsize; // minimum window size
274 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
275#elif defined(VK_USE_PLATFORM_XLIB_KHR)
276 Window xlib_window;
277 Atom xlib_wm_delete_window;
278 Display *display;
279#elif defined(VK_USE_PLATFORM_XCB_KHR)
280 xcb_window_t xcb_window;
281 xcb_screen_t *screen;
282 xcb_connection_t *connection;
283 xcb_intern_atom_reply_t *atom_wm_delete_window;
284#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
285 wl_display *display;
286 wl_registry *registry;
287 wl_compositor *compositor;
288 wl_surface *window;
289 wl_shell *shell;
290 wl_shell_surface *shell_surface;
291 wl_seat *seat;
292 wl_pointer *pointer;
293 wl_keyboard *keyboard;
Karl Schultz9ceac062017-12-12 10:33:01 -0500294#elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
295 void *window;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600296#endif
297
298 vk::SurfaceKHR surface;
299 bool prepared;
300 bool use_staging_buffer;
301 bool use_xlib;
302 bool separate_present_queue;
303
304 vk::Instance inst;
305 vk::PhysicalDevice gpu;
306 vk::Device device;
307 vk::Queue graphics_queue;
308 vk::Queue present_queue;
309 uint32_t graphics_queue_family_index;
310 uint32_t present_queue_family_index;
311 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
312 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
313 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
314 vk::PhysicalDeviceProperties gpu_props;
315 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
316 vk::PhysicalDeviceMemoryProperties memory_properties;
317
318 uint32_t enabled_extension_count;
319 uint32_t enabled_layer_count;
320 char const *extension_names[64];
321 char const *enabled_layers[64];
322
323 uint32_t width;
324 uint32_t height;
325 vk::Format format;
326 vk::ColorSpaceKHR color_space;
327
328 uint32_t swapchainImageCount;
329 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600330 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600331 vk::PresentModeKHR presentMode;
332 vk::Fence fences[FRAME_LAG];
333 uint32_t frame_index;
334
335 vk::CommandPool cmd_pool;
336 vk::CommandPool present_cmd_pool;
337
338 struct {
339 vk::Format format;
340 vk::Image image;
341 vk::MemoryAllocateInfo mem_alloc;
342 vk::DeviceMemory mem;
343 vk::ImageView view;
344 } depth;
345
346 static int32_t const texture_count = 1;
347 texture_object textures[texture_count];
348 texture_object staging_texture;
349
350 struct {
351 vk::Buffer buf;
352 vk::MemoryAllocateInfo mem_alloc;
353 vk::DeviceMemory mem;
354 vk::DescriptorBufferInfo buffer_info;
355 } uniform_data;
356
357 vk::CommandBuffer cmd; // Buffer for initialization commands
358 vk::PipelineLayout pipeline_layout;
359 vk::DescriptorSetLayout desc_layout;
360 vk::PipelineCache pipelineCache;
361 vk::RenderPass render_pass;
362 vk::Pipeline pipeline;
363
364 mat4x4 projection_matrix;
365 mat4x4 view_matrix;
366 mat4x4 model_matrix;
367
368 float spin_angle;
369 float spin_increment;
370 bool pause;
371
372 vk::ShaderModule vert_shader_module;
373 vk::ShaderModule frag_shader_module;
374
375 vk::DescriptorPool desc_pool;
376 vk::DescriptorSet desc_set;
377
378 std::unique_ptr<vk::Framebuffer[]> framebuffers;
379
380 bool quit;
381 uint32_t curFrame;
382 uint32_t frameCount;
383 bool validate;
384 bool use_break;
385 bool suppress_popups;
386
387 uint32_t current_buffer;
388 uint32_t queue_family_count;
389};
390
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600391#ifdef _WIN32
392// MS-Windows event handling function:
393LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
394#endif
395
Karl Schultz23cc2182016-11-23 17:15:17 -0700396#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700397static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700398 wl_shell_surface_pong(shell_surface, serial);
399}
400
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700401static 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 -0700402
403static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
404
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700405static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700406
Joey Bzdek15eb0702017-06-07 09:40:36 -0600407static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
408 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700409
Joey Bzdek15eb0702017-06-07 09:40:36 -0600410static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700411
Joey Bzdek15eb0702017-06-07 09:40:36 -0600412static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
413
414static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
415 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600416 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600417 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
418 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
419 }
420}
421
422static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
423
424static const struct wl_pointer_listener pointer_listener = {
425 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
426};
427
428static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
429
430static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
431 struct wl_array *keys) {}
432
433static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
434
435static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
436 uint32_t state) {
437 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
438 Demo *demo = (Demo *)data;
439 switch (key) {
440 case KEY_ESC: // Escape
441 demo->quit = true;
442 break;
443 case KEY_LEFT: // left arrow key
444 demo->spin_angle -= demo->spin_increment;
445 break;
446 case KEY_RIGHT: // right arrow key
447 demo->spin_angle += demo->spin_increment;
448 break;
449 case KEY_SPACE: // space bar
450 demo->pause = !demo->pause;
451 break;
452 }
453}
454
455static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
456 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
457
458static const struct wl_keyboard_listener keyboard_listener = {
459 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
460};
461
462static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
463 // Subscribe to pointer events
464 Demo *demo = (Demo *)data;
465 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
466 demo->pointer = wl_seat_get_pointer(seat);
467 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
468 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
469 wl_pointer_destroy(demo->pointer);
470 demo->pointer = NULL;
471 }
472 // Subscribe to keyboard events
473 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
474 demo->keyboard = wl_seat_get_keyboard(seat);
475 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
476 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
477 wl_keyboard_destroy(demo->keyboard);
478 demo->keyboard = NULL;
479 }
480}
481
482static const wl_seat_listener seat_listener = {
483 seat_handle_capabilities,
484};
485
486static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
487 Demo *demo = (Demo *)data;
488 // pickup wayland objects when they appear
489 if (strcmp(interface, "wl_compositor") == 0) {
490 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
491 } else if (strcmp(interface, "wl_shell") == 0) {
492 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
493 } else if (strcmp(interface, "wl_seat") == 0) {
494 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
495 wl_seat_add_listener(demo->seat, &seat_listener, demo);
496 }
497}
498
499static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
500
501static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700502#endif
503
Joey Bzdekbaf66472017-06-07 09:37:37 -0600504Demo::Demo()
505 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600506#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600507 connection{nullptr},
508 window{nullptr},
509 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600510#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700511
Tony Barbour78d6b572016-11-14 14:46:33 -0700512#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600513 xlib_window{0},
514 xlib_wm_delete_window{0},
515 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700516#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600517 xcb_window{0},
518 screen{nullptr},
519 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700520#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521 display{nullptr},
522 registry{nullptr},
523 compositor{nullptr},
524 window{nullptr},
525 shell{nullptr},
526 shell_surface{nullptr},
527 seat{nullptr},
528 pointer{nullptr},
529 keyboard{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700530#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600531 prepared{false},
532 use_staging_buffer{false},
533 use_xlib{false},
534 graphics_queue_family_index{0},
535 present_queue_family_index{0},
536 enabled_extension_count{0},
537 enabled_layer_count{0},
538 width{0},
539 height{0},
540 swapchainImageCount{0},
541 frame_index{0},
542 spin_angle{0.0f},
543 spin_increment{0.0f},
544 pause{false},
545 quit{false},
546 curFrame{0},
547 frameCount{0},
548 validate{false},
549 use_break{false},
550 suppress_popups{false},
551 current_buffer{0},
552 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600553#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700554 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600555#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700556 memset(projection_matrix, 0, sizeof(projection_matrix));
557 memset(view_matrix, 0, sizeof(view_matrix));
558 memset(model_matrix, 0, sizeof(model_matrix));
559}
560
561void Demo::build_image_ownership_cmd(uint32_t const &i) {
562 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
563 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
564 VERIFY(result == vk::Result::eSuccess);
565
566 auto const image_ownership_barrier =
567 vk::ImageMemoryBarrier()
568 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600569 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700570 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
571 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
572 .setSrcQueueFamilyIndex(graphics_queue_family_index)
573 .setDstQueueFamilyIndex(present_queue_family_index)
574 .setImage(swapchain_image_resources[i].image)
575 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
576
577 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600578 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
579 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700580
581 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
582 VERIFY(result == vk::Result::eSuccess);
583}
584
585vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
586 vk::LayerProperties *layers) {
587 for (uint32_t i = 0; i < check_count; i++) {
588 vk::Bool32 found = VK_FALSE;
589 for (uint32_t j = 0; j < layer_count; j++) {
590 if (!strcmp(check_names[i], layers[j].layerName)) {
591 found = VK_TRUE;
592 break;
593 }
594 }
595 if (!found) {
596 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
597 return 0;
598 }
599 }
600 return VK_TRUE;
601}
602
603void Demo::cleanup() {
604 prepared = false;
605 device.waitIdle();
606
607 // Wait for fences from present operations
608 for (uint32_t i = 0; i < FRAME_LAG; i++) {
609 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
610 device.destroyFence(fences[i], nullptr);
611 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
612 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
613 if (separate_present_queue) {
614 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
615 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600616 }
617
Dave Houlton5fa47912018-02-16 11:02:26 -0700618 for (uint32_t i = 0; i < swapchainImageCount; i++) {
619 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
620 }
621 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600622
Dave Houlton5fa47912018-02-16 11:02:26 -0700623 device.destroyPipeline(pipeline, nullptr);
624 device.destroyPipelineCache(pipelineCache, nullptr);
625 device.destroyRenderPass(render_pass, nullptr);
626 device.destroyPipelineLayout(pipeline_layout, nullptr);
627 device.destroyDescriptorSetLayout(desc_layout, nullptr);
628
629 for (uint32_t i = 0; i < texture_count; i++) {
630 device.destroyImageView(textures[i].view, nullptr);
631 device.destroyImage(textures[i].image, nullptr);
632 device.freeMemory(textures[i].mem, nullptr);
633 device.destroySampler(textures[i].sampler, nullptr);
634 }
635 device.destroySwapchainKHR(swapchain, nullptr);
636
637 device.destroyImageView(depth.view, nullptr);
638 device.destroyImage(depth.image, nullptr);
639 device.freeMemory(depth.mem, nullptr);
640
641 for (uint32_t i = 0; i < swapchainImageCount; i++) {
642 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
643 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
644 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
645 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
646 }
647
648 device.destroyCommandPool(cmd_pool, nullptr);
649
650 if (separate_present_queue) {
651 device.destroyCommandPool(present_cmd_pool, nullptr);
652 }
653 device.waitIdle();
654 device.destroy(nullptr);
655 inst.destroySurfaceKHR(surface, nullptr);
656
657#if defined(VK_USE_PLATFORM_XLIB_KHR)
658 XDestroyWindow(display, xlib_window);
659 XCloseDisplay(display);
660#elif defined(VK_USE_PLATFORM_XCB_KHR)
661 xcb_destroy_window(connection, xcb_window);
662 xcb_disconnect(connection);
663 free(atom_wm_delete_window);
664#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
665 wl_keyboard_destroy(keyboard);
666 wl_pointer_destroy(pointer);
667 wl_seat_destroy(seat);
668 wl_shell_surface_destroy(shell_surface);
669 wl_surface_destroy(window);
670 wl_shell_destroy(shell);
671 wl_compositor_destroy(compositor);
672 wl_registry_destroy(registry);
673 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700674#endif
675
676 inst.destroy(nullptr);
677}
678
679void Demo::create_device() {
680 float const priorities[1] = {0.0};
681
682 vk::DeviceQueueCreateInfo queues[2];
683 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
684 queues[0].setQueueCount(1);
685 queues[0].setPQueuePriorities(priorities);
686
687 auto deviceInfo = vk::DeviceCreateInfo()
688 .setQueueCreateInfoCount(1)
689 .setPQueueCreateInfos(queues)
690 .setEnabledLayerCount(0)
691 .setPpEnabledLayerNames(nullptr)
692 .setEnabledExtensionCount(enabled_extension_count)
693 .setPpEnabledExtensionNames((const char *const *)extension_names)
694 .setPEnabledFeatures(nullptr);
695
696 if (separate_present_queue) {
697 queues[1].setQueueFamilyIndex(present_queue_family_index);
698 queues[1].setQueueCount(1);
699 queues[1].setPQueuePriorities(priorities);
700 deviceInfo.setQueueCreateInfoCount(2);
701 }
702
703 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
704 VERIFY(result == vk::Result::eSuccess);
705}
706
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600707void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700708 // clean up staging resources
709 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600710 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
711 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700712}
713
714void Demo::draw() {
715 // Ensure no more than FRAME_LAG renderings are outstanding
716 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
717 device.resetFences(1, &fences[frame_index]);
718
719 vk::Result result;
720 do {
721 result =
722 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
723 if (result == vk::Result::eErrorOutOfDateKHR) {
724 // demo->swapchain is out of date (e.g. the window was resized) and
725 // must be recreated:
726 resize();
727 } else if (result == vk::Result::eSuboptimalKHR) {
728 // swapchain is not as optimal as it could be, but the platform's
729 // presentation engine will still present the image correctly.
730 break;
731 } else {
732 VERIFY(result == vk::Result::eSuccess);
733 }
734 } while (result != vk::Result::eSuccess);
735
736 update_data_buffer();
737
738 // Wait for the image acquired semaphore to be signaled to ensure
739 // that the image won't be rendered to until the presentation
740 // engine has fully released ownership to the application, and it is
741 // okay to render to the image.
742 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
743 auto const submit_info = vk::SubmitInfo()
744 .setPWaitDstStageMask(&pipe_stage_flags)
745 .setWaitSemaphoreCount(1)
746 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
747 .setCommandBufferCount(1)
748 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
749 .setSignalSemaphoreCount(1)
750 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
751
752 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
753 VERIFY(result == vk::Result::eSuccess);
754
755 if (separate_present_queue) {
756 // If we are using separate queues, change image ownership to the
757 // present queue before presenting, waiting for the draw complete
758 // semaphore and signalling the ownership released semaphore when
759 // finished
760 auto const present_submit_info = vk::SubmitInfo()
761 .setPWaitDstStageMask(&pipe_stage_flags)
762 .setWaitSemaphoreCount(1)
763 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
764 .setCommandBufferCount(1)
765 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
766 .setSignalSemaphoreCount(1)
767 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
768
769 result = present_queue.submit(1, &present_submit_info, vk::Fence());
770 VERIFY(result == vk::Result::eSuccess);
771 }
772
773 // If we are using separate queues we have to wait for image ownership,
774 // otherwise wait for draw complete
775 auto const presentInfo = vk::PresentInfoKHR()
776 .setWaitSemaphoreCount(1)
777 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
778 : &draw_complete_semaphores[frame_index])
779 .setSwapchainCount(1)
780 .setPSwapchains(&swapchain)
781 .setPImageIndices(&current_buffer);
782
783 result = present_queue.presentKHR(&presentInfo);
784 frame_index += 1;
785 frame_index %= FRAME_LAG;
786 if (result == vk::Result::eErrorOutOfDateKHR) {
787 // swapchain is out of date (e.g. the window was resized) and
788 // must be recreated:
789 resize();
790 } else if (result == vk::Result::eSuboptimalKHR) {
791 // swapchain is not as optimal as it could be, but the platform's
792 // presentation engine will still present the image correctly.
793 } else {
794 VERIFY(result == vk::Result::eSuccess);
795 }
796}
797
798void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
799 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
800
801 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
802 vk::ClearDepthStencilValue(1.0f, 0u)};
803
804 auto const passInfo = vk::RenderPassBeginInfo()
805 .setRenderPass(render_pass)
806 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
807 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
808 .setClearValueCount(2)
809 .setPClearValues(clearValues);
810
811 auto result = commandBuffer.begin(&commandInfo);
812 VERIFY(result == vk::Result::eSuccess);
813
814 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
815 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
816 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
817 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
818
819 auto const viewport =
820 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
821 commandBuffer.setViewport(0, 1, &viewport);
822
823 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
824 commandBuffer.setScissor(0, 1, &scissor);
825 commandBuffer.draw(12 * 3, 1, 0, 0);
826 // Note that ending the renderpass changes the image's layout from
827 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
828 commandBuffer.endRenderPass();
829
830 if (separate_present_queue) {
831 // We have to transfer ownership from the graphics queue family to
832 // the
833 // present queue family to be able to present. Note that we don't
834 // have
835 // to transfer from present queue family back to graphics queue
836 // family at
837 // the start of the next frame because we don't care about the
838 // image's
839 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600840 auto const image_ownership_barrier =
841 vk::ImageMemoryBarrier()
842 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600843 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600844 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
845 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
846 .setSrcQueueFamilyIndex(graphics_queue_family_index)
847 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700848 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700849 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600850
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600851 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700852 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600853 }
854
Dave Houlton5fa47912018-02-16 11:02:26 -0700855 result = commandBuffer.end();
856 VERIFY(result == vk::Result::eSuccess);
857}
858
859void Demo::flush_init_cmd() {
860 // TODO: hmm.
861 // This function could get called twice if the texture uses a staging
862 // buffer
863 // In that case the second call should be ignored
864 if (!cmd) {
865 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600866 }
867
Dave Houlton5fa47912018-02-16 11:02:26 -0700868 auto result = cmd.end();
869 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600870
Dave Houlton5fa47912018-02-16 11:02:26 -0700871 auto const fenceInfo = vk::FenceCreateInfo();
872 vk::Fence fence;
873 result = device.createFence(&fenceInfo, nullptr, &fence);
874 VERIFY(result == vk::Result::eSuccess);
875
876 vk::CommandBuffer const commandBuffers[] = {cmd};
877 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
878
879 result = graphics_queue.submit(1, &submitInfo, fence);
880 VERIFY(result == vk::Result::eSuccess);
881
882 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
883 VERIFY(result == vk::Result::eSuccess);
884
885 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
886 device.destroyFence(fence, nullptr);
887
888 cmd = vk::CommandBuffer();
889}
890
891void Demo::init(int argc, char **argv) {
892 vec3 eye = {0.0f, 3.0f, 5.0f};
893 vec3 origin = {0, 0, 0};
894 vec3 up = {0.0f, 1.0f, 0.0};
895
896 presentMode = vk::PresentModeKHR::eFifo;
897 frameCount = UINT32_MAX;
898 use_xlib = false;
899
900 for (int i = 1; i < argc; i++) {
901 if (strcmp(argv[i], "--use_staging") == 0) {
902 use_staging_buffer = true;
903 continue;
904 }
905 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
906 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
907 i++;
908 continue;
909 }
910 if (strcmp(argv[i], "--break") == 0) {
911 use_break = true;
912 continue;
913 }
914 if (strcmp(argv[i], "--validate") == 0) {
915 validate = true;
916 continue;
917 }
918 if (strcmp(argv[i], "--xlib") == 0) {
919 fprintf(stderr, "--xlib is deprecated and no longer does anything");
920 continue;
921 }
922 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
923 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
924 i++;
925 continue;
926 }
927 if (strcmp(argv[i], "--suppress_popups") == 0) {
928 suppress_popups = true;
929 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600930 }
931
Dave Houlton5fa47912018-02-16 11:02:26 -0700932 fprintf(stderr,
933 "Usage:\n %s [--use_staging] [--validate] [--break] [--c <framecount>] \n"
934 " [--suppress_popups] [--present_mode {0,1,2,3}]\n"
935 "\n"
936 "Options for --present_mode:\n"
937 " %d: VK_PRESENT_MODE_IMMEDIATE_KHR\n"
938 " %d: VK_PRESENT_MODE_MAILBOX_KHR\n"
939 " %d: VK_PRESENT_MODE_FIFO_KHR (default)\n"
940 " %d: VK_PRESENT_MODE_FIFO_RELAXED_KHR\n",
941 APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
942 VK_PRESENT_MODE_FIFO_RELAXED_KHR);
943 fflush(stderr);
944 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600945 }
946
Dave Houlton5fa47912018-02-16 11:02:26 -0700947 if (!use_xlib) {
948 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600949 }
950
Dave Houlton5fa47912018-02-16 11:02:26 -0700951 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600952
Dave Houlton5fa47912018-02-16 11:02:26 -0700953 width = 500;
954 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600955
Dave Houlton5fa47912018-02-16 11:02:26 -0700956 spin_angle = 4.0f;
957 spin_increment = 0.2f;
958 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600959
Dave Houlton5fa47912018-02-16 11:02:26 -0700960 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
961 mat4x4_look_at(view_matrix, eye, origin, up);
962 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600963
Dave Houlton5fa47912018-02-16 11:02:26 -0700964 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
965}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600966
Dave Houlton5fa47912018-02-16 11:02:26 -0700967void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600968#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700969 const xcb_setup_t *setup;
970 xcb_screen_iterator_t iter;
971 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600972
Dave Houlton5fa47912018-02-16 11:02:26 -0700973 const char *display_envar = getenv("DISPLAY");
974 if (display_envar == nullptr || display_envar[0] == '\0') {
975 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
976 fflush(stdout);
977 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600978 }
979
Dave Houlton5fa47912018-02-16 11:02:26 -0700980 connection = xcb_connect(nullptr, &scr);
981 if (xcb_connection_has_error(connection) > 0) {
982 printf(
983 "Cannot find a compatible Vulkan installable client driver "
984 "(ICD).\nExiting ...\n");
985 fflush(stdout);
986 exit(1);
987 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600988
Dave Houlton5fa47912018-02-16 11:02:26 -0700989 setup = xcb_get_setup(connection);
990 iter = xcb_setup_roots_iterator(setup);
991 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600992
Dave Houlton5fa47912018-02-16 11:02:26 -0700993 screen = iter.data;
994#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
995 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600996
Dave Houlton5fa47912018-02-16 11:02:26 -0700997 if (display == nullptr) {
998 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
999 fflush(stdout);
1000 exit(1);
1001 }
1002
1003 registry = wl_display_get_registry(display);
1004 wl_registry_add_listener(registry, &registry_listener, this);
1005 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001006#endif
1007}
1008
1009void Demo::init_vk() {
1010 uint32_t instance_extension_count = 0;
1011 uint32_t instance_layer_count = 0;
1012 uint32_t validation_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001013 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001014 enabled_extension_count = 0;
1015 enabled_layer_count = 0;
1016
Dave Houlton5fa47912018-02-16 11:02:26 -07001017 // Look for validation layers
1018 vk::Bool32 validation_found = VK_FALSE;
1019 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001020 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001021 VERIFY(result == vk::Result::eSuccess);
1022
Dave Houlton5fa47912018-02-16 11:02:26 -07001023 if (instance_layer_count > 0) {
1024 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1025 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001026 VERIFY(result == vk::Result::eSuccess);
1027
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001028 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001029 instance_layer_count, instance_layers.get());
1030 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001031 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1032 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Dave Houlton5fa47912018-02-16 11:02:26 -07001033 validation_layer_count = 1;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001034 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001035 }
1036
Dave Houlton5fa47912018-02-16 11:02:26 -07001037 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001038 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001039 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1040 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001041 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001042 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001043 }
1044
Dave Houlton5fa47912018-02-16 11:02:26 -07001045 /* Look for instance extensions */
1046 vk::Bool32 surfaceExtFound = VK_FALSE;
1047 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1048 memset(extension_names, 0, sizeof(extension_names));
1049
Mike Schuchardt7510c832018-10-29 13:23:08 -07001050 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1051 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001052 VERIFY(result == vk::Result::eSuccess);
1053
1054 if (instance_extension_count > 0) {
1055 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1056 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1057 VERIFY(result == vk::Result::eSuccess);
1058
1059 for (uint32_t i = 0; i < instance_extension_count; i++) {
1060 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1061 surfaceExtFound = 1;
1062 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1063 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001064#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001065 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1066 platformSurfaceExtFound = 1;
1067 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1068 }
1069#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1070 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1071 platformSurfaceExtFound = 1;
1072 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1073 }
1074#elif defined(VK_USE_PLATFORM_XCB_KHR)
1075 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1076 platformSurfaceExtFound = 1;
1077 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1078 }
Tony Barbour153cb062016-12-07 13:43:36 -07001079#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001080 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1081 platformSurfaceExtFound = 1;
1082 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1083 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001084#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1085 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1086 platformSurfaceExtFound = 1;
1087 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1088 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001089#elif defined(VK_USE_PLATFORM_IOS_MVK)
1090 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1091 platformSurfaceExtFound = 1;
1092 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1093 }
1094#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1095 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1096 platformSurfaceExtFound = 1;
1097 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1098 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001099
Dave Houlton5fa47912018-02-16 11:02:26 -07001100#endif
1101 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001102 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001103 }
1104
1105 if (!surfaceExtFound) {
1106 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1107 " extension.\n\n"
1108 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1109 "Please look at the Getting Started guide for additional information.\n",
1110 "vkCreateInstance Failure");
1111 }
1112
1113 if (!platformSurfaceExtFound) {
1114#if defined(VK_USE_PLATFORM_WIN32_KHR)
1115 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1116 " extension.\n\n"
1117 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1118 "Please look at the Getting Started guide for additional information.\n",
1119 "vkCreateInstance Failure");
1120#elif defined(VK_USE_PLATFORM_XCB_KHR)
1121 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1122 " extension.\n\n"
1123 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1124 "Please look at the Getting Started guide for additional information.\n",
1125 "vkCreateInstance Failure");
1126#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1127 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1128 " extension.\n\n"
1129 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1130 "Please look at the Getting Started guide for additional information.\n",
1131 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001132#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001133 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1134 " extension.\n\n"
1135 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1136 "Please look at the Getting Started guide for additional information.\n",
1137 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001138#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001139 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1140 " extension.\n\n"
1141 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1142 "Please look at the Getting Started guide for additional information.\n",
1143 "vkCreateInstance Failure");
Karl Schultz9ceac062017-12-12 10:33:01 -05001144#elif defined(VK_USE_PLATFORM_IOS_MVK)
1145 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1146 " extension.\n\nDo you have a compatible "
1147 "Vulkan installable client driver (ICD) installed?\nPlease "
1148 "look at the Getting Started guide for additional "
1149 "information.\n",
1150 "vkCreateInstance Failure");
1151#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1152 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1153 " extension.\n\nDo you have a compatible "
1154 "Vulkan installable client driver (ICD) installed?\nPlease "
1155 "look at the Getting Started guide for additional "
1156 "information.\n",
1157 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001158#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001159 }
1160 auto const app = vk::ApplicationInfo()
1161 .setPApplicationName(APP_SHORT_NAME)
1162 .setApplicationVersion(0)
1163 .setPEngineName(APP_SHORT_NAME)
1164 .setEngineVersion(0)
1165 .setApiVersion(VK_API_VERSION_1_0);
1166 auto const inst_info = vk::InstanceCreateInfo()
1167 .setPApplicationInfo(&app)
1168 .setEnabledLayerCount(enabled_layer_count)
1169 .setPpEnabledLayerNames(instance_validation_layers)
1170 .setEnabledExtensionCount(enabled_extension_count)
1171 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001172
Dave Houlton5fa47912018-02-16 11:02:26 -07001173 result = vk::createInstance(&inst_info, nullptr, &inst);
1174 if (result == vk::Result::eErrorIncompatibleDriver) {
1175 ERR_EXIT(
1176 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1177 "Please look at the Getting Started guide for additional information.\n",
1178 "vkCreateInstance Failure");
1179 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1180 ERR_EXIT(
1181 "Cannot find a specified extension library.\n"
1182 "Make sure your layers path is set appropriately.\n",
1183 "vkCreateInstance Failure");
1184 } else if (result != vk::Result::eSuccess) {
1185 ERR_EXIT(
1186 "vkCreateInstance failed.\n\n"
1187 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1188 "Please look at the Getting Started guide for additional information.\n",
1189 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001190 }
1191
Dave Houlton5fa47912018-02-16 11:02:26 -07001192 /* Make initial call to query gpu_count, then second call for gpu info*/
1193 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001194 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001195 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001196
1197 if (gpu_count > 0) {
1198 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1199 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001200 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001201 /* For cube demo we just grab the first physical device */
1202 gpu = physical_devices[0];
1203 } else {
1204 ERR_EXIT(
1205 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1206 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1207 "Please look at the Getting Started guide for additional information.\n",
1208 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001209 }
1210
Dave Houlton5fa47912018-02-16 11:02:26 -07001211 /* Look for device extensions */
1212 uint32_t device_extension_count = 0;
1213 vk::Bool32 swapchainExtFound = VK_FALSE;
1214 enabled_extension_count = 0;
1215 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001216
Mike Schuchardt7510c832018-10-29 13:23:08 -07001217 result =
1218 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001219 VERIFY(result == vk::Result::eSuccess);
1220
1221 if (device_extension_count > 0) {
1222 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1223 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001224 VERIFY(result == vk::Result::eSuccess);
1225
Dave Houlton5fa47912018-02-16 11:02:26 -07001226 for (uint32_t i = 0; i < device_extension_count; i++) {
1227 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1228 swapchainExtFound = 1;
1229 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001230 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001231 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001232 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001233 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001234
Dave Houlton5fa47912018-02-16 11:02:26 -07001235 if (!swapchainExtFound) {
1236 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1237 " extension.\n\n"
1238 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1239 "Please look at the Getting Started guide for additional information.\n",
1240 "vkCreateInstance Failure");
1241 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001242
Dave Houlton5fa47912018-02-16 11:02:26 -07001243 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001244
Dave Houlton5fa47912018-02-16 11:02:26 -07001245 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001246 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001247 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001248
Dave Houlton5fa47912018-02-16 11:02:26 -07001249 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1250 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001251
Dave Houlton5fa47912018-02-16 11:02:26 -07001252 // Query fine-grained feature support for this device.
1253 // If app has specific feature requirements it should check supported
1254 // features based on this query
1255 vk::PhysicalDeviceFeatures physDevFeatures;
1256 gpu.getFeatures(&physDevFeatures);
1257}
1258
1259void Demo::init_vk_swapchain() {
1260// Create a WSI surface for the window:
1261#if defined(VK_USE_PLATFORM_WIN32_KHR)
1262 {
1263 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1264
1265 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1266 VERIFY(result == vk::Result::eSuccess);
1267 }
1268#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1269 {
1270 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1271
1272 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1273 VERIFY(result == vk::Result::eSuccess);
1274 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001275#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1276 {
1277 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1278
1279 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1280 VERIFY(result == vk::Result::eSuccess);
1281 }
1282#elif defined(VK_USE_PLATFORM_XCB_KHR)
1283 {
1284 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1285
1286 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1287 VERIFY(result == vk::Result::eSuccess);
1288 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001289#elif defined(VK_USE_PLATFORM_IOS_MVK)
1290 {
1291 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1292
1293 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1294 VERIFY(result == vk::Result::eSuccess);
1295 }
1296#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1297 {
1298 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1299
1300 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1301 VERIFY(result == vk::Result::eSuccess);
1302 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001303#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1304 {
1305 auto result = create_display_surface();
1306 VERIFY(result == vk::Result::eSuccess);
1307 }
1308#endif
1309 // Iterate over each queue to learn whether it supports presenting:
1310 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1311 for (uint32_t i = 0; i < queue_family_count; i++) {
1312 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1313 }
1314
1315 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1316 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1317 for (uint32_t i = 0; i < queue_family_count; i++) {
1318 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1319 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1320 graphicsQueueFamilyIndex = i;
1321 }
1322
1323 if (supportsPresent[i] == VK_TRUE) {
1324 graphicsQueueFamilyIndex = i;
1325 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001326 break;
1327 }
1328 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001329 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001330
Dave Houlton5fa47912018-02-16 11:02:26 -07001331 if (presentQueueFamilyIndex == UINT32_MAX) {
1332 // If didn't find a queue that supports both graphics and present,
1333 // then
1334 // find a separate present queue.
1335 for (uint32_t i = 0; i < queue_family_count; ++i) {
1336 if (supportsPresent[i] == VK_TRUE) {
1337 presentQueueFamilyIndex = i;
1338 break;
1339 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001340 }
1341 }
1342
Dave Houlton5fa47912018-02-16 11:02:26 -07001343 // Generate error if could not find both a graphics and a present queue
1344 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1345 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1346 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001347
Dave Houlton5fa47912018-02-16 11:02:26 -07001348 graphics_queue_family_index = graphicsQueueFamilyIndex;
1349 present_queue_family_index = presentQueueFamilyIndex;
1350 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001351
Dave Houlton5fa47912018-02-16 11:02:26 -07001352 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001353
Dave Houlton5fa47912018-02-16 11:02:26 -07001354 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1355 if (!separate_present_queue) {
1356 present_queue = graphics_queue;
1357 } else {
1358 device.getQueue(present_queue_family_index, 0, &present_queue);
1359 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001360
Dave Houlton5fa47912018-02-16 11:02:26 -07001361 // Get the list of VkFormat's that are supported:
1362 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001363 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001364 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001365
Dave Houlton5fa47912018-02-16 11:02:26 -07001366 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1367 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1368 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001369
Dave Houlton5fa47912018-02-16 11:02:26 -07001370 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1371 // the surface has no preferred format. Otherwise, at least one
1372 // supported format will be returned.
1373 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1374 format = vk::Format::eB8G8R8A8Unorm;
1375 } else {
1376 assert(formatCount >= 1);
1377 format = surfFormats[0].format;
1378 }
1379 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001380
Dave Houlton5fa47912018-02-16 11:02:26 -07001381 quit = false;
1382 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 // Create semaphores to synchronize acquiring presentable buffers before
1385 // rendering and waiting for drawing to be complete before presenting
1386 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001387
Dave Houlton5fa47912018-02-16 11:02:26 -07001388 // Create fences that we can use to throttle if we get too far
1389 // ahead of the image presents
1390 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1391 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1392 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1393 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001394
Dave Houlton5fa47912018-02-16 11:02:26 -07001395 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1396 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001397
Dave Houlton5fa47912018-02-16 11:02:26 -07001398 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1399 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001400
Dave Houlton5fa47912018-02-16 11:02:26 -07001401 if (separate_present_queue) {
1402 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001403 VERIFY(result == vk::Result::eSuccess);
1404 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001405 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001406 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001407
Dave Houlton5fa47912018-02-16 11:02:26 -07001408 // Get Memory information and properties
1409 gpu.getMemoryProperties(&memory_properties);
1410}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001411
Dave Houlton5fa47912018-02-16 11:02:26 -07001412void Demo::prepare() {
1413 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1414 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1415 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001416
Dave Houlton5fa47912018-02-16 11:02:26 -07001417 auto const cmd = vk::CommandBufferAllocateInfo()
1418 .setCommandPool(cmd_pool)
1419 .setLevel(vk::CommandBufferLevel::ePrimary)
1420 .setCommandBufferCount(1);
1421
1422 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1423 VERIFY(result == vk::Result::eSuccess);
1424
1425 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1426
1427 result = this->cmd.begin(&cmd_buf_info);
1428 VERIFY(result == vk::Result::eSuccess);
1429
1430 prepare_buffers();
1431 prepare_depth();
1432 prepare_textures();
1433 prepare_cube_data_buffers();
1434
1435 prepare_descriptor_layout();
1436 prepare_render_pass();
1437 prepare_pipeline();
1438
1439 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1440 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1441 VERIFY(result == vk::Result::eSuccess);
1442 }
1443
1444 if (separate_present_queue) {
1445 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1446
1447 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1448 VERIFY(result == vk::Result::eSuccess);
1449
1450 auto const present_cmd = vk::CommandBufferAllocateInfo()
1451 .setCommandPool(present_cmd_pool)
1452 .setLevel(vk::CommandBufferLevel::ePrimary)
1453 .setCommandBufferCount(1);
1454
1455 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1456 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1457 VERIFY(result == vk::Result::eSuccess);
1458
1459 build_image_ownership_cmd(i);
1460 }
1461 }
1462
1463 prepare_descriptor_pool();
1464 prepare_descriptor_set();
1465
1466 prepare_framebuffers();
1467
1468 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1469 current_buffer = i;
1470 draw_build_cmd(swapchain_image_resources[i].cmd);
1471 }
1472
1473 /*
1474 * Prepare functions above may generate pipeline commands
1475 * that need to be flushed before beginning the render loop.
1476 */
1477 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001478 if (staging_texture.buffer) {
1479 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001480 }
1481
1482 current_buffer = 0;
1483 prepared = true;
1484}
1485
1486void Demo::prepare_buffers() {
1487 vk::SwapchainKHR oldSwapchain = swapchain;
1488
1489 // Check the surface capabilities and formats
1490 vk::SurfaceCapabilitiesKHR surfCapabilities;
1491 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1492 VERIFY(result == vk::Result::eSuccess);
1493
1494 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001495 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001496 VERIFY(result == vk::Result::eSuccess);
1497
1498 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1499 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1500 VERIFY(result == vk::Result::eSuccess);
1501
1502 vk::Extent2D swapchainExtent;
1503 // width and height are either both -1, or both not -1.
1504 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1505 // If the surface size is undefined, the size is set to
1506 // the size of the images requested.
1507 swapchainExtent.width = width;
1508 swapchainExtent.height = height;
1509 } else {
1510 // If the surface size is defined, the swap chain size must match
1511 swapchainExtent = surfCapabilities.currentExtent;
1512 width = surfCapabilities.currentExtent.width;
1513 height = surfCapabilities.currentExtent.height;
1514 }
1515
1516 // The FIFO present mode is guaranteed by the spec to be supported
1517 // and to have no tearing. It's a great default present mode to use.
1518 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1519
1520 // There are times when you may wish to use another present mode. The
1521 // following code shows how to select them, and the comments provide some
1522 // reasons you may wish to use them.
1523 //
1524 // It should be noted that Vulkan 1.0 doesn't provide a method for
1525 // synchronizing rendering with the presentation engine's display. There
1526 // is a method provided for throttling rendering with the display, but
1527 // there are some presentation engines for which this method will not work.
1528 // If an application doesn't throttle its rendering, and if it renders much
1529 // faster than the refresh rate of the display, this can waste power on
1530 // mobile devices. That is because power is being spent rendering images
1531 // that may never be seen.
1532
1533 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1534 // about
1535 // tearing, or have some way of synchronizing their rendering with the
1536 // display.
1537 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1538 // generally render a new presentable image every refresh cycle, but are
1539 // occasionally early. In this case, the application wants the new
1540 // image
1541 // to be displayed instead of the previously-queued-for-presentation
1542 // image
1543 // that has not yet been displayed.
1544 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1545 // render a new presentable image every refresh cycle, but are
1546 // occasionally
1547 // late. In this case (perhaps because of stuttering/latency concerns),
1548 // the application wants the late image to be immediately displayed,
1549 // even
1550 // though that may mean some tearing.
1551
1552 if (presentMode != swapchainPresentMode) {
1553 for (size_t i = 0; i < presentModeCount; ++i) {
1554 if (presentModes[i] == presentMode) {
1555 swapchainPresentMode = presentMode;
1556 break;
1557 }
1558 }
1559 }
1560
1561 if (swapchainPresentMode != presentMode) {
1562 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1563 }
1564
1565 // Determine the number of VkImages to use in the swap chain.
1566 // Application desires to acquire 3 images at a time for triple
1567 // buffering
1568 uint32_t desiredNumOfSwapchainImages = 3;
1569 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1570 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1571 }
1572
1573 // If maxImageCount is 0, we can ask for as many images as we want,
1574 // otherwise
1575 // we're limited to maxImageCount
1576 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1577 // Application must settle for fewer images than desired:
1578 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1579 }
1580
1581 vk::SurfaceTransformFlagBitsKHR preTransform;
1582 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1583 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1584 } else {
1585 preTransform = surfCapabilities.currentTransform;
1586 }
1587
1588 // Find a supported composite alpha mode - one of these is guaranteed to be set
1589 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1590 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1591 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1592 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1593 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1594 vk::CompositeAlphaFlagBitsKHR::eInherit,
1595 };
1596 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1597 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1598 compositeAlpha = compositeAlphaFlags[i];
1599 break;
1600 }
1601 }
1602
1603 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1604 .setSurface(surface)
1605 .setMinImageCount(desiredNumOfSwapchainImages)
1606 .setImageFormat(format)
1607 .setImageColorSpace(color_space)
1608 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1609 .setImageArrayLayers(1)
1610 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1611 .setImageSharingMode(vk::SharingMode::eExclusive)
1612 .setQueueFamilyIndexCount(0)
1613 .setPQueueFamilyIndices(nullptr)
1614 .setPreTransform(preTransform)
1615 .setCompositeAlpha(compositeAlpha)
1616 .setPresentMode(swapchainPresentMode)
1617 .setClipped(true)
1618 .setOldSwapchain(oldSwapchain);
1619
1620 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1621 VERIFY(result == vk::Result::eSuccess);
1622
1623 // If we just re-created an existing swapchain, we should destroy the
1624 // old
1625 // swapchain at this point.
1626 // Note: destroying the swapchain also cleans up all its associated
1627 // presentable images once the platform is done with them.
1628 if (oldSwapchain) {
1629 device.destroySwapchainKHR(oldSwapchain, nullptr);
1630 }
1631
Mike Schuchardt7510c832018-10-29 13:23:08 -07001632 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001633 VERIFY(result == vk::Result::eSuccess);
1634
1635 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1636 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1637 VERIFY(result == vk::Result::eSuccess);
1638
1639 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1640
1641 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1642 auto color_image_view = vk::ImageViewCreateInfo()
1643 .setViewType(vk::ImageViewType::e2D)
1644 .setFormat(format)
1645 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1646
1647 swapchain_image_resources[i].image = swapchainImages[i];
1648
1649 color_image_view.image = swapchain_image_resources[i].image;
1650
1651 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1652 VERIFY(result == vk::Result::eSuccess);
1653 }
1654}
1655
1656void Demo::prepare_cube_data_buffers() {
1657 mat4x4 VP;
1658 mat4x4_mul(VP, projection_matrix, view_matrix);
1659
1660 mat4x4 MVP;
1661 mat4x4_mul(MVP, VP, model_matrix);
1662
1663 vktexcube_vs_uniform data;
1664 memcpy(data.mvp, MVP, sizeof(MVP));
1665 // dumpMatrix("MVP", MVP)
1666
1667 for (int32_t i = 0; i < 12 * 3; i++) {
1668 data.position[i][0] = g_vertex_buffer_data[i * 3];
1669 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1670 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1671 data.position[i][3] = 1.0f;
1672 data.attr[i][0] = g_uv_buffer_data[2 * i];
1673 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1674 data.attr[i][2] = 0;
1675 data.attr[i][3] = 0;
1676 }
1677
1678 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1679
1680 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1681 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001682 VERIFY(result == vk::Result::eSuccess);
1683
1684 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001685 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001686
Dave Houlton5fa47912018-02-16 11:02:26 -07001687 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001688
Dave Houlton5fa47912018-02-16 11:02:26 -07001689 bool const pass = memory_type_from_properties(
1690 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1691 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001692 VERIFY(pass);
1693
Dave Houlton5fa47912018-02-16 11:02:26 -07001694 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001695 VERIFY(result == vk::Result::eSuccess);
1696
Dave Houlton5fa47912018-02-16 11:02:26 -07001697 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1698 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001699
Dave Houlton5fa47912018-02-16 11:02:26 -07001700 memcpy(pData.value, &data, sizeof data);
1701
1702 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1703
1704 result =
1705 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001706 VERIFY(result == vk::Result::eSuccess);
1707 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001708}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001709
Dave Houlton5fa47912018-02-16 11:02:26 -07001710void Demo::prepare_depth() {
1711 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001712
Dave Houlton5fa47912018-02-16 11:02:26 -07001713 auto const image = vk::ImageCreateInfo()
1714 .setImageType(vk::ImageType::e2D)
1715 .setFormat(depth.format)
1716 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1717 .setMipLevels(1)
1718 .setArrayLayers(1)
1719 .setSamples(vk::SampleCountFlagBits::e1)
1720 .setTiling(vk::ImageTiling::eOptimal)
1721 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1722 .setSharingMode(vk::SharingMode::eExclusive)
1723 .setQueueFamilyIndexCount(0)
1724 .setPQueueFamilyIndices(nullptr)
1725 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001726
Dave Houlton5fa47912018-02-16 11:02:26 -07001727 auto result = device.createImage(&image, nullptr, &depth.image);
1728 VERIFY(result == vk::Result::eSuccess);
1729
1730 vk::MemoryRequirements mem_reqs;
1731 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1732
1733 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1734 depth.mem_alloc.setMemoryTypeIndex(0);
1735
1736 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1737 &depth.mem_alloc.memoryTypeIndex);
1738 VERIFY(pass);
1739
1740 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1741 VERIFY(result == vk::Result::eSuccess);
1742
1743 result = device.bindImageMemory(depth.image, depth.mem, 0);
1744 VERIFY(result == vk::Result::eSuccess);
1745
1746 auto const view = vk::ImageViewCreateInfo()
1747 .setImage(depth.image)
1748 .setViewType(vk::ImageViewType::e2D)
1749 .setFormat(depth.format)
1750 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1751 result = device.createImageView(&view, nullptr, &depth.view);
1752 VERIFY(result == vk::Result::eSuccess);
1753}
1754
1755void Demo::prepare_descriptor_layout() {
1756 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1757 .setBinding(0)
1758 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1759 .setDescriptorCount(1)
1760 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1761 .setPImmutableSamplers(nullptr),
1762 vk::DescriptorSetLayoutBinding()
1763 .setBinding(1)
1764 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1765 .setDescriptorCount(texture_count)
1766 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1767 .setPImmutableSamplers(nullptr)};
1768
1769 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1770
1771 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1772 VERIFY(result == vk::Result::eSuccess);
1773
1774 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1775
1776 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1777 VERIFY(result == vk::Result::eSuccess);
1778}
1779
1780void Demo::prepare_descriptor_pool() {
1781 vk::DescriptorPoolSize const poolSizes[2] = {
1782 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1783 vk::DescriptorPoolSize()
1784 .setType(vk::DescriptorType::eCombinedImageSampler)
1785 .setDescriptorCount(swapchainImageCount * texture_count)};
1786
1787 auto const descriptor_pool =
1788 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1789
1790 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1791 VERIFY(result == vk::Result::eSuccess);
1792}
1793
1794void Demo::prepare_descriptor_set() {
1795 auto const alloc_info =
1796 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1797
1798 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1799
1800 vk::DescriptorImageInfo tex_descs[texture_count];
1801 for (uint32_t i = 0; i < texture_count; i++) {
1802 tex_descs[i].setSampler(textures[i].sampler);
1803 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001804 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001805 }
1806
1807 vk::WriteDescriptorSet writes[2];
1808
1809 writes[0].setDescriptorCount(1);
1810 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1811 writes[0].setPBufferInfo(&buffer_info);
1812
1813 writes[1].setDstBinding(1);
1814 writes[1].setDescriptorCount(texture_count);
1815 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1816 writes[1].setPImageInfo(tex_descs);
1817
1818 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1819 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001820 VERIFY(result == vk::Result::eSuccess);
1821
Dave Houlton5fa47912018-02-16 11:02:26 -07001822 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1823 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1824 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1825 device.updateDescriptorSets(2, writes, 0, nullptr);
1826 }
1827}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001828
Dave Houlton5fa47912018-02-16 11:02:26 -07001829void Demo::prepare_framebuffers() {
1830 vk::ImageView attachments[2];
1831 attachments[1] = depth.view;
1832
1833 auto const fb_info = vk::FramebufferCreateInfo()
1834 .setRenderPass(render_pass)
1835 .setAttachmentCount(2)
1836 .setPAttachments(attachments)
1837 .setWidth((uint32_t)width)
1838 .setHeight((uint32_t)height)
1839 .setLayers(1);
1840
1841 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1842 attachments[0] = swapchain_image_resources[i].view;
1843 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001844 VERIFY(result == vk::Result::eSuccess);
1845 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001846}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001847
Dave Houlton5fa47912018-02-16 11:02:26 -07001848vk::ShaderModule Demo::prepare_fs() {
1849 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001850#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001851 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001852
Dave Houlton5fa47912018-02-16 11:02:26 -07001853 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001854
Dave Houlton5fa47912018-02-16 11:02:26 -07001855 return frag_shader_module;
1856}
1857
1858void Demo::prepare_pipeline() {
1859 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1860 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1861 VERIFY(result == vk::Result::eSuccess);
1862
1863 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1864 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1865 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1866
1867 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1868
1869 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1870
1871 // TODO: Where are pViewports and pScissors set?
1872 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1873
1874 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1875 .setDepthClampEnable(VK_FALSE)
1876 .setRasterizerDiscardEnable(VK_FALSE)
1877 .setPolygonMode(vk::PolygonMode::eFill)
1878 .setCullMode(vk::CullModeFlagBits::eBack)
1879 .setFrontFace(vk::FrontFace::eCounterClockwise)
1880 .setDepthBiasEnable(VK_FALSE)
1881 .setLineWidth(1.0f);
1882
1883 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1884
1885 auto const stencilOp =
1886 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1887
1888 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1889 .setDepthTestEnable(VK_TRUE)
1890 .setDepthWriteEnable(VK_TRUE)
1891 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1892 .setDepthBoundsTestEnable(VK_FALSE)
1893 .setStencilTestEnable(VK_FALSE)
1894 .setFront(stencilOp)
1895 .setBack(stencilOp);
1896
1897 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1898 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1899 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1900
1901 auto const colorBlendInfo =
1902 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1903
1904 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1905
1906 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1907
1908 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1909 .setStageCount(2)
1910 .setPStages(shaderStageInfo)
1911 .setPVertexInputState(&vertexInputInfo)
1912 .setPInputAssemblyState(&inputAssemblyInfo)
1913 .setPViewportState(&viewportInfo)
1914 .setPRasterizationState(&rasterizationInfo)
1915 .setPMultisampleState(&multisampleInfo)
1916 .setPDepthStencilState(&depthStencilInfo)
1917 .setPColorBlendState(&colorBlendInfo)
1918 .setPDynamicState(&dynamicStateInfo)
1919 .setLayout(pipeline_layout)
1920 .setRenderPass(render_pass);
1921
1922 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1923 VERIFY(result == vk::Result::eSuccess);
1924
1925 device.destroyShaderModule(frag_shader_module, nullptr);
1926 device.destroyShaderModule(vert_shader_module, nullptr);
1927}
1928
1929void Demo::prepare_render_pass() {
1930 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1931 // because at the start of the renderpass, we don't care about their contents.
1932 // At the start of the subpass, the color attachment's layout will be transitioned
1933 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1934 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1935 // the renderpass, the color attachment's layout will be transitioned to
1936 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1937 // the renderpass, no barriers are necessary.
1938 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1939 .setFormat(format)
1940 .setSamples(vk::SampleCountFlagBits::e1)
1941 .setLoadOp(vk::AttachmentLoadOp::eClear)
1942 .setStoreOp(vk::AttachmentStoreOp::eStore)
1943 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1944 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1945 .setInitialLayout(vk::ImageLayout::eUndefined)
1946 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1947 vk::AttachmentDescription()
1948 .setFormat(depth.format)
1949 .setSamples(vk::SampleCountFlagBits::e1)
1950 .setLoadOp(vk::AttachmentLoadOp::eClear)
1951 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1952 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1953 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1954 .setInitialLayout(vk::ImageLayout::eUndefined)
1955 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1956
1957 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1958
1959 auto const depth_reference =
1960 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1961
1962 auto const subpass = vk::SubpassDescription()
1963 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1964 .setInputAttachmentCount(0)
1965 .setPInputAttachments(nullptr)
1966 .setColorAttachmentCount(1)
1967 .setPColorAttachments(&color_reference)
1968 .setPResolveAttachments(nullptr)
1969 .setPDepthStencilAttachment(&depth_reference)
1970 .setPreserveAttachmentCount(0)
1971 .setPPreserveAttachments(nullptr);
1972
1973 auto const rp_info = vk::RenderPassCreateInfo()
1974 .setAttachmentCount(2)
1975 .setPAttachments(attachments)
1976 .setSubpassCount(1)
1977 .setPSubpasses(&subpass)
1978 .setDependencyCount(0)
1979 .setPDependencies(nullptr);
1980
1981 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
1982 VERIFY(result == vk::Result::eSuccess);
1983}
1984
1985vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
1986 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
1987
1988 vk::ShaderModule module;
1989 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
1990 VERIFY(result == vk::Result::eSuccess);
1991
1992 return module;
1993}
1994
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001995void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
1996 int32_t tex_width;
1997 int32_t tex_height;
1998
1999 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2000 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2001 }
2002
2003 tex_obj->tex_width = tex_width;
2004 tex_obj->tex_height = tex_height;
2005
2006 auto const buffer_create_info = vk::BufferCreateInfo()
2007 .setSize(tex_width * tex_height * 4)
2008 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2009 .setSharingMode(vk::SharingMode::eExclusive)
2010 .setQueueFamilyIndexCount(0)
2011 .setPQueueFamilyIndices(nullptr);
2012
2013 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2014 VERIFY(result == vk::Result::eSuccess);
2015
2016 vk::MemoryRequirements mem_reqs;
2017 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2018
2019 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2020 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2021
2022 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2023 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2024 VERIFY(pass == true);
2025
2026 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2027 VERIFY(result == vk::Result::eSuccess);
2028
2029 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2030 VERIFY(result == vk::Result::eSuccess);
2031
2032 vk::SubresourceLayout layout;
2033 memset(&layout, 0, sizeof(layout));
2034 layout.rowPitch = tex_width * 4;
2035 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2036 VERIFY(data.result == vk::Result::eSuccess);
2037
2038 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2039 fprintf(stderr, "Error loading texture: %s\n", filename);
2040 }
2041
2042 device.unmapMemory(tex_obj->mem);
2043}
2044
Dave Houlton5fa47912018-02-16 11:02:26 -07002045void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2046 vk::MemoryPropertyFlags required_props) {
2047 int32_t tex_width;
2048 int32_t tex_height;
2049 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2050 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002051 }
2052
Dave Houlton5fa47912018-02-16 11:02:26 -07002053 tex_obj->tex_width = tex_width;
2054 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002055
Dave Houlton5fa47912018-02-16 11:02:26 -07002056 auto const image_create_info = vk::ImageCreateInfo()
2057 .setImageType(vk::ImageType::e2D)
2058 .setFormat(vk::Format::eR8G8B8A8Unorm)
2059 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2060 .setMipLevels(1)
2061 .setArrayLayers(1)
2062 .setSamples(vk::SampleCountFlagBits::e1)
2063 .setTiling(tiling)
2064 .setUsage(usage)
2065 .setSharingMode(vk::SharingMode::eExclusive)
2066 .setQueueFamilyIndexCount(0)
2067 .setPQueueFamilyIndices(nullptr)
2068 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002069
Dave Houlton5fa47912018-02-16 11:02:26 -07002070 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2071 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002072
Dave Houlton5fa47912018-02-16 11:02:26 -07002073 vk::MemoryRequirements mem_reqs;
2074 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002075
Dave Houlton5fa47912018-02-16 11:02:26 -07002076 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2077 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002078
Dave Houlton5fa47912018-02-16 11:02:26 -07002079 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2080 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002081
Dave Houlton5fa47912018-02-16 11:02:26 -07002082 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2083 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002084
Dave Houlton5fa47912018-02-16 11:02:26 -07002085 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2086 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002087
Dave Houlton5fa47912018-02-16 11:02:26 -07002088 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2089 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2090 vk::SubresourceLayout layout;
2091 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002092
Dave Houlton5fa47912018-02-16 11:02:26 -07002093 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002094 VERIFY(data.result == vk::Result::eSuccess);
2095
Dave Houlton5fa47912018-02-16 11:02:26 -07002096 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2097 fprintf(stderr, "Error loading texture: %s\n", filename);
2098 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002099
Dave Houlton5fa47912018-02-16 11:02:26 -07002100 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002101 }
2102
Dave Houlton5fa47912018-02-16 11:02:26 -07002103 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2104}
2105
2106void Demo::prepare_textures() {
2107 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2108 vk::FormatProperties props;
2109 gpu.getFormatProperties(tex_format, &props);
2110
2111 for (uint32_t i = 0; i < texture_count; i++) {
2112 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2113 /* Device can texture using linear textures */
2114 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2115 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2116 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2117 // shader to run until layout transition completes
2118 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2119 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2120 vk::PipelineStageFlagBits::eFragmentShader);
2121 staging_texture.image = vk::Image();
2122 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2123 /* Must use staging buffer to copy linear texture to optimized */
2124
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002125 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002126
2127 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2128 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2129 vk::MemoryPropertyFlagBits::eDeviceLocal);
2130
Dave Houlton5fa47912018-02-16 11:02:26 -07002131 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2132 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2133 vk::PipelineStageFlagBits::eTransfer);
2134
2135 auto const subresource = vk::ImageSubresourceLayers()
2136 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2137 .setMipLevel(0)
2138 .setBaseArrayLayer(0)
2139 .setLayerCount(1);
2140
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002141 auto const copy_region =
2142 vk::BufferImageCopy()
2143 .setBufferOffset(0)
2144 .setBufferRowLength(staging_texture.tex_width)
2145 .setBufferImageHeight(staging_texture.tex_height)
2146 .setImageSubresource(subresource)
2147 .setImageOffset({0, 0, 0})
2148 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002149
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002150 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002151
2152 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2153 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2154 vk::PipelineStageFlagBits::eFragmentShader);
2155 } else {
2156 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002157 }
2158
Dave Houlton5fa47912018-02-16 11:02:26 -07002159 auto const samplerInfo = vk::SamplerCreateInfo()
2160 .setMagFilter(vk::Filter::eNearest)
2161 .setMinFilter(vk::Filter::eNearest)
2162 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2163 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2164 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2165 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2166 .setMipLodBias(0.0f)
2167 .setAnisotropyEnable(VK_FALSE)
2168 .setMaxAnisotropy(1)
2169 .setCompareEnable(VK_FALSE)
2170 .setCompareOp(vk::CompareOp::eNever)
2171 .setMinLod(0.0f)
2172 .setMaxLod(0.0f)
2173 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2174 .setUnnormalizedCoordinates(VK_FALSE);
2175
2176 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2177 VERIFY(result == vk::Result::eSuccess);
2178
2179 auto const viewInfo = vk::ImageViewCreateInfo()
2180 .setImage(textures[i].image)
2181 .setViewType(vk::ImageViewType::e2D)
2182 .setFormat(tex_format)
2183 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2184
2185 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2186 VERIFY(result == vk::Result::eSuccess);
2187 }
2188}
2189
2190vk::ShaderModule Demo::prepare_vs() {
2191 const uint32_t vertShaderCode[] = {
2192#include "cube.vert.inc"
2193 };
2194
2195 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2196
2197 return vert_shader_module;
2198}
2199
2200void Demo::resize() {
2201 uint32_t i;
2202
2203 // Don't react to resize until after first initialization.
2204 if (!prepared) {
2205 return;
2206 }
2207
2208 // In order to properly resize the window, we must re-create the
2209 // swapchain
2210 // AND redo the command buffers, etc.
2211 //
2212 // First, perform part of the cleanup() function:
2213 prepared = false;
2214 auto result = device.waitIdle();
2215 VERIFY(result == vk::Result::eSuccess);
2216
2217 for (i = 0; i < swapchainImageCount; i++) {
2218 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2219 }
2220
2221 device.destroyDescriptorPool(desc_pool, nullptr);
2222
2223 device.destroyPipeline(pipeline, nullptr);
2224 device.destroyPipelineCache(pipelineCache, nullptr);
2225 device.destroyRenderPass(render_pass, nullptr);
2226 device.destroyPipelineLayout(pipeline_layout, nullptr);
2227 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2228
2229 for (i = 0; i < texture_count; i++) {
2230 device.destroyImageView(textures[i].view, nullptr);
2231 device.destroyImage(textures[i].image, nullptr);
2232 device.freeMemory(textures[i].mem, nullptr);
2233 device.destroySampler(textures[i].sampler, nullptr);
2234 }
2235
2236 device.destroyImageView(depth.view, nullptr);
2237 device.destroyImage(depth.image, nullptr);
2238 device.freeMemory(depth.mem, nullptr);
2239
2240 for (i = 0; i < swapchainImageCount; i++) {
2241 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2242 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2243 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2244 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2245 }
2246
2247 device.destroyCommandPool(cmd_pool, nullptr);
2248 if (separate_present_queue) {
2249 device.destroyCommandPool(present_cmd_pool, nullptr);
2250 }
2251
2252 // Second, re-perform the prepare() function, which will re-create the
2253 // swapchain.
2254 prepare();
2255}
2256
2257void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2258 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2259 assert(cmd);
2260
2261 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2262 vk::AccessFlags flags;
2263
2264 switch (layout) {
2265 case vk::ImageLayout::eTransferDstOptimal:
2266 // Make sure anything that was copying from this image has
2267 // completed
2268 flags = vk::AccessFlagBits::eTransferWrite;
2269 break;
2270 case vk::ImageLayout::eColorAttachmentOptimal:
2271 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2272 break;
2273 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2274 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2275 break;
2276 case vk::ImageLayout::eShaderReadOnlyOptimal:
2277 // Make sure any Copy or CPU writes to image are flushed
2278 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2279 break;
2280 case vk::ImageLayout::eTransferSrcOptimal:
2281 flags = vk::AccessFlagBits::eTransferRead;
2282 break;
2283 case vk::ImageLayout::ePresentSrcKHR:
2284 flags = vk::AccessFlagBits::eMemoryRead;
2285 break;
2286 default:
2287 break;
2288 }
2289
2290 return flags;
2291 };
2292
2293 auto const barrier = vk::ImageMemoryBarrier()
2294 .setSrcAccessMask(srcAccessMask)
2295 .setDstAccessMask(DstAccessMask(newLayout))
2296 .setOldLayout(oldLayout)
2297 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002298 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2299 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002300 .setImage(image)
2301 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2302
2303 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2304}
2305
2306void Demo::update_data_buffer() {
2307 mat4x4 VP;
2308 mat4x4_mul(VP, projection_matrix, view_matrix);
2309
2310 // Rotate around the Y axis
2311 mat4x4 Model;
2312 mat4x4_dup(Model, model_matrix);
2313 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2314
2315 mat4x4 MVP;
2316 mat4x4_mul(MVP, VP, model_matrix);
2317
2318 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2319 VERIFY(data.result == vk::Result::eSuccess);
2320
2321 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2322
2323 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2324}
2325
Karl Schultzb7940402018-05-29 13:09:22 -06002326/* Convert ppm image data from header file into RGBA texture image */
2327#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002328bool 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 -06002329 (void)filename;
2330 char *cPtr;
2331 cPtr = (char *)lunarg_ppm;
2332 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002333 return false;
2334 }
Karl Schultzb7940402018-05-29 13:09:22 -06002335 while (strncmp(cPtr++, "\n", 1))
2336 ;
2337 sscanf(cPtr, "%u %u", width, height);
2338 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002339 return true;
2340 }
Karl Schultzb7940402018-05-29 13:09:22 -06002341 while (strncmp(cPtr++, "\n", 1))
2342 ;
2343 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002344 return false;
2345 }
Karl Schultzb7940402018-05-29 13:09:22 -06002346 while (strncmp(cPtr++, "\n", 1))
2347 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002348 for (int y = 0; y < *height; y++) {
2349 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002350 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002351 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002352 rowPtr[3] = 255; /* Alpha of 1 */
2353 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002354 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002355 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002356 rgba_data += layout->rowPitch;
2357 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002358 return true;
2359}
2360
2361bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2362 // Search memtypes to find first index with those properties
2363 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2364 if ((typeBits & 1) == 1) {
2365 // Type is available, does it match user properties?
2366 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2367 *typeIndex = i;
2368 return true;
2369 }
2370 }
2371 typeBits >>= 1;
2372 }
2373
2374 // No memory types matched, return failure
2375 return false;
2376}
2377
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002378#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002379void Demo::run() {
2380 if (!prepared) {
2381 return;
2382 }
2383
2384 draw();
2385 curFrame++;
2386
Petr Krausd88e4e52019-01-23 18:45:04 +01002387 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002388 PostQuitMessage(validation_error);
2389 }
2390}
2391
2392void Demo::create_window() {
2393 WNDCLASSEX win_class;
2394
2395 // Initialize the window class structure:
2396 win_class.cbSize = sizeof(WNDCLASSEX);
2397 win_class.style = CS_HREDRAW | CS_VREDRAW;
2398 win_class.lpfnWndProc = WndProc;
2399 win_class.cbClsExtra = 0;
2400 win_class.cbWndExtra = 0;
2401 win_class.hInstance = connection; // hInstance
2402 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2403 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2404 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2405 win_class.lpszMenuName = nullptr;
2406 win_class.lpszClassName = name;
2407 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2408
2409 // Register window class:
2410 if (!RegisterClassEx(&win_class)) {
2411 // It didn't work, so try to give a useful error:
2412 printf("Unexpected error trying to start the application!\n");
2413 fflush(stdout);
2414 exit(1);
2415 }
2416
2417 // Create window with the registered class:
2418 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2419 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2420 window = CreateWindowEx(0,
2421 name, // class name
2422 name, // app name
2423 WS_OVERLAPPEDWINDOW | // window style
2424 WS_VISIBLE | WS_SYSMENU,
2425 100, 100, // x/y coords
2426 wr.right - wr.left, // width
2427 wr.bottom - wr.top, // height
2428 nullptr, // handle to parent
2429 nullptr, // handle to menu
2430 connection, // hInstance
2431 nullptr); // no extra parameters
2432
2433 if (!window) {
2434 // It didn't work, so try to give a useful error:
2435 printf("Cannot create a window in which to draw!\n");
2436 fflush(stdout);
2437 exit(1);
2438 }
2439
2440 // Window client area size must be at least 1 pixel high, to prevent
2441 // crash.
2442 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2443 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2444}
2445#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2446
2447void Demo::create_xlib_window() {
2448 const char *display_envar = getenv("DISPLAY");
2449 if (display_envar == nullptr || display_envar[0] == '\0') {
2450 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2451 fflush(stdout);
2452 exit(1);
2453 }
2454
2455 XInitThreads();
2456 display = XOpenDisplay(nullptr);
2457 long visualMask = VisualScreenMask;
2458 int numberOfVisuals;
2459 XVisualInfo vInfoTemplate = {};
2460 vInfoTemplate.screen = DefaultScreen(display);
2461 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2462
2463 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2464
2465 XSetWindowAttributes windowAttributes = {};
2466 windowAttributes.colormap = colormap;
2467 windowAttributes.background_pixel = 0xFFFFFFFF;
2468 windowAttributes.border_pixel = 0;
2469 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2470
2471 xlib_window =
2472 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2473 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2474
2475 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2476 XMapWindow(display, xlib_window);
2477 XFlush(display);
2478 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2479}
2480
2481void Demo::handle_xlib_event(const XEvent *event) {
2482 switch (event->type) {
2483 case ClientMessage:
2484 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2485 quit = true;
2486 }
2487 break;
2488 case KeyPress:
2489 switch (event->xkey.keycode) {
2490 case 0x9: // Escape
2491 quit = true;
2492 break;
2493 case 0x71: // left arrow key
2494 spin_angle -= spin_increment;
2495 break;
2496 case 0x72: // right arrow key
2497 spin_angle += spin_increment;
2498 break;
2499 case 0x41: // space bar
2500 pause = !pause;
2501 break;
2502 }
2503 break;
2504 case ConfigureNotify:
2505 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2506 width = event->xconfigure.width;
2507 height = event->xconfigure.height;
2508 resize();
2509 }
2510 break;
2511 default:
2512 break;
2513 }
2514}
2515
2516void Demo::run_xlib() {
2517 while (!quit) {
2518 XEvent event;
2519
2520 if (pause) {
2521 XNextEvent(display, &event);
2522 handle_xlib_event(&event);
2523 }
2524 while (XPending(display) > 0) {
2525 XNextEvent(display, &event);
2526 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002527 }
2528
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002529 draw();
2530 curFrame++;
2531
Dave Houlton5fa47912018-02-16 11:02:26 -07002532 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2533 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002534 }
2535 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002536}
Tony Barbour153cb062016-12-07 13:43:36 -07002537#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002538
Dave Houlton5fa47912018-02-16 11:02:26 -07002539void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2540 uint8_t event_code = event->response_type & 0x7f;
2541 switch (event_code) {
2542 case XCB_EXPOSE:
2543 // TODO: Resize window
2544 break;
2545 case XCB_CLIENT_MESSAGE:
2546 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2547 quit = true;
2548 }
2549 break;
2550 case XCB_KEY_RELEASE: {
2551 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002552
Dave Houlton5fa47912018-02-16 11:02:26 -07002553 switch (key->detail) {
2554 case 0x9: // Escape
2555 quit = true;
2556 break;
2557 case 0x71: // left arrow key
2558 spin_angle -= spin_increment;
2559 break;
2560 case 0x72: // right arrow key
2561 spin_angle += spin_increment;
2562 break;
2563 case 0x41: // space bar
2564 pause = !pause;
2565 break;
2566 }
2567 } break;
2568 case XCB_CONFIGURE_NOTIFY: {
2569 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2570 if ((width != cfg->width) || (height != cfg->height)) {
2571 width = cfg->width;
2572 height = cfg->height;
2573 resize();
2574 }
2575 } break;
2576 default:
2577 break;
2578 }
2579}
2580
2581void Demo::run_xcb() {
2582 xcb_flush(connection);
2583
2584 while (!quit) {
2585 xcb_generic_event_t *event;
2586
2587 if (pause) {
2588 event = xcb_wait_for_event(connection);
2589 } else {
2590 event = xcb_poll_for_event(connection);
2591 }
2592 while (event) {
2593 handle_xcb_event(event);
2594 free(event);
2595 event = xcb_poll_for_event(connection);
2596 }
2597
2598 draw();
2599 curFrame++;
2600 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2601 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002602 }
2603 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002604}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002605
Dave Houlton5fa47912018-02-16 11:02:26 -07002606void Demo::create_xcb_window() {
2607 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002608
Dave Houlton5fa47912018-02-16 11:02:26 -07002609 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002610
Dave Houlton5fa47912018-02-16 11:02:26 -07002611 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2612 value_list[0] = screen->black_pixel;
2613 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002614
Dave Houlton5fa47912018-02-16 11:02:26 -07002615 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2616 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2617
2618 /* Magic code that will send notification when window is destroyed */
2619 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2620 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2621
2622 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2623 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2624
2625 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2626
2627 free(reply);
2628
2629 xcb_map_window(connection, xcb_window);
2630
2631 // Force the x/y coordinates to 100,100 results are identical in
2632 // consecutive
2633 // runs
2634 const uint32_t coords[] = {100, 100};
2635 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2636}
2637#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2638
2639void Demo::run() {
2640 while (!quit) {
2641 if (pause) {
2642 wl_display_dispatch(display);
2643 } else {
2644 wl_display_dispatch_pending(display);
2645 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002646 draw();
2647 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002648 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002649 quit = true;
2650 }
2651 }
2652 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002653}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002654
Dave Houlton5fa47912018-02-16 11:02:26 -07002655void Demo::create_window() {
2656 window = wl_compositor_create_surface(compositor);
2657 if (!window) {
2658 printf("Can not create wayland_surface from compositor!\n");
2659 fflush(stdout);
2660 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002661 }
2662
Dave Houlton5fa47912018-02-16 11:02:26 -07002663 shell_surface = wl_shell_get_shell_surface(shell, window);
2664 if (!shell_surface) {
2665 printf("Can not get shell_surface from wayland_surface!\n");
2666 fflush(stdout);
2667 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002668 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002669
2670 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2671 wl_shell_surface_set_toplevel(shell_surface);
2672 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2673}
Karl Schultz206b1c52018-04-13 18:02:07 -06002674#elif defined(VK_USE_PLATFORM_MACOS_MVK)
2675void Demo::run() {
2676 draw();
2677 curFrame++;
2678 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2679 quit = true;
2680 }
2681}
Damien Leone600c3052017-01-31 10:26:07 -07002682#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2683
Dave Houlton5fa47912018-02-16 11:02:26 -07002684vk::Result Demo::create_display_surface() {
2685 vk::Result result;
2686 uint32_t display_count;
2687 uint32_t mode_count;
2688 uint32_t plane_count;
2689 vk::DisplayPropertiesKHR display_props;
2690 vk::DisplayKHR display;
2691 vk::DisplayModePropertiesKHR mode_props;
2692 vk::DisplayPlanePropertiesKHR *plane_props;
2693 vk::Bool32 found_plane = VK_FALSE;
2694 uint32_t plane_index;
2695 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002696
Dave Houlton5fa47912018-02-16 11:02:26 -07002697 // Get the first display
2698 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2699 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002700
Dave Houlton5fa47912018-02-16 11:02:26 -07002701 if (display_count == 0) {
2702 printf("Cannot find any display!\n");
2703 fflush(stdout);
2704 exit(1);
2705 }
2706
2707 display_count = 1;
2708 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2709 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2710
2711 display = display_props.display;
2712
2713 // Get the first mode of the display
2714 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2715 VERIFY(result == vk::Result::eSuccess);
2716
2717 if (mode_count == 0) {
2718 printf("Cannot find any mode for the display!\n");
2719 fflush(stdout);
2720 exit(1);
2721 }
2722
2723 mode_count = 1;
2724 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2725 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2726
2727 // Get the list of planes
2728 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2729 VERIFY(result == vk::Result::eSuccess);
2730
2731 if (plane_count == 0) {
2732 printf("Cannot find any plane!\n");
2733 fflush(stdout);
2734 exit(1);
2735 }
2736
2737 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2738 VERIFY(plane_props != nullptr);
2739
2740 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2741 VERIFY(result == vk::Result::eSuccess);
2742
2743 // Find a plane compatible with the display
2744 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2745 uint32_t supported_count;
2746 vk::DisplayKHR *supported_displays;
2747
2748 // Disqualify planes that are bound to a different display
2749 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2750 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002751 }
2752
Dave Houlton5fa47912018-02-16 11:02:26 -07002753 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002754 VERIFY(result == vk::Result::eSuccess);
2755
Dave Houlton5fa47912018-02-16 11:02:26 -07002756 if (supported_count == 0) {
2757 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002758 }
2759
Dave Houlton5fa47912018-02-16 11:02:26 -07002760 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2761 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002762
Dave Houlton5fa47912018-02-16 11:02:26 -07002763 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002764 VERIFY(result == vk::Result::eSuccess);
2765
Dave Houlton5fa47912018-02-16 11:02:26 -07002766 for (uint32_t i = 0; i < supported_count; i++) {
2767 if (supported_displays[i] == display) {
2768 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002769 break;
2770 }
2771 }
2772
Dave Houlton5fa47912018-02-16 11:02:26 -07002773 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002774
Dave Houlton5fa47912018-02-16 11:02:26 -07002775 if (found_plane) {
2776 break;
Damien Leone600c3052017-01-31 10:26:07 -07002777 }
2778 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002779
2780 if (!found_plane) {
2781 printf("Cannot find a plane compatible with the display!\n");
2782 fflush(stdout);
2783 exit(1);
2784 }
2785
2786 free(plane_props);
2787
2788 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2789 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2790 // Find a supported alpha mode
2791 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2792 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2793 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2794 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2795 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2796 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2797 };
2798 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2799 if (planeCaps.supportedAlpha & alphaModes[i]) {
2800 alphaMode = alphaModes[i];
2801 break;
2802 }
2803 }
2804
2805 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2806 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2807
2808 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2809 .setDisplayMode(mode_props.displayMode)
2810 .setPlaneIndex(plane_index)
2811 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2812 .setGlobalAlpha(1.0f)
2813 .setAlphaMode(alphaMode)
2814 .setImageExtent(image_extent);
2815
2816 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2817}
2818
2819void Demo::run_display() {
2820 while (!quit) {
2821 draw();
2822 curFrame++;
2823
Petr Krausd88e4e52019-01-23 18:45:04 +01002824 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002825 quit = true;
2826 }
2827 }
2828}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002829#endif
2830
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002831#if _WIN32
2832// Include header required for parsing the command line options.
2833#include <shellapi.h>
2834
2835Demo demo;
2836
2837// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002838LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2839 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002840 case WM_CLOSE:
2841 PostQuitMessage(validation_error);
2842 break;
2843 case WM_PAINT:
2844 demo.run();
2845 break;
2846 case WM_GETMINMAXINFO: // set window's minimum size
2847 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2848 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002849 case WM_ERASEBKGND:
2850 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002851 case WM_SIZE:
2852 // Resize the application to the new window size, except when
2853 // it was minimized. Vulkan doesn't support images or swapchains
2854 // with width=0 and height=0.
2855 if (wParam != SIZE_MINIMIZED) {
2856 demo.width = lParam & 0xffff;
2857 demo.height = (lParam & 0xffff0000) >> 16;
2858 demo.resize();
2859 }
2860 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002861 case WM_KEYDOWN:
2862 switch (wParam) {
2863 case VK_ESCAPE:
2864 PostQuitMessage(validation_error);
2865 break;
2866 case VK_LEFT:
2867 demo.spin_angle -= demo.spin_increment;
2868 break;
2869 case VK_RIGHT:
2870 demo.spin_angle += demo.spin_increment;
2871 break;
2872 case VK_SPACE:
2873 demo.pause = !demo.pause;
2874 break;
2875 }
2876 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002877 default:
2878 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002879 }
2880
2881 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2882}
2883
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002884int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002885 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002886 MSG msg; // message
2887 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002888 int argc;
2889 char **argv;
2890
Jamie Madillb2ff6502017-03-15 16:17:46 -04002891 // Ensure wParam is initialized.
2892 msg.wParam = 0;
2893
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002894 // Use the CommandLine functions to get the command line arguments.
2895 // Unfortunately, Microsoft outputs
2896 // this information as wide characters for Unicode, and we simply want the
2897 // Ascii version to be compatible
2898 // with the non-Windows side. So, we have to convert the information to
2899 // Ascii character strings.
2900 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002901 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002902 argc = 0;
2903 }
2904
Jeremy Hayes9d304782016-10-09 11:48:12 -06002905 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002906 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002907 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002908 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002909 } else {
2910 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002911 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2912 size_t numConverted = 0;
2913
2914 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002915 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002916 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002917 }
2918 }
2919 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002920 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002921 argv = nullptr;
2922 }
2923
2924 demo.init(argc, argv);
2925
2926 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002927 if (argc > 0 && argv != nullptr) {
2928 for (int iii = 0; iii < argc; iii++) {
2929 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002930 free(argv[iii]);
2931 }
2932 }
2933 free(argv);
2934 }
2935
2936 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07002937 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002938 demo.create_window();
2939 demo.init_vk_swapchain();
2940
2941 demo.prepare();
2942
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002943 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002944
2945 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002946 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01002947 if (demo.pause) {
2948 const BOOL succ = WaitMessage();
2949
2950 if (!succ) {
2951 const auto &suppress_popups = demo.suppress_popups;
2952 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2953 }
2954 }
2955
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002956 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002957 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002958 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002959 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002960 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002961 /* Translate and dispatch to event queue*/
2962 TranslateMessage(&msg);
2963 DispatchMessage(&msg);
2964 }
2965 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2966 }
2967
2968 demo.cleanup();
2969
2970 return (int)msg.wParam;
2971}
2972
2973#elif __linux__
2974
Jeremy Hayes9d304782016-10-09 11:48:12 -06002975int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002976 Demo demo;
2977
2978 demo.init(argc, argv);
2979
Tony Barbour153cb062016-12-07 13:43:36 -07002980#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06002981 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002982#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07002983 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002984 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002985#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06002986 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002987#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002988
2989 demo.init_vk_swapchain();
2990
2991 demo.prepare();
2992
Tony Barbour153cb062016-12-07 13:43:36 -07002993#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002994 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002995#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002996 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002997#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002998 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07002999#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3000 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003001#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003002
3003 demo.cleanup();
3004
3005 return validation_error;
3006}
3007
Karl Schultz9ceac062017-12-12 10:33:01 -05003008#elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3009
3010// Global function invoked from NS or UI views and controllers to create demo
Karl Schultz206b1c52018-04-13 18:02:07 -06003011static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003012
3013 demo.init(argc, (char **)argv);
3014 demo.window = view;
3015 demo.init_vk_swapchain();
3016 demo.prepare();
3017 demo.spin_angle = 0.4f;
3018}
3019
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003020#else
3021#error "Platform not supported"
3022#endif