blob: 87b24f9fb3852793b2ccb1cc02bde1b8945b33cd [file] [log] [blame]
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001/*
Tony-LunarG495604b2019-06-13 15:32:05 -06002 * Copyright (c) 2015-2019 The Khronos Group Inc.
3 * Copyright (c) 2015-2019 Valve Corporation
4 * Copyright (c) 2015-2019 LunarG, Inc.
Dave Houlton5fa47912018-02-16 11:02:26 -07005 *
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>
Tony-LunarGd74734f2019-06-04 14:11:43 -060033#include <iostream>
34#include <sstream>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060035#include <memory>
36
Mark Lobodzinskidefadcf2017-10-23 09:23:06 -060037#define VULKAN_HPP_NO_SMART_HANDLE
Jeremy Hayesf56427a2016-09-07 15:55:11 -060038#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060039#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060040#include <vulkan/vulkan.hpp>
41#include <vulkan/vk_sdk_platform.h>
42
43#include "linmath.h"
44
45#ifndef NDEBUG
46#define VERIFY(x) assert(x)
47#else
48#define VERIFY(x) ((void)(x))
49#endif
50
Lenny Komowffe446c2018-11-19 17:08:04 -070051#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060052#ifdef _WIN32
53#define APP_NAME_STR_LEN 80
54#endif
55
56// Allow a maximum of two outstanding presentation operations.
57#define FRAME_LAG 2
58
59#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
60
61#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070062#define ERR_EXIT(err_msg, err_class) \
63 do { \
64 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
65 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060066 } while (0)
67#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070068#define ERR_EXIT(err_msg, err_class) \
69 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080070 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070071 fflush(stdout); \
72 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060073 } while (0)
74#endif
75
Jeremy Hayes9d304782016-10-09 11:48:12 -060076struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060077 vk::Sampler sampler;
78
79 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060080 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070081 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060082
83 vk::MemoryAllocateInfo mem_alloc;
84 vk::DeviceMemory mem;
85 vk::ImageView view;
86
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070087 int32_t tex_width{0};
88 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060089};
90
Jeremy Hayes9d304782016-10-09 11:48:12 -060091static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060092
93static int validation_error = 0;
94
95struct vkcube_vs_uniform {
96 // Must start with MVP
97 float mvp[4][4];
98 float position[12 * 3][4];
99 float color[12 * 3][4];
100};
101
102struct vktexcube_vs_uniform {
103 // Must start with MVP
104 float mvp[4][4];
105 float position[12 * 3][4];
106 float attr[12 * 3][4];
107};
108
109//--------------------------------------------------------------------------------------
110// Mesh and VertexFormat Data
111//--------------------------------------------------------------------------------------
112// clang-format off
113static const float g_vertex_buffer_data[] = {
114 -1.0f,-1.0f,-1.0f, // -X side
115 -1.0f,-1.0f, 1.0f,
116 -1.0f, 1.0f, 1.0f,
117 -1.0f, 1.0f, 1.0f,
118 -1.0f, 1.0f,-1.0f,
119 -1.0f,-1.0f,-1.0f,
120
121 -1.0f,-1.0f,-1.0f, // -Z side
122 1.0f, 1.0f,-1.0f,
123 1.0f,-1.0f,-1.0f,
124 -1.0f,-1.0f,-1.0f,
125 -1.0f, 1.0f,-1.0f,
126 1.0f, 1.0f,-1.0f,
127
128 -1.0f,-1.0f,-1.0f, // -Y side
129 1.0f,-1.0f,-1.0f,
130 1.0f,-1.0f, 1.0f,
131 -1.0f,-1.0f,-1.0f,
132 1.0f,-1.0f, 1.0f,
133 -1.0f,-1.0f, 1.0f,
134
135 -1.0f, 1.0f,-1.0f, // +Y side
136 -1.0f, 1.0f, 1.0f,
137 1.0f, 1.0f, 1.0f,
138 -1.0f, 1.0f,-1.0f,
139 1.0f, 1.0f, 1.0f,
140 1.0f, 1.0f,-1.0f,
141
142 1.0f, 1.0f,-1.0f, // +X side
143 1.0f, 1.0f, 1.0f,
144 1.0f,-1.0f, 1.0f,
145 1.0f,-1.0f, 1.0f,
146 1.0f,-1.0f,-1.0f,
147 1.0f, 1.0f,-1.0f,
148
149 -1.0f, 1.0f, 1.0f, // +Z side
150 -1.0f,-1.0f, 1.0f,
151 1.0f, 1.0f, 1.0f,
152 -1.0f,-1.0f, 1.0f,
153 1.0f,-1.0f, 1.0f,
154 1.0f, 1.0f, 1.0f,
155};
156
157static const float g_uv_buffer_data[] = {
158 0.0f, 1.0f, // -X side
159 1.0f, 1.0f,
160 1.0f, 0.0f,
161 1.0f, 0.0f,
162 0.0f, 0.0f,
163 0.0f, 1.0f,
164
165 1.0f, 1.0f, // -Z side
166 0.0f, 0.0f,
167 0.0f, 1.0f,
168 1.0f, 1.0f,
169 1.0f, 0.0f,
170 0.0f, 0.0f,
171
172 1.0f, 0.0f, // -Y side
173 1.0f, 1.0f,
174 0.0f, 1.0f,
175 1.0f, 0.0f,
176 0.0f, 1.0f,
177 0.0f, 0.0f,
178
179 1.0f, 0.0f, // +Y side
180 0.0f, 0.0f,
181 0.0f, 1.0f,
182 1.0f, 0.0f,
183 0.0f, 1.0f,
184 1.0f, 1.0f,
185
186 1.0f, 0.0f, // +X side
187 0.0f, 0.0f,
188 0.0f, 1.0f,
189 0.0f, 1.0f,
190 1.0f, 1.0f,
191 1.0f, 0.0f,
192
193 0.0f, 0.0f, // +Z side
194 0.0f, 1.0f,
195 1.0f, 0.0f,
196 0.0f, 1.0f,
197 1.0f, 1.0f,
198 1.0f, 0.0f,
199};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600200// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600201
Jeremy Hayes9d304782016-10-09 11:48:12 -0600202typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600203 vk::Image image;
204 vk::CommandBuffer cmd;
205 vk::CommandBuffer graphics_to_present_cmd;
206 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600207 vk::Buffer uniform_buffer;
208 vk::DeviceMemory uniform_memory;
209 vk::Framebuffer framebuffer;
210 vk::DescriptorSet descriptor_set;
211} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600212
Joey Bzdekbaf66472017-06-07 09:37:37 -0600213struct Demo {
214 Demo();
215 void build_image_ownership_cmd(uint32_t const &);
216 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
217 void cleanup();
218 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600219 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600220 void draw();
221 void draw_build_cmd(vk::CommandBuffer);
222 void flush_init_cmd();
223 void init(int, char **);
224 void init_connection();
225 void init_vk();
226 void init_vk_swapchain();
227 void prepare();
228 void prepare_buffers();
229 void prepare_cube_data_buffers();
230 void prepare_depth();
231 void prepare_descriptor_layout();
232 void prepare_descriptor_pool();
233 void prepare_descriptor_set();
234 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100235 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
236 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600237 vk::ShaderModule prepare_fs();
238 void prepare_pipeline();
239 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600240 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600241 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600242 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100243
Joey Bzdekbaf66472017-06-07 09:37:37 -0600244 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600245 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600246 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
247 vk::PipelineStageFlags, vk::PipelineStageFlags);
248 void update_data_buffer();
249 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
250 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
251
252#if defined(VK_USE_PLATFORM_WIN32_KHR)
253 void run();
254 void create_window();
255#elif defined(VK_USE_PLATFORM_XLIB_KHR)
256 void create_xlib_window();
257 void handle_xlib_event(const XEvent *);
258 void run_xlib();
259#elif defined(VK_USE_PLATFORM_XCB_KHR)
260 void handle_xcb_event(const xcb_generic_event_t *);
261 void run_xcb();
262 void create_xcb_window();
263#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
264 void run();
265 void create_window();
Karl Schultz206b1c52018-04-13 18:02:07 -0600266#elif defined(VK_USE_PLATFORM_MACOS_MVK)
267 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600268#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
269 vk::Result create_display_surface();
270 void run_display();
271#endif
272
273#if defined(VK_USE_PLATFORM_WIN32_KHR)
274 HINSTANCE connection; // hInstance - Windows Instance
275 HWND window; // hWnd - window handle
276 POINT minsize; // minimum window size
277 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
278#elif defined(VK_USE_PLATFORM_XLIB_KHR)
279 Window xlib_window;
280 Atom xlib_wm_delete_window;
281 Display *display;
282#elif defined(VK_USE_PLATFORM_XCB_KHR)
283 xcb_window_t xcb_window;
284 xcb_screen_t *screen;
285 xcb_connection_t *connection;
286 xcb_intern_atom_reply_t *atom_wm_delete_window;
287#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
288 wl_display *display;
289 wl_registry *registry;
290 wl_compositor *compositor;
291 wl_surface *window;
292 wl_shell *shell;
293 wl_shell_surface *shell_surface;
294 wl_seat *seat;
295 wl_pointer *pointer;
296 wl_keyboard *keyboard;
Karl Schultz9ceac062017-12-12 10:33:01 -0500297#elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
298 void *window;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600299#endif
300
301 vk::SurfaceKHR surface;
302 bool prepared;
303 bool use_staging_buffer;
304 bool use_xlib;
305 bool separate_present_queue;
306
307 vk::Instance inst;
308 vk::PhysicalDevice gpu;
309 vk::Device device;
310 vk::Queue graphics_queue;
311 vk::Queue present_queue;
312 uint32_t graphics_queue_family_index;
313 uint32_t present_queue_family_index;
314 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
315 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
316 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
317 vk::PhysicalDeviceProperties gpu_props;
318 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
319 vk::PhysicalDeviceMemoryProperties memory_properties;
320
321 uint32_t enabled_extension_count;
322 uint32_t enabled_layer_count;
323 char const *extension_names[64];
324 char const *enabled_layers[64];
325
326 uint32_t width;
327 uint32_t height;
328 vk::Format format;
329 vk::ColorSpaceKHR color_space;
330
331 uint32_t swapchainImageCount;
332 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600333 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600334 vk::PresentModeKHR presentMode;
335 vk::Fence fences[FRAME_LAG];
336 uint32_t frame_index;
337
338 vk::CommandPool cmd_pool;
339 vk::CommandPool present_cmd_pool;
340
341 struct {
342 vk::Format format;
343 vk::Image image;
344 vk::MemoryAllocateInfo mem_alloc;
345 vk::DeviceMemory mem;
346 vk::ImageView view;
347 } depth;
348
349 static int32_t const texture_count = 1;
350 texture_object textures[texture_count];
351 texture_object staging_texture;
352
353 struct {
354 vk::Buffer buf;
355 vk::MemoryAllocateInfo mem_alloc;
356 vk::DeviceMemory mem;
357 vk::DescriptorBufferInfo buffer_info;
358 } uniform_data;
359
360 vk::CommandBuffer cmd; // Buffer for initialization commands
361 vk::PipelineLayout pipeline_layout;
362 vk::DescriptorSetLayout desc_layout;
363 vk::PipelineCache pipelineCache;
364 vk::RenderPass render_pass;
365 vk::Pipeline pipeline;
366
367 mat4x4 projection_matrix;
368 mat4x4 view_matrix;
369 mat4x4 model_matrix;
370
371 float spin_angle;
372 float spin_increment;
373 bool pause;
374
375 vk::ShaderModule vert_shader_module;
376 vk::ShaderModule frag_shader_module;
377
378 vk::DescriptorPool desc_pool;
379 vk::DescriptorSet desc_set;
380
381 std::unique_ptr<vk::Framebuffer[]> framebuffers;
382
383 bool quit;
384 uint32_t curFrame;
385 uint32_t frameCount;
386 bool validate;
387 bool use_break;
388 bool suppress_popups;
389
390 uint32_t current_buffer;
391 uint32_t queue_family_count;
392};
393
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600394#ifdef _WIN32
395// MS-Windows event handling function:
396LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
397#endif
398
Karl Schultz23cc2182016-11-23 17:15:17 -0700399#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700400static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700401 wl_shell_surface_pong(shell_surface, serial);
402}
403
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700404static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700405
406static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
407
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700408static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700409
Joey Bzdek15eb0702017-06-07 09:40:36 -0600410static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
411 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700412
Joey Bzdek15eb0702017-06-07 09:40:36 -0600413static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700414
Joey Bzdek15eb0702017-06-07 09:40:36 -0600415static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
416
417static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
418 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600419 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600420 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
421 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
422 }
423}
424
425static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
426
427static const struct wl_pointer_listener pointer_listener = {
428 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
429};
430
431static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
432
433static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
434 struct wl_array *keys) {}
435
436static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
437
438static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
439 uint32_t state) {
440 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
441 Demo *demo = (Demo *)data;
442 switch (key) {
443 case KEY_ESC: // Escape
444 demo->quit = true;
445 break;
446 case KEY_LEFT: // left arrow key
447 demo->spin_angle -= demo->spin_increment;
448 break;
449 case KEY_RIGHT: // right arrow key
450 demo->spin_angle += demo->spin_increment;
451 break;
452 case KEY_SPACE: // space bar
453 demo->pause = !demo->pause;
454 break;
455 }
456}
457
458static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
459 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
460
461static const struct wl_keyboard_listener keyboard_listener = {
462 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
463};
464
465static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
466 // Subscribe to pointer events
467 Demo *demo = (Demo *)data;
468 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
469 demo->pointer = wl_seat_get_pointer(seat);
470 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
471 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
472 wl_pointer_destroy(demo->pointer);
473 demo->pointer = NULL;
474 }
475 // Subscribe to keyboard events
476 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
477 demo->keyboard = wl_seat_get_keyboard(seat);
478 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
479 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
480 wl_keyboard_destroy(demo->keyboard);
481 demo->keyboard = NULL;
482 }
483}
484
485static const wl_seat_listener seat_listener = {
486 seat_handle_capabilities,
487};
488
489static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
490 Demo *demo = (Demo *)data;
491 // pickup wayland objects when they appear
492 if (strcmp(interface, "wl_compositor") == 0) {
493 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
494 } else if (strcmp(interface, "wl_shell") == 0) {
495 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
496 } else if (strcmp(interface, "wl_seat") == 0) {
497 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
498 wl_seat_add_listener(demo->seat, &seat_listener, demo);
499 }
500}
501
502static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
503
504static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700505#endif
506
Joey Bzdekbaf66472017-06-07 09:37:37 -0600507Demo::Demo()
508 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600509#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600510 connection{nullptr},
511 window{nullptr},
512 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600513#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700514
Tony Barbour78d6b572016-11-14 14:46:33 -0700515#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600516 xlib_window{0},
517 xlib_wm_delete_window{0},
518 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700519#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600520 xcb_window{0},
521 screen{nullptr},
522 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700523#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600524 display{nullptr},
525 registry{nullptr},
526 compositor{nullptr},
527 window{nullptr},
528 shell{nullptr},
529 shell_surface{nullptr},
530 seat{nullptr},
531 pointer{nullptr},
532 keyboard{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700533#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600534 prepared{false},
535 use_staging_buffer{false},
536 use_xlib{false},
537 graphics_queue_family_index{0},
538 present_queue_family_index{0},
539 enabled_extension_count{0},
540 enabled_layer_count{0},
541 width{0},
542 height{0},
543 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000544 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600545 frame_index{0},
546 spin_angle{0.0f},
547 spin_increment{0.0f},
548 pause{false},
549 quit{false},
550 curFrame{0},
551 frameCount{0},
552 validate{false},
553 use_break{false},
554 suppress_popups{false},
555 current_buffer{0},
556 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600557#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700558 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600559#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700560 memset(projection_matrix, 0, sizeof(projection_matrix));
561 memset(view_matrix, 0, sizeof(view_matrix));
562 memset(model_matrix, 0, sizeof(model_matrix));
563}
564
565void Demo::build_image_ownership_cmd(uint32_t const &i) {
566 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
567 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
568 VERIFY(result == vk::Result::eSuccess);
569
570 auto const image_ownership_barrier =
571 vk::ImageMemoryBarrier()
572 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600573 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700574 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
575 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setSrcQueueFamilyIndex(graphics_queue_family_index)
577 .setDstQueueFamilyIndex(present_queue_family_index)
578 .setImage(swapchain_image_resources[i].image)
579 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
580
581 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600582 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
583 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700584
585 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
586 VERIFY(result == vk::Result::eSuccess);
587}
588
589vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
590 vk::LayerProperties *layers) {
591 for (uint32_t i = 0; i < check_count; i++) {
592 vk::Bool32 found = VK_FALSE;
593 for (uint32_t j = 0; j < layer_count; j++) {
594 if (!strcmp(check_names[i], layers[j].layerName)) {
595 found = VK_TRUE;
596 break;
597 }
598 }
599 if (!found) {
600 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
601 return 0;
602 }
603 }
604 return VK_TRUE;
605}
606
607void Demo::cleanup() {
608 prepared = false;
609 device.waitIdle();
610
611 // Wait for fences from present operations
612 for (uint32_t i = 0; i < FRAME_LAG; i++) {
613 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
614 device.destroyFence(fences[i], nullptr);
615 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
616 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
617 if (separate_present_queue) {
618 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
619 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600620 }
621
Dave Houlton5fa47912018-02-16 11:02:26 -0700622 for (uint32_t i = 0; i < swapchainImageCount; i++) {
623 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
624 }
625 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600626
Dave Houlton5fa47912018-02-16 11:02:26 -0700627 device.destroyPipeline(pipeline, nullptr);
628 device.destroyPipelineCache(pipelineCache, nullptr);
629 device.destroyRenderPass(render_pass, nullptr);
630 device.destroyPipelineLayout(pipeline_layout, nullptr);
631 device.destroyDescriptorSetLayout(desc_layout, nullptr);
632
633 for (uint32_t i = 0; i < texture_count; i++) {
634 device.destroyImageView(textures[i].view, nullptr);
635 device.destroyImage(textures[i].image, nullptr);
636 device.freeMemory(textures[i].mem, nullptr);
637 device.destroySampler(textures[i].sampler, nullptr);
638 }
639 device.destroySwapchainKHR(swapchain, nullptr);
640
641 device.destroyImageView(depth.view, nullptr);
642 device.destroyImage(depth.image, nullptr);
643 device.freeMemory(depth.mem, nullptr);
644
645 for (uint32_t i = 0; i < swapchainImageCount; i++) {
646 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
647 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
648 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
649 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
650 }
651
652 device.destroyCommandPool(cmd_pool, nullptr);
653
654 if (separate_present_queue) {
655 device.destroyCommandPool(present_cmd_pool, nullptr);
656 }
657 device.waitIdle();
658 device.destroy(nullptr);
659 inst.destroySurfaceKHR(surface, nullptr);
660
661#if defined(VK_USE_PLATFORM_XLIB_KHR)
662 XDestroyWindow(display, xlib_window);
663 XCloseDisplay(display);
664#elif defined(VK_USE_PLATFORM_XCB_KHR)
665 xcb_destroy_window(connection, xcb_window);
666 xcb_disconnect(connection);
667 free(atom_wm_delete_window);
668#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
669 wl_keyboard_destroy(keyboard);
670 wl_pointer_destroy(pointer);
671 wl_seat_destroy(seat);
672 wl_shell_surface_destroy(shell_surface);
673 wl_surface_destroy(window);
674 wl_shell_destroy(shell);
675 wl_compositor_destroy(compositor);
676 wl_registry_destroy(registry);
677 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700678#endif
679
680 inst.destroy(nullptr);
681}
682
683void Demo::create_device() {
684 float const priorities[1] = {0.0};
685
686 vk::DeviceQueueCreateInfo queues[2];
687 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
688 queues[0].setQueueCount(1);
689 queues[0].setPQueuePriorities(priorities);
690
691 auto deviceInfo = vk::DeviceCreateInfo()
692 .setQueueCreateInfoCount(1)
693 .setPQueueCreateInfos(queues)
694 .setEnabledLayerCount(0)
695 .setPpEnabledLayerNames(nullptr)
696 .setEnabledExtensionCount(enabled_extension_count)
697 .setPpEnabledExtensionNames((const char *const *)extension_names)
698 .setPEnabledFeatures(nullptr);
699
700 if (separate_present_queue) {
701 queues[1].setQueueFamilyIndex(present_queue_family_index);
702 queues[1].setQueueCount(1);
703 queues[1].setPQueuePriorities(priorities);
704 deviceInfo.setQueueCreateInfoCount(2);
705 }
706
707 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
708 VERIFY(result == vk::Result::eSuccess);
709}
710
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600711void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700712 // clean up staging resources
713 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600714 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
715 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700716}
717
718void Demo::draw() {
719 // Ensure no more than FRAME_LAG renderings are outstanding
720 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
721 device.resetFences(1, &fences[frame_index]);
722
723 vk::Result result;
724 do {
725 result =
726 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
727 if (result == vk::Result::eErrorOutOfDateKHR) {
728 // demo->swapchain is out of date (e.g. the window was resized) and
729 // must be recreated:
730 resize();
731 } else if (result == vk::Result::eSuboptimalKHR) {
732 // swapchain is not as optimal as it could be, but the platform's
733 // presentation engine will still present the image correctly.
734 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600735 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
736 inst.destroySurfaceKHR(surface, nullptr);
737 create_surface();
738 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700739 } else {
740 VERIFY(result == vk::Result::eSuccess);
741 }
742 } while (result != vk::Result::eSuccess);
743
744 update_data_buffer();
745
746 // Wait for the image acquired semaphore to be signaled to ensure
747 // that the image won't be rendered to until the presentation
748 // engine has fully released ownership to the application, and it is
749 // okay to render to the image.
750 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
751 auto const submit_info = vk::SubmitInfo()
752 .setPWaitDstStageMask(&pipe_stage_flags)
753 .setWaitSemaphoreCount(1)
754 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
755 .setCommandBufferCount(1)
756 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
757 .setSignalSemaphoreCount(1)
758 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
759
760 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
761 VERIFY(result == vk::Result::eSuccess);
762
763 if (separate_present_queue) {
764 // If we are using separate queues, change image ownership to the
765 // present queue before presenting, waiting for the draw complete
766 // semaphore and signalling the ownership released semaphore when
767 // finished
768 auto const present_submit_info = vk::SubmitInfo()
769 .setPWaitDstStageMask(&pipe_stage_flags)
770 .setWaitSemaphoreCount(1)
771 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
772 .setCommandBufferCount(1)
773 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
774 .setSignalSemaphoreCount(1)
775 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
776
777 result = present_queue.submit(1, &present_submit_info, vk::Fence());
778 VERIFY(result == vk::Result::eSuccess);
779 }
780
781 // If we are using separate queues we have to wait for image ownership,
782 // otherwise wait for draw complete
783 auto const presentInfo = vk::PresentInfoKHR()
784 .setWaitSemaphoreCount(1)
785 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
786 : &draw_complete_semaphores[frame_index])
787 .setSwapchainCount(1)
788 .setPSwapchains(&swapchain)
789 .setPImageIndices(&current_buffer);
790
791 result = present_queue.presentKHR(&presentInfo);
792 frame_index += 1;
793 frame_index %= FRAME_LAG;
794 if (result == vk::Result::eErrorOutOfDateKHR) {
795 // swapchain is out of date (e.g. the window was resized) and
796 // must be recreated:
797 resize();
798 } else if (result == vk::Result::eSuboptimalKHR) {
799 // swapchain is not as optimal as it could be, but the platform's
800 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600801 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
802 inst.destroySurfaceKHR(surface, nullptr);
803 create_surface();
804 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700805 } else {
806 VERIFY(result == vk::Result::eSuccess);
807 }
808}
809
810void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
811 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
812
813 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
814 vk::ClearDepthStencilValue(1.0f, 0u)};
815
816 auto const passInfo = vk::RenderPassBeginInfo()
817 .setRenderPass(render_pass)
818 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
819 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
820 .setClearValueCount(2)
821 .setPClearValues(clearValues);
822
823 auto result = commandBuffer.begin(&commandInfo);
824 VERIFY(result == vk::Result::eSuccess);
825
826 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
827 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
828 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
829 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
830
831 auto const viewport =
832 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
833 commandBuffer.setViewport(0, 1, &viewport);
834
835 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
836 commandBuffer.setScissor(0, 1, &scissor);
837 commandBuffer.draw(12 * 3, 1, 0, 0);
838 // Note that ending the renderpass changes the image's layout from
839 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
840 commandBuffer.endRenderPass();
841
842 if (separate_present_queue) {
843 // We have to transfer ownership from the graphics queue family to
844 // the
845 // present queue family to be able to present. Note that we don't
846 // have
847 // to transfer from present queue family back to graphics queue
848 // family at
849 // the start of the next frame because we don't care about the
850 // image's
851 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600852 auto const image_ownership_barrier =
853 vk::ImageMemoryBarrier()
854 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600855 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600856 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
857 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
858 .setSrcQueueFamilyIndex(graphics_queue_family_index)
859 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700860 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700861 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600862
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600863 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700864 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600865 }
866
Dave Houlton5fa47912018-02-16 11:02:26 -0700867 result = commandBuffer.end();
868 VERIFY(result == vk::Result::eSuccess);
869}
870
871void Demo::flush_init_cmd() {
872 // TODO: hmm.
873 // This function could get called twice if the texture uses a staging
874 // buffer
875 // In that case the second call should be ignored
876 if (!cmd) {
877 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600878 }
879
Dave Houlton5fa47912018-02-16 11:02:26 -0700880 auto result = cmd.end();
881 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600882
Dave Houlton5fa47912018-02-16 11:02:26 -0700883 auto const fenceInfo = vk::FenceCreateInfo();
884 vk::Fence fence;
885 result = device.createFence(&fenceInfo, nullptr, &fence);
886 VERIFY(result == vk::Result::eSuccess);
887
888 vk::CommandBuffer const commandBuffers[] = {cmd};
889 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
890
891 result = graphics_queue.submit(1, &submitInfo, fence);
892 VERIFY(result == vk::Result::eSuccess);
893
894 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
895 VERIFY(result == vk::Result::eSuccess);
896
897 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
898 device.destroyFence(fence, nullptr);
899
900 cmd = vk::CommandBuffer();
901}
902
903void Demo::init(int argc, char **argv) {
904 vec3 eye = {0.0f, 3.0f, 5.0f};
905 vec3 origin = {0, 0, 0};
906 vec3 up = {0.0f, 1.0f, 0.0};
907
908 presentMode = vk::PresentModeKHR::eFifo;
909 frameCount = UINT32_MAX;
910 use_xlib = false;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600911
Dave Houlton5fa47912018-02-16 11:02:26 -0700912 for (int i = 1; i < argc; i++) {
913 if (strcmp(argv[i], "--use_staging") == 0) {
914 use_staging_buffer = true;
915 continue;
916 }
917 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
918 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
919 i++;
920 continue;
921 }
922 if (strcmp(argv[i], "--break") == 0) {
923 use_break = true;
924 continue;
925 }
926 if (strcmp(argv[i], "--validate") == 0) {
927 validate = true;
928 continue;
929 }
930 if (strcmp(argv[i], "--xlib") == 0) {
931 fprintf(stderr, "--xlib is deprecated and no longer does anything");
932 continue;
933 }
934 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
935 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
936 i++;
937 continue;
938 }
939 if (strcmp(argv[i], "--suppress_popups") == 0) {
940 suppress_popups = true;
941 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600942 }
943
Tony-LunarGd74734f2019-06-04 14:11:43 -0600944 std::stringstream usage;
945 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
946 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
947 << "\t[--present_mode <present mode enum>]\n"
948 << "\t<present_mode_enum>\n"
949 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
950 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
951 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
952 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
953
954#if defined(_WIN32)
955 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
956#else
957 std::cerr << usage.str();
958 std::cerr.flush();
959#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700960 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600961 }
962
Dave Houlton5fa47912018-02-16 11:02:26 -0700963 if (!use_xlib) {
964 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600965 }
966
Dave Houlton5fa47912018-02-16 11:02:26 -0700967 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600968
Dave Houlton5fa47912018-02-16 11:02:26 -0700969 width = 500;
970 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600971
Dave Houlton5fa47912018-02-16 11:02:26 -0700972 spin_angle = 4.0f;
973 spin_increment = 0.2f;
974 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600975
Dave Houlton5fa47912018-02-16 11:02:26 -0700976 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
977 mat4x4_look_at(view_matrix, eye, origin, up);
978 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600979
Dave Houlton5fa47912018-02-16 11:02:26 -0700980 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
981}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600982
Dave Houlton5fa47912018-02-16 11:02:26 -0700983void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600984#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700985 const xcb_setup_t *setup;
986 xcb_screen_iterator_t iter;
987 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600988
Dave Houlton5fa47912018-02-16 11:02:26 -0700989 const char *display_envar = getenv("DISPLAY");
990 if (display_envar == nullptr || display_envar[0] == '\0') {
991 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
992 fflush(stdout);
993 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600994 }
995
Dave Houlton5fa47912018-02-16 11:02:26 -0700996 connection = xcb_connect(nullptr, &scr);
997 if (xcb_connection_has_error(connection) > 0) {
998 printf(
999 "Cannot find a compatible Vulkan installable client driver "
1000 "(ICD).\nExiting ...\n");
1001 fflush(stdout);
1002 exit(1);
1003 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001004
Dave Houlton5fa47912018-02-16 11:02:26 -07001005 setup = xcb_get_setup(connection);
1006 iter = xcb_setup_roots_iterator(setup);
1007 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001008
Dave Houlton5fa47912018-02-16 11:02:26 -07001009 screen = iter.data;
1010#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1011 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001012
Dave Houlton5fa47912018-02-16 11:02:26 -07001013 if (display == nullptr) {
1014 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1015 fflush(stdout);
1016 exit(1);
1017 }
1018
1019 registry = wl_display_get_registry(display);
1020 wl_registry_add_listener(registry, &registry_listener, this);
1021 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001022#endif
1023}
1024
1025void Demo::init_vk() {
1026 uint32_t instance_extension_count = 0;
1027 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001028 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001029 enabled_extension_count = 0;
1030 enabled_layer_count = 0;
1031
Dave Houlton5fa47912018-02-16 11:02:26 -07001032 // Look for validation layers
1033 vk::Bool32 validation_found = VK_FALSE;
1034 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001035 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001036 VERIFY(result == vk::Result::eSuccess);
1037
Dave Houlton5fa47912018-02-16 11:02:26 -07001038 if (instance_layer_count > 0) {
1039 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1040 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001041 VERIFY(result == vk::Result::eSuccess);
1042
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001043 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001044 instance_layer_count, instance_layers.get());
1045 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001046 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1047 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001048 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001049 }
1050
Dave Houlton5fa47912018-02-16 11:02:26 -07001051 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001052 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1054 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001055 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001056 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001057 }
1058
Dave Houlton5fa47912018-02-16 11:02:26 -07001059 /* Look for instance extensions */
1060 vk::Bool32 surfaceExtFound = VK_FALSE;
1061 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1062 memset(extension_names, 0, sizeof(extension_names));
1063
Mike Schuchardt7510c832018-10-29 13:23:08 -07001064 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1065 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001066 VERIFY(result == vk::Result::eSuccess);
1067
1068 if (instance_extension_count > 0) {
1069 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1070 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1071 VERIFY(result == vk::Result::eSuccess);
1072
1073 for (uint32_t i = 0; i < instance_extension_count; i++) {
1074 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1075 surfaceExtFound = 1;
1076 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1077 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001078#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001079 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1080 platformSurfaceExtFound = 1;
1081 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1082 }
1083#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1084 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1085 platformSurfaceExtFound = 1;
1086 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1087 }
1088#elif defined(VK_USE_PLATFORM_XCB_KHR)
1089 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1090 platformSurfaceExtFound = 1;
1091 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1092 }
Tony Barbour153cb062016-12-07 13:43:36 -07001093#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001094 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1095 platformSurfaceExtFound = 1;
1096 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1097 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001098#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1099 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1100 platformSurfaceExtFound = 1;
1101 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1102 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001103#elif defined(VK_USE_PLATFORM_IOS_MVK)
1104 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1105 platformSurfaceExtFound = 1;
1106 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1107 }
1108#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1109 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1110 platformSurfaceExtFound = 1;
1111 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1112 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001113
Dave Houlton5fa47912018-02-16 11:02:26 -07001114#endif
1115 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001116 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001117 }
1118
1119 if (!surfaceExtFound) {
1120 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1121 " extension.\n\n"
1122 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1123 "Please look at the Getting Started guide for additional information.\n",
1124 "vkCreateInstance Failure");
1125 }
1126
1127 if (!platformSurfaceExtFound) {
1128#if defined(VK_USE_PLATFORM_WIN32_KHR)
1129 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1130 " extension.\n\n"
1131 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1132 "Please look at the Getting Started guide for additional information.\n",
1133 "vkCreateInstance Failure");
1134#elif defined(VK_USE_PLATFORM_XCB_KHR)
1135 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1136 " extension.\n\n"
1137 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1138 "Please look at the Getting Started guide for additional information.\n",
1139 "vkCreateInstance Failure");
1140#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1141 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1142 " extension.\n\n"
1143 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1144 "Please look at the Getting Started guide for additional information.\n",
1145 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001146#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001147 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1148 " extension.\n\n"
1149 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1150 "Please look at the Getting Started guide for additional information.\n",
1151 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001152#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001153 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1154 " extension.\n\n"
1155 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1156 "Please look at the Getting Started guide for additional information.\n",
1157 "vkCreateInstance Failure");
Karl Schultz9ceac062017-12-12 10:33:01 -05001158#elif defined(VK_USE_PLATFORM_IOS_MVK)
1159 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1160 " extension.\n\nDo you have a compatible "
1161 "Vulkan installable client driver (ICD) installed?\nPlease "
1162 "look at the Getting Started guide for additional "
1163 "information.\n",
1164 "vkCreateInstance Failure");
1165#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1166 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1167 " extension.\n\nDo you have a compatible "
1168 "Vulkan installable client driver (ICD) installed?\nPlease "
1169 "look at the Getting Started guide for additional "
1170 "information.\n",
1171 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001172#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001173 }
1174 auto const app = vk::ApplicationInfo()
1175 .setPApplicationName(APP_SHORT_NAME)
1176 .setApplicationVersion(0)
1177 .setPEngineName(APP_SHORT_NAME)
1178 .setEngineVersion(0)
1179 .setApiVersion(VK_API_VERSION_1_0);
1180 auto const inst_info = vk::InstanceCreateInfo()
1181 .setPApplicationInfo(&app)
1182 .setEnabledLayerCount(enabled_layer_count)
1183 .setPpEnabledLayerNames(instance_validation_layers)
1184 .setEnabledExtensionCount(enabled_extension_count)
1185 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001186
Dave Houlton5fa47912018-02-16 11:02:26 -07001187 result = vk::createInstance(&inst_info, nullptr, &inst);
1188 if (result == vk::Result::eErrorIncompatibleDriver) {
1189 ERR_EXIT(
1190 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1191 "Please look at the Getting Started guide for additional information.\n",
1192 "vkCreateInstance Failure");
1193 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1194 ERR_EXIT(
1195 "Cannot find a specified extension library.\n"
1196 "Make sure your layers path is set appropriately.\n",
1197 "vkCreateInstance Failure");
1198 } else if (result != vk::Result::eSuccess) {
1199 ERR_EXIT(
1200 "vkCreateInstance failed.\n\n"
1201 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1202 "Please look at the Getting Started guide for additional information.\n",
1203 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001204 }
1205
Dave Houlton5fa47912018-02-16 11:02:26 -07001206 /* Make initial call to query gpu_count, then second call for gpu info*/
1207 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001208 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001209 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001210
1211 if (gpu_count > 0) {
1212 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1213 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001214 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001215 /* For cube demo we just grab the first physical device */
1216 gpu = physical_devices[0];
1217 } else {
1218 ERR_EXIT(
1219 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1220 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1221 "Please look at the Getting Started guide for additional information.\n",
1222 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001223 }
1224
Dave Houlton5fa47912018-02-16 11:02:26 -07001225 /* Look for device extensions */
1226 uint32_t device_extension_count = 0;
1227 vk::Bool32 swapchainExtFound = VK_FALSE;
1228 enabled_extension_count = 0;
1229 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001230
Mike Schuchardt7510c832018-10-29 13:23:08 -07001231 result =
1232 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001233 VERIFY(result == vk::Result::eSuccess);
1234
1235 if (device_extension_count > 0) {
1236 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1237 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001238 VERIFY(result == vk::Result::eSuccess);
1239
Dave Houlton5fa47912018-02-16 11:02:26 -07001240 for (uint32_t i = 0; i < device_extension_count; i++) {
1241 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1242 swapchainExtFound = 1;
1243 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001244 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001245 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001246 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001247 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001248
Dave Houlton5fa47912018-02-16 11:02:26 -07001249 if (!swapchainExtFound) {
1250 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1251 " extension.\n\n"
1252 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1253 "Please look at the Getting Started guide for additional information.\n",
1254 "vkCreateInstance Failure");
1255 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001256
Dave Houlton5fa47912018-02-16 11:02:26 -07001257 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001258
Dave Houlton5fa47912018-02-16 11:02:26 -07001259 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001260 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001261 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001262
Dave Houlton5fa47912018-02-16 11:02:26 -07001263 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1264 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001265
Dave Houlton5fa47912018-02-16 11:02:26 -07001266 // Query fine-grained feature support for this device.
1267 // If app has specific feature requirements it should check supported
1268 // features based on this query
1269 vk::PhysicalDeviceFeatures physDevFeatures;
1270 gpu.getFeatures(&physDevFeatures);
1271}
1272
Tony-LunarG6cebf142019-09-11 14:32:23 -06001273void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001274// Create a WSI surface for the window:
1275#if defined(VK_USE_PLATFORM_WIN32_KHR)
1276 {
1277 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1278
1279 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1280 VERIFY(result == vk::Result::eSuccess);
1281 }
1282#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1283 {
1284 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1285
1286 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1287 VERIFY(result == vk::Result::eSuccess);
1288 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001289#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1290 {
1291 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1292
1293 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1294 VERIFY(result == vk::Result::eSuccess);
1295 }
1296#elif defined(VK_USE_PLATFORM_XCB_KHR)
1297 {
1298 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1299
1300 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1301 VERIFY(result == vk::Result::eSuccess);
1302 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001303#elif defined(VK_USE_PLATFORM_IOS_MVK)
1304 {
1305 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1306
1307 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1308 VERIFY(result == vk::Result::eSuccess);
1309 }
1310#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1311 {
1312 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1313
1314 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1315 VERIFY(result == vk::Result::eSuccess);
1316 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001317#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1318 {
1319 auto result = create_display_surface();
1320 VERIFY(result == vk::Result::eSuccess);
1321 }
1322#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001323}
1324
1325void Demo::init_vk_swapchain() {
1326 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001327 // Iterate over each queue to learn whether it supports presenting:
1328 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1329 for (uint32_t i = 0; i < queue_family_count; i++) {
1330 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1331 }
1332
1333 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1334 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1335 for (uint32_t i = 0; i < queue_family_count; i++) {
1336 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1337 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1338 graphicsQueueFamilyIndex = i;
1339 }
1340
1341 if (supportsPresent[i] == VK_TRUE) {
1342 graphicsQueueFamilyIndex = i;
1343 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001344 break;
1345 }
1346 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001347 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001348
Dave Houlton5fa47912018-02-16 11:02:26 -07001349 if (presentQueueFamilyIndex == UINT32_MAX) {
1350 // If didn't find a queue that supports both graphics and present,
1351 // then
1352 // find a separate present queue.
1353 for (uint32_t i = 0; i < queue_family_count; ++i) {
1354 if (supportsPresent[i] == VK_TRUE) {
1355 presentQueueFamilyIndex = i;
1356 break;
1357 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001358 }
1359 }
1360
Dave Houlton5fa47912018-02-16 11:02:26 -07001361 // Generate error if could not find both a graphics and a present queue
1362 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1363 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1364 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001365
Dave Houlton5fa47912018-02-16 11:02:26 -07001366 graphics_queue_family_index = graphicsQueueFamilyIndex;
1367 present_queue_family_index = presentQueueFamilyIndex;
1368 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001369
Dave Houlton5fa47912018-02-16 11:02:26 -07001370 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001371
Dave Houlton5fa47912018-02-16 11:02:26 -07001372 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1373 if (!separate_present_queue) {
1374 present_queue = graphics_queue;
1375 } else {
1376 device.getQueue(present_queue_family_index, 0, &present_queue);
1377 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001378
Dave Houlton5fa47912018-02-16 11:02:26 -07001379 // Get the list of VkFormat's that are supported:
1380 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001381 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001382 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1385 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1386 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001387
Dave Houlton5fa47912018-02-16 11:02:26 -07001388 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1389 // the surface has no preferred format. Otherwise, at least one
1390 // supported format will be returned.
1391 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1392 format = vk::Format::eB8G8R8A8Unorm;
1393 } else {
1394 assert(formatCount >= 1);
1395 format = surfFormats[0].format;
1396 }
1397 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001398
Dave Houlton5fa47912018-02-16 11:02:26 -07001399 quit = false;
1400 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001401
Dave Houlton5fa47912018-02-16 11:02:26 -07001402 // Create semaphores to synchronize acquiring presentable buffers before
1403 // rendering and waiting for drawing to be complete before presenting
1404 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001405
Dave Houlton5fa47912018-02-16 11:02:26 -07001406 // Create fences that we can use to throttle if we get too far
1407 // ahead of the image presents
1408 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1409 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1410 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1411 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001412
Dave Houlton5fa47912018-02-16 11:02:26 -07001413 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1414 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001415
Dave Houlton5fa47912018-02-16 11:02:26 -07001416 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1417 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001418
Dave Houlton5fa47912018-02-16 11:02:26 -07001419 if (separate_present_queue) {
1420 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001421 VERIFY(result == vk::Result::eSuccess);
1422 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001423 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001424 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001425
Dave Houlton5fa47912018-02-16 11:02:26 -07001426 // Get Memory information and properties
1427 gpu.getMemoryProperties(&memory_properties);
1428}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001429
Dave Houlton5fa47912018-02-16 11:02:26 -07001430void Demo::prepare() {
1431 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1432 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1433 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001434
Dave Houlton5fa47912018-02-16 11:02:26 -07001435 auto const cmd = vk::CommandBufferAllocateInfo()
1436 .setCommandPool(cmd_pool)
1437 .setLevel(vk::CommandBufferLevel::ePrimary)
1438 .setCommandBufferCount(1);
1439
1440 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1441 VERIFY(result == vk::Result::eSuccess);
1442
1443 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1444
1445 result = this->cmd.begin(&cmd_buf_info);
1446 VERIFY(result == vk::Result::eSuccess);
1447
1448 prepare_buffers();
1449 prepare_depth();
1450 prepare_textures();
1451 prepare_cube_data_buffers();
1452
1453 prepare_descriptor_layout();
1454 prepare_render_pass();
1455 prepare_pipeline();
1456
1457 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1458 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1459 VERIFY(result == vk::Result::eSuccess);
1460 }
1461
1462 if (separate_present_queue) {
1463 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1464
1465 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1466 VERIFY(result == vk::Result::eSuccess);
1467
1468 auto const present_cmd = vk::CommandBufferAllocateInfo()
1469 .setCommandPool(present_cmd_pool)
1470 .setLevel(vk::CommandBufferLevel::ePrimary)
1471 .setCommandBufferCount(1);
1472
1473 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1474 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1475 VERIFY(result == vk::Result::eSuccess);
1476
1477 build_image_ownership_cmd(i);
1478 }
1479 }
1480
1481 prepare_descriptor_pool();
1482 prepare_descriptor_set();
1483
1484 prepare_framebuffers();
1485
1486 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1487 current_buffer = i;
1488 draw_build_cmd(swapchain_image_resources[i].cmd);
1489 }
1490
1491 /*
1492 * Prepare functions above may generate pipeline commands
1493 * that need to be flushed before beginning the render loop.
1494 */
1495 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001496 if (staging_texture.buffer) {
1497 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001498 }
1499
1500 current_buffer = 0;
1501 prepared = true;
1502}
1503
1504void Demo::prepare_buffers() {
1505 vk::SwapchainKHR oldSwapchain = swapchain;
1506
1507 // Check the surface capabilities and formats
1508 vk::SurfaceCapabilitiesKHR surfCapabilities;
1509 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1510 VERIFY(result == vk::Result::eSuccess);
1511
1512 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001513 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001514 VERIFY(result == vk::Result::eSuccess);
1515
1516 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1517 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1518 VERIFY(result == vk::Result::eSuccess);
1519
1520 vk::Extent2D swapchainExtent;
1521 // width and height are either both -1, or both not -1.
1522 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1523 // If the surface size is undefined, the size is set to
1524 // the size of the images requested.
1525 swapchainExtent.width = width;
1526 swapchainExtent.height = height;
1527 } else {
1528 // If the surface size is defined, the swap chain size must match
1529 swapchainExtent = surfCapabilities.currentExtent;
1530 width = surfCapabilities.currentExtent.width;
1531 height = surfCapabilities.currentExtent.height;
1532 }
1533
1534 // The FIFO present mode is guaranteed by the spec to be supported
1535 // and to have no tearing. It's a great default present mode to use.
1536 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1537
1538 // There are times when you may wish to use another present mode. The
1539 // following code shows how to select them, and the comments provide some
1540 // reasons you may wish to use them.
1541 //
1542 // It should be noted that Vulkan 1.0 doesn't provide a method for
1543 // synchronizing rendering with the presentation engine's display. There
1544 // is a method provided for throttling rendering with the display, but
1545 // there are some presentation engines for which this method will not work.
1546 // If an application doesn't throttle its rendering, and if it renders much
1547 // faster than the refresh rate of the display, this can waste power on
1548 // mobile devices. That is because power is being spent rendering images
1549 // that may never be seen.
1550
1551 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1552 // about
1553 // tearing, or have some way of synchronizing their rendering with the
1554 // display.
1555 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1556 // generally render a new presentable image every refresh cycle, but are
1557 // occasionally early. In this case, the application wants the new
1558 // image
1559 // to be displayed instead of the previously-queued-for-presentation
1560 // image
1561 // that has not yet been displayed.
1562 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1563 // render a new presentable image every refresh cycle, but are
1564 // occasionally
1565 // late. In this case (perhaps because of stuttering/latency concerns),
1566 // the application wants the late image to be immediately displayed,
1567 // even
1568 // though that may mean some tearing.
1569
1570 if (presentMode != swapchainPresentMode) {
1571 for (size_t i = 0; i < presentModeCount; ++i) {
1572 if (presentModes[i] == presentMode) {
1573 swapchainPresentMode = presentMode;
1574 break;
1575 }
1576 }
1577 }
1578
1579 if (swapchainPresentMode != presentMode) {
1580 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1581 }
1582
1583 // Determine the number of VkImages to use in the swap chain.
1584 // Application desires to acquire 3 images at a time for triple
1585 // buffering
1586 uint32_t desiredNumOfSwapchainImages = 3;
1587 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1588 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1589 }
1590
1591 // If maxImageCount is 0, we can ask for as many images as we want,
1592 // otherwise
1593 // we're limited to maxImageCount
1594 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1595 // Application must settle for fewer images than desired:
1596 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1597 }
1598
1599 vk::SurfaceTransformFlagBitsKHR preTransform;
1600 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1601 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1602 } else {
1603 preTransform = surfCapabilities.currentTransform;
1604 }
1605
1606 // Find a supported composite alpha mode - one of these is guaranteed to be set
1607 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1608 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1609 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1610 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1611 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1612 vk::CompositeAlphaFlagBitsKHR::eInherit,
1613 };
1614 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1615 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1616 compositeAlpha = compositeAlphaFlags[i];
1617 break;
1618 }
1619 }
1620
1621 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1622 .setSurface(surface)
1623 .setMinImageCount(desiredNumOfSwapchainImages)
1624 .setImageFormat(format)
1625 .setImageColorSpace(color_space)
1626 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1627 .setImageArrayLayers(1)
1628 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1629 .setImageSharingMode(vk::SharingMode::eExclusive)
1630 .setQueueFamilyIndexCount(0)
1631 .setPQueueFamilyIndices(nullptr)
1632 .setPreTransform(preTransform)
1633 .setCompositeAlpha(compositeAlpha)
1634 .setPresentMode(swapchainPresentMode)
1635 .setClipped(true)
1636 .setOldSwapchain(oldSwapchain);
1637
1638 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1639 VERIFY(result == vk::Result::eSuccess);
1640
1641 // If we just re-created an existing swapchain, we should destroy the
1642 // old
1643 // swapchain at this point.
1644 // Note: destroying the swapchain also cleans up all its associated
1645 // presentable images once the platform is done with them.
1646 if (oldSwapchain) {
1647 device.destroySwapchainKHR(oldSwapchain, nullptr);
1648 }
1649
Mike Schuchardt7510c832018-10-29 13:23:08 -07001650 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001651 VERIFY(result == vk::Result::eSuccess);
1652
1653 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1654 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1655 VERIFY(result == vk::Result::eSuccess);
1656
1657 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1658
1659 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1660 auto color_image_view = vk::ImageViewCreateInfo()
1661 .setViewType(vk::ImageViewType::e2D)
1662 .setFormat(format)
1663 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1664
1665 swapchain_image_resources[i].image = swapchainImages[i];
1666
1667 color_image_view.image = swapchain_image_resources[i].image;
1668
1669 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1670 VERIFY(result == vk::Result::eSuccess);
1671 }
1672}
1673
1674void Demo::prepare_cube_data_buffers() {
1675 mat4x4 VP;
1676 mat4x4_mul(VP, projection_matrix, view_matrix);
1677
1678 mat4x4 MVP;
1679 mat4x4_mul(MVP, VP, model_matrix);
1680
1681 vktexcube_vs_uniform data;
1682 memcpy(data.mvp, MVP, sizeof(MVP));
1683 // dumpMatrix("MVP", MVP)
1684
1685 for (int32_t i = 0; i < 12 * 3; i++) {
1686 data.position[i][0] = g_vertex_buffer_data[i * 3];
1687 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1688 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1689 data.position[i][3] = 1.0f;
1690 data.attr[i][0] = g_uv_buffer_data[2 * i];
1691 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1692 data.attr[i][2] = 0;
1693 data.attr[i][3] = 0;
1694 }
1695
1696 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1697
1698 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1699 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001700 VERIFY(result == vk::Result::eSuccess);
1701
1702 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001703 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001704
Dave Houlton5fa47912018-02-16 11:02:26 -07001705 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001706
Dave Houlton5fa47912018-02-16 11:02:26 -07001707 bool const pass = memory_type_from_properties(
1708 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1709 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001710 VERIFY(pass);
1711
Dave Houlton5fa47912018-02-16 11:02:26 -07001712 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001713 VERIFY(result == vk::Result::eSuccess);
1714
Dave Houlton5fa47912018-02-16 11:02:26 -07001715 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1716 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001717
Dave Houlton5fa47912018-02-16 11:02:26 -07001718 memcpy(pData.value, &data, sizeof data);
1719
1720 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1721
1722 result =
1723 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001724 VERIFY(result == vk::Result::eSuccess);
1725 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001726}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001727
Dave Houlton5fa47912018-02-16 11:02:26 -07001728void Demo::prepare_depth() {
1729 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001730
Dave Houlton5fa47912018-02-16 11:02:26 -07001731 auto const image = vk::ImageCreateInfo()
1732 .setImageType(vk::ImageType::e2D)
1733 .setFormat(depth.format)
1734 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1735 .setMipLevels(1)
1736 .setArrayLayers(1)
1737 .setSamples(vk::SampleCountFlagBits::e1)
1738 .setTiling(vk::ImageTiling::eOptimal)
1739 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1740 .setSharingMode(vk::SharingMode::eExclusive)
1741 .setQueueFamilyIndexCount(0)
1742 .setPQueueFamilyIndices(nullptr)
1743 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001744
Dave Houlton5fa47912018-02-16 11:02:26 -07001745 auto result = device.createImage(&image, nullptr, &depth.image);
1746 VERIFY(result == vk::Result::eSuccess);
1747
1748 vk::MemoryRequirements mem_reqs;
1749 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1750
1751 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1752 depth.mem_alloc.setMemoryTypeIndex(0);
1753
1754 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1755 &depth.mem_alloc.memoryTypeIndex);
1756 VERIFY(pass);
1757
1758 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1759 VERIFY(result == vk::Result::eSuccess);
1760
1761 result = device.bindImageMemory(depth.image, depth.mem, 0);
1762 VERIFY(result == vk::Result::eSuccess);
1763
1764 auto const view = vk::ImageViewCreateInfo()
1765 .setImage(depth.image)
1766 .setViewType(vk::ImageViewType::e2D)
1767 .setFormat(depth.format)
1768 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1769 result = device.createImageView(&view, nullptr, &depth.view);
1770 VERIFY(result == vk::Result::eSuccess);
1771}
1772
1773void Demo::prepare_descriptor_layout() {
1774 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1775 .setBinding(0)
1776 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1777 .setDescriptorCount(1)
1778 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1779 .setPImmutableSamplers(nullptr),
1780 vk::DescriptorSetLayoutBinding()
1781 .setBinding(1)
1782 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1783 .setDescriptorCount(texture_count)
1784 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1785 .setPImmutableSamplers(nullptr)};
1786
1787 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1788
1789 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1790 VERIFY(result == vk::Result::eSuccess);
1791
1792 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1793
1794 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1795 VERIFY(result == vk::Result::eSuccess);
1796}
1797
1798void Demo::prepare_descriptor_pool() {
1799 vk::DescriptorPoolSize const poolSizes[2] = {
1800 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1801 vk::DescriptorPoolSize()
1802 .setType(vk::DescriptorType::eCombinedImageSampler)
1803 .setDescriptorCount(swapchainImageCount * texture_count)};
1804
1805 auto const descriptor_pool =
1806 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1807
1808 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1809 VERIFY(result == vk::Result::eSuccess);
1810}
1811
1812void Demo::prepare_descriptor_set() {
1813 auto const alloc_info =
1814 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1815
1816 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1817
1818 vk::DescriptorImageInfo tex_descs[texture_count];
1819 for (uint32_t i = 0; i < texture_count; i++) {
1820 tex_descs[i].setSampler(textures[i].sampler);
1821 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001822 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001823 }
1824
1825 vk::WriteDescriptorSet writes[2];
1826
1827 writes[0].setDescriptorCount(1);
1828 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1829 writes[0].setPBufferInfo(&buffer_info);
1830
1831 writes[1].setDstBinding(1);
1832 writes[1].setDescriptorCount(texture_count);
1833 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1834 writes[1].setPImageInfo(tex_descs);
1835
1836 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1837 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001838 VERIFY(result == vk::Result::eSuccess);
1839
Dave Houlton5fa47912018-02-16 11:02:26 -07001840 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1841 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1842 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1843 device.updateDescriptorSets(2, writes, 0, nullptr);
1844 }
1845}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001846
Dave Houlton5fa47912018-02-16 11:02:26 -07001847void Demo::prepare_framebuffers() {
1848 vk::ImageView attachments[2];
1849 attachments[1] = depth.view;
1850
1851 auto const fb_info = vk::FramebufferCreateInfo()
1852 .setRenderPass(render_pass)
1853 .setAttachmentCount(2)
1854 .setPAttachments(attachments)
1855 .setWidth((uint32_t)width)
1856 .setHeight((uint32_t)height)
1857 .setLayers(1);
1858
1859 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1860 attachments[0] = swapchain_image_resources[i].view;
1861 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001862 VERIFY(result == vk::Result::eSuccess);
1863 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001864}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001865
Dave Houlton5fa47912018-02-16 11:02:26 -07001866vk::ShaderModule Demo::prepare_fs() {
1867 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001868#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001869 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001870
Dave Houlton5fa47912018-02-16 11:02:26 -07001871 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001872
Dave Houlton5fa47912018-02-16 11:02:26 -07001873 return frag_shader_module;
1874}
1875
1876void Demo::prepare_pipeline() {
1877 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1878 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1879 VERIFY(result == vk::Result::eSuccess);
1880
1881 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1882 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1883 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1884
1885 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1886
1887 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1888
1889 // TODO: Where are pViewports and pScissors set?
1890 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1891
1892 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1893 .setDepthClampEnable(VK_FALSE)
1894 .setRasterizerDiscardEnable(VK_FALSE)
1895 .setPolygonMode(vk::PolygonMode::eFill)
1896 .setCullMode(vk::CullModeFlagBits::eBack)
1897 .setFrontFace(vk::FrontFace::eCounterClockwise)
1898 .setDepthBiasEnable(VK_FALSE)
1899 .setLineWidth(1.0f);
1900
1901 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1902
1903 auto const stencilOp =
1904 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1905
1906 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1907 .setDepthTestEnable(VK_TRUE)
1908 .setDepthWriteEnable(VK_TRUE)
1909 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1910 .setDepthBoundsTestEnable(VK_FALSE)
1911 .setStencilTestEnable(VK_FALSE)
1912 .setFront(stencilOp)
1913 .setBack(stencilOp);
1914
1915 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1916 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1917 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1918
1919 auto const colorBlendInfo =
1920 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1921
1922 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1923
1924 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1925
1926 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1927 .setStageCount(2)
1928 .setPStages(shaderStageInfo)
1929 .setPVertexInputState(&vertexInputInfo)
1930 .setPInputAssemblyState(&inputAssemblyInfo)
1931 .setPViewportState(&viewportInfo)
1932 .setPRasterizationState(&rasterizationInfo)
1933 .setPMultisampleState(&multisampleInfo)
1934 .setPDepthStencilState(&depthStencilInfo)
1935 .setPColorBlendState(&colorBlendInfo)
1936 .setPDynamicState(&dynamicStateInfo)
1937 .setLayout(pipeline_layout)
1938 .setRenderPass(render_pass);
1939
1940 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1941 VERIFY(result == vk::Result::eSuccess);
1942
1943 device.destroyShaderModule(frag_shader_module, nullptr);
1944 device.destroyShaderModule(vert_shader_module, nullptr);
1945}
1946
1947void Demo::prepare_render_pass() {
1948 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1949 // because at the start of the renderpass, we don't care about their contents.
1950 // At the start of the subpass, the color attachment's layout will be transitioned
1951 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1952 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1953 // the renderpass, the color attachment's layout will be transitioned to
1954 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1955 // the renderpass, no barriers are necessary.
1956 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1957 .setFormat(format)
1958 .setSamples(vk::SampleCountFlagBits::e1)
1959 .setLoadOp(vk::AttachmentLoadOp::eClear)
1960 .setStoreOp(vk::AttachmentStoreOp::eStore)
1961 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1962 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1963 .setInitialLayout(vk::ImageLayout::eUndefined)
1964 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1965 vk::AttachmentDescription()
1966 .setFormat(depth.format)
1967 .setSamples(vk::SampleCountFlagBits::e1)
1968 .setLoadOp(vk::AttachmentLoadOp::eClear)
1969 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1970 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1971 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1972 .setInitialLayout(vk::ImageLayout::eUndefined)
1973 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1974
1975 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1976
1977 auto const depth_reference =
1978 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1979
1980 auto const subpass = vk::SubpassDescription()
1981 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1982 .setInputAttachmentCount(0)
1983 .setPInputAttachments(nullptr)
1984 .setColorAttachmentCount(1)
1985 .setPColorAttachments(&color_reference)
1986 .setPResolveAttachments(nullptr)
1987 .setPDepthStencilAttachment(&depth_reference)
1988 .setPreserveAttachmentCount(0)
1989 .setPPreserveAttachments(nullptr);
1990
Tony-LunarG495604b2019-06-13 15:32:05 -06001991 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
1992 vk::SubpassDependency const dependencies[2] = {
1993 vk::SubpassDependency() // Depth buffer is shared between swapchain images
1994 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1995 .setDstSubpass(0)
1996 .setSrcStageMask(stages)
1997 .setDstStageMask(stages)
1998 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1999 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2000 .setDependencyFlags(vk::DependencyFlags()),
2001 vk::SubpassDependency() // Image layout transition
2002 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2003 .setDstSubpass(0)
2004 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2005 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2006 .setSrcAccessMask(vk::AccessFlagBits())
2007 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2008 .setDependencyFlags(vk::DependencyFlags()),
2009 };
2010
Dave Houlton5fa47912018-02-16 11:02:26 -07002011 auto const rp_info = vk::RenderPassCreateInfo()
2012 .setAttachmentCount(2)
2013 .setPAttachments(attachments)
2014 .setSubpassCount(1)
2015 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002016 .setDependencyCount(2)
2017 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002018
2019 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2020 VERIFY(result == vk::Result::eSuccess);
2021}
2022
2023vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2024 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2025
2026 vk::ShaderModule module;
2027 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2028 VERIFY(result == vk::Result::eSuccess);
2029
2030 return module;
2031}
2032
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002033void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2034 int32_t tex_width;
2035 int32_t tex_height;
2036
2037 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2038 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2039 }
2040
2041 tex_obj->tex_width = tex_width;
2042 tex_obj->tex_height = tex_height;
2043
2044 auto const buffer_create_info = vk::BufferCreateInfo()
2045 .setSize(tex_width * tex_height * 4)
2046 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2047 .setSharingMode(vk::SharingMode::eExclusive)
2048 .setQueueFamilyIndexCount(0)
2049 .setPQueueFamilyIndices(nullptr);
2050
2051 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2052 VERIFY(result == vk::Result::eSuccess);
2053
2054 vk::MemoryRequirements mem_reqs;
2055 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2056
2057 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2058 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2059
2060 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2061 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2062 VERIFY(pass == true);
2063
2064 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2065 VERIFY(result == vk::Result::eSuccess);
2066
2067 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2068 VERIFY(result == vk::Result::eSuccess);
2069
2070 vk::SubresourceLayout layout;
2071 memset(&layout, 0, sizeof(layout));
2072 layout.rowPitch = tex_width * 4;
2073 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2074 VERIFY(data.result == vk::Result::eSuccess);
2075
2076 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2077 fprintf(stderr, "Error loading texture: %s\n", filename);
2078 }
2079
2080 device.unmapMemory(tex_obj->mem);
2081}
2082
Dave Houlton5fa47912018-02-16 11:02:26 -07002083void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2084 vk::MemoryPropertyFlags required_props) {
2085 int32_t tex_width;
2086 int32_t tex_height;
2087 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2088 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002089 }
2090
Dave Houlton5fa47912018-02-16 11:02:26 -07002091 tex_obj->tex_width = tex_width;
2092 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002093
Dave Houlton5fa47912018-02-16 11:02:26 -07002094 auto const image_create_info = vk::ImageCreateInfo()
2095 .setImageType(vk::ImageType::e2D)
2096 .setFormat(vk::Format::eR8G8B8A8Unorm)
2097 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2098 .setMipLevels(1)
2099 .setArrayLayers(1)
2100 .setSamples(vk::SampleCountFlagBits::e1)
2101 .setTiling(tiling)
2102 .setUsage(usage)
2103 .setSharingMode(vk::SharingMode::eExclusive)
2104 .setQueueFamilyIndexCount(0)
2105 .setPQueueFamilyIndices(nullptr)
2106 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002107
Dave Houlton5fa47912018-02-16 11:02:26 -07002108 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2109 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002110
Dave Houlton5fa47912018-02-16 11:02:26 -07002111 vk::MemoryRequirements mem_reqs;
2112 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002113
Dave Houlton5fa47912018-02-16 11:02:26 -07002114 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2115 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002116
Dave Houlton5fa47912018-02-16 11:02:26 -07002117 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2118 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002119
Dave Houlton5fa47912018-02-16 11:02:26 -07002120 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2121 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002122
Dave Houlton5fa47912018-02-16 11:02:26 -07002123 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2124 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002125
Dave Houlton5fa47912018-02-16 11:02:26 -07002126 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2127 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2128 vk::SubresourceLayout layout;
2129 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002130
Dave Houlton5fa47912018-02-16 11:02:26 -07002131 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002132 VERIFY(data.result == vk::Result::eSuccess);
2133
Dave Houlton5fa47912018-02-16 11:02:26 -07002134 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2135 fprintf(stderr, "Error loading texture: %s\n", filename);
2136 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002137
Dave Houlton5fa47912018-02-16 11:02:26 -07002138 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002139 }
2140
Dave Houlton5fa47912018-02-16 11:02:26 -07002141 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2142}
2143
2144void Demo::prepare_textures() {
2145 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2146 vk::FormatProperties props;
2147 gpu.getFormatProperties(tex_format, &props);
2148
2149 for (uint32_t i = 0; i < texture_count; i++) {
2150 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2151 /* Device can texture using linear textures */
2152 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2153 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2154 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2155 // shader to run until layout transition completes
2156 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2157 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2158 vk::PipelineStageFlagBits::eFragmentShader);
2159 staging_texture.image = vk::Image();
2160 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2161 /* Must use staging buffer to copy linear texture to optimized */
2162
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002163 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002164
2165 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2166 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2167 vk::MemoryPropertyFlagBits::eDeviceLocal);
2168
Dave Houlton5fa47912018-02-16 11:02:26 -07002169 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2170 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2171 vk::PipelineStageFlagBits::eTransfer);
2172
2173 auto const subresource = vk::ImageSubresourceLayers()
2174 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2175 .setMipLevel(0)
2176 .setBaseArrayLayer(0)
2177 .setLayerCount(1);
2178
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002179 auto const copy_region =
2180 vk::BufferImageCopy()
2181 .setBufferOffset(0)
2182 .setBufferRowLength(staging_texture.tex_width)
2183 .setBufferImageHeight(staging_texture.tex_height)
2184 .setImageSubresource(subresource)
2185 .setImageOffset({0, 0, 0})
2186 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002187
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002188 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002189
2190 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2191 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2192 vk::PipelineStageFlagBits::eFragmentShader);
2193 } else {
2194 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002195 }
2196
Dave Houlton5fa47912018-02-16 11:02:26 -07002197 auto const samplerInfo = vk::SamplerCreateInfo()
2198 .setMagFilter(vk::Filter::eNearest)
2199 .setMinFilter(vk::Filter::eNearest)
2200 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2201 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2202 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2203 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2204 .setMipLodBias(0.0f)
2205 .setAnisotropyEnable(VK_FALSE)
2206 .setMaxAnisotropy(1)
2207 .setCompareEnable(VK_FALSE)
2208 .setCompareOp(vk::CompareOp::eNever)
2209 .setMinLod(0.0f)
2210 .setMaxLod(0.0f)
2211 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2212 .setUnnormalizedCoordinates(VK_FALSE);
2213
2214 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2215 VERIFY(result == vk::Result::eSuccess);
2216
2217 auto const viewInfo = vk::ImageViewCreateInfo()
2218 .setImage(textures[i].image)
2219 .setViewType(vk::ImageViewType::e2D)
2220 .setFormat(tex_format)
2221 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2222
2223 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2224 VERIFY(result == vk::Result::eSuccess);
2225 }
2226}
2227
2228vk::ShaderModule Demo::prepare_vs() {
2229 const uint32_t vertShaderCode[] = {
2230#include "cube.vert.inc"
2231 };
2232
2233 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2234
2235 return vert_shader_module;
2236}
2237
2238void Demo::resize() {
2239 uint32_t i;
2240
2241 // Don't react to resize until after first initialization.
2242 if (!prepared) {
2243 return;
2244 }
2245
2246 // In order to properly resize the window, we must re-create the
2247 // swapchain
2248 // AND redo the command buffers, etc.
2249 //
2250 // First, perform part of the cleanup() function:
2251 prepared = false;
2252 auto result = device.waitIdle();
2253 VERIFY(result == vk::Result::eSuccess);
2254
2255 for (i = 0; i < swapchainImageCount; i++) {
2256 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2257 }
2258
2259 device.destroyDescriptorPool(desc_pool, nullptr);
2260
2261 device.destroyPipeline(pipeline, nullptr);
2262 device.destroyPipelineCache(pipelineCache, nullptr);
2263 device.destroyRenderPass(render_pass, nullptr);
2264 device.destroyPipelineLayout(pipeline_layout, nullptr);
2265 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2266
2267 for (i = 0; i < texture_count; i++) {
2268 device.destroyImageView(textures[i].view, nullptr);
2269 device.destroyImage(textures[i].image, nullptr);
2270 device.freeMemory(textures[i].mem, nullptr);
2271 device.destroySampler(textures[i].sampler, nullptr);
2272 }
2273
2274 device.destroyImageView(depth.view, nullptr);
2275 device.destroyImage(depth.image, nullptr);
2276 device.freeMemory(depth.mem, nullptr);
2277
2278 for (i = 0; i < swapchainImageCount; i++) {
2279 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2280 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2281 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2282 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2283 }
2284
2285 device.destroyCommandPool(cmd_pool, nullptr);
2286 if (separate_present_queue) {
2287 device.destroyCommandPool(present_cmd_pool, nullptr);
2288 }
2289
2290 // Second, re-perform the prepare() function, which will re-create the
2291 // swapchain.
2292 prepare();
2293}
2294
2295void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2296 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2297 assert(cmd);
2298
2299 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2300 vk::AccessFlags flags;
2301
2302 switch (layout) {
2303 case vk::ImageLayout::eTransferDstOptimal:
2304 // Make sure anything that was copying from this image has
2305 // completed
2306 flags = vk::AccessFlagBits::eTransferWrite;
2307 break;
2308 case vk::ImageLayout::eColorAttachmentOptimal:
2309 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2310 break;
2311 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2312 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2313 break;
2314 case vk::ImageLayout::eShaderReadOnlyOptimal:
2315 // Make sure any Copy or CPU writes to image are flushed
2316 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2317 break;
2318 case vk::ImageLayout::eTransferSrcOptimal:
2319 flags = vk::AccessFlagBits::eTransferRead;
2320 break;
2321 case vk::ImageLayout::ePresentSrcKHR:
2322 flags = vk::AccessFlagBits::eMemoryRead;
2323 break;
2324 default:
2325 break;
2326 }
2327
2328 return flags;
2329 };
2330
2331 auto const barrier = vk::ImageMemoryBarrier()
2332 .setSrcAccessMask(srcAccessMask)
2333 .setDstAccessMask(DstAccessMask(newLayout))
2334 .setOldLayout(oldLayout)
2335 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002336 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2337 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002338 .setImage(image)
2339 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2340
2341 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2342}
2343
2344void Demo::update_data_buffer() {
2345 mat4x4 VP;
2346 mat4x4_mul(VP, projection_matrix, view_matrix);
2347
2348 // Rotate around the Y axis
2349 mat4x4 Model;
2350 mat4x4_dup(Model, model_matrix);
2351 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2352
2353 mat4x4 MVP;
2354 mat4x4_mul(MVP, VP, model_matrix);
2355
2356 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2357 VERIFY(data.result == vk::Result::eSuccess);
2358
2359 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2360
2361 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2362}
2363
Karl Schultzb7940402018-05-29 13:09:22 -06002364/* Convert ppm image data from header file into RGBA texture image */
2365#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002366bool 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 -06002367 (void)filename;
2368 char *cPtr;
2369 cPtr = (char *)lunarg_ppm;
2370 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002371 return false;
2372 }
Karl Schultzb7940402018-05-29 13:09:22 -06002373 while (strncmp(cPtr++, "\n", 1))
2374 ;
2375 sscanf(cPtr, "%u %u", width, height);
2376 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002377 return true;
2378 }
Karl Schultzb7940402018-05-29 13:09:22 -06002379 while (strncmp(cPtr++, "\n", 1))
2380 ;
2381 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002382 return false;
2383 }
Karl Schultzb7940402018-05-29 13:09:22 -06002384 while (strncmp(cPtr++, "\n", 1))
2385 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002386 for (int y = 0; y < *height; y++) {
2387 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002388 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002389 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002390 rowPtr[3] = 255; /* Alpha of 1 */
2391 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002392 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002393 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002394 rgba_data += layout->rowPitch;
2395 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002396 return true;
2397}
2398
2399bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2400 // Search memtypes to find first index with those properties
2401 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2402 if ((typeBits & 1) == 1) {
2403 // Type is available, does it match user properties?
2404 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2405 *typeIndex = i;
2406 return true;
2407 }
2408 }
2409 typeBits >>= 1;
2410 }
2411
2412 // No memory types matched, return failure
2413 return false;
2414}
2415
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002416#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002417void Demo::run() {
2418 if (!prepared) {
2419 return;
2420 }
2421
2422 draw();
2423 curFrame++;
2424
Petr Krausd88e4e52019-01-23 18:45:04 +01002425 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002426 PostQuitMessage(validation_error);
2427 }
2428}
2429
2430void Demo::create_window() {
2431 WNDCLASSEX win_class;
2432
2433 // Initialize the window class structure:
2434 win_class.cbSize = sizeof(WNDCLASSEX);
2435 win_class.style = CS_HREDRAW | CS_VREDRAW;
2436 win_class.lpfnWndProc = WndProc;
2437 win_class.cbClsExtra = 0;
2438 win_class.cbWndExtra = 0;
2439 win_class.hInstance = connection; // hInstance
2440 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2441 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2442 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2443 win_class.lpszMenuName = nullptr;
2444 win_class.lpszClassName = name;
2445 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2446
2447 // Register window class:
2448 if (!RegisterClassEx(&win_class)) {
2449 // It didn't work, so try to give a useful error:
2450 printf("Unexpected error trying to start the application!\n");
2451 fflush(stdout);
2452 exit(1);
2453 }
2454
2455 // Create window with the registered class:
2456 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2457 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2458 window = CreateWindowEx(0,
2459 name, // class name
2460 name, // app name
2461 WS_OVERLAPPEDWINDOW | // window style
2462 WS_VISIBLE | WS_SYSMENU,
2463 100, 100, // x/y coords
2464 wr.right - wr.left, // width
2465 wr.bottom - wr.top, // height
2466 nullptr, // handle to parent
2467 nullptr, // handle to menu
2468 connection, // hInstance
2469 nullptr); // no extra parameters
2470
2471 if (!window) {
2472 // It didn't work, so try to give a useful error:
2473 printf("Cannot create a window in which to draw!\n");
2474 fflush(stdout);
2475 exit(1);
2476 }
2477
2478 // Window client area size must be at least 1 pixel high, to prevent
2479 // crash.
2480 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2481 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2482}
2483#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2484
2485void Demo::create_xlib_window() {
2486 const char *display_envar = getenv("DISPLAY");
2487 if (display_envar == nullptr || display_envar[0] == '\0') {
2488 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2489 fflush(stdout);
2490 exit(1);
2491 }
2492
2493 XInitThreads();
2494 display = XOpenDisplay(nullptr);
2495 long visualMask = VisualScreenMask;
2496 int numberOfVisuals;
2497 XVisualInfo vInfoTemplate = {};
2498 vInfoTemplate.screen = DefaultScreen(display);
2499 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2500
2501 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2502
2503 XSetWindowAttributes windowAttributes = {};
2504 windowAttributes.colormap = colormap;
2505 windowAttributes.background_pixel = 0xFFFFFFFF;
2506 windowAttributes.border_pixel = 0;
2507 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2508
2509 xlib_window =
2510 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2511 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2512
2513 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2514 XMapWindow(display, xlib_window);
2515 XFlush(display);
2516 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2517}
2518
2519void Demo::handle_xlib_event(const XEvent *event) {
2520 switch (event->type) {
2521 case ClientMessage:
2522 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2523 quit = true;
2524 }
2525 break;
2526 case KeyPress:
2527 switch (event->xkey.keycode) {
2528 case 0x9: // Escape
2529 quit = true;
2530 break;
2531 case 0x71: // left arrow key
2532 spin_angle -= spin_increment;
2533 break;
2534 case 0x72: // right arrow key
2535 spin_angle += spin_increment;
2536 break;
2537 case 0x41: // space bar
2538 pause = !pause;
2539 break;
2540 }
2541 break;
2542 case ConfigureNotify:
2543 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2544 width = event->xconfigure.width;
2545 height = event->xconfigure.height;
2546 resize();
2547 }
2548 break;
2549 default:
2550 break;
2551 }
2552}
2553
2554void Demo::run_xlib() {
2555 while (!quit) {
2556 XEvent event;
2557
2558 if (pause) {
2559 XNextEvent(display, &event);
2560 handle_xlib_event(&event);
2561 }
2562 while (XPending(display) > 0) {
2563 XNextEvent(display, &event);
2564 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002565 }
2566
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002567 draw();
2568 curFrame++;
2569
Dave Houlton5fa47912018-02-16 11:02:26 -07002570 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2571 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002572 }
2573 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002574}
Tony Barbour153cb062016-12-07 13:43:36 -07002575#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002576
Dave Houlton5fa47912018-02-16 11:02:26 -07002577void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2578 uint8_t event_code = event->response_type & 0x7f;
2579 switch (event_code) {
2580 case XCB_EXPOSE:
2581 // TODO: Resize window
2582 break;
2583 case XCB_CLIENT_MESSAGE:
2584 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2585 quit = true;
2586 }
2587 break;
2588 case XCB_KEY_RELEASE: {
2589 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002590
Dave Houlton5fa47912018-02-16 11:02:26 -07002591 switch (key->detail) {
2592 case 0x9: // Escape
2593 quit = true;
2594 break;
2595 case 0x71: // left arrow key
2596 spin_angle -= spin_increment;
2597 break;
2598 case 0x72: // right arrow key
2599 spin_angle += spin_increment;
2600 break;
2601 case 0x41: // space bar
2602 pause = !pause;
2603 break;
2604 }
2605 } break;
2606 case XCB_CONFIGURE_NOTIFY: {
2607 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2608 if ((width != cfg->width) || (height != cfg->height)) {
2609 width = cfg->width;
2610 height = cfg->height;
2611 resize();
2612 }
2613 } break;
2614 default:
2615 break;
2616 }
2617}
2618
2619void Demo::run_xcb() {
2620 xcb_flush(connection);
2621
2622 while (!quit) {
2623 xcb_generic_event_t *event;
2624
2625 if (pause) {
2626 event = xcb_wait_for_event(connection);
2627 } else {
2628 event = xcb_poll_for_event(connection);
2629 }
2630 while (event) {
2631 handle_xcb_event(event);
2632 free(event);
2633 event = xcb_poll_for_event(connection);
2634 }
2635
2636 draw();
2637 curFrame++;
2638 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2639 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002640 }
2641 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002642}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002643
Dave Houlton5fa47912018-02-16 11:02:26 -07002644void Demo::create_xcb_window() {
2645 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002646
Dave Houlton5fa47912018-02-16 11:02:26 -07002647 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002648
Dave Houlton5fa47912018-02-16 11:02:26 -07002649 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2650 value_list[0] = screen->black_pixel;
2651 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002652
Dave Houlton5fa47912018-02-16 11:02:26 -07002653 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2654 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2655
2656 /* Magic code that will send notification when window is destroyed */
2657 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2658 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2659
2660 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2661 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2662
2663 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2664
2665 free(reply);
2666
2667 xcb_map_window(connection, xcb_window);
2668
2669 // Force the x/y coordinates to 100,100 results are identical in
2670 // consecutive
2671 // runs
2672 const uint32_t coords[] = {100, 100};
2673 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2674}
2675#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2676
2677void Demo::run() {
2678 while (!quit) {
2679 if (pause) {
2680 wl_display_dispatch(display);
2681 } else {
2682 wl_display_dispatch_pending(display);
2683 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002684 draw();
2685 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002686 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002687 quit = true;
2688 }
2689 }
2690 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002691}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002692
Dave Houlton5fa47912018-02-16 11:02:26 -07002693void Demo::create_window() {
2694 window = wl_compositor_create_surface(compositor);
2695 if (!window) {
2696 printf("Can not create wayland_surface from compositor!\n");
2697 fflush(stdout);
2698 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002699 }
2700
Dave Houlton5fa47912018-02-16 11:02:26 -07002701 shell_surface = wl_shell_get_shell_surface(shell, window);
2702 if (!shell_surface) {
2703 printf("Can not get shell_surface from wayland_surface!\n");
2704 fflush(stdout);
2705 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002706 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002707
2708 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2709 wl_shell_surface_set_toplevel(shell_surface);
2710 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2711}
Karl Schultz206b1c52018-04-13 18:02:07 -06002712#elif defined(VK_USE_PLATFORM_MACOS_MVK)
2713void Demo::run() {
2714 draw();
2715 curFrame++;
2716 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2717 quit = true;
2718 }
2719}
Damien Leone600c3052017-01-31 10:26:07 -07002720#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2721
Dave Houlton5fa47912018-02-16 11:02:26 -07002722vk::Result Demo::create_display_surface() {
2723 vk::Result result;
2724 uint32_t display_count;
2725 uint32_t mode_count;
2726 uint32_t plane_count;
2727 vk::DisplayPropertiesKHR display_props;
2728 vk::DisplayKHR display;
2729 vk::DisplayModePropertiesKHR mode_props;
2730 vk::DisplayPlanePropertiesKHR *plane_props;
2731 vk::Bool32 found_plane = VK_FALSE;
2732 uint32_t plane_index;
2733 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002734
Dave Houlton5fa47912018-02-16 11:02:26 -07002735 // Get the first display
2736 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2737 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002738
Dave Houlton5fa47912018-02-16 11:02:26 -07002739 if (display_count == 0) {
2740 printf("Cannot find any display!\n");
2741 fflush(stdout);
2742 exit(1);
2743 }
2744
2745 display_count = 1;
2746 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2747 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2748
2749 display = display_props.display;
2750
2751 // Get the first mode of the display
2752 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2753 VERIFY(result == vk::Result::eSuccess);
2754
2755 if (mode_count == 0) {
2756 printf("Cannot find any mode for the display!\n");
2757 fflush(stdout);
2758 exit(1);
2759 }
2760
2761 mode_count = 1;
2762 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2763 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2764
2765 // Get the list of planes
2766 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2767 VERIFY(result == vk::Result::eSuccess);
2768
2769 if (plane_count == 0) {
2770 printf("Cannot find any plane!\n");
2771 fflush(stdout);
2772 exit(1);
2773 }
2774
2775 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2776 VERIFY(plane_props != nullptr);
2777
2778 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2779 VERIFY(result == vk::Result::eSuccess);
2780
2781 // Find a plane compatible with the display
2782 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2783 uint32_t supported_count;
2784 vk::DisplayKHR *supported_displays;
2785
2786 // Disqualify planes that are bound to a different display
2787 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2788 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002789 }
2790
Dave Houlton5fa47912018-02-16 11:02:26 -07002791 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002792 VERIFY(result == vk::Result::eSuccess);
2793
Dave Houlton5fa47912018-02-16 11:02:26 -07002794 if (supported_count == 0) {
2795 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002796 }
2797
Dave Houlton5fa47912018-02-16 11:02:26 -07002798 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2799 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002800
Dave Houlton5fa47912018-02-16 11:02:26 -07002801 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002802 VERIFY(result == vk::Result::eSuccess);
2803
Dave Houlton5fa47912018-02-16 11:02:26 -07002804 for (uint32_t i = 0; i < supported_count; i++) {
2805 if (supported_displays[i] == display) {
2806 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002807 break;
2808 }
2809 }
2810
Dave Houlton5fa47912018-02-16 11:02:26 -07002811 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002812
Dave Houlton5fa47912018-02-16 11:02:26 -07002813 if (found_plane) {
2814 break;
Damien Leone600c3052017-01-31 10:26:07 -07002815 }
2816 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002817
2818 if (!found_plane) {
2819 printf("Cannot find a plane compatible with the display!\n");
2820 fflush(stdout);
2821 exit(1);
2822 }
2823
2824 free(plane_props);
2825
2826 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2827 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2828 // Find a supported alpha mode
2829 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2830 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2831 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2832 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2833 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2834 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2835 };
2836 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2837 if (planeCaps.supportedAlpha & alphaModes[i]) {
2838 alphaMode = alphaModes[i];
2839 break;
2840 }
2841 }
2842
2843 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2844 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2845
2846 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2847 .setDisplayMode(mode_props.displayMode)
2848 .setPlaneIndex(plane_index)
2849 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2850 .setGlobalAlpha(1.0f)
2851 .setAlphaMode(alphaMode)
2852 .setImageExtent(image_extent);
2853
2854 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2855}
2856
2857void Demo::run_display() {
2858 while (!quit) {
2859 draw();
2860 curFrame++;
2861
Petr Krausd88e4e52019-01-23 18:45:04 +01002862 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002863 quit = true;
2864 }
2865 }
2866}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002867#endif
2868
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002869#if _WIN32
2870// Include header required for parsing the command line options.
2871#include <shellapi.h>
2872
2873Demo demo;
2874
2875// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002876LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2877 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002878 case WM_CLOSE:
2879 PostQuitMessage(validation_error);
2880 break;
2881 case WM_PAINT:
2882 demo.run();
2883 break;
2884 case WM_GETMINMAXINFO: // set window's minimum size
2885 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2886 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002887 case WM_ERASEBKGND:
2888 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002889 case WM_SIZE:
2890 // Resize the application to the new window size, except when
2891 // it was minimized. Vulkan doesn't support images or swapchains
2892 // with width=0 and height=0.
2893 if (wParam != SIZE_MINIMIZED) {
2894 demo.width = lParam & 0xffff;
2895 demo.height = (lParam & 0xffff0000) >> 16;
2896 demo.resize();
2897 }
2898 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002899 case WM_KEYDOWN:
2900 switch (wParam) {
2901 case VK_ESCAPE:
2902 PostQuitMessage(validation_error);
2903 break;
2904 case VK_LEFT:
2905 demo.spin_angle -= demo.spin_increment;
2906 break;
2907 case VK_RIGHT:
2908 demo.spin_angle += demo.spin_increment;
2909 break;
2910 case VK_SPACE:
2911 demo.pause = !demo.pause;
2912 break;
2913 }
2914 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002915 default:
2916 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002917 }
2918
2919 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2920}
2921
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002922int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002923 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002924 MSG msg; // message
2925 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002926 int argc;
2927 char **argv;
2928
Jamie Madillb2ff6502017-03-15 16:17:46 -04002929 // Ensure wParam is initialized.
2930 msg.wParam = 0;
2931
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002932 // Use the CommandLine functions to get the command line arguments.
2933 // Unfortunately, Microsoft outputs
2934 // this information as wide characters for Unicode, and we simply want the
2935 // Ascii version to be compatible
2936 // with the non-Windows side. So, we have to convert the information to
2937 // Ascii character strings.
2938 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002939 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002940 argc = 0;
2941 }
2942
Jeremy Hayes9d304782016-10-09 11:48:12 -06002943 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002944 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002945 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002946 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002947 } else {
2948 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002949 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2950 size_t numConverted = 0;
2951
2952 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002953 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002954 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002955 }
2956 }
2957 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002958 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002959 argv = nullptr;
2960 }
2961
2962 demo.init(argc, argv);
2963
2964 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002965 if (argc > 0 && argv != nullptr) {
2966 for (int iii = 0; iii < argc; iii++) {
2967 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002968 free(argv[iii]);
2969 }
2970 }
2971 free(argv);
2972 }
2973
2974 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07002975 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002976 demo.create_window();
2977 demo.init_vk_swapchain();
2978
2979 demo.prepare();
2980
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002981 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002982
2983 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002984 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01002985 if (demo.pause) {
2986 const BOOL succ = WaitMessage();
2987
2988 if (!succ) {
2989 const auto &suppress_popups = demo.suppress_popups;
2990 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2991 }
2992 }
2993
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002994 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002995 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002996 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002997 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002998 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002999 /* Translate and dispatch to event queue*/
3000 TranslateMessage(&msg);
3001 DispatchMessage(&msg);
3002 }
3003 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3004 }
3005
3006 demo.cleanup();
3007
3008 return (int)msg.wParam;
3009}
3010
3011#elif __linux__
3012
Jeremy Hayes9d304782016-10-09 11:48:12 -06003013int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003014 Demo demo;
3015
3016 demo.init(argc, argv);
3017
Tony Barbour153cb062016-12-07 13:43:36 -07003018#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003019 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003020#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003021 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003022 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003023#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003024 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003025#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003026
3027 demo.init_vk_swapchain();
3028
3029 demo.prepare();
3030
Tony Barbour153cb062016-12-07 13:43:36 -07003031#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003032 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003033#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003034 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003035#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003036 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003037#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3038 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003039#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003040
3041 demo.cleanup();
3042
3043 return validation_error;
3044}
3045
Karl Schultz9ceac062017-12-12 10:33:01 -05003046#elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3047
3048// Global function invoked from NS or UI views and controllers to create demo
Karl Schultz206b1c52018-04-13 18:02:07 -06003049static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003050 demo.init(argc, (char **)argv);
3051 demo.window = view;
3052 demo.init_vk_swapchain();
3053 demo.prepare();
3054 demo.spin_angle = 0.4f;
3055}
3056
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003057#else
3058#error "Platform not supported"
3059#endif