blob: ce594626cf1ad92208789c08d0a9181b6a55334c [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 */
Richard S. Wright Jra7825742021-01-06 16:02:12 -050020
Jeremy Hayesf56427a2016-09-07 15:55:11 -060021#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
37#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060038#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060039#include <vulkan/vulkan.hpp>
40#include <vulkan/vk_sdk_platform.h>
41
42#include "linmath.h"
43
44#ifndef NDEBUG
45#define VERIFY(x) assert(x)
46#else
47#define VERIFY(x) ((void)(x))
48#endif
49
Lenny Komowffe446c2018-11-19 17:08:04 -070050#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060051#ifdef _WIN32
52#define APP_NAME_STR_LEN 80
53#endif
54
55// Allow a maximum of two outstanding presentation operations.
56#define FRAME_LAG 2
57
58#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
59
60#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070061#define ERR_EXIT(err_msg, err_class) \
62 do { \
63 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
64 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060065 } while (0)
66#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070067#define ERR_EXIT(err_msg, err_class) \
68 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080069 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070070 fflush(stdout); \
71 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060072 } while (0)
73#endif
74
Jeremy Hayes9d304782016-10-09 11:48:12 -060075struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060076 vk::Sampler sampler;
77
78 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060079 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070080 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060081
82 vk::MemoryAllocateInfo mem_alloc;
83 vk::DeviceMemory mem;
84 vk::ImageView view;
85
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070086 int32_t tex_width{0};
87 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060088};
89
Jeremy Hayes9d304782016-10-09 11:48:12 -060090static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060091
92static int validation_error = 0;
93
94struct vkcube_vs_uniform {
95 // Must start with MVP
96 float mvp[4][4];
97 float position[12 * 3][4];
98 float color[12 * 3][4];
99};
100
101struct vktexcube_vs_uniform {
102 // Must start with MVP
103 float mvp[4][4];
104 float position[12 * 3][4];
105 float attr[12 * 3][4];
106};
107
108//--------------------------------------------------------------------------------------
109// Mesh and VertexFormat Data
110//--------------------------------------------------------------------------------------
111// clang-format off
112static const float g_vertex_buffer_data[] = {
113 -1.0f,-1.0f,-1.0f, // -X side
114 -1.0f,-1.0f, 1.0f,
115 -1.0f, 1.0f, 1.0f,
116 -1.0f, 1.0f, 1.0f,
117 -1.0f, 1.0f,-1.0f,
118 -1.0f,-1.0f,-1.0f,
119
120 -1.0f,-1.0f,-1.0f, // -Z side
121 1.0f, 1.0f,-1.0f,
122 1.0f,-1.0f,-1.0f,
123 -1.0f,-1.0f,-1.0f,
124 -1.0f, 1.0f,-1.0f,
125 1.0f, 1.0f,-1.0f,
126
127 -1.0f,-1.0f,-1.0f, // -Y side
128 1.0f,-1.0f,-1.0f,
129 1.0f,-1.0f, 1.0f,
130 -1.0f,-1.0f,-1.0f,
131 1.0f,-1.0f, 1.0f,
132 -1.0f,-1.0f, 1.0f,
133
134 -1.0f, 1.0f,-1.0f, // +Y side
135 -1.0f, 1.0f, 1.0f,
136 1.0f, 1.0f, 1.0f,
137 -1.0f, 1.0f,-1.0f,
138 1.0f, 1.0f, 1.0f,
139 1.0f, 1.0f,-1.0f,
140
141 1.0f, 1.0f,-1.0f, // +X side
142 1.0f, 1.0f, 1.0f,
143 1.0f,-1.0f, 1.0f,
144 1.0f,-1.0f, 1.0f,
145 1.0f,-1.0f,-1.0f,
146 1.0f, 1.0f,-1.0f,
147
148 -1.0f, 1.0f, 1.0f, // +Z side
149 -1.0f,-1.0f, 1.0f,
150 1.0f, 1.0f, 1.0f,
151 -1.0f,-1.0f, 1.0f,
152 1.0f,-1.0f, 1.0f,
153 1.0f, 1.0f, 1.0f,
154};
155
156static const float g_uv_buffer_data[] = {
157 0.0f, 1.0f, // -X side
158 1.0f, 1.0f,
159 1.0f, 0.0f,
160 1.0f, 0.0f,
161 0.0f, 0.0f,
162 0.0f, 1.0f,
163
164 1.0f, 1.0f, // -Z side
165 0.0f, 0.0f,
166 0.0f, 1.0f,
167 1.0f, 1.0f,
168 1.0f, 0.0f,
169 0.0f, 0.0f,
170
171 1.0f, 0.0f, // -Y side
172 1.0f, 1.0f,
173 0.0f, 1.0f,
174 1.0f, 0.0f,
175 0.0f, 1.0f,
176 0.0f, 0.0f,
177
178 1.0f, 0.0f, // +Y side
179 0.0f, 0.0f,
180 0.0f, 1.0f,
181 1.0f, 0.0f,
182 0.0f, 1.0f,
183 1.0f, 1.0f,
184
185 1.0f, 0.0f, // +X side
186 0.0f, 0.0f,
187 0.0f, 1.0f,
188 0.0f, 1.0f,
189 1.0f, 1.0f,
190 1.0f, 0.0f,
191
192 0.0f, 0.0f, // +Z side
193 0.0f, 1.0f,
194 1.0f, 0.0f,
195 0.0f, 1.0f,
196 1.0f, 1.0f,
197 1.0f, 0.0f,
198};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600199// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600200
Jeremy Hayes9d304782016-10-09 11:48:12 -0600201typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600202 vk::Image image;
203 vk::CommandBuffer cmd;
204 vk::CommandBuffer graphics_to_present_cmd;
205 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600206 vk::Buffer uniform_buffer;
207 vk::DeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700208 void *uniform_memory_ptr;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600209 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();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200266#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
267 void handle_directfb_event(const DFBInputEvent *);
268 void run_directfb();
269 void create_directfb_window();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400270#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600271 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600272#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
273 vk::Result create_display_surface();
274 void run_display();
275#endif
276
277#if defined(VK_USE_PLATFORM_WIN32_KHR)
278 HINSTANCE connection; // hInstance - Windows Instance
279 HWND window; // hWnd - window handle
280 POINT minsize; // minimum window size
281 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
282#elif defined(VK_USE_PLATFORM_XLIB_KHR)
283 Window xlib_window;
284 Atom xlib_wm_delete_window;
285 Display *display;
286#elif defined(VK_USE_PLATFORM_XCB_KHR)
287 xcb_window_t xcb_window;
288 xcb_screen_t *screen;
289 xcb_connection_t *connection;
290 xcb_intern_atom_reply_t *atom_wm_delete_window;
291#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
292 wl_display *display;
293 wl_registry *registry;
294 wl_compositor *compositor;
295 wl_surface *window;
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700296 wl_shell *shell;
297 wl_shell_surface *shell_surface;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600298 wl_seat *seat;
299 wl_pointer *pointer;
300 wl_keyboard *keyboard;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200301#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
302 IDirectFB *dfb;
303 IDirectFBSurface *window;
304 IDirectFBEventBuffer *event_buffer;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400305#elif defined(VK_USE_PLATFORM_METAL_EXT)
306 void *caMetalLayer;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600307#endif
308
309 vk::SurfaceKHR surface;
310 bool prepared;
311 bool use_staging_buffer;
312 bool use_xlib;
313 bool separate_present_queue;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000314 int32_t gpu_number;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600315
316 vk::Instance inst;
317 vk::PhysicalDevice gpu;
318 vk::Device device;
319 vk::Queue graphics_queue;
320 vk::Queue present_queue;
321 uint32_t graphics_queue_family_index;
322 uint32_t present_queue_family_index;
323 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
324 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
325 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
326 vk::PhysicalDeviceProperties gpu_props;
327 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
328 vk::PhysicalDeviceMemoryProperties memory_properties;
329
330 uint32_t enabled_extension_count;
331 uint32_t enabled_layer_count;
332 char const *extension_names[64];
333 char const *enabled_layers[64];
334
335 uint32_t width;
336 uint32_t height;
337 vk::Format format;
338 vk::ColorSpaceKHR color_space;
339
340 uint32_t swapchainImageCount;
341 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600342 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600343 vk::PresentModeKHR presentMode;
344 vk::Fence fences[FRAME_LAG];
345 uint32_t frame_index;
346
347 vk::CommandPool cmd_pool;
348 vk::CommandPool present_cmd_pool;
349
350 struct {
351 vk::Format format;
352 vk::Image image;
353 vk::MemoryAllocateInfo mem_alloc;
354 vk::DeviceMemory mem;
355 vk::ImageView view;
356 } depth;
357
358 static int32_t const texture_count = 1;
359 texture_object textures[texture_count];
360 texture_object staging_texture;
361
362 struct {
363 vk::Buffer buf;
364 vk::MemoryAllocateInfo mem_alloc;
365 vk::DeviceMemory mem;
366 vk::DescriptorBufferInfo buffer_info;
367 } uniform_data;
368
369 vk::CommandBuffer cmd; // Buffer for initialization commands
370 vk::PipelineLayout pipeline_layout;
371 vk::DescriptorSetLayout desc_layout;
372 vk::PipelineCache pipelineCache;
373 vk::RenderPass render_pass;
374 vk::Pipeline pipeline;
375
376 mat4x4 projection_matrix;
377 mat4x4 view_matrix;
378 mat4x4 model_matrix;
379
380 float spin_angle;
381 float spin_increment;
382 bool pause;
383
384 vk::ShaderModule vert_shader_module;
385 vk::ShaderModule frag_shader_module;
386
387 vk::DescriptorPool desc_pool;
388 vk::DescriptorSet desc_set;
389
390 std::unique_ptr<vk::Framebuffer[]> framebuffers;
391
392 bool quit;
393 uint32_t curFrame;
394 uint32_t frameCount;
395 bool validate;
396 bool use_break;
397 bool suppress_popups;
398
399 uint32_t current_buffer;
400 uint32_t queue_family_count;
401};
402
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600403#ifdef _WIN32
404// MS-Windows event handling function:
405LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
406#endif
407
Karl Schultz23cc2182016-11-23 17:15:17 -0700408#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700409static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700410 wl_shell_surface_pong(shell_surface, serial);
411}
412
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700413static 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 -0700414
415static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
416
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700417static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700418
Joey Bzdek15eb0702017-06-07 09:40:36 -0600419static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
420 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700421
Joey Bzdek15eb0702017-06-07 09:40:36 -0600422static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700423
Joey Bzdek15eb0702017-06-07 09:40:36 -0600424static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
425
426static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
427 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600428 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600429 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700430 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600431 }
432}
433
434static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
435
436static const struct wl_pointer_listener pointer_listener = {
437 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
438};
439
440static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
441
442static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
443 struct wl_array *keys) {}
444
445static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
446
447static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
448 uint32_t state) {
449 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
450 Demo *demo = (Demo *)data;
451 switch (key) {
452 case KEY_ESC: // Escape
453 demo->quit = true;
454 break;
455 case KEY_LEFT: // left arrow key
456 demo->spin_angle -= demo->spin_increment;
457 break;
458 case KEY_RIGHT: // right arrow key
459 demo->spin_angle += demo->spin_increment;
460 break;
461 case KEY_SPACE: // space bar
462 demo->pause = !demo->pause;
463 break;
464 }
465}
466
467static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
468 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
469
470static const struct wl_keyboard_listener keyboard_listener = {
471 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
472};
473
474static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
475 // Subscribe to pointer events
476 Demo *demo = (Demo *)data;
477 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
478 demo->pointer = wl_seat_get_pointer(seat);
479 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
480 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
481 wl_pointer_destroy(demo->pointer);
482 demo->pointer = NULL;
483 }
484 // Subscribe to keyboard events
485 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
486 demo->keyboard = wl_seat_get_keyboard(seat);
487 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
488 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
489 wl_keyboard_destroy(demo->keyboard);
490 demo->keyboard = NULL;
491 }
492}
493
494static const wl_seat_listener seat_listener = {
495 seat_handle_capabilities,
496};
497
498static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
499 Demo *demo = (Demo *)data;
500 // pickup wayland objects when they appear
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700501 if (strcmp(interface, "wl_compositor") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600502 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700503 } else if (strcmp(interface, "wl_shell") == 0) {
504 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
505 } else if (strcmp(interface, "wl_seat") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600506 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
507 wl_seat_add_listener(demo->seat, &seat_listener, demo);
508 }
509}
510
511static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
512
513static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700514#endif
515
Joey Bzdekbaf66472017-06-07 09:37:37 -0600516Demo::Demo()
517 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600518#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600519 connection{nullptr},
520 window{nullptr},
521 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600522#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700523
Tony Barbour78d6b572016-11-14 14:46:33 -0700524#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600525 xlib_window{0},
526 xlib_wm_delete_window{0},
527 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700528#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600529 xcb_window{0},
530 screen{nullptr},
531 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700532#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600533 display{nullptr},
534 registry{nullptr},
535 compositor{nullptr},
536 window{nullptr},
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700537 shell{nullptr},
538 shell_surface{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600539 seat{nullptr},
540 pointer{nullptr},
541 keyboard{nullptr},
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200542#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
543 dfb{nullptr},
544 window{nullptr},
545 event_buffer{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700546#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600547 prepared{false},
548 use_staging_buffer{false},
549 use_xlib{false},
550 graphics_queue_family_index{0},
551 present_queue_family_index{0},
552 enabled_extension_count{0},
553 enabled_layer_count{0},
554 width{0},
555 height{0},
556 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000557 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600558 frame_index{0},
559 spin_angle{0.0f},
560 spin_increment{0.0f},
561 pause{false},
562 quit{false},
563 curFrame{0},
564 frameCount{0},
565 validate{false},
566 use_break{false},
567 suppress_popups{false},
568 current_buffer{0},
569 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600570#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700571 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600572#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700573 memset(projection_matrix, 0, sizeof(projection_matrix));
574 memset(view_matrix, 0, sizeof(view_matrix));
575 memset(model_matrix, 0, sizeof(model_matrix));
576}
577
578void Demo::build_image_ownership_cmd(uint32_t const &i) {
579 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
580 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
581 VERIFY(result == vk::Result::eSuccess);
582
583 auto const image_ownership_barrier =
584 vk::ImageMemoryBarrier()
585 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600586 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700587 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
588 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
589 .setSrcQueueFamilyIndex(graphics_queue_family_index)
590 .setDstQueueFamilyIndex(present_queue_family_index)
591 .setImage(swapchain_image_resources[i].image)
592 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
593
594 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600595 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
596 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700597
598 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
599 VERIFY(result == vk::Result::eSuccess);
600}
601
602vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
603 vk::LayerProperties *layers) {
604 for (uint32_t i = 0; i < check_count; i++) {
605 vk::Bool32 found = VK_FALSE;
606 for (uint32_t j = 0; j < layer_count; j++) {
607 if (!strcmp(check_names[i], layers[j].layerName)) {
608 found = VK_TRUE;
609 break;
610 }
611 }
612 if (!found) {
613 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
614 return 0;
615 }
616 }
617 return VK_TRUE;
618}
619
620void Demo::cleanup() {
621 prepared = false;
622 device.waitIdle();
623
624 // Wait for fences from present operations
625 for (uint32_t i = 0; i < FRAME_LAG; i++) {
626 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
627 device.destroyFence(fences[i], nullptr);
628 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
629 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
630 if (separate_present_queue) {
631 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
632 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600633 }
634
Dave Houlton5fa47912018-02-16 11:02:26 -0700635 for (uint32_t i = 0; i < swapchainImageCount; i++) {
636 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
637 }
638 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600639
Dave Houlton5fa47912018-02-16 11:02:26 -0700640 device.destroyPipeline(pipeline, nullptr);
641 device.destroyPipelineCache(pipelineCache, nullptr);
642 device.destroyRenderPass(render_pass, nullptr);
643 device.destroyPipelineLayout(pipeline_layout, nullptr);
644 device.destroyDescriptorSetLayout(desc_layout, nullptr);
645
646 for (uint32_t i = 0; i < texture_count; i++) {
647 device.destroyImageView(textures[i].view, nullptr);
648 device.destroyImage(textures[i].image, nullptr);
649 device.freeMemory(textures[i].mem, nullptr);
650 device.destroySampler(textures[i].sampler, nullptr);
651 }
652 device.destroySwapchainKHR(swapchain, nullptr);
653
654 device.destroyImageView(depth.view, nullptr);
655 device.destroyImage(depth.image, nullptr);
656 device.freeMemory(depth.mem, nullptr);
657
658 for (uint32_t i = 0; i < swapchainImageCount; i++) {
659 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700660 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700661 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700662 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700663 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
664 }
665
666 device.destroyCommandPool(cmd_pool, nullptr);
667
668 if (separate_present_queue) {
669 device.destroyCommandPool(present_cmd_pool, nullptr);
670 }
671 device.waitIdle();
672 device.destroy(nullptr);
673 inst.destroySurfaceKHR(surface, nullptr);
674
675#if defined(VK_USE_PLATFORM_XLIB_KHR)
676 XDestroyWindow(display, xlib_window);
677 XCloseDisplay(display);
678#elif defined(VK_USE_PLATFORM_XCB_KHR)
679 xcb_destroy_window(connection, xcb_window);
680 xcb_disconnect(connection);
681 free(atom_wm_delete_window);
682#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
683 wl_keyboard_destroy(keyboard);
684 wl_pointer_destroy(pointer);
685 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700686 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700687 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700688 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700689 wl_compositor_destroy(compositor);
690 wl_registry_destroy(registry);
691 wl_display_disconnect(display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200692#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
693 event_buffer->Release(event_buffer);
694 window->Release(window);
695 dfb->Release(dfb);
Dave Houlton5fa47912018-02-16 11:02:26 -0700696#endif
697
698 inst.destroy(nullptr);
699}
700
701void Demo::create_device() {
702 float const priorities[1] = {0.0};
703
704 vk::DeviceQueueCreateInfo queues[2];
705 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
706 queues[0].setQueueCount(1);
707 queues[0].setPQueuePriorities(priorities);
708
709 auto deviceInfo = vk::DeviceCreateInfo()
710 .setQueueCreateInfoCount(1)
711 .setPQueueCreateInfos(queues)
712 .setEnabledLayerCount(0)
713 .setPpEnabledLayerNames(nullptr)
714 .setEnabledExtensionCount(enabled_extension_count)
715 .setPpEnabledExtensionNames((const char *const *)extension_names)
716 .setPEnabledFeatures(nullptr);
717
718 if (separate_present_queue) {
719 queues[1].setQueueFamilyIndex(present_queue_family_index);
720 queues[1].setQueueCount(1);
721 queues[1].setPQueuePriorities(priorities);
722 deviceInfo.setQueueCreateInfoCount(2);
723 }
724
725 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
726 VERIFY(result == vk::Result::eSuccess);
727}
728
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600729void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700730 // clean up staging resources
731 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600732 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
733 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700734}
735
736void Demo::draw() {
737 // Ensure no more than FRAME_LAG renderings are outstanding
738 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700739 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700740
741 vk::Result result;
742 do {
743 result =
744 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
745 if (result == vk::Result::eErrorOutOfDateKHR) {
746 // demo->swapchain is out of date (e.g. the window was resized) and
747 // must be recreated:
748 resize();
749 } else if (result == vk::Result::eSuboptimalKHR) {
750 // swapchain is not as optimal as it could be, but the platform's
751 // presentation engine will still present the image correctly.
752 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600753 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
754 inst.destroySurfaceKHR(surface, nullptr);
755 create_surface();
756 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700757 } else {
758 VERIFY(result == vk::Result::eSuccess);
759 }
760 } while (result != vk::Result::eSuccess);
761
762 update_data_buffer();
763
764 // Wait for the image acquired semaphore to be signaled to ensure
765 // that the image won't be rendered to until the presentation
766 // engine has fully released ownership to the application, and it is
767 // okay to render to the image.
768 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
769 auto const submit_info = vk::SubmitInfo()
770 .setPWaitDstStageMask(&pipe_stage_flags)
771 .setWaitSemaphoreCount(1)
772 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
773 .setCommandBufferCount(1)
774 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
775 .setSignalSemaphoreCount(1)
776 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
777
778 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
779 VERIFY(result == vk::Result::eSuccess);
780
781 if (separate_present_queue) {
782 // If we are using separate queues, change image ownership to the
783 // present queue before presenting, waiting for the draw complete
784 // semaphore and signalling the ownership released semaphore when
785 // finished
786 auto const present_submit_info = vk::SubmitInfo()
787 .setPWaitDstStageMask(&pipe_stage_flags)
788 .setWaitSemaphoreCount(1)
789 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
790 .setCommandBufferCount(1)
791 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
792 .setSignalSemaphoreCount(1)
793 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
794
795 result = present_queue.submit(1, &present_submit_info, vk::Fence());
796 VERIFY(result == vk::Result::eSuccess);
797 }
798
799 // If we are using separate queues we have to wait for image ownership,
800 // otherwise wait for draw complete
801 auto const presentInfo = vk::PresentInfoKHR()
802 .setWaitSemaphoreCount(1)
803 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
804 : &draw_complete_semaphores[frame_index])
805 .setSwapchainCount(1)
806 .setPSwapchains(&swapchain)
807 .setPImageIndices(&current_buffer);
808
809 result = present_queue.presentKHR(&presentInfo);
810 frame_index += 1;
811 frame_index %= FRAME_LAG;
812 if (result == vk::Result::eErrorOutOfDateKHR) {
813 // swapchain is out of date (e.g. the window was resized) and
814 // must be recreated:
815 resize();
816 } else if (result == vk::Result::eSuboptimalKHR) {
817 // swapchain is not as optimal as it could be, but the platform's
818 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600819 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
820 inst.destroySurfaceKHR(surface, nullptr);
821 create_surface();
822 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700823 } else {
824 VERIFY(result == vk::Result::eSuccess);
825 }
826}
827
828void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
829 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
830
831 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
832 vk::ClearDepthStencilValue(1.0f, 0u)};
833
834 auto const passInfo = vk::RenderPassBeginInfo()
835 .setRenderPass(render_pass)
836 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
837 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
838 .setClearValueCount(2)
839 .setPClearValues(clearValues);
840
841 auto result = commandBuffer.begin(&commandInfo);
842 VERIFY(result == vk::Result::eSuccess);
843
844 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
845 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
846 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
847 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700848 float viewport_dimension;
849 float viewport_x = 0.0f;
850 float viewport_y = 0.0f;
851 if (width < height) {
852 viewport_dimension = (float)width;
853 viewport_y = (height - width) / 2.0f;
854 } else {
855 viewport_dimension = (float)height;
856 viewport_x = (width - height) / 2.0f;
857 }
858 auto const viewport = vk::Viewport()
859 .setX(viewport_x)
860 .setY(viewport_y)
861 .setWidth((float)viewport_dimension)
862 .setHeight((float)viewport_dimension)
863 .setMinDepth((float)0.0f)
864 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700865 commandBuffer.setViewport(0, 1, &viewport);
866
867 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
868 commandBuffer.setScissor(0, 1, &scissor);
869 commandBuffer.draw(12 * 3, 1, 0, 0);
870 // Note that ending the renderpass changes the image's layout from
871 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
872 commandBuffer.endRenderPass();
873
874 if (separate_present_queue) {
875 // We have to transfer ownership from the graphics queue family to
876 // the
877 // present queue family to be able to present. Note that we don't
878 // have
879 // to transfer from present queue family back to graphics queue
880 // family at
881 // the start of the next frame because we don't care about the
882 // image's
883 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600884 auto const image_ownership_barrier =
885 vk::ImageMemoryBarrier()
886 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600887 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600888 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
889 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
890 .setSrcQueueFamilyIndex(graphics_queue_family_index)
891 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700892 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700893 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600894
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600895 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700896 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600897 }
898
Dave Houlton5fa47912018-02-16 11:02:26 -0700899 result = commandBuffer.end();
900 VERIFY(result == vk::Result::eSuccess);
901}
902
903void Demo::flush_init_cmd() {
904 // TODO: hmm.
905 // This function could get called twice if the texture uses a staging
906 // buffer
907 // In that case the second call should be ignored
908 if (!cmd) {
909 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600910 }
911
Dave Houlton5fa47912018-02-16 11:02:26 -0700912 auto result = cmd.end();
913 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600914
Dave Houlton5fa47912018-02-16 11:02:26 -0700915 auto const fenceInfo = vk::FenceCreateInfo();
916 vk::Fence fence;
917 result = device.createFence(&fenceInfo, nullptr, &fence);
918 VERIFY(result == vk::Result::eSuccess);
919
920 vk::CommandBuffer const commandBuffers[] = {cmd};
921 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
922
923 result = graphics_queue.submit(1, &submitInfo, fence);
924 VERIFY(result == vk::Result::eSuccess);
925
926 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
927 VERIFY(result == vk::Result::eSuccess);
928
929 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
930 device.destroyFence(fence, nullptr);
931
932 cmd = vk::CommandBuffer();
933}
934
935void Demo::init(int argc, char **argv) {
936 vec3 eye = {0.0f, 3.0f, 5.0f};
937 vec3 origin = {0, 0, 0};
938 vec3 up = {0.0f, 1.0f, 0.0};
939
940 presentMode = vk::PresentModeKHR::eFifo;
941 frameCount = UINT32_MAX;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100942 width = 500;
943 height = 500;
Dave Houlton5fa47912018-02-16 11:02:26 -0700944 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000945 /* Autodetect suitable / best GPU by default */
946 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600947
Dave Houlton5fa47912018-02-16 11:02:26 -0700948 for (int i = 1; i < argc; i++) {
949 if (strcmp(argv[i], "--use_staging") == 0) {
950 use_staging_buffer = true;
951 continue;
952 }
953 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
954 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
955 i++;
956 continue;
957 }
958 if (strcmp(argv[i], "--break") == 0) {
959 use_break = true;
960 continue;
961 }
962 if (strcmp(argv[i], "--validate") == 0) {
963 validate = true;
964 continue;
965 }
966 if (strcmp(argv[i], "--xlib") == 0) {
967 fprintf(stderr, "--xlib is deprecated and no longer does anything");
968 continue;
969 }
970 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
971 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
972 i++;
973 continue;
974 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100975 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &width) == 1 && width > 0) {
976 i++;
977 continue;
978 }
979 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &height) == 1 && height > 0) {
980 i++;
981 continue;
982 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700983 if (strcmp(argv[i], "--suppress_popups") == 0) {
984 suppress_popups = true;
985 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600986 }
Tony-LunarG50e737c2020-07-16 14:26:03 -0600987 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
988 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +0000989 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -0600990 i++;
991 continue;
992 }
Tony-LunarGd74734f2019-06-04 14:11:43 -0600993 std::stringstream usage;
994 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
995 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -0600996 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600997 << "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100998 << "\t[--width <width>] [--height <height>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600999 << "\t<present_mode_enum>\n"
1000 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
1001 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
1002 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +00001003 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -06001004
1005#if defined(_WIN32)
1006 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
1007#else
1008 std::cerr << usage.str();
1009 std::cerr.flush();
1010#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001011 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001012 }
1013
Dave Houlton5fa47912018-02-16 11:02:26 -07001014 if (!use_xlib) {
1015 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001016 }
1017
Dave Houlton5fa47912018-02-16 11:02:26 -07001018 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001019
Dave Houlton5fa47912018-02-16 11:02:26 -07001020 spin_angle = 4.0f;
1021 spin_increment = 0.2f;
1022 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001023
Dave Houlton5fa47912018-02-16 11:02:26 -07001024 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1025 mat4x4_look_at(view_matrix, eye, origin, up);
1026 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001027
Dave Houlton5fa47912018-02-16 11:02:26 -07001028 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1029}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001030
Dave Houlton5fa47912018-02-16 11:02:26 -07001031void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001032#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001033 const xcb_setup_t *setup;
1034 xcb_screen_iterator_t iter;
1035 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001036
Dave Houlton5fa47912018-02-16 11:02:26 -07001037 const char *display_envar = getenv("DISPLAY");
1038 if (display_envar == nullptr || display_envar[0] == '\0') {
1039 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1040 fflush(stdout);
1041 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001042 }
1043
Dave Houlton5fa47912018-02-16 11:02:26 -07001044 connection = xcb_connect(nullptr, &scr);
1045 if (xcb_connection_has_error(connection) > 0) {
1046 printf(
1047 "Cannot find a compatible Vulkan installable client driver "
1048 "(ICD).\nExiting ...\n");
1049 fflush(stdout);
1050 exit(1);
1051 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001052
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 setup = xcb_get_setup(connection);
1054 iter = xcb_setup_roots_iterator(setup);
1055 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001056
Dave Houlton5fa47912018-02-16 11:02:26 -07001057 screen = iter.data;
1058#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1059 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001060
Dave Houlton5fa47912018-02-16 11:02:26 -07001061 if (display == nullptr) {
1062 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1063 fflush(stdout);
1064 exit(1);
1065 }
1066
1067 registry = wl_display_get_registry(display);
1068 wl_registry_add_listener(registry, &registry_listener, this);
1069 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001070#endif
1071}
Tony-LunarG27c21242021-03-11 16:28:19 -07001072#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1073int find_display_gpu(int gpu_number, uint32_t gpu_count, std::unique_ptr<vk::PhysicalDevice[]> &physical_devices) {
1074 uint32_t display_count = 0;
1075 vk::Result result;
1076 int gpu_return = gpu_number;
1077 if (gpu_number >= 0) {
1078 result = physical_devices[gpu_number].getDisplayPropertiesKHR(&display_count, nullptr);
1079 VERIFY(result == vk::Result::eSuccess);
1080 } else {
1081 for (uint32_t i = 0; i < gpu_count; i++) {
1082 result = physical_devices[i].getDisplayPropertiesKHR(&display_count, nullptr);
1083 VERIFY(result == vk::Result::eSuccess);
1084 if (display_count) {
1085 gpu_return = i;
1086 break;
1087 }
1088 }
1089 }
1090 if (display_count > 0)
1091 return gpu_return;
1092 else
1093 return -1;
1094}
1095#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001096void Demo::init_vk() {
1097 uint32_t instance_extension_count = 0;
1098 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001099 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001100 enabled_extension_count = 0;
1101 enabled_layer_count = 0;
1102
Dave Houlton5fa47912018-02-16 11:02:26 -07001103 // Look for validation layers
1104 vk::Bool32 validation_found = VK_FALSE;
1105 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001106 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001107 VERIFY(result == vk::Result::eSuccess);
1108
Dave Houlton5fa47912018-02-16 11:02:26 -07001109 if (instance_layer_count > 0) {
1110 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1111 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001112 VERIFY(result == vk::Result::eSuccess);
1113
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001114 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001115 instance_layer_count, instance_layers.get());
1116 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001117 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1118 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001119 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001120 }
1121
Dave Houlton5fa47912018-02-16 11:02:26 -07001122 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001123 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001124 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1125 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001126 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001127 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001128 }
1129
Dave Houlton5fa47912018-02-16 11:02:26 -07001130 /* Look for instance extensions */
1131 vk::Bool32 surfaceExtFound = VK_FALSE;
1132 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1133 memset(extension_names, 0, sizeof(extension_names));
1134
Mike Schuchardt7510c832018-10-29 13:23:08 -07001135 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1136 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001137 VERIFY(result == vk::Result::eSuccess);
1138
1139 if (instance_extension_count > 0) {
1140 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1141 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1142 VERIFY(result == vk::Result::eSuccess);
1143
1144 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001145 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1146 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1147 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001148 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1149 surfaceExtFound = 1;
1150 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1151 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001152#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001153 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1154 platformSurfaceExtFound = 1;
1155 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1156 }
1157#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1158 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1159 platformSurfaceExtFound = 1;
1160 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1161 }
1162#elif defined(VK_USE_PLATFORM_XCB_KHR)
1163 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1164 platformSurfaceExtFound = 1;
1165 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1166 }
Tony Barbour153cb062016-12-07 13:43:36 -07001167#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001168 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1169 platformSurfaceExtFound = 1;
1170 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1171 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001172#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1173 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1174 platformSurfaceExtFound = 1;
1175 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1176 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001177#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1178 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1179 platformSurfaceExtFound = 1;
1180 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1181 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001182#elif defined(VK_USE_PLATFORM_METAL_EXT)
1183 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001184 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001185 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001186 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001187#endif
1188 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001189 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001190 }
1191
1192 if (!surfaceExtFound) {
1193 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1194 " extension.\n\n"
1195 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1196 "Please look at the Getting Started guide for additional information.\n",
1197 "vkCreateInstance Failure");
1198 }
1199
1200 if (!platformSurfaceExtFound) {
1201#if defined(VK_USE_PLATFORM_WIN32_KHR)
1202 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1203 " extension.\n\n"
1204 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1205 "Please look at the Getting Started guide for additional information.\n",
1206 "vkCreateInstance Failure");
1207#elif defined(VK_USE_PLATFORM_XCB_KHR)
1208 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1209 " extension.\n\n"
1210 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1211 "Please look at the Getting Started guide for additional information.\n",
1212 "vkCreateInstance Failure");
1213#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1214 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1215 " extension.\n\n"
1216 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1217 "Please look at the Getting Started guide for additional information.\n",
1218 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001219#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001220 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1221 " extension.\n\n"
1222 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1223 "Please look at the Getting Started guide for additional information.\n",
1224 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001225#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1226 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1227 " extension.\n\n"
1228 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1229 "Please look at the Getting Started guide for additional information.\n",
1230 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001231#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001232 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1233 " extension.\n\n"
1234 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1235 "Please look at the Getting Started guide for additional information.\n",
1236 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001237#elif defined(VK_USE_PLATFORM_METAL_EXT)
1238 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001239 " extension.\n\nDo you have a compatible "
1240 "Vulkan installable client driver (ICD) installed?\nPlease "
1241 "look at the Getting Started guide for additional "
1242 "information.\n",
1243 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001244#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001245 }
1246 auto const app = vk::ApplicationInfo()
1247 .setPApplicationName(APP_SHORT_NAME)
1248 .setApplicationVersion(0)
1249 .setPEngineName(APP_SHORT_NAME)
1250 .setEngineVersion(0)
1251 .setApiVersion(VK_API_VERSION_1_0);
1252 auto const inst_info = vk::InstanceCreateInfo()
1253 .setPApplicationInfo(&app)
1254 .setEnabledLayerCount(enabled_layer_count)
1255 .setPpEnabledLayerNames(instance_validation_layers)
1256 .setEnabledExtensionCount(enabled_extension_count)
1257 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001258
Dave Houlton5fa47912018-02-16 11:02:26 -07001259 result = vk::createInstance(&inst_info, nullptr, &inst);
1260 if (result == vk::Result::eErrorIncompatibleDriver) {
1261 ERR_EXIT(
1262 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1263 "Please look at the Getting Started guide for additional information.\n",
1264 "vkCreateInstance Failure");
1265 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1266 ERR_EXIT(
1267 "Cannot find a specified extension library.\n"
1268 "Make sure your layers path is set appropriately.\n",
1269 "vkCreateInstance Failure");
1270 } else if (result != vk::Result::eSuccess) {
1271 ERR_EXIT(
1272 "vkCreateInstance failed.\n\n"
1273 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1274 "Please look at the Getting Started guide for additional information.\n",
1275 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001276 }
1277
Witold Baryluka3b988f2021-01-07 19:03:02 +00001278 /* Make initial call to query gpu_count, then second call for gpu info */
1279 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001280 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001281 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001282
Witold Baryluka3b988f2021-01-07 19:03:02 +00001283 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001284 ERR_EXIT(
1285 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1286 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1287 "Please look at the Getting Started guide for additional information.\n",
1288 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001289 }
1290
Witold Baryluka3b988f2021-01-07 19:03:02 +00001291 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1292 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1293 VERIFY(result == vk::Result::eSuccess);
1294
1295 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1296 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1297 ERR_EXIT("Specified GPU number is not present", "User Error");
1298 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001299#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1300 gpu_number = find_display_gpu(gpu_number, gpu_count, physical_devices);
1301 if (gpu_number < 0) {
1302 printf("Cannot find any display!\n");
1303 fflush(stdout);
1304 exit(1);
1305 }
1306#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00001307 /* Try to auto select most suitable device */
1308 if (gpu_number == -1) {
1309 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1310 memset(count_device_type, 0, sizeof(count_device_type));
1311
1312 for (uint32_t i = 0; i < gpu_count; i++) {
1313 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1314 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1315 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1316 }
1317
1318 const vk::PhysicalDeviceType device_type_preference[] = {
1319 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1320 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1321 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1322 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1323 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1324 search_for_device_type = device_type_preference[i];
1325 break;
1326 }
1327 }
1328
1329 for (uint32_t i = 0; i < gpu_count; i++) {
1330 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1331 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1332 gpu_number = i;
1333 break;
1334 }
1335 }
1336 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001337#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00001338 assert(gpu_number >= 0);
1339 gpu = physical_devices[gpu_number];
1340 {
1341 auto physicalDeviceProperties = gpu.getProperties();
1342 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1343 to_string(physicalDeviceProperties.deviceType).c_str());
1344 }
1345 physical_devices.reset();
1346
Dave Houlton5fa47912018-02-16 11:02:26 -07001347 /* Look for device extensions */
1348 uint32_t device_extension_count = 0;
1349 vk::Bool32 swapchainExtFound = VK_FALSE;
1350 enabled_extension_count = 0;
1351 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001352
Mike Schuchardt7510c832018-10-29 13:23:08 -07001353 result =
1354 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001355 VERIFY(result == vk::Result::eSuccess);
1356
1357 if (device_extension_count > 0) {
1358 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1359 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001360 VERIFY(result == vk::Result::eSuccess);
1361
Dave Houlton5fa47912018-02-16 11:02:26 -07001362 for (uint32_t i = 0; i < device_extension_count; i++) {
1363 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1364 swapchainExtFound = 1;
1365 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001366 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001367 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1368 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001369 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001370 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001371 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001372 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001373
Dave Houlton5fa47912018-02-16 11:02:26 -07001374 if (!swapchainExtFound) {
1375 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1376 " extension.\n\n"
1377 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1378 "Please look at the Getting Started guide for additional information.\n",
1379 "vkCreateInstance Failure");
1380 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001381
Dave Houlton5fa47912018-02-16 11:02:26 -07001382 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001385 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001386 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001387
Dave Houlton5fa47912018-02-16 11:02:26 -07001388 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1389 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001390
Dave Houlton5fa47912018-02-16 11:02:26 -07001391 // Query fine-grained feature support for this device.
1392 // If app has specific feature requirements it should check supported
1393 // features based on this query
1394 vk::PhysicalDeviceFeatures physDevFeatures;
1395 gpu.getFeatures(&physDevFeatures);
1396}
1397
Tony-LunarG6cebf142019-09-11 14:32:23 -06001398void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001399// Create a WSI surface for the window:
1400#if defined(VK_USE_PLATFORM_WIN32_KHR)
1401 {
1402 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1403
1404 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1405 VERIFY(result == vk::Result::eSuccess);
1406 }
1407#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1408 {
1409 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1410
1411 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1412 VERIFY(result == vk::Result::eSuccess);
1413 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001414#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1415 {
1416 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1417
1418 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1419 VERIFY(result == vk::Result::eSuccess);
1420 }
1421#elif defined(VK_USE_PLATFORM_XCB_KHR)
1422 {
1423 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1424
1425 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1426 VERIFY(result == vk::Result::eSuccess);
1427 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001428#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1429 {
1430 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1431
1432 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1433 VERIFY(result == vk::Result::eSuccess);
1434 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001435#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001436 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001437 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001438
Bill Hollings0a0625a2019-07-15 17:39:18 -04001439 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001440 VERIFY(result == vk::Result::eSuccess);
1441 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001442#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1443 {
1444 auto result = create_display_surface();
1445 VERIFY(result == vk::Result::eSuccess);
1446 }
1447#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001448}
1449
1450void Demo::init_vk_swapchain() {
1451 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001452 // Iterate over each queue to learn whether it supports presenting:
1453 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1454 for (uint32_t i = 0; i < queue_family_count; i++) {
1455 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1456 }
1457
1458 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1459 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1460 for (uint32_t i = 0; i < queue_family_count; i++) {
1461 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1462 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1463 graphicsQueueFamilyIndex = i;
1464 }
1465
1466 if (supportsPresent[i] == VK_TRUE) {
1467 graphicsQueueFamilyIndex = i;
1468 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001469 break;
1470 }
1471 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001472 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001473
Dave Houlton5fa47912018-02-16 11:02:26 -07001474 if (presentQueueFamilyIndex == UINT32_MAX) {
1475 // If didn't find a queue that supports both graphics and present,
1476 // then
1477 // find a separate present queue.
1478 for (uint32_t i = 0; i < queue_family_count; ++i) {
1479 if (supportsPresent[i] == VK_TRUE) {
1480 presentQueueFamilyIndex = i;
1481 break;
1482 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001483 }
1484 }
1485
Dave Houlton5fa47912018-02-16 11:02:26 -07001486 // Generate error if could not find both a graphics and a present queue
1487 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1488 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1489 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001490
Dave Houlton5fa47912018-02-16 11:02:26 -07001491 graphics_queue_family_index = graphicsQueueFamilyIndex;
1492 present_queue_family_index = presentQueueFamilyIndex;
1493 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001494
Dave Houlton5fa47912018-02-16 11:02:26 -07001495 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001496
Dave Houlton5fa47912018-02-16 11:02:26 -07001497 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1498 if (!separate_present_queue) {
1499 present_queue = graphics_queue;
1500 } else {
1501 device.getQueue(present_queue_family_index, 0, &present_queue);
1502 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001503
Dave Houlton5fa47912018-02-16 11:02:26 -07001504 // Get the list of VkFormat's that are supported:
1505 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001506 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001507 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001508
Dave Houlton5fa47912018-02-16 11:02:26 -07001509 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1510 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1511 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001512
Dave Houlton5fa47912018-02-16 11:02:26 -07001513 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1514 // the surface has no preferred format. Otherwise, at least one
1515 // supported format will be returned.
1516 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1517 format = vk::Format::eB8G8R8A8Unorm;
1518 } else {
1519 assert(formatCount >= 1);
1520 format = surfFormats[0].format;
1521 }
1522 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001523
Dave Houlton5fa47912018-02-16 11:02:26 -07001524 quit = false;
1525 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001526
Dave Houlton5fa47912018-02-16 11:02:26 -07001527 // Create semaphores to synchronize acquiring presentable buffers before
1528 // rendering and waiting for drawing to be complete before presenting
1529 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001530
Dave Houlton5fa47912018-02-16 11:02:26 -07001531 // Create fences that we can use to throttle if we get too far
1532 // ahead of the image presents
1533 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1534 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1535 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1536 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001537
Dave Houlton5fa47912018-02-16 11:02:26 -07001538 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1539 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001540
Dave Houlton5fa47912018-02-16 11:02:26 -07001541 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1542 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001543
Dave Houlton5fa47912018-02-16 11:02:26 -07001544 if (separate_present_queue) {
1545 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001546 VERIFY(result == vk::Result::eSuccess);
1547 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001548 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001549 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001550
Dave Houlton5fa47912018-02-16 11:02:26 -07001551 // Get Memory information and properties
1552 gpu.getMemoryProperties(&memory_properties);
1553}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001554
Dave Houlton5fa47912018-02-16 11:02:26 -07001555void Demo::prepare() {
1556 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1557 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1558 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001559
Dave Houlton5fa47912018-02-16 11:02:26 -07001560 auto const cmd = vk::CommandBufferAllocateInfo()
1561 .setCommandPool(cmd_pool)
1562 .setLevel(vk::CommandBufferLevel::ePrimary)
1563 .setCommandBufferCount(1);
1564
1565 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1566 VERIFY(result == vk::Result::eSuccess);
1567
1568 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1569
1570 result = this->cmd.begin(&cmd_buf_info);
1571 VERIFY(result == vk::Result::eSuccess);
1572
1573 prepare_buffers();
1574 prepare_depth();
1575 prepare_textures();
1576 prepare_cube_data_buffers();
1577
1578 prepare_descriptor_layout();
1579 prepare_render_pass();
1580 prepare_pipeline();
1581
1582 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1583 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1584 VERIFY(result == vk::Result::eSuccess);
1585 }
1586
1587 if (separate_present_queue) {
1588 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1589
1590 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1591 VERIFY(result == vk::Result::eSuccess);
1592
1593 auto const present_cmd = vk::CommandBufferAllocateInfo()
1594 .setCommandPool(present_cmd_pool)
1595 .setLevel(vk::CommandBufferLevel::ePrimary)
1596 .setCommandBufferCount(1);
1597
1598 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1599 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1600 VERIFY(result == vk::Result::eSuccess);
1601
1602 build_image_ownership_cmd(i);
1603 }
1604 }
1605
1606 prepare_descriptor_pool();
1607 prepare_descriptor_set();
1608
1609 prepare_framebuffers();
1610
1611 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1612 current_buffer = i;
1613 draw_build_cmd(swapchain_image_resources[i].cmd);
1614 }
1615
1616 /*
1617 * Prepare functions above may generate pipeline commands
1618 * that need to be flushed before beginning the render loop.
1619 */
1620 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001621 if (staging_texture.buffer) {
1622 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001623 }
1624
1625 current_buffer = 0;
1626 prepared = true;
1627}
1628
1629void Demo::prepare_buffers() {
1630 vk::SwapchainKHR oldSwapchain = swapchain;
1631
1632 // Check the surface capabilities and formats
1633 vk::SurfaceCapabilitiesKHR surfCapabilities;
1634 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1635 VERIFY(result == vk::Result::eSuccess);
1636
1637 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001638 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001639 VERIFY(result == vk::Result::eSuccess);
1640
1641 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1642 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1643 VERIFY(result == vk::Result::eSuccess);
1644
1645 vk::Extent2D swapchainExtent;
1646 // width and height are either both -1, or both not -1.
1647 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1648 // If the surface size is undefined, the size is set to
1649 // the size of the images requested.
1650 swapchainExtent.width = width;
1651 swapchainExtent.height = height;
1652 } else {
1653 // If the surface size is defined, the swap chain size must match
1654 swapchainExtent = surfCapabilities.currentExtent;
1655 width = surfCapabilities.currentExtent.width;
1656 height = surfCapabilities.currentExtent.height;
1657 }
1658
1659 // The FIFO present mode is guaranteed by the spec to be supported
1660 // and to have no tearing. It's a great default present mode to use.
1661 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1662
1663 // There are times when you may wish to use another present mode. The
1664 // following code shows how to select them, and the comments provide some
1665 // reasons you may wish to use them.
1666 //
1667 // It should be noted that Vulkan 1.0 doesn't provide a method for
1668 // synchronizing rendering with the presentation engine's display. There
1669 // is a method provided for throttling rendering with the display, but
1670 // there are some presentation engines for which this method will not work.
1671 // If an application doesn't throttle its rendering, and if it renders much
1672 // faster than the refresh rate of the display, this can waste power on
1673 // mobile devices. That is because power is being spent rendering images
1674 // that may never be seen.
1675
1676 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1677 // about
1678 // tearing, or have some way of synchronizing their rendering with the
1679 // display.
1680 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1681 // generally render a new presentable image every refresh cycle, but are
1682 // occasionally early. In this case, the application wants the new
1683 // image
1684 // to be displayed instead of the previously-queued-for-presentation
1685 // image
1686 // that has not yet been displayed.
1687 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1688 // render a new presentable image every refresh cycle, but are
1689 // occasionally
1690 // late. In this case (perhaps because of stuttering/latency concerns),
1691 // the application wants the late image to be immediately displayed,
1692 // even
1693 // though that may mean some tearing.
1694
1695 if (presentMode != swapchainPresentMode) {
1696 for (size_t i = 0; i < presentModeCount; ++i) {
1697 if (presentModes[i] == presentMode) {
1698 swapchainPresentMode = presentMode;
1699 break;
1700 }
1701 }
1702 }
1703
1704 if (swapchainPresentMode != presentMode) {
1705 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1706 }
1707
1708 // Determine the number of VkImages to use in the swap chain.
1709 // Application desires to acquire 3 images at a time for triple
1710 // buffering
1711 uint32_t desiredNumOfSwapchainImages = 3;
1712 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1713 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1714 }
1715
1716 // If maxImageCount is 0, we can ask for as many images as we want,
1717 // otherwise
1718 // we're limited to maxImageCount
1719 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1720 // Application must settle for fewer images than desired:
1721 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1722 }
1723
1724 vk::SurfaceTransformFlagBitsKHR preTransform;
1725 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1726 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1727 } else {
1728 preTransform = surfCapabilities.currentTransform;
1729 }
1730
1731 // Find a supported composite alpha mode - one of these is guaranteed to be set
1732 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1733 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1734 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1735 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1736 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1737 vk::CompositeAlphaFlagBitsKHR::eInherit,
1738 };
1739 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1740 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1741 compositeAlpha = compositeAlphaFlags[i];
1742 break;
1743 }
1744 }
1745
1746 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1747 .setSurface(surface)
1748 .setMinImageCount(desiredNumOfSwapchainImages)
1749 .setImageFormat(format)
1750 .setImageColorSpace(color_space)
1751 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1752 .setImageArrayLayers(1)
1753 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1754 .setImageSharingMode(vk::SharingMode::eExclusive)
1755 .setQueueFamilyIndexCount(0)
1756 .setPQueueFamilyIndices(nullptr)
1757 .setPreTransform(preTransform)
1758 .setCompositeAlpha(compositeAlpha)
1759 .setPresentMode(swapchainPresentMode)
1760 .setClipped(true)
1761 .setOldSwapchain(oldSwapchain);
1762
1763 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1764 VERIFY(result == vk::Result::eSuccess);
1765
1766 // If we just re-created an existing swapchain, we should destroy the
1767 // old
1768 // swapchain at this point.
1769 // Note: destroying the swapchain also cleans up all its associated
1770 // presentable images once the platform is done with them.
1771 if (oldSwapchain) {
1772 device.destroySwapchainKHR(oldSwapchain, nullptr);
1773 }
1774
Mike Schuchardt7510c832018-10-29 13:23:08 -07001775 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001776 VERIFY(result == vk::Result::eSuccess);
1777
1778 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1779 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1780 VERIFY(result == vk::Result::eSuccess);
1781
1782 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1783
1784 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1785 auto color_image_view = vk::ImageViewCreateInfo()
1786 .setViewType(vk::ImageViewType::e2D)
1787 .setFormat(format)
1788 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1789
1790 swapchain_image_resources[i].image = swapchainImages[i];
1791
1792 color_image_view.image = swapchain_image_resources[i].image;
1793
1794 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1795 VERIFY(result == vk::Result::eSuccess);
1796 }
1797}
1798
1799void Demo::prepare_cube_data_buffers() {
1800 mat4x4 VP;
1801 mat4x4_mul(VP, projection_matrix, view_matrix);
1802
1803 mat4x4 MVP;
1804 mat4x4_mul(MVP, VP, model_matrix);
1805
1806 vktexcube_vs_uniform data;
1807 memcpy(data.mvp, MVP, sizeof(MVP));
1808 // dumpMatrix("MVP", MVP)
1809
1810 for (int32_t i = 0; i < 12 * 3; i++) {
1811 data.position[i][0] = g_vertex_buffer_data[i * 3];
1812 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1813 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1814 data.position[i][3] = 1.0f;
1815 data.attr[i][0] = g_uv_buffer_data[2 * i];
1816 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1817 data.attr[i][2] = 0;
1818 data.attr[i][3] = 0;
1819 }
1820
1821 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1822
1823 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1824 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001825 VERIFY(result == vk::Result::eSuccess);
1826
1827 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001828 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001829
Dave Houlton5fa47912018-02-16 11:02:26 -07001830 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001831
Dave Houlton5fa47912018-02-16 11:02:26 -07001832 bool const pass = memory_type_from_properties(
1833 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1834 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001835 VERIFY(pass);
1836
Dave Houlton5fa47912018-02-16 11:02:26 -07001837 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001838 VERIFY(result == vk::Result::eSuccess);
1839
Tony-LunarG37af49f2019-12-19 12:04:19 -07001840 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1841 &swapchain_image_resources[i].uniform_memory_ptr);
1842 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001843
Tony-LunarG37af49f2019-12-19 12:04:19 -07001844 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001845
1846 result =
1847 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001848 VERIFY(result == vk::Result::eSuccess);
1849 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001850}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001851
Dave Houlton5fa47912018-02-16 11:02:26 -07001852void Demo::prepare_depth() {
1853 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001854
Dave Houlton5fa47912018-02-16 11:02:26 -07001855 auto const image = vk::ImageCreateInfo()
1856 .setImageType(vk::ImageType::e2D)
1857 .setFormat(depth.format)
1858 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1859 .setMipLevels(1)
1860 .setArrayLayers(1)
1861 .setSamples(vk::SampleCountFlagBits::e1)
1862 .setTiling(vk::ImageTiling::eOptimal)
1863 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1864 .setSharingMode(vk::SharingMode::eExclusive)
1865 .setQueueFamilyIndexCount(0)
1866 .setPQueueFamilyIndices(nullptr)
1867 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001868
Dave Houlton5fa47912018-02-16 11:02:26 -07001869 auto result = device.createImage(&image, nullptr, &depth.image);
1870 VERIFY(result == vk::Result::eSuccess);
1871
1872 vk::MemoryRequirements mem_reqs;
1873 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1874
1875 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1876 depth.mem_alloc.setMemoryTypeIndex(0);
1877
1878 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1879 &depth.mem_alloc.memoryTypeIndex);
1880 VERIFY(pass);
1881
1882 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1883 VERIFY(result == vk::Result::eSuccess);
1884
1885 result = device.bindImageMemory(depth.image, depth.mem, 0);
1886 VERIFY(result == vk::Result::eSuccess);
1887
1888 auto const view = vk::ImageViewCreateInfo()
1889 .setImage(depth.image)
1890 .setViewType(vk::ImageViewType::e2D)
1891 .setFormat(depth.format)
1892 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1893 result = device.createImageView(&view, nullptr, &depth.view);
1894 VERIFY(result == vk::Result::eSuccess);
1895}
1896
1897void Demo::prepare_descriptor_layout() {
1898 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1899 .setBinding(0)
1900 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1901 .setDescriptorCount(1)
1902 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1903 .setPImmutableSamplers(nullptr),
1904 vk::DescriptorSetLayoutBinding()
1905 .setBinding(1)
1906 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1907 .setDescriptorCount(texture_count)
1908 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1909 .setPImmutableSamplers(nullptr)};
1910
1911 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1912
1913 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1914 VERIFY(result == vk::Result::eSuccess);
1915
1916 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1917
1918 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1919 VERIFY(result == vk::Result::eSuccess);
1920}
1921
1922void Demo::prepare_descriptor_pool() {
1923 vk::DescriptorPoolSize const poolSizes[2] = {
1924 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1925 vk::DescriptorPoolSize()
1926 .setType(vk::DescriptorType::eCombinedImageSampler)
1927 .setDescriptorCount(swapchainImageCount * texture_count)};
1928
1929 auto const descriptor_pool =
1930 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1931
1932 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1933 VERIFY(result == vk::Result::eSuccess);
1934}
1935
1936void Demo::prepare_descriptor_set() {
1937 auto const alloc_info =
1938 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1939
1940 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1941
1942 vk::DescriptorImageInfo tex_descs[texture_count];
1943 for (uint32_t i = 0; i < texture_count; i++) {
1944 tex_descs[i].setSampler(textures[i].sampler);
1945 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001946 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001947 }
1948
1949 vk::WriteDescriptorSet writes[2];
1950
1951 writes[0].setDescriptorCount(1);
1952 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1953 writes[0].setPBufferInfo(&buffer_info);
1954
1955 writes[1].setDstBinding(1);
1956 writes[1].setDescriptorCount(texture_count);
1957 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1958 writes[1].setPImageInfo(tex_descs);
1959
1960 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1961 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001962 VERIFY(result == vk::Result::eSuccess);
1963
Dave Houlton5fa47912018-02-16 11:02:26 -07001964 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1965 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1966 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1967 device.updateDescriptorSets(2, writes, 0, nullptr);
1968 }
1969}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001970
Dave Houlton5fa47912018-02-16 11:02:26 -07001971void Demo::prepare_framebuffers() {
1972 vk::ImageView attachments[2];
1973 attachments[1] = depth.view;
1974
1975 auto const fb_info = vk::FramebufferCreateInfo()
1976 .setRenderPass(render_pass)
1977 .setAttachmentCount(2)
1978 .setPAttachments(attachments)
1979 .setWidth((uint32_t)width)
1980 .setHeight((uint32_t)height)
1981 .setLayers(1);
1982
1983 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1984 attachments[0] = swapchain_image_resources[i].view;
1985 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001986 VERIFY(result == vk::Result::eSuccess);
1987 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001988}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001989
Dave Houlton5fa47912018-02-16 11:02:26 -07001990vk::ShaderModule Demo::prepare_fs() {
1991 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001992#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001993 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001994
Dave Houlton5fa47912018-02-16 11:02:26 -07001995 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001996
Dave Houlton5fa47912018-02-16 11:02:26 -07001997 return frag_shader_module;
1998}
1999
2000void Demo::prepare_pipeline() {
2001 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
2002 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
2003 VERIFY(result == vk::Result::eSuccess);
2004
2005 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
2006 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2007 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2008
2009 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2010
2011 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2012
2013 // TODO: Where are pViewports and pScissors set?
2014 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2015
2016 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2017 .setDepthClampEnable(VK_FALSE)
2018 .setRasterizerDiscardEnable(VK_FALSE)
2019 .setPolygonMode(vk::PolygonMode::eFill)
2020 .setCullMode(vk::CullModeFlagBits::eBack)
2021 .setFrontFace(vk::FrontFace::eCounterClockwise)
2022 .setDepthBiasEnable(VK_FALSE)
2023 .setLineWidth(1.0f);
2024
2025 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2026
2027 auto const stencilOp =
2028 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2029
2030 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2031 .setDepthTestEnable(VK_TRUE)
2032 .setDepthWriteEnable(VK_TRUE)
2033 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2034 .setDepthBoundsTestEnable(VK_FALSE)
2035 .setStencilTestEnable(VK_FALSE)
2036 .setFront(stencilOp)
2037 .setBack(stencilOp);
2038
2039 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2040 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2041 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2042
2043 auto const colorBlendInfo =
2044 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2045
2046 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2047
2048 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2049
2050 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2051 .setStageCount(2)
2052 .setPStages(shaderStageInfo)
2053 .setPVertexInputState(&vertexInputInfo)
2054 .setPInputAssemblyState(&inputAssemblyInfo)
2055 .setPViewportState(&viewportInfo)
2056 .setPRasterizationState(&rasterizationInfo)
2057 .setPMultisampleState(&multisampleInfo)
2058 .setPDepthStencilState(&depthStencilInfo)
2059 .setPColorBlendState(&colorBlendInfo)
2060 .setPDynamicState(&dynamicStateInfo)
2061 .setLayout(pipeline_layout)
2062 .setRenderPass(render_pass);
2063
2064 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2065 VERIFY(result == vk::Result::eSuccess);
2066
2067 device.destroyShaderModule(frag_shader_module, nullptr);
2068 device.destroyShaderModule(vert_shader_module, nullptr);
2069}
2070
2071void Demo::prepare_render_pass() {
2072 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2073 // because at the start of the renderpass, we don't care about their contents.
2074 // At the start of the subpass, the color attachment's layout will be transitioned
2075 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2076 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2077 // the renderpass, the color attachment's layout will be transitioned to
2078 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2079 // the renderpass, no barriers are necessary.
2080 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2081 .setFormat(format)
2082 .setSamples(vk::SampleCountFlagBits::e1)
2083 .setLoadOp(vk::AttachmentLoadOp::eClear)
2084 .setStoreOp(vk::AttachmentStoreOp::eStore)
2085 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2086 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2087 .setInitialLayout(vk::ImageLayout::eUndefined)
2088 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2089 vk::AttachmentDescription()
2090 .setFormat(depth.format)
2091 .setSamples(vk::SampleCountFlagBits::e1)
2092 .setLoadOp(vk::AttachmentLoadOp::eClear)
2093 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2094 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2095 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2096 .setInitialLayout(vk::ImageLayout::eUndefined)
2097 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2098
2099 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2100
2101 auto const depth_reference =
2102 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2103
2104 auto const subpass = vk::SubpassDescription()
2105 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2106 .setInputAttachmentCount(0)
2107 .setPInputAttachments(nullptr)
2108 .setColorAttachmentCount(1)
2109 .setPColorAttachments(&color_reference)
2110 .setPResolveAttachments(nullptr)
2111 .setPDepthStencilAttachment(&depth_reference)
2112 .setPreserveAttachmentCount(0)
2113 .setPPreserveAttachments(nullptr);
2114
Tony-LunarG495604b2019-06-13 15:32:05 -06002115 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2116 vk::SubpassDependency const dependencies[2] = {
2117 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2118 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2119 .setDstSubpass(0)
2120 .setSrcStageMask(stages)
2121 .setDstStageMask(stages)
2122 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2123 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2124 .setDependencyFlags(vk::DependencyFlags()),
2125 vk::SubpassDependency() // Image layout transition
2126 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2127 .setDstSubpass(0)
2128 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2129 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2130 .setSrcAccessMask(vk::AccessFlagBits())
2131 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2132 .setDependencyFlags(vk::DependencyFlags()),
2133 };
2134
Dave Houlton5fa47912018-02-16 11:02:26 -07002135 auto const rp_info = vk::RenderPassCreateInfo()
2136 .setAttachmentCount(2)
2137 .setPAttachments(attachments)
2138 .setSubpassCount(1)
2139 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002140 .setDependencyCount(2)
2141 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002142
2143 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2144 VERIFY(result == vk::Result::eSuccess);
2145}
2146
2147vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2148 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2149
2150 vk::ShaderModule module;
2151 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2152 VERIFY(result == vk::Result::eSuccess);
2153
2154 return module;
2155}
2156
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002157void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2158 int32_t tex_width;
2159 int32_t tex_height;
2160
2161 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2162 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2163 }
2164
2165 tex_obj->tex_width = tex_width;
2166 tex_obj->tex_height = tex_height;
2167
2168 auto const buffer_create_info = vk::BufferCreateInfo()
2169 .setSize(tex_width * tex_height * 4)
2170 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2171 .setSharingMode(vk::SharingMode::eExclusive)
2172 .setQueueFamilyIndexCount(0)
2173 .setPQueueFamilyIndices(nullptr);
2174
2175 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2176 VERIFY(result == vk::Result::eSuccess);
2177
2178 vk::MemoryRequirements mem_reqs;
2179 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2180
2181 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2182 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2183
2184 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2185 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2186 VERIFY(pass == true);
2187
2188 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2189 VERIFY(result == vk::Result::eSuccess);
2190
2191 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2192 VERIFY(result == vk::Result::eSuccess);
2193
2194 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002195 layout.rowPitch = tex_width * 4;
2196 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2197 VERIFY(data.result == vk::Result::eSuccess);
2198
2199 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2200 fprintf(stderr, "Error loading texture: %s\n", filename);
2201 }
2202
2203 device.unmapMemory(tex_obj->mem);
2204}
2205
Dave Houlton5fa47912018-02-16 11:02:26 -07002206void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2207 vk::MemoryPropertyFlags required_props) {
2208 int32_t tex_width;
2209 int32_t tex_height;
2210 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2211 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002212 }
2213
Dave Houlton5fa47912018-02-16 11:02:26 -07002214 tex_obj->tex_width = tex_width;
2215 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002216
Dave Houlton5fa47912018-02-16 11:02:26 -07002217 auto const image_create_info = vk::ImageCreateInfo()
2218 .setImageType(vk::ImageType::e2D)
2219 .setFormat(vk::Format::eR8G8B8A8Unorm)
2220 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2221 .setMipLevels(1)
2222 .setArrayLayers(1)
2223 .setSamples(vk::SampleCountFlagBits::e1)
2224 .setTiling(tiling)
2225 .setUsage(usage)
2226 .setSharingMode(vk::SharingMode::eExclusive)
2227 .setQueueFamilyIndexCount(0)
2228 .setPQueueFamilyIndices(nullptr)
2229 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002230
Dave Houlton5fa47912018-02-16 11:02:26 -07002231 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2232 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002233
Dave Houlton5fa47912018-02-16 11:02:26 -07002234 vk::MemoryRequirements mem_reqs;
2235 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002236
Dave Houlton5fa47912018-02-16 11:02:26 -07002237 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2238 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002239
Dave Houlton5fa47912018-02-16 11:02:26 -07002240 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2241 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002242
Dave Houlton5fa47912018-02-16 11:02:26 -07002243 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2244 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002245
Dave Houlton5fa47912018-02-16 11:02:26 -07002246 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2247 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002248
Dave Houlton5fa47912018-02-16 11:02:26 -07002249 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2250 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2251 vk::SubresourceLayout layout;
2252 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002253
Dave Houlton5fa47912018-02-16 11:02:26 -07002254 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002255 VERIFY(data.result == vk::Result::eSuccess);
2256
Dave Houlton5fa47912018-02-16 11:02:26 -07002257 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2258 fprintf(stderr, "Error loading texture: %s\n", filename);
2259 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002260
Dave Houlton5fa47912018-02-16 11:02:26 -07002261 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002262 }
2263
Dave Houlton5fa47912018-02-16 11:02:26 -07002264 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2265}
2266
2267void Demo::prepare_textures() {
2268 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2269 vk::FormatProperties props;
2270 gpu.getFormatProperties(tex_format, &props);
2271
2272 for (uint32_t i = 0; i < texture_count; i++) {
2273 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2274 /* Device can texture using linear textures */
2275 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2276 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2277 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2278 // shader to run until layout transition completes
2279 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2280 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2281 vk::PipelineStageFlagBits::eFragmentShader);
2282 staging_texture.image = vk::Image();
2283 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2284 /* Must use staging buffer to copy linear texture to optimized */
2285
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002286 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002287
2288 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2289 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2290 vk::MemoryPropertyFlagBits::eDeviceLocal);
2291
Dave Houlton5fa47912018-02-16 11:02:26 -07002292 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2293 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2294 vk::PipelineStageFlagBits::eTransfer);
2295
2296 auto const subresource = vk::ImageSubresourceLayers()
2297 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2298 .setMipLevel(0)
2299 .setBaseArrayLayer(0)
2300 .setLayerCount(1);
2301
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002302 auto const copy_region =
2303 vk::BufferImageCopy()
2304 .setBufferOffset(0)
2305 .setBufferRowLength(staging_texture.tex_width)
2306 .setBufferImageHeight(staging_texture.tex_height)
2307 .setImageSubresource(subresource)
2308 .setImageOffset({0, 0, 0})
2309 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002310
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002311 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002312
2313 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2314 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2315 vk::PipelineStageFlagBits::eFragmentShader);
2316 } else {
2317 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002318 }
2319
Dave Houlton5fa47912018-02-16 11:02:26 -07002320 auto const samplerInfo = vk::SamplerCreateInfo()
2321 .setMagFilter(vk::Filter::eNearest)
2322 .setMinFilter(vk::Filter::eNearest)
2323 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2324 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2325 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2326 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2327 .setMipLodBias(0.0f)
2328 .setAnisotropyEnable(VK_FALSE)
2329 .setMaxAnisotropy(1)
2330 .setCompareEnable(VK_FALSE)
2331 .setCompareOp(vk::CompareOp::eNever)
2332 .setMinLod(0.0f)
2333 .setMaxLod(0.0f)
2334 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2335 .setUnnormalizedCoordinates(VK_FALSE);
2336
2337 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2338 VERIFY(result == vk::Result::eSuccess);
2339
2340 auto const viewInfo = vk::ImageViewCreateInfo()
2341 .setImage(textures[i].image)
2342 .setViewType(vk::ImageViewType::e2D)
2343 .setFormat(tex_format)
2344 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2345
2346 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2347 VERIFY(result == vk::Result::eSuccess);
2348 }
2349}
2350
2351vk::ShaderModule Demo::prepare_vs() {
2352 const uint32_t vertShaderCode[] = {
2353#include "cube.vert.inc"
2354 };
2355
2356 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2357
2358 return vert_shader_module;
2359}
2360
2361void Demo::resize() {
2362 uint32_t i;
2363
2364 // Don't react to resize until after first initialization.
2365 if (!prepared) {
2366 return;
2367 }
2368
2369 // In order to properly resize the window, we must re-create the
2370 // swapchain
2371 // AND redo the command buffers, etc.
2372 //
2373 // First, perform part of the cleanup() function:
2374 prepared = false;
2375 auto result = device.waitIdle();
2376 VERIFY(result == vk::Result::eSuccess);
2377
2378 for (i = 0; i < swapchainImageCount; i++) {
2379 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2380 }
2381
2382 device.destroyDescriptorPool(desc_pool, nullptr);
2383
2384 device.destroyPipeline(pipeline, nullptr);
2385 device.destroyPipelineCache(pipelineCache, nullptr);
2386 device.destroyRenderPass(render_pass, nullptr);
2387 device.destroyPipelineLayout(pipeline_layout, nullptr);
2388 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2389
2390 for (i = 0; i < texture_count; i++) {
2391 device.destroyImageView(textures[i].view, nullptr);
2392 device.destroyImage(textures[i].image, nullptr);
2393 device.freeMemory(textures[i].mem, nullptr);
2394 device.destroySampler(textures[i].sampler, nullptr);
2395 }
2396
2397 device.destroyImageView(depth.view, nullptr);
2398 device.destroyImage(depth.image, nullptr);
2399 device.freeMemory(depth.mem, nullptr);
2400
2401 for (i = 0; i < swapchainImageCount; i++) {
2402 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002403 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002404 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002405 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002406 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2407 }
2408
2409 device.destroyCommandPool(cmd_pool, nullptr);
2410 if (separate_present_queue) {
2411 device.destroyCommandPool(present_cmd_pool, nullptr);
2412 }
2413
2414 // Second, re-perform the prepare() function, which will re-create the
2415 // swapchain.
2416 prepare();
2417}
2418
2419void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2420 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2421 assert(cmd);
2422
2423 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2424 vk::AccessFlags flags;
2425
2426 switch (layout) {
2427 case vk::ImageLayout::eTransferDstOptimal:
2428 // Make sure anything that was copying from this image has
2429 // completed
2430 flags = vk::AccessFlagBits::eTransferWrite;
2431 break;
2432 case vk::ImageLayout::eColorAttachmentOptimal:
2433 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2434 break;
2435 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2436 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2437 break;
2438 case vk::ImageLayout::eShaderReadOnlyOptimal:
2439 // Make sure any Copy or CPU writes to image are flushed
2440 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2441 break;
2442 case vk::ImageLayout::eTransferSrcOptimal:
2443 flags = vk::AccessFlagBits::eTransferRead;
2444 break;
2445 case vk::ImageLayout::ePresentSrcKHR:
2446 flags = vk::AccessFlagBits::eMemoryRead;
2447 break;
2448 default:
2449 break;
2450 }
2451
2452 return flags;
2453 };
2454
2455 auto const barrier = vk::ImageMemoryBarrier()
2456 .setSrcAccessMask(srcAccessMask)
2457 .setDstAccessMask(DstAccessMask(newLayout))
2458 .setOldLayout(oldLayout)
2459 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002460 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2461 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002462 .setImage(image)
2463 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2464
2465 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2466}
2467
2468void Demo::update_data_buffer() {
2469 mat4x4 VP;
2470 mat4x4_mul(VP, projection_matrix, view_matrix);
2471
2472 // Rotate around the Y axis
2473 mat4x4 Model;
2474 mat4x4_dup(Model, model_matrix);
2475 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2476
2477 mat4x4 MVP;
2478 mat4x4_mul(MVP, VP, model_matrix);
2479
Tony-LunarG37af49f2019-12-19 12:04:19 -07002480 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002481}
2482
Karl Schultzb7940402018-05-29 13:09:22 -06002483/* Convert ppm image data from header file into RGBA texture image */
2484#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002485bool 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 -06002486 (void)filename;
2487 char *cPtr;
2488 cPtr = (char *)lunarg_ppm;
2489 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002490 return false;
2491 }
Karl Schultzb7940402018-05-29 13:09:22 -06002492 while (strncmp(cPtr++, "\n", 1))
2493 ;
2494 sscanf(cPtr, "%u %u", width, height);
2495 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002496 return true;
2497 }
Karl Schultzb7940402018-05-29 13:09:22 -06002498 while (strncmp(cPtr++, "\n", 1))
2499 ;
2500 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002501 return false;
2502 }
Karl Schultzb7940402018-05-29 13:09:22 -06002503 while (strncmp(cPtr++, "\n", 1))
2504 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002505 for (int y = 0; y < *height; y++) {
2506 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002507 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002508 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002509 rowPtr[3] = 255; /* Alpha of 1 */
2510 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002511 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002512 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002513 rgba_data += layout->rowPitch;
2514 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002515 return true;
2516}
2517
2518bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2519 // Search memtypes to find first index with those properties
2520 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2521 if ((typeBits & 1) == 1) {
2522 // Type is available, does it match user properties?
2523 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2524 *typeIndex = i;
2525 return true;
2526 }
2527 }
2528 typeBits >>= 1;
2529 }
2530
2531 // No memory types matched, return failure
2532 return false;
2533}
2534
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002535#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002536void Demo::run() {
2537 if (!prepared) {
2538 return;
2539 }
2540
2541 draw();
2542 curFrame++;
2543
Petr Krausd88e4e52019-01-23 18:45:04 +01002544 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002545 PostQuitMessage(validation_error);
2546 }
2547}
2548
2549void Demo::create_window() {
2550 WNDCLASSEX win_class;
2551
2552 // Initialize the window class structure:
2553 win_class.cbSize = sizeof(WNDCLASSEX);
2554 win_class.style = CS_HREDRAW | CS_VREDRAW;
2555 win_class.lpfnWndProc = WndProc;
2556 win_class.cbClsExtra = 0;
2557 win_class.cbWndExtra = 0;
2558 win_class.hInstance = connection; // hInstance
2559 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2560 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2561 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2562 win_class.lpszMenuName = nullptr;
2563 win_class.lpszClassName = name;
2564 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2565
2566 // Register window class:
2567 if (!RegisterClassEx(&win_class)) {
2568 // It didn't work, so try to give a useful error:
2569 printf("Unexpected error trying to start the application!\n");
2570 fflush(stdout);
2571 exit(1);
2572 }
2573
2574 // Create window with the registered class:
2575 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2576 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2577 window = CreateWindowEx(0,
2578 name, // class name
2579 name, // app name
2580 WS_OVERLAPPEDWINDOW | // window style
2581 WS_VISIBLE | WS_SYSMENU,
2582 100, 100, // x/y coords
2583 wr.right - wr.left, // width
2584 wr.bottom - wr.top, // height
2585 nullptr, // handle to parent
2586 nullptr, // handle to menu
2587 connection, // hInstance
2588 nullptr); // no extra parameters
2589
2590 if (!window) {
2591 // It didn't work, so try to give a useful error:
2592 printf("Cannot create a window in which to draw!\n");
2593 fflush(stdout);
2594 exit(1);
2595 }
2596
2597 // Window client area size must be at least 1 pixel high, to prevent
2598 // crash.
2599 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2600 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2601}
2602#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2603
2604void Demo::create_xlib_window() {
2605 const char *display_envar = getenv("DISPLAY");
2606 if (display_envar == nullptr || display_envar[0] == '\0') {
2607 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2608 fflush(stdout);
2609 exit(1);
2610 }
2611
2612 XInitThreads();
2613 display = XOpenDisplay(nullptr);
2614 long visualMask = VisualScreenMask;
2615 int numberOfVisuals;
2616 XVisualInfo vInfoTemplate = {};
2617 vInfoTemplate.screen = DefaultScreen(display);
2618 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2619
2620 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2621
2622 XSetWindowAttributes windowAttributes = {};
2623 windowAttributes.colormap = colormap;
2624 windowAttributes.background_pixel = 0xFFFFFFFF;
2625 windowAttributes.border_pixel = 0;
2626 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2627
2628 xlib_window =
2629 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2630 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2631
2632 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2633 XMapWindow(display, xlib_window);
2634 XFlush(display);
2635 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2636}
2637
2638void Demo::handle_xlib_event(const XEvent *event) {
2639 switch (event->type) {
2640 case ClientMessage:
2641 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2642 quit = true;
2643 }
2644 break;
2645 case KeyPress:
2646 switch (event->xkey.keycode) {
2647 case 0x9: // Escape
2648 quit = true;
2649 break;
2650 case 0x71: // left arrow key
2651 spin_angle -= spin_increment;
2652 break;
2653 case 0x72: // right arrow key
2654 spin_angle += spin_increment;
2655 break;
2656 case 0x41: // space bar
2657 pause = !pause;
2658 break;
2659 }
2660 break;
2661 case ConfigureNotify:
2662 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2663 width = event->xconfigure.width;
2664 height = event->xconfigure.height;
2665 resize();
2666 }
2667 break;
2668 default:
2669 break;
2670 }
2671}
2672
2673void Demo::run_xlib() {
2674 while (!quit) {
2675 XEvent event;
2676
2677 if (pause) {
2678 XNextEvent(display, &event);
2679 handle_xlib_event(&event);
2680 }
2681 while (XPending(display) > 0) {
2682 XNextEvent(display, &event);
2683 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002684 }
2685
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002686 draw();
2687 curFrame++;
2688
Dave Houlton5fa47912018-02-16 11:02:26 -07002689 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2690 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002691 }
2692 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002693}
Tony Barbour153cb062016-12-07 13:43:36 -07002694#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002695
Dave Houlton5fa47912018-02-16 11:02:26 -07002696void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2697 uint8_t event_code = event->response_type & 0x7f;
2698 switch (event_code) {
2699 case XCB_EXPOSE:
2700 // TODO: Resize window
2701 break;
2702 case XCB_CLIENT_MESSAGE:
2703 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2704 quit = true;
2705 }
2706 break;
2707 case XCB_KEY_RELEASE: {
2708 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002709
Dave Houlton5fa47912018-02-16 11:02:26 -07002710 switch (key->detail) {
2711 case 0x9: // Escape
2712 quit = true;
2713 break;
2714 case 0x71: // left arrow key
2715 spin_angle -= spin_increment;
2716 break;
2717 case 0x72: // right arrow key
2718 spin_angle += spin_increment;
2719 break;
2720 case 0x41: // space bar
2721 pause = !pause;
2722 break;
2723 }
2724 } break;
2725 case XCB_CONFIGURE_NOTIFY: {
2726 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2727 if ((width != cfg->width) || (height != cfg->height)) {
2728 width = cfg->width;
2729 height = cfg->height;
2730 resize();
2731 }
2732 } break;
2733 default:
2734 break;
2735 }
2736}
2737
2738void Demo::run_xcb() {
2739 xcb_flush(connection);
2740
2741 while (!quit) {
2742 xcb_generic_event_t *event;
2743
2744 if (pause) {
2745 event = xcb_wait_for_event(connection);
2746 } else {
2747 event = xcb_poll_for_event(connection);
2748 }
2749 while (event) {
2750 handle_xcb_event(event);
2751 free(event);
2752 event = xcb_poll_for_event(connection);
2753 }
2754
2755 draw();
2756 curFrame++;
2757 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2758 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002759 }
2760 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002761}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002762
Dave Houlton5fa47912018-02-16 11:02:26 -07002763void Demo::create_xcb_window() {
2764 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002765
Dave Houlton5fa47912018-02-16 11:02:26 -07002766 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002767
Dave Houlton5fa47912018-02-16 11:02:26 -07002768 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2769 value_list[0] = screen->black_pixel;
2770 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002771
Dave Houlton5fa47912018-02-16 11:02:26 -07002772 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2773 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2774
2775 /* Magic code that will send notification when window is destroyed */
2776 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2777 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2778
2779 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2780 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2781
2782 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2783
2784 free(reply);
2785
2786 xcb_map_window(connection, xcb_window);
2787
2788 // Force the x/y coordinates to 100,100 results are identical in
2789 // consecutive
2790 // runs
2791 const uint32_t coords[] = {100, 100};
2792 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2793}
2794#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2795
2796void Demo::run() {
2797 while (!quit) {
2798 if (pause) {
2799 wl_display_dispatch(display);
2800 } else {
2801 wl_display_dispatch_pending(display);
2802 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002803 draw();
2804 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002805 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002806 quit = true;
2807 }
2808 }
2809 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002810}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002811
Dave Houlton5fa47912018-02-16 11:02:26 -07002812void Demo::create_window() {
2813 window = wl_compositor_create_surface(compositor);
2814 if (!window) {
2815 printf("Can not create wayland_surface from compositor!\n");
2816 fflush(stdout);
2817 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002818 }
2819
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002820 shell_surface = wl_shell_get_shell_surface(shell, window);
2821 if (!shell_surface) {
2822 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002823 fflush(stdout);
2824 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002825 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002826
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002827 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2828 wl_shell_surface_set_toplevel(shell_surface);
2829 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002830}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002831#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2832
2833void Demo::handle_directfb_event(const DFBInputEvent *event) {
2834 if (event->type != DIET_KEYPRESS) return;
2835 switch (event->key_symbol) {
2836 case DIKS_ESCAPE: // Escape
2837 quit = true;
2838 break;
2839 case DIKS_CURSOR_LEFT: // left arrow key
2840 spin_angle -= spin_increment;
2841 break;
2842 case DIKS_CURSOR_RIGHT: // right arrow key
2843 spin_angle += spin_increment;
2844 break;
2845 case DIKS_SPACE: // space bar
2846 pause = !pause;
2847 break;
2848 default:
2849 break;
2850 }
2851}
2852
2853void Demo::run_directfb() {
2854 while (!quit) {
2855 DFBInputEvent event;
2856
2857 if (pause) {
2858 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002859 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002860 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002861 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002862
2863 draw();
2864 curFrame++;
2865 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2866 quit = true;
2867 }
2868 }
2869 }
2870}
2871
2872void Demo::create_directfb_window() {
2873 DFBResult ret;
2874
2875 ret = DirectFBInit(NULL, NULL);
2876 if (ret) {
2877 printf("DirectFBInit failed to initialize DirectFB!\n");
2878 fflush(stdout);
2879 exit(1);
2880 }
2881
2882 ret = DirectFBCreate(&dfb);
2883 if (ret) {
2884 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2885 fflush(stdout);
2886 exit(1);
2887 }
2888
2889 DFBSurfaceDescription desc;
2890 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2891 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002892 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002893 desc.height = height;
2894 ret = dfb->CreateSurface(dfb, &desc, &window);
2895 if (ret) {
2896 printf("CreateSurface failed to create DirectFB surface interface!\n");
2897 fflush(stdout);
2898 exit(1);
2899 }
2900
2901 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2902 if (ret) {
2903 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2904 fflush(stdout);
2905 exit(1);
2906 }
2907}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002908#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002909void Demo::run() {
2910 draw();
2911 curFrame++;
2912 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2913 quit = true;
2914 }
2915}
Damien Leone600c3052017-01-31 10:26:07 -07002916#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2917
Dave Houlton5fa47912018-02-16 11:02:26 -07002918vk::Result Demo::create_display_surface() {
2919 vk::Result result;
2920 uint32_t display_count;
2921 uint32_t mode_count;
2922 uint32_t plane_count;
2923 vk::DisplayPropertiesKHR display_props;
2924 vk::DisplayKHR display;
2925 vk::DisplayModePropertiesKHR mode_props;
2926 vk::DisplayPlanePropertiesKHR *plane_props;
2927 vk::Bool32 found_plane = VK_FALSE;
2928 uint32_t plane_index;
2929 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002930
Dave Houlton5fa47912018-02-16 11:02:26 -07002931 display_count = 1;
2932 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2933 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2934
2935 display = display_props.display;
2936
2937 // Get the first mode of the display
2938 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2939 VERIFY(result == vk::Result::eSuccess);
2940
2941 if (mode_count == 0) {
2942 printf("Cannot find any mode for the display!\n");
2943 fflush(stdout);
2944 exit(1);
2945 }
2946
2947 mode_count = 1;
2948 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2949 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2950
2951 // Get the list of planes
2952 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2953 VERIFY(result == vk::Result::eSuccess);
2954
2955 if (plane_count == 0) {
2956 printf("Cannot find any plane!\n");
2957 fflush(stdout);
2958 exit(1);
2959 }
2960
2961 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2962 VERIFY(plane_props != nullptr);
2963
2964 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2965 VERIFY(result == vk::Result::eSuccess);
2966
2967 // Find a plane compatible with the display
2968 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2969 uint32_t supported_count;
2970 vk::DisplayKHR *supported_displays;
2971
2972 // Disqualify planes that are bound to a different display
2973 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2974 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002975 }
2976
Dave Houlton5fa47912018-02-16 11:02:26 -07002977 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002978 VERIFY(result == vk::Result::eSuccess);
2979
Dave Houlton5fa47912018-02-16 11:02:26 -07002980 if (supported_count == 0) {
2981 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002982 }
2983
Dave Houlton5fa47912018-02-16 11:02:26 -07002984 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2985 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002986
Dave Houlton5fa47912018-02-16 11:02:26 -07002987 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002988 VERIFY(result == vk::Result::eSuccess);
2989
Dave Houlton5fa47912018-02-16 11:02:26 -07002990 for (uint32_t i = 0; i < supported_count; i++) {
2991 if (supported_displays[i] == display) {
2992 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002993 break;
2994 }
2995 }
2996
Dave Houlton5fa47912018-02-16 11:02:26 -07002997 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002998
Dave Houlton5fa47912018-02-16 11:02:26 -07002999 if (found_plane) {
3000 break;
Damien Leone600c3052017-01-31 10:26:07 -07003001 }
3002 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003003
3004 if (!found_plane) {
3005 printf("Cannot find a plane compatible with the display!\n");
3006 fflush(stdout);
3007 exit(1);
3008 }
3009
3010 free(plane_props);
3011
3012 vk::DisplayPlaneCapabilitiesKHR planeCaps;
3013 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
3014 // Find a supported alpha mode
3015 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3016 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
3017 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3018 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3019 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3020 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3021 };
3022 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3023 if (planeCaps.supportedAlpha & alphaModes[i]) {
3024 alphaMode = alphaModes[i];
3025 break;
3026 }
3027 }
3028
3029 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3030 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3031
3032 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3033 .setDisplayMode(mode_props.displayMode)
3034 .setPlaneIndex(plane_index)
3035 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3036 .setGlobalAlpha(1.0f)
3037 .setAlphaMode(alphaMode)
3038 .setImageExtent(image_extent);
3039
3040 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3041}
3042
3043void Demo::run_display() {
3044 while (!quit) {
3045 draw();
3046 curFrame++;
3047
Petr Krausd88e4e52019-01-23 18:45:04 +01003048 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003049 quit = true;
3050 }
3051 }
3052}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003053#endif
3054
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003055#if _WIN32
3056// Include header required for parsing the command line options.
3057#include <shellapi.h>
3058
3059Demo demo;
3060
3061// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003062LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3063 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003064 case WM_CLOSE:
3065 PostQuitMessage(validation_error);
3066 break;
3067 case WM_PAINT:
3068 demo.run();
3069 break;
3070 case WM_GETMINMAXINFO: // set window's minimum size
3071 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3072 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003073 case WM_ERASEBKGND:
3074 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003075 case WM_SIZE:
3076 // Resize the application to the new window size, except when
3077 // it was minimized. Vulkan doesn't support images or swapchains
3078 // with width=0 and height=0.
3079 if (wParam != SIZE_MINIMIZED) {
3080 demo.width = lParam & 0xffff;
3081 demo.height = (lParam & 0xffff0000) >> 16;
3082 demo.resize();
3083 }
3084 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003085 case WM_KEYDOWN:
3086 switch (wParam) {
3087 case VK_ESCAPE:
3088 PostQuitMessage(validation_error);
3089 break;
3090 case VK_LEFT:
3091 demo.spin_angle -= demo.spin_increment;
3092 break;
3093 case VK_RIGHT:
3094 demo.spin_angle += demo.spin_increment;
3095 break;
3096 case VK_SPACE:
3097 demo.pause = !demo.pause;
3098 break;
3099 }
3100 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003101 default:
3102 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003103 }
3104
3105 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3106}
3107
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003108int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003109 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003110 MSG msg; // message
3111 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003112 int argc;
3113 char **argv;
3114
Jamie Madillb2ff6502017-03-15 16:17:46 -04003115 // Ensure wParam is initialized.
3116 msg.wParam = 0;
3117
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003118 // Use the CommandLine functions to get the command line arguments.
3119 // Unfortunately, Microsoft outputs
3120 // this information as wide characters for Unicode, and we simply want the
3121 // Ascii version to be compatible
3122 // with the non-Windows side. So, we have to convert the information to
3123 // Ascii character strings.
3124 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003125 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003126 argc = 0;
3127 }
3128
Jeremy Hayes9d304782016-10-09 11:48:12 -06003129 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003130 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003131 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003132 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003133 } else {
3134 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003135 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3136 size_t numConverted = 0;
3137
3138 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003139 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003140 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003141 }
3142 }
3143 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003144 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003145 argv = nullptr;
3146 }
3147
3148 demo.init(argc, argv);
3149
3150 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003151 if (argc > 0 && argv != nullptr) {
3152 for (int iii = 0; iii < argc; iii++) {
3153 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003154 free(argv[iii]);
3155 }
3156 }
3157 free(argv);
3158 }
3159
3160 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003161 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003162 demo.create_window();
3163 demo.init_vk_swapchain();
3164
3165 demo.prepare();
3166
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003167 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003168
3169 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003170 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003171 if (demo.pause) {
3172 const BOOL succ = WaitMessage();
3173
3174 if (!succ) {
3175 const auto &suppress_popups = demo.suppress_popups;
3176 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3177 }
3178 }
3179
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003180 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003181 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003182 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003183 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003184 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003185 /* Translate and dispatch to event queue*/
3186 TranslateMessage(&msg);
3187 DispatchMessage(&msg);
3188 }
3189 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3190 }
3191
3192 demo.cleanup();
3193
3194 return (int)msg.wParam;
3195}
3196
3197#elif __linux__
3198
Jeremy Hayes9d304782016-10-09 11:48:12 -06003199int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003200 Demo demo;
3201
3202 demo.init(argc, argv);
3203
Tony Barbour153cb062016-12-07 13:43:36 -07003204#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003205 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003206#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003207 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003208 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003209#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003210 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003211#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3212 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003213#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003214
3215 demo.init_vk_swapchain();
3216
3217 demo.prepare();
3218
Tony Barbour153cb062016-12-07 13:43:36 -07003219#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003220 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003221#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003222 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003223#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003224 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003225#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3226 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003227#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3228 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003229#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003230
3231 demo.cleanup();
3232
3233 return validation_error;
3234}
3235
Bill Hollings0a0625a2019-07-15 17:39:18 -04003236#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003237
3238// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003239static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003240 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003241 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003242 demo.init_vk_swapchain();
3243 demo.prepare();
3244 demo.spin_angle = 0.4f;
3245}
3246
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003247#else
3248#error "Platform not supported"
3249#endif