2 * Copyright (c) 2015-2019 The Khronos Group Inc.
3 * Copyright (c) 2015-2019 Valve Corporation
4 * Copyright (c) 2015-2019 LunarG, Inc.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Author: Jeremy Hayes <jeremy@lunarg.com>
21 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
22 #include <X11/Xutil.h>
23 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
24 #include <linux/input.h>
25 #include "xdg-shell-client-header.h"
26 #include "xdg-decoration-client-header.h"
39 #define VULKAN_HPP_NO_SMART_HANDLE
40 #define VULKAN_HPP_NO_EXCEPTIONS
41 #define VULKAN_HPP_TYPESAFE_CONVERSION
42 #include <vulkan/vulkan.hpp>
43 #include <vulkan/vk_sdk_platform.h>
48 #define VERIFY(x) assert(x)
50 #define VERIFY(x) ((void)(x))
53 #define APP_SHORT_NAME "vkcube"
55 #define APP_NAME_STR_LEN 80
58 // Allow a maximum of two outstanding presentation operations.
61 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
64 #define ERR_EXIT(err_msg, err_class) \
66 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
70 #define ERR_EXIT(err_msg, err_class) \
72 printf("%s\n", err_msg); \
78 struct texture_object {
83 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
85 vk::MemoryAllocateInfo mem_alloc;
90 int32_t tex_height{0};
93 static char const *const tex_files[] = {"lunarg.ppm"};
95 static int validation_error = 0;
97 struct vkcube_vs_uniform {
98 // Must start with MVP
100 float position[12 * 3][4];
101 float color[12 * 3][4];
104 struct vktexcube_vs_uniform {
105 // Must start with MVP
107 float position[12 * 3][4];
108 float attr[12 * 3][4];
111 //--------------------------------------------------------------------------------------
112 // Mesh and VertexFormat Data
113 //--------------------------------------------------------------------------------------
115 static const float g_vertex_buffer_data[] = {
116 -1.0f,-1.0f,-1.0f, // -X side
123 -1.0f,-1.0f,-1.0f, // -Z side
130 -1.0f,-1.0f,-1.0f, // -Y side
137 -1.0f, 1.0f,-1.0f, // +Y side
144 1.0f, 1.0f,-1.0f, // +X side
151 -1.0f, 1.0f, 1.0f, // +Z side
159 static const float g_uv_buffer_data[] = {
160 0.0f, 1.0f, // -X side
167 1.0f, 1.0f, // -Z side
174 1.0f, 0.0f, // -Y side
181 1.0f, 0.0f, // +Y side
188 1.0f, 0.0f, // +X side
195 0.0f, 0.0f, // +Z side
206 vk::CommandBuffer cmd;
207 vk::CommandBuffer graphics_to_present_cmd;
209 vk::Buffer uniform_buffer;
210 vk::DeviceMemory uniform_memory;
211 vk::Framebuffer framebuffer;
212 vk::DescriptorSet descriptor_set;
213 } SwapchainImageResources;
217 void build_image_ownership_cmd(uint32_t const &);
218 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
220 void create_device();
221 void destroy_texture(texture_object *);
223 void draw_build_cmd(vk::CommandBuffer);
224 void flush_init_cmd();
225 void init(int, char **);
226 void init_connection();
228 void init_vk_swapchain();
230 void prepare_buffers();
231 void prepare_cube_data_buffers();
232 void prepare_depth();
233 void prepare_descriptor_layout();
234 void prepare_descriptor_pool();
235 void prepare_descriptor_set();
236 void prepare_framebuffers();
237 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
238 vk::ShaderModule prepare_vs();
239 vk::ShaderModule prepare_fs();
240 void prepare_pipeline();
241 void prepare_render_pass();
242 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
243 void prepare_texture_buffer(const char *, texture_object *);
244 void prepare_textures();
247 void create_surface();
248 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
249 vk::PipelineStageFlags, vk::PipelineStageFlags);
250 void update_data_buffer();
251 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
252 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
254 #if defined(VK_USE_PLATFORM_WIN32_KHR)
256 void create_window();
257 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
258 void create_xlib_window();
259 void handle_xlib_event(const XEvent *);
261 #elif defined(VK_USE_PLATFORM_XCB_KHR)
262 void handle_xcb_event(const xcb_generic_event_t *);
264 void create_xcb_window();
265 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
267 void create_window();
268 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
270 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
271 vk::Result create_display_surface();
275 #if defined(VK_USE_PLATFORM_WIN32_KHR)
276 HINSTANCE connection; // hInstance - Windows Instance
277 HWND window; // hWnd - window handle
278 POINT minsize; // minimum window size
279 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
280 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
282 Atom xlib_wm_delete_window;
284 #elif defined(VK_USE_PLATFORM_XCB_KHR)
285 xcb_window_t xcb_window;
286 xcb_screen_t *screen;
287 xcb_connection_t *connection;
288 xcb_intern_atom_reply_t *atom_wm_delete_window;
289 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
291 wl_registry *registry;
292 wl_compositor *compositor;
294 xdg_wm_base *wm_base;
295 zxdg_decoration_manager_v1 *xdg_decoration_mgr;
296 zxdg_toplevel_decoration_v1 *toplevel_decoration;
297 xdg_surface *window_surface;
298 bool xdg_surface_has_been_configured;
299 xdg_toplevel *window_toplevel;
302 wl_keyboard *keyboard;
303 #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
307 vk::SurfaceKHR surface;
309 bool use_staging_buffer;
311 bool separate_present_queue;
314 vk::PhysicalDevice gpu;
316 vk::Queue graphics_queue;
317 vk::Queue present_queue;
318 uint32_t graphics_queue_family_index;
319 uint32_t present_queue_family_index;
320 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
321 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
322 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
323 vk::PhysicalDeviceProperties gpu_props;
324 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
325 vk::PhysicalDeviceMemoryProperties memory_properties;
327 uint32_t enabled_extension_count;
328 uint32_t enabled_layer_count;
329 char const *extension_names[64];
330 char const *enabled_layers[64];
335 vk::ColorSpaceKHR color_space;
337 uint32_t swapchainImageCount;
338 vk::SwapchainKHR swapchain;
339 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
340 vk::PresentModeKHR presentMode;
341 vk::Fence fences[FRAME_LAG];
342 uint32_t frame_index;
344 vk::CommandPool cmd_pool;
345 vk::CommandPool present_cmd_pool;
350 vk::MemoryAllocateInfo mem_alloc;
351 vk::DeviceMemory mem;
355 static int32_t const texture_count = 1;
356 texture_object textures[texture_count];
357 texture_object staging_texture;
361 vk::MemoryAllocateInfo mem_alloc;
362 vk::DeviceMemory mem;
363 vk::DescriptorBufferInfo buffer_info;
366 vk::CommandBuffer cmd; // Buffer for initialization commands
367 vk::PipelineLayout pipeline_layout;
368 vk::DescriptorSetLayout desc_layout;
369 vk::PipelineCache pipelineCache;
370 vk::RenderPass render_pass;
371 vk::Pipeline pipeline;
373 mat4x4 projection_matrix;
378 float spin_increment;
381 vk::ShaderModule vert_shader_module;
382 vk::ShaderModule frag_shader_module;
384 vk::DescriptorPool desc_pool;
385 vk::DescriptorSet desc_set;
387 std::unique_ptr<vk::Framebuffer[]> framebuffers;
394 bool suppress_popups;
396 uint32_t current_buffer;
397 uint32_t queue_family_count;
401 // MS-Windows event handling function:
402 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
405 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
406 static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
407 wl_shell_surface_pong(shell_surface, serial);
410 static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
412 static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
414 static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
416 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
419 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
421 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
423 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
425 Demo *demo = (Demo *)data;
426 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
427 xdg_toplevel_move(demo->window_toplevel, demo->seat, serial);
431 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
433 static const struct wl_pointer_listener pointer_listener = {
434 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
437 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
439 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
440 struct wl_array *keys) {}
442 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
444 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
446 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
447 Demo *demo = (Demo *)data;
449 case KEY_ESC: // Escape
452 case KEY_LEFT: // left arrow key
453 demo->spin_angle -= demo->spin_increment;
455 case KEY_RIGHT: // right arrow key
456 demo->spin_angle += demo->spin_increment;
458 case KEY_SPACE: // space bar
459 demo->pause = !demo->pause;
464 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
465 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
467 static const struct wl_keyboard_listener keyboard_listener = {
468 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
471 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
472 // Subscribe to pointer events
473 Demo *demo = (Demo *)data;
474 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
475 demo->pointer = wl_seat_get_pointer(seat);
476 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
477 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
478 wl_pointer_destroy(demo->pointer);
479 demo->pointer = NULL;
481 // Subscribe to keyboard events
482 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
483 demo->keyboard = wl_seat_get_keyboard(seat);
484 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
485 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
486 wl_keyboard_destroy(demo->keyboard);
487 demo->keyboard = NULL;
491 static const wl_seat_listener seat_listener = {
492 seat_handle_capabilities,
495 static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
497 static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
499 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
500 Demo *demo = (Demo *)data;
501 // pickup wayland objects when they appear
502 if (strcmp(interface, wl_compositor_interface.name) == 0) {
503 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
504 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
505 demo->wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
506 xdg_wm_base_add_listener(demo->wm_base, &wm_base_listener, nullptr);
507 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
508 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
509 wl_seat_add_listener(demo->seat, &seat_listener, demo);
510 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
511 demo->xdg_decoration_mgr =
512 (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
516 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
518 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
523 #if defined(VK_USE_PLATFORM_WIN32_KHR)
526 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
529 #if defined(VK_USE_PLATFORM_XLIB_KHR)
531 xlib_wm_delete_window{0},
533 #elif defined(VK_USE_PLATFORM_XCB_KHR)
537 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
543 xdg_decoration_mgr{nullptr},
544 toplevel_decoration{nullptr},
545 window_surface{nullptr},
546 xdg_surface_has_been_configured{false},
547 window_toplevel{nullptr},
553 use_staging_buffer{false},
555 graphics_queue_family_index{0},
556 present_queue_family_index{0},
557 enabled_extension_count{0},
558 enabled_layer_count{0},
561 swapchainImageCount{0},
562 presentMode{vk::PresentModeKHR::eFifo},
565 spin_increment{0.0f},
572 suppress_popups{false},
574 queue_family_count{0} {
575 #if defined(VK_USE_PLATFORM_WIN32_KHR)
576 memset(name, '\0', APP_NAME_STR_LEN);
578 memset(projection_matrix, 0, sizeof(projection_matrix));
579 memset(view_matrix, 0, sizeof(view_matrix));
580 memset(model_matrix, 0, sizeof(model_matrix));
583 void Demo::build_image_ownership_cmd(uint32_t const &i) {
584 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
585 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
586 VERIFY(result == vk::Result::eSuccess);
588 auto const image_ownership_barrier =
589 vk::ImageMemoryBarrier()
590 .setSrcAccessMask(vk::AccessFlags())
591 .setDstAccessMask(vk::AccessFlags())
592 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
593 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
594 .setSrcQueueFamilyIndex(graphics_queue_family_index)
595 .setDstQueueFamilyIndex(present_queue_family_index)
596 .setImage(swapchain_image_resources[i].image)
597 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
599 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
600 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
601 nullptr, 1, &image_ownership_barrier);
603 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
604 VERIFY(result == vk::Result::eSuccess);
607 vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
608 vk::LayerProperties *layers) {
609 for (uint32_t i = 0; i < check_count; i++) {
610 vk::Bool32 found = VK_FALSE;
611 for (uint32_t j = 0; j < layer_count; j++) {
612 if (!strcmp(check_names[i], layers[j].layerName)) {
618 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
625 void Demo::cleanup() {
629 // Wait for fences from present operations
630 for (uint32_t i = 0; i < FRAME_LAG; i++) {
631 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
632 device.destroyFence(fences[i], nullptr);
633 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
634 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
635 if (separate_present_queue) {
636 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
640 for (uint32_t i = 0; i < swapchainImageCount; i++) {
641 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
643 device.destroyDescriptorPool(desc_pool, nullptr);
645 device.destroyPipeline(pipeline, nullptr);
646 device.destroyPipelineCache(pipelineCache, nullptr);
647 device.destroyRenderPass(render_pass, nullptr);
648 device.destroyPipelineLayout(pipeline_layout, nullptr);
649 device.destroyDescriptorSetLayout(desc_layout, nullptr);
651 for (uint32_t i = 0; i < texture_count; i++) {
652 device.destroyImageView(textures[i].view, nullptr);
653 device.destroyImage(textures[i].image, nullptr);
654 device.freeMemory(textures[i].mem, nullptr);
655 device.destroySampler(textures[i].sampler, nullptr);
657 device.destroySwapchainKHR(swapchain, nullptr);
659 device.destroyImageView(depth.view, nullptr);
660 device.destroyImage(depth.image, nullptr);
661 device.freeMemory(depth.mem, nullptr);
663 for (uint32_t i = 0; i < swapchainImageCount; i++) {
664 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
665 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
666 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
667 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
670 device.destroyCommandPool(cmd_pool, nullptr);
672 if (separate_present_queue) {
673 device.destroyCommandPool(present_cmd_pool, nullptr);
676 device.destroy(nullptr);
677 inst.destroySurfaceKHR(surface, nullptr);
679 #if defined(VK_USE_PLATFORM_XLIB_KHR)
680 XDestroyWindow(display, xlib_window);
681 XCloseDisplay(display);
682 #elif defined(VK_USE_PLATFORM_XCB_KHR)
683 xcb_destroy_window(connection, xcb_window);
684 xcb_disconnect(connection);
685 free(atom_wm_delete_window);
686 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
687 wl_keyboard_destroy(keyboard);
688 wl_pointer_destroy(pointer);
689 wl_seat_destroy(seat);
690 xdg_toplevel_destroy(window_toplevel);
691 xdg_surface_destroy(window_surface);
692 wl_surface_destroy(window);
693 xdg_wm_base_destroy(wm_base);
694 if (xdg_decoration_mgr) {
695 zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
696 zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
698 wl_compositor_destroy(compositor);
699 wl_registry_destroy(registry);
700 wl_display_disconnect(display);
703 inst.destroy(nullptr);
706 void Demo::create_device() {
707 float const priorities[1] = {0.0};
709 vk::DeviceQueueCreateInfo queues[2];
710 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
711 queues[0].setQueueCount(1);
712 queues[0].setPQueuePriorities(priorities);
714 auto deviceInfo = vk::DeviceCreateInfo()
715 .setQueueCreateInfoCount(1)
716 .setPQueueCreateInfos(queues)
717 .setEnabledLayerCount(0)
718 .setPpEnabledLayerNames(nullptr)
719 .setEnabledExtensionCount(enabled_extension_count)
720 .setPpEnabledExtensionNames((const char *const *)extension_names)
721 .setPEnabledFeatures(nullptr);
723 if (separate_present_queue) {
724 queues[1].setQueueFamilyIndex(present_queue_family_index);
725 queues[1].setQueueCount(1);
726 queues[1].setPQueuePriorities(priorities);
727 deviceInfo.setQueueCreateInfoCount(2);
730 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
731 VERIFY(result == vk::Result::eSuccess);
734 void Demo::destroy_texture(texture_object *tex_objs) {
735 // clean up staging resources
736 device.freeMemory(tex_objs->mem, nullptr);
737 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
738 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
742 // Ensure no more than FRAME_LAG renderings are outstanding
743 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
744 device.resetFences(1, &fences[frame_index]);
749 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer);
750 if (result == vk::Result::eErrorOutOfDateKHR) {
751 // demo->swapchain is out of date (e.g. the window was resized) and
752 // must be recreated:
754 } else if (result == vk::Result::eSuboptimalKHR) {
755 // swapchain is not as optimal as it could be, but the platform's
756 // presentation engine will still present the image correctly.
758 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
759 inst.destroySurfaceKHR(surface, nullptr);
763 VERIFY(result == vk::Result::eSuccess);
765 } while (result != vk::Result::eSuccess);
767 update_data_buffer();
769 // Wait for the image acquired semaphore to be signaled to ensure
770 // that the image won't be rendered to until the presentation
771 // engine has fully released ownership to the application, and it is
772 // okay to render to the image.
773 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
774 auto const submit_info = vk::SubmitInfo()
775 .setPWaitDstStageMask(&pipe_stage_flags)
776 .setWaitSemaphoreCount(1)
777 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
778 .setCommandBufferCount(1)
779 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
780 .setSignalSemaphoreCount(1)
781 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
783 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
784 VERIFY(result == vk::Result::eSuccess);
786 if (separate_present_queue) {
787 // If we are using separate queues, change image ownership to the
788 // present queue before presenting, waiting for the draw complete
789 // semaphore and signalling the ownership released semaphore when
791 auto const present_submit_info = vk::SubmitInfo()
792 .setPWaitDstStageMask(&pipe_stage_flags)
793 .setWaitSemaphoreCount(1)
794 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
795 .setCommandBufferCount(1)
796 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
797 .setSignalSemaphoreCount(1)
798 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
800 result = present_queue.submit(1, &present_submit_info, vk::Fence());
801 VERIFY(result == vk::Result::eSuccess);
804 // If we are using separate queues we have to wait for image ownership,
805 // otherwise wait for draw complete
806 auto const presentInfo = vk::PresentInfoKHR()
807 .setWaitSemaphoreCount(1)
808 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
809 : &draw_complete_semaphores[frame_index])
810 .setSwapchainCount(1)
811 .setPSwapchains(&swapchain)
812 .setPImageIndices(¤t_buffer);
814 result = present_queue.presentKHR(&presentInfo);
816 frame_index %= FRAME_LAG;
817 if (result == vk::Result::eErrorOutOfDateKHR) {
818 // swapchain is out of date (e.g. the window was resized) and
819 // must be recreated:
821 } else if (result == vk::Result::eSuboptimalKHR) {
822 // swapchain is not as optimal as it could be, but the platform's
823 // presentation engine will still present the image correctly.
824 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
825 inst.destroySurfaceKHR(surface, nullptr);
829 VERIFY(result == vk::Result::eSuccess);
833 void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
834 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
836 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
837 vk::ClearDepthStencilValue(1.0f, 0u)};
839 auto const passInfo = vk::RenderPassBeginInfo()
840 .setRenderPass(render_pass)
841 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
842 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
843 .setClearValueCount(2)
844 .setPClearValues(clearValues);
846 auto result = commandBuffer.begin(&commandInfo);
847 VERIFY(result == vk::Result::eSuccess);
849 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
850 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
851 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
852 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
854 auto const viewport =
855 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
856 commandBuffer.setViewport(0, 1, &viewport);
858 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
859 commandBuffer.setScissor(0, 1, &scissor);
860 commandBuffer.draw(12 * 3, 1, 0, 0);
861 // Note that ending the renderpass changes the image's layout from
862 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
863 commandBuffer.endRenderPass();
865 if (separate_present_queue) {
866 // We have to transfer ownership from the graphics queue family to
868 // present queue family to be able to present. Note that we don't
870 // to transfer from present queue family back to graphics queue
872 // the start of the next frame because we don't care about the
874 // contents at that point.
875 auto const image_ownership_barrier =
876 vk::ImageMemoryBarrier()
877 .setSrcAccessMask(vk::AccessFlags())
878 .setDstAccessMask(vk::AccessFlags())
879 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
880 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
881 .setSrcQueueFamilyIndex(graphics_queue_family_index)
882 .setDstQueueFamilyIndex(present_queue_family_index)
883 .setImage(swapchain_image_resources[current_buffer].image)
884 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
886 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
887 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
890 result = commandBuffer.end();
891 VERIFY(result == vk::Result::eSuccess);
894 void Demo::flush_init_cmd() {
896 // This function could get called twice if the texture uses a staging
898 // In that case the second call should be ignored
903 auto result = cmd.end();
904 VERIFY(result == vk::Result::eSuccess);
906 auto const fenceInfo = vk::FenceCreateInfo();
908 result = device.createFence(&fenceInfo, nullptr, &fence);
909 VERIFY(result == vk::Result::eSuccess);
911 vk::CommandBuffer const commandBuffers[] = {cmd};
912 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
914 result = graphics_queue.submit(1, &submitInfo, fence);
915 VERIFY(result == vk::Result::eSuccess);
917 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
918 VERIFY(result == vk::Result::eSuccess);
920 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
921 device.destroyFence(fence, nullptr);
923 cmd = vk::CommandBuffer();
926 void Demo::init(int argc, char **argv) {
927 vec3 eye = {0.0f, 3.0f, 5.0f};
928 vec3 origin = {0, 0, 0};
929 vec3 up = {0.0f, 1.0f, 0.0};
931 presentMode = vk::PresentModeKHR::eFifo;
932 frameCount = UINT32_MAX;
935 for (int i = 1; i < argc; i++) {
936 if (strcmp(argv[i], "--use_staging") == 0) {
937 use_staging_buffer = true;
940 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
941 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
945 if (strcmp(argv[i], "--break") == 0) {
949 if (strcmp(argv[i], "--validate") == 0) {
953 if (strcmp(argv[i], "--xlib") == 0) {
954 fprintf(stderr, "--xlib is deprecated and no longer does anything");
957 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
958 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
962 if (strcmp(argv[i], "--suppress_popups") == 0) {
963 suppress_popups = true;
967 std::stringstream usage;
968 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
969 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
970 << "\t[--present_mode <present mode enum>]\n"
971 << "\t<present_mode_enum>\n"
972 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
973 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
974 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
975 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
978 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
980 std::cerr << usage.str();
996 spin_increment = 0.2f;
999 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1000 mat4x4_look_at(view_matrix, eye, origin, up);
1001 mat4x4_identity(model_matrix);
1003 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1006 void Demo::init_connection() {
1007 #if defined(VK_USE_PLATFORM_XCB_KHR)
1008 const xcb_setup_t *setup;
1009 xcb_screen_iterator_t iter;
1012 const char *display_envar = getenv("DISPLAY");
1013 if (display_envar == nullptr || display_envar[0] == '\0') {
1014 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1019 connection = xcb_connect(nullptr, &scr);
1020 if (xcb_connection_has_error(connection) > 0) {
1022 "Cannot find a compatible Vulkan installable client driver "
1023 "(ICD).\nExiting ...\n");
1028 setup = xcb_get_setup(connection);
1029 iter = xcb_setup_roots_iterator(setup);
1030 while (scr-- > 0) xcb_screen_next(&iter);
1033 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1034 display = wl_display_connect(nullptr);
1036 if (display == nullptr) {
1037 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1042 registry = wl_display_get_registry(display);
1043 wl_registry_add_listener(registry, ®istry_listener, this);
1044 wl_display_dispatch(display);
1048 void Demo::init_vk() {
1049 uint32_t instance_extension_count = 0;
1050 uint32_t instance_layer_count = 0;
1051 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
1052 enabled_extension_count = 0;
1053 enabled_layer_count = 0;
1055 // Look for validation layers
1056 vk::Bool32 validation_found = VK_FALSE;
1058 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
1059 VERIFY(result == vk::Result::eSuccess);
1061 if (instance_layer_count > 0) {
1062 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1063 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
1064 VERIFY(result == vk::Result::eSuccess);
1066 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
1067 instance_layer_count, instance_layers.get());
1068 if (validation_found) {
1069 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1070 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
1074 if (!validation_found) {
1076 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1077 "Please look at the Getting Started guide for additional information.\n",
1078 "vkCreateInstance Failure");
1082 /* Look for instance extensions */
1083 vk::Bool32 surfaceExtFound = VK_FALSE;
1084 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1085 memset(extension_names, 0, sizeof(extension_names));
1087 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1088 static_cast<vk::ExtensionProperties *>(nullptr));
1089 VERIFY(result == vk::Result::eSuccess);
1091 if (instance_extension_count > 0) {
1092 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1093 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1094 VERIFY(result == vk::Result::eSuccess);
1096 for (uint32_t i = 0; i < instance_extension_count; i++) {
1097 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1098 surfaceExtFound = 1;
1099 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1101 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1102 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1103 platformSurfaceExtFound = 1;
1104 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1106 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1107 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1108 platformSurfaceExtFound = 1;
1109 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1111 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1112 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1113 platformSurfaceExtFound = 1;
1114 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1116 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1117 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1118 platformSurfaceExtFound = 1;
1119 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1121 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1122 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1123 platformSurfaceExtFound = 1;
1124 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1126 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1127 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1128 platformSurfaceExtFound = 1;
1129 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1131 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1132 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1133 platformSurfaceExtFound = 1;
1134 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1138 assert(enabled_extension_count < 64);
1142 if (!surfaceExtFound) {
1143 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1145 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1146 "Please look at the Getting Started guide for additional information.\n",
1147 "vkCreateInstance Failure");
1150 if (!platformSurfaceExtFound) {
1151 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1152 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1154 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1155 "Please look at the Getting Started guide for additional information.\n",
1156 "vkCreateInstance Failure");
1157 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1158 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1160 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1161 "Please look at the Getting Started guide for additional information.\n",
1162 "vkCreateInstance Failure");
1163 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1164 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1166 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1167 "Please look at the Getting Started guide for additional information.\n",
1168 "vkCreateInstance Failure");
1169 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1170 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1172 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1173 "Please look at the Getting Started guide for additional information.\n",
1174 "vkCreateInstance Failure");
1175 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1176 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1178 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1179 "Please look at the Getting Started guide for additional information.\n",
1180 "vkCreateInstance Failure");
1181 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1182 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1183 " extension.\n\nDo you have a compatible "
1184 "Vulkan installable client driver (ICD) installed?\nPlease "
1185 "look at the Getting Started guide for additional "
1187 "vkCreateInstance Failure");
1188 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1189 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1190 " extension.\n\nDo you have a compatible "
1191 "Vulkan installable client driver (ICD) installed?\nPlease "
1192 "look at the Getting Started guide for additional "
1194 "vkCreateInstance Failure");
1197 auto const app = vk::ApplicationInfo()
1198 .setPApplicationName(APP_SHORT_NAME)
1199 .setApplicationVersion(0)
1200 .setPEngineName(APP_SHORT_NAME)
1201 .setEngineVersion(0)
1202 .setApiVersion(VK_API_VERSION_1_0);
1203 auto const inst_info = vk::InstanceCreateInfo()
1204 .setPApplicationInfo(&app)
1205 .setEnabledLayerCount(enabled_layer_count)
1206 .setPpEnabledLayerNames(instance_validation_layers)
1207 .setEnabledExtensionCount(enabled_extension_count)
1208 .setPpEnabledExtensionNames(extension_names);
1210 result = vk::createInstance(&inst_info, nullptr, &inst);
1211 if (result == vk::Result::eErrorIncompatibleDriver) {
1213 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1214 "Please look at the Getting Started guide for additional information.\n",
1215 "vkCreateInstance Failure");
1216 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1218 "Cannot find a specified extension library.\n"
1219 "Make sure your layers path is set appropriately.\n",
1220 "vkCreateInstance Failure");
1221 } else if (result != vk::Result::eSuccess) {
1223 "vkCreateInstance failed.\n\n"
1224 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1225 "Please look at the Getting Started guide for additional information.\n",
1226 "vkCreateInstance Failure");
1229 /* Make initial call to query gpu_count, then second call for gpu info*/
1231 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
1232 VERIFY(result == vk::Result::eSuccess);
1234 if (gpu_count > 0) {
1235 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1236 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1237 VERIFY(result == vk::Result::eSuccess);
1238 /* For cube demo we just grab the first physical device */
1239 gpu = physical_devices[0];
1242 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1243 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1244 "Please look at the Getting Started guide for additional information.\n",
1245 "vkEnumeratePhysicalDevices Failure");
1248 /* Look for device extensions */
1249 uint32_t device_extension_count = 0;
1250 vk::Bool32 swapchainExtFound = VK_FALSE;
1251 enabled_extension_count = 0;
1252 memset(extension_names, 0, sizeof(extension_names));
1255 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
1256 VERIFY(result == vk::Result::eSuccess);
1258 if (device_extension_count > 0) {
1259 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1260 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1261 VERIFY(result == vk::Result::eSuccess);
1263 for (uint32_t i = 0; i < device_extension_count; i++) {
1264 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1265 swapchainExtFound = 1;
1266 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1268 assert(enabled_extension_count < 64);
1272 if (!swapchainExtFound) {
1273 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1275 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1276 "Please look at the Getting Started guide for additional information.\n",
1277 "vkCreateInstance Failure");
1280 gpu.getProperties(&gpu_props);
1282 /* Call with nullptr data to get count */
1283 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
1284 assert(queue_family_count >= 1);
1286 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1287 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1289 // Query fine-grained feature support for this device.
1290 // If app has specific feature requirements it should check supported
1291 // features based on this query
1292 vk::PhysicalDeviceFeatures physDevFeatures;
1293 gpu.getFeatures(&physDevFeatures);
1296 void Demo::create_surface() {
1297 // Create a WSI surface for the window:
1298 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1300 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1302 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1303 VERIFY(result == vk::Result::eSuccess);
1305 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1307 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1309 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1310 VERIFY(result == vk::Result::eSuccess);
1312 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1314 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1316 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1317 VERIFY(result == vk::Result::eSuccess);
1319 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1321 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1323 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1324 VERIFY(result == vk::Result::eSuccess);
1326 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1328 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1330 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1331 VERIFY(result == vk::Result::eSuccess);
1333 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1335 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1337 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1338 VERIFY(result == vk::Result::eSuccess);
1340 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1342 auto result = create_display_surface();
1343 VERIFY(result == vk::Result::eSuccess);
1348 void Demo::init_vk_swapchain() {
1350 // Iterate over each queue to learn whether it supports presenting:
1351 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1352 for (uint32_t i = 0; i < queue_family_count; i++) {
1353 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1356 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1357 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1358 for (uint32_t i = 0; i < queue_family_count; i++) {
1359 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1360 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1361 graphicsQueueFamilyIndex = i;
1364 if (supportsPresent[i] == VK_TRUE) {
1365 graphicsQueueFamilyIndex = i;
1366 presentQueueFamilyIndex = i;
1372 if (presentQueueFamilyIndex == UINT32_MAX) {
1373 // If didn't find a queue that supports both graphics and present,
1375 // find a separate present queue.
1376 for (uint32_t i = 0; i < queue_family_count; ++i) {
1377 if (supportsPresent[i] == VK_TRUE) {
1378 presentQueueFamilyIndex = i;
1384 // Generate error if could not find both a graphics and a present queue
1385 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1386 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1389 graphics_queue_family_index = graphicsQueueFamilyIndex;
1390 present_queue_family_index = presentQueueFamilyIndex;
1391 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1395 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1396 if (!separate_present_queue) {
1397 present_queue = graphics_queue;
1399 device.getQueue(present_queue_family_index, 0, &present_queue);
1402 // Get the list of VkFormat's that are supported:
1403 uint32_t formatCount;
1404 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
1405 VERIFY(result == vk::Result::eSuccess);
1407 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1408 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1409 VERIFY(result == vk::Result::eSuccess);
1411 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1412 // the surface has no preferred format. Otherwise, at least one
1413 // supported format will be returned.
1414 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1415 format = vk::Format::eB8G8R8A8Unorm;
1417 assert(formatCount >= 1);
1418 format = surfFormats[0].format;
1420 color_space = surfFormats[0].colorSpace;
1425 // Create semaphores to synchronize acquiring presentable buffers before
1426 // rendering and waiting for drawing to be complete before presenting
1427 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1429 // Create fences that we can use to throttle if we get too far
1430 // ahead of the image presents
1431 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1432 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1433 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1434 VERIFY(result == vk::Result::eSuccess);
1436 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1437 VERIFY(result == vk::Result::eSuccess);
1439 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1440 VERIFY(result == vk::Result::eSuccess);
1442 if (separate_present_queue) {
1443 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1444 VERIFY(result == vk::Result::eSuccess);
1449 // Get Memory information and properties
1450 gpu.getMemoryProperties(&memory_properties);
1453 void Demo::prepare() {
1454 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1455 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1456 VERIFY(result == vk::Result::eSuccess);
1458 auto const cmd = vk::CommandBufferAllocateInfo()
1459 .setCommandPool(cmd_pool)
1460 .setLevel(vk::CommandBufferLevel::ePrimary)
1461 .setCommandBufferCount(1);
1463 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1464 VERIFY(result == vk::Result::eSuccess);
1466 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1468 result = this->cmd.begin(&cmd_buf_info);
1469 VERIFY(result == vk::Result::eSuccess);
1474 prepare_cube_data_buffers();
1476 prepare_descriptor_layout();
1477 prepare_render_pass();
1480 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1481 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1482 VERIFY(result == vk::Result::eSuccess);
1485 if (separate_present_queue) {
1486 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1488 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1489 VERIFY(result == vk::Result::eSuccess);
1491 auto const present_cmd = vk::CommandBufferAllocateInfo()
1492 .setCommandPool(present_cmd_pool)
1493 .setLevel(vk::CommandBufferLevel::ePrimary)
1494 .setCommandBufferCount(1);
1496 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1497 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1498 VERIFY(result == vk::Result::eSuccess);
1500 build_image_ownership_cmd(i);
1504 prepare_descriptor_pool();
1505 prepare_descriptor_set();
1507 prepare_framebuffers();
1509 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1511 draw_build_cmd(swapchain_image_resources[i].cmd);
1515 * Prepare functions above may generate pipeline commands
1516 * that need to be flushed before beginning the render loop.
1519 if (staging_texture.buffer) {
1520 destroy_texture(&staging_texture);
1527 void Demo::prepare_buffers() {
1528 vk::SwapchainKHR oldSwapchain = swapchain;
1530 // Check the surface capabilities and formats
1531 vk::SurfaceCapabilitiesKHR surfCapabilities;
1532 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1533 VERIFY(result == vk::Result::eSuccess);
1535 uint32_t presentModeCount;
1536 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
1537 VERIFY(result == vk::Result::eSuccess);
1539 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1540 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1541 VERIFY(result == vk::Result::eSuccess);
1543 vk::Extent2D swapchainExtent;
1544 // width and height are either both -1, or both not -1.
1545 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1546 // If the surface size is undefined, the size is set to
1547 // the size of the images requested.
1548 swapchainExtent.width = width;
1549 swapchainExtent.height = height;
1551 // If the surface size is defined, the swap chain size must match
1552 swapchainExtent = surfCapabilities.currentExtent;
1553 width = surfCapabilities.currentExtent.width;
1554 height = surfCapabilities.currentExtent.height;
1557 // The FIFO present mode is guaranteed by the spec to be supported
1558 // and to have no tearing. It's a great default present mode to use.
1559 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1561 // There are times when you may wish to use another present mode. The
1562 // following code shows how to select them, and the comments provide some
1563 // reasons you may wish to use them.
1565 // It should be noted that Vulkan 1.0 doesn't provide a method for
1566 // synchronizing rendering with the presentation engine's display. There
1567 // is a method provided for throttling rendering with the display, but
1568 // there are some presentation engines for which this method will not work.
1569 // If an application doesn't throttle its rendering, and if it renders much
1570 // faster than the refresh rate of the display, this can waste power on
1571 // mobile devices. That is because power is being spent rendering images
1572 // that may never be seen.
1574 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1576 // tearing, or have some way of synchronizing their rendering with the
1578 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1579 // generally render a new presentable image every refresh cycle, but are
1580 // occasionally early. In this case, the application wants the new
1582 // to be displayed instead of the previously-queued-for-presentation
1584 // that has not yet been displayed.
1585 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1586 // render a new presentable image every refresh cycle, but are
1588 // late. In this case (perhaps because of stuttering/latency concerns),
1589 // the application wants the late image to be immediately displayed,
1591 // though that may mean some tearing.
1593 if (presentMode != swapchainPresentMode) {
1594 for (size_t i = 0; i < presentModeCount; ++i) {
1595 if (presentModes[i] == presentMode) {
1596 swapchainPresentMode = presentMode;
1602 if (swapchainPresentMode != presentMode) {
1603 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1606 // Determine the number of VkImages to use in the swap chain.
1607 // Application desires to acquire 3 images at a time for triple
1609 uint32_t desiredNumOfSwapchainImages = 3;
1610 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1611 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1614 // If maxImageCount is 0, we can ask for as many images as we want,
1616 // we're limited to maxImageCount
1617 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1618 // Application must settle for fewer images than desired:
1619 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1622 vk::SurfaceTransformFlagBitsKHR preTransform;
1623 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1624 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1626 preTransform = surfCapabilities.currentTransform;
1629 // Find a supported composite alpha mode - one of these is guaranteed to be set
1630 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1631 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1632 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1633 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1634 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1635 vk::CompositeAlphaFlagBitsKHR::eInherit,
1637 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1638 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1639 compositeAlpha = compositeAlphaFlags[i];
1644 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1645 .setSurface(surface)
1646 .setMinImageCount(desiredNumOfSwapchainImages)
1647 .setImageFormat(format)
1648 .setImageColorSpace(color_space)
1649 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1650 .setImageArrayLayers(1)
1651 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1652 .setImageSharingMode(vk::SharingMode::eExclusive)
1653 .setQueueFamilyIndexCount(0)
1654 .setPQueueFamilyIndices(nullptr)
1655 .setPreTransform(preTransform)
1656 .setCompositeAlpha(compositeAlpha)
1657 .setPresentMode(swapchainPresentMode)
1659 .setOldSwapchain(oldSwapchain);
1661 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1662 VERIFY(result == vk::Result::eSuccess);
1664 // If we just re-created an existing swapchain, we should destroy the
1666 // swapchain at this point.
1667 // Note: destroying the swapchain also cleans up all its associated
1668 // presentable images once the platform is done with them.
1670 device.destroySwapchainKHR(oldSwapchain, nullptr);
1673 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
1674 VERIFY(result == vk::Result::eSuccess);
1676 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1677 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1678 VERIFY(result == vk::Result::eSuccess);
1680 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1682 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1683 auto color_image_view = vk::ImageViewCreateInfo()
1684 .setViewType(vk::ImageViewType::e2D)
1686 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1688 swapchain_image_resources[i].image = swapchainImages[i];
1690 color_image_view.image = swapchain_image_resources[i].image;
1692 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1693 VERIFY(result == vk::Result::eSuccess);
1697 void Demo::prepare_cube_data_buffers() {
1699 mat4x4_mul(VP, projection_matrix, view_matrix);
1702 mat4x4_mul(MVP, VP, model_matrix);
1704 vktexcube_vs_uniform data;
1705 memcpy(data.mvp, MVP, sizeof(MVP));
1706 // dumpMatrix("MVP", MVP)
1708 for (int32_t i = 0; i < 12 * 3; i++) {
1709 data.position[i][0] = g_vertex_buffer_data[i * 3];
1710 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1711 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1712 data.position[i][3] = 1.0f;
1713 data.attr[i][0] = g_uv_buffer_data[2 * i];
1714 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1715 data.attr[i][2] = 0;
1716 data.attr[i][3] = 0;
1719 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1721 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1722 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
1723 VERIFY(result == vk::Result::eSuccess);
1725 vk::MemoryRequirements mem_reqs;
1726 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1728 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1730 bool const pass = memory_type_from_properties(
1731 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1732 &mem_alloc.memoryTypeIndex);
1735 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
1736 VERIFY(result == vk::Result::eSuccess);
1738 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1739 VERIFY(pData.result == vk::Result::eSuccess);
1741 memcpy(pData.value, &data, sizeof data);
1743 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1746 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
1747 VERIFY(result == vk::Result::eSuccess);
1751 void Demo::prepare_depth() {
1752 depth.format = vk::Format::eD16Unorm;
1754 auto const image = vk::ImageCreateInfo()
1755 .setImageType(vk::ImageType::e2D)
1756 .setFormat(depth.format)
1757 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1760 .setSamples(vk::SampleCountFlagBits::e1)
1761 .setTiling(vk::ImageTiling::eOptimal)
1762 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1763 .setSharingMode(vk::SharingMode::eExclusive)
1764 .setQueueFamilyIndexCount(0)
1765 .setPQueueFamilyIndices(nullptr)
1766 .setInitialLayout(vk::ImageLayout::eUndefined);
1768 auto result = device.createImage(&image, nullptr, &depth.image);
1769 VERIFY(result == vk::Result::eSuccess);
1771 vk::MemoryRequirements mem_reqs;
1772 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1774 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1775 depth.mem_alloc.setMemoryTypeIndex(0);
1777 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1778 &depth.mem_alloc.memoryTypeIndex);
1781 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1782 VERIFY(result == vk::Result::eSuccess);
1784 result = device.bindImageMemory(depth.image, depth.mem, 0);
1785 VERIFY(result == vk::Result::eSuccess);
1787 auto const view = vk::ImageViewCreateInfo()
1788 .setImage(depth.image)
1789 .setViewType(vk::ImageViewType::e2D)
1790 .setFormat(depth.format)
1791 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1792 result = device.createImageView(&view, nullptr, &depth.view);
1793 VERIFY(result == vk::Result::eSuccess);
1796 void Demo::prepare_descriptor_layout() {
1797 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1799 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1800 .setDescriptorCount(1)
1801 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1802 .setPImmutableSamplers(nullptr),
1803 vk::DescriptorSetLayoutBinding()
1805 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1806 .setDescriptorCount(texture_count)
1807 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1808 .setPImmutableSamplers(nullptr)};
1810 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1812 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1813 VERIFY(result == vk::Result::eSuccess);
1815 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1817 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1818 VERIFY(result == vk::Result::eSuccess);
1821 void Demo::prepare_descriptor_pool() {
1822 vk::DescriptorPoolSize const poolSizes[2] = {
1823 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1824 vk::DescriptorPoolSize()
1825 .setType(vk::DescriptorType::eCombinedImageSampler)
1826 .setDescriptorCount(swapchainImageCount * texture_count)};
1828 auto const descriptor_pool =
1829 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1831 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1832 VERIFY(result == vk::Result::eSuccess);
1835 void Demo::prepare_descriptor_set() {
1836 auto const alloc_info =
1837 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1839 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1841 vk::DescriptorImageInfo tex_descs[texture_count];
1842 for (uint32_t i = 0; i < texture_count; i++) {
1843 tex_descs[i].setSampler(textures[i].sampler);
1844 tex_descs[i].setImageView(textures[i].view);
1845 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1848 vk::WriteDescriptorSet writes[2];
1850 writes[0].setDescriptorCount(1);
1851 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1852 writes[0].setPBufferInfo(&buffer_info);
1854 writes[1].setDstBinding(1);
1855 writes[1].setDescriptorCount(texture_count);
1856 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1857 writes[1].setPImageInfo(tex_descs);
1859 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1860 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
1861 VERIFY(result == vk::Result::eSuccess);
1863 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1864 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1865 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1866 device.updateDescriptorSets(2, writes, 0, nullptr);
1870 void Demo::prepare_framebuffers() {
1871 vk::ImageView attachments[2];
1872 attachments[1] = depth.view;
1874 auto const fb_info = vk::FramebufferCreateInfo()
1875 .setRenderPass(render_pass)
1876 .setAttachmentCount(2)
1877 .setPAttachments(attachments)
1878 .setWidth((uint32_t)width)
1879 .setHeight((uint32_t)height)
1882 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1883 attachments[0] = swapchain_image_resources[i].view;
1884 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
1885 VERIFY(result == vk::Result::eSuccess);
1889 vk::ShaderModule Demo::prepare_fs() {
1890 const uint32_t fragShaderCode[] = {
1891 #include "cube.frag.inc"
1894 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
1896 return frag_shader_module;
1899 void Demo::prepare_pipeline() {
1900 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1901 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1902 VERIFY(result == vk::Result::eSuccess);
1904 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1905 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1906 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1908 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1910 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1912 // TODO: Where are pViewports and pScissors set?
1913 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1915 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1916 .setDepthClampEnable(VK_FALSE)
1917 .setRasterizerDiscardEnable(VK_FALSE)
1918 .setPolygonMode(vk::PolygonMode::eFill)
1919 .setCullMode(vk::CullModeFlagBits::eBack)
1920 .setFrontFace(vk::FrontFace::eCounterClockwise)
1921 .setDepthBiasEnable(VK_FALSE)
1922 .setLineWidth(1.0f);
1924 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1926 auto const stencilOp =
1927 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1929 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1930 .setDepthTestEnable(VK_TRUE)
1931 .setDepthWriteEnable(VK_TRUE)
1932 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1933 .setDepthBoundsTestEnable(VK_FALSE)
1934 .setStencilTestEnable(VK_FALSE)
1935 .setFront(stencilOp)
1936 .setBack(stencilOp);
1938 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1939 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1940 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1942 auto const colorBlendInfo =
1943 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1945 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1947 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1949 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1951 .setPStages(shaderStageInfo)
1952 .setPVertexInputState(&vertexInputInfo)
1953 .setPInputAssemblyState(&inputAssemblyInfo)
1954 .setPViewportState(&viewportInfo)
1955 .setPRasterizationState(&rasterizationInfo)
1956 .setPMultisampleState(&multisampleInfo)
1957 .setPDepthStencilState(&depthStencilInfo)
1958 .setPColorBlendState(&colorBlendInfo)
1959 .setPDynamicState(&dynamicStateInfo)
1960 .setLayout(pipeline_layout)
1961 .setRenderPass(render_pass);
1963 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1964 VERIFY(result == vk::Result::eSuccess);
1966 device.destroyShaderModule(frag_shader_module, nullptr);
1967 device.destroyShaderModule(vert_shader_module, nullptr);
1970 void Demo::prepare_render_pass() {
1971 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1972 // because at the start of the renderpass, we don't care about their contents.
1973 // At the start of the subpass, the color attachment's layout will be transitioned
1974 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1975 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1976 // the renderpass, the color attachment's layout will be transitioned to
1977 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1978 // the renderpass, no barriers are necessary.
1979 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1981 .setSamples(vk::SampleCountFlagBits::e1)
1982 .setLoadOp(vk::AttachmentLoadOp::eClear)
1983 .setStoreOp(vk::AttachmentStoreOp::eStore)
1984 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1985 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1986 .setInitialLayout(vk::ImageLayout::eUndefined)
1987 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1988 vk::AttachmentDescription()
1989 .setFormat(depth.format)
1990 .setSamples(vk::SampleCountFlagBits::e1)
1991 .setLoadOp(vk::AttachmentLoadOp::eClear)
1992 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1993 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1994 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1995 .setInitialLayout(vk::ImageLayout::eUndefined)
1996 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1998 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2000 auto const depth_reference =
2001 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2003 auto const subpass = vk::SubpassDescription()
2004 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2005 .setInputAttachmentCount(0)
2006 .setPInputAttachments(nullptr)
2007 .setColorAttachmentCount(1)
2008 .setPColorAttachments(&color_reference)
2009 .setPResolveAttachments(nullptr)
2010 .setPDepthStencilAttachment(&depth_reference)
2011 .setPreserveAttachmentCount(0)
2012 .setPPreserveAttachments(nullptr);
2014 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2015 vk::SubpassDependency const dependencies[2] = {
2016 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2017 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2019 .setSrcStageMask(stages)
2020 .setDstStageMask(stages)
2021 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2022 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2023 .setDependencyFlags(vk::DependencyFlags()),
2024 vk::SubpassDependency() // Image layout transition
2025 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2027 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2028 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2029 .setSrcAccessMask(vk::AccessFlagBits())
2030 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2031 .setDependencyFlags(vk::DependencyFlags()),
2034 auto const rp_info = vk::RenderPassCreateInfo()
2035 .setAttachmentCount(2)
2036 .setPAttachments(attachments)
2038 .setPSubpasses(&subpass)
2039 .setDependencyCount(2)
2040 .setPDependencies(dependencies);
2042 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2043 VERIFY(result == vk::Result::eSuccess);
2046 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2047 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2049 vk::ShaderModule module;
2050 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2051 VERIFY(result == vk::Result::eSuccess);
2056 void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2060 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2061 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2064 tex_obj->tex_width = tex_width;
2065 tex_obj->tex_height = tex_height;
2067 auto const buffer_create_info = vk::BufferCreateInfo()
2068 .setSize(tex_width * tex_height * 4)
2069 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2070 .setSharingMode(vk::SharingMode::eExclusive)
2071 .setQueueFamilyIndexCount(0)
2072 .setPQueueFamilyIndices(nullptr);
2074 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2075 VERIFY(result == vk::Result::eSuccess);
2077 vk::MemoryRequirements mem_reqs;
2078 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2080 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2081 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2083 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2084 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2085 VERIFY(pass == true);
2087 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2088 VERIFY(result == vk::Result::eSuccess);
2090 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2091 VERIFY(result == vk::Result::eSuccess);
2093 vk::SubresourceLayout layout;
2094 memset(&layout, 0, sizeof(layout));
2095 layout.rowPitch = tex_width * 4;
2096 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2097 VERIFY(data.result == vk::Result::eSuccess);
2099 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2100 fprintf(stderr, "Error loading texture: %s\n", filename);
2103 device.unmapMemory(tex_obj->mem);
2106 void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2107 vk::MemoryPropertyFlags required_props) {
2110 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2111 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2114 tex_obj->tex_width = tex_width;
2115 tex_obj->tex_height = tex_height;
2117 auto const image_create_info = vk::ImageCreateInfo()
2118 .setImageType(vk::ImageType::e2D)
2119 .setFormat(vk::Format::eR8G8B8A8Unorm)
2120 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2123 .setSamples(vk::SampleCountFlagBits::e1)
2126 .setSharingMode(vk::SharingMode::eExclusive)
2127 .setQueueFamilyIndexCount(0)
2128 .setPQueueFamilyIndices(nullptr)
2129 .setInitialLayout(vk::ImageLayout::ePreinitialized);
2131 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2132 VERIFY(result == vk::Result::eSuccess);
2134 vk::MemoryRequirements mem_reqs;
2135 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
2137 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2138 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2140 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2141 VERIFY(pass == true);
2143 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2144 VERIFY(result == vk::Result::eSuccess);
2146 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2147 VERIFY(result == vk::Result::eSuccess);
2149 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2150 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2151 vk::SubresourceLayout layout;
2152 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
2154 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2155 VERIFY(data.result == vk::Result::eSuccess);
2157 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2158 fprintf(stderr, "Error loading texture: %s\n", filename);
2161 device.unmapMemory(tex_obj->mem);
2164 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2167 void Demo::prepare_textures() {
2168 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2169 vk::FormatProperties props;
2170 gpu.getFormatProperties(tex_format, &props);
2172 for (uint32_t i = 0; i < texture_count; i++) {
2173 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2174 /* Device can texture using linear textures */
2175 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2176 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2177 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2178 // shader to run until layout transition completes
2179 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2180 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2181 vk::PipelineStageFlagBits::eFragmentShader);
2182 staging_texture.image = vk::Image();
2183 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2184 /* Must use staging buffer to copy linear texture to optimized */
2186 prepare_texture_buffer(tex_files[i], &staging_texture);
2188 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2189 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2190 vk::MemoryPropertyFlagBits::eDeviceLocal);
2192 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2193 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2194 vk::PipelineStageFlagBits::eTransfer);
2196 auto const subresource = vk::ImageSubresourceLayers()
2197 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2199 .setBaseArrayLayer(0)
2202 auto const copy_region =
2203 vk::BufferImageCopy()
2205 .setBufferRowLength(staging_texture.tex_width)
2206 .setBufferImageHeight(staging_texture.tex_height)
2207 .setImageSubresource(subresource)
2208 .setImageOffset({0, 0, 0})
2209 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2211 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, ©_region);
2213 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2214 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2215 vk::PipelineStageFlagBits::eFragmentShader);
2217 assert(!"No support for R8G8B8A8_UNORM as texture image format");
2220 auto const samplerInfo = vk::SamplerCreateInfo()
2221 .setMagFilter(vk::Filter::eNearest)
2222 .setMinFilter(vk::Filter::eNearest)
2223 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2224 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2225 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2226 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2227 .setMipLodBias(0.0f)
2228 .setAnisotropyEnable(VK_FALSE)
2229 .setMaxAnisotropy(1)
2230 .setCompareEnable(VK_FALSE)
2231 .setCompareOp(vk::CompareOp::eNever)
2234 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2235 .setUnnormalizedCoordinates(VK_FALSE);
2237 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2238 VERIFY(result == vk::Result::eSuccess);
2240 auto const viewInfo = vk::ImageViewCreateInfo()
2241 .setImage(textures[i].image)
2242 .setViewType(vk::ImageViewType::e2D)
2243 .setFormat(tex_format)
2244 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2246 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2247 VERIFY(result == vk::Result::eSuccess);
2251 vk::ShaderModule Demo::prepare_vs() {
2252 const uint32_t vertShaderCode[] = {
2253 #include "cube.vert.inc"
2256 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2258 return vert_shader_module;
2261 void Demo::resize() {
2264 // Don't react to resize until after first initialization.
2269 // In order to properly resize the window, we must re-create the
2271 // AND redo the command buffers, etc.
2273 // First, perform part of the cleanup() function:
2275 auto result = device.waitIdle();
2276 VERIFY(result == vk::Result::eSuccess);
2278 for (i = 0; i < swapchainImageCount; i++) {
2279 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2282 device.destroyDescriptorPool(desc_pool, nullptr);
2284 device.destroyPipeline(pipeline, nullptr);
2285 device.destroyPipelineCache(pipelineCache, nullptr);
2286 device.destroyRenderPass(render_pass, nullptr);
2287 device.destroyPipelineLayout(pipeline_layout, nullptr);
2288 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2290 for (i = 0; i < texture_count; i++) {
2291 device.destroyImageView(textures[i].view, nullptr);
2292 device.destroyImage(textures[i].image, nullptr);
2293 device.freeMemory(textures[i].mem, nullptr);
2294 device.destroySampler(textures[i].sampler, nullptr);
2297 device.destroyImageView(depth.view, nullptr);
2298 device.destroyImage(depth.image, nullptr);
2299 device.freeMemory(depth.mem, nullptr);
2301 for (i = 0; i < swapchainImageCount; i++) {
2302 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2303 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2304 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2305 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2308 device.destroyCommandPool(cmd_pool, nullptr);
2309 if (separate_present_queue) {
2310 device.destroyCommandPool(present_cmd_pool, nullptr);
2313 // Second, re-perform the prepare() function, which will re-create the
2318 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2319 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2322 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2323 vk::AccessFlags flags;
2326 case vk::ImageLayout::eTransferDstOptimal:
2327 // Make sure anything that was copying from this image has
2329 flags = vk::AccessFlagBits::eTransferWrite;
2331 case vk::ImageLayout::eColorAttachmentOptimal:
2332 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2334 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2335 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2337 case vk::ImageLayout::eShaderReadOnlyOptimal:
2338 // Make sure any Copy or CPU writes to image are flushed
2339 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2341 case vk::ImageLayout::eTransferSrcOptimal:
2342 flags = vk::AccessFlagBits::eTransferRead;
2344 case vk::ImageLayout::ePresentSrcKHR:
2345 flags = vk::AccessFlagBits::eMemoryRead;
2354 auto const barrier = vk::ImageMemoryBarrier()
2355 .setSrcAccessMask(srcAccessMask)
2356 .setDstAccessMask(DstAccessMask(newLayout))
2357 .setOldLayout(oldLayout)
2358 .setNewLayout(newLayout)
2359 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2360 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2362 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2364 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2367 void Demo::update_data_buffer() {
2369 mat4x4_mul(VP, projection_matrix, view_matrix);
2371 // Rotate around the Y axis
2373 mat4x4_dup(Model, model_matrix);
2374 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2377 mat4x4_mul(MVP, VP, model_matrix);
2379 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2380 VERIFY(data.result == vk::Result::eSuccess);
2382 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2384 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2387 /* Convert ppm image data from header file into RGBA texture image */
2388 #include "lunarg.ppm.h"
2389 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
2392 cPtr = (char *)lunarg_ppm;
2393 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2396 while (strncmp(cPtr++, "\n", 1))
2398 sscanf(cPtr, "%u %u", width, height);
2399 if (rgba_data == NULL) {
2402 while (strncmp(cPtr++, "\n", 1))
2404 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2407 while (strncmp(cPtr++, "\n", 1))
2409 for (int y = 0; y < *height; y++) {
2410 uint8_t *rowPtr = rgba_data;
2411 for (int x = 0; x < *width; x++) {
2412 memcpy(rowPtr, cPtr, 3);
2413 rowPtr[3] = 255; /* Alpha of 1 */
2417 rgba_data += layout->rowPitch;
2422 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2423 // Search memtypes to find first index with those properties
2424 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2425 if ((typeBits & 1) == 1) {
2426 // Type is available, does it match user properties?
2427 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2435 // No memory types matched, return failure
2439 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2448 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2449 PostQuitMessage(validation_error);
2453 void Demo::create_window() {
2454 WNDCLASSEX win_class;
2456 // Initialize the window class structure:
2457 win_class.cbSize = sizeof(WNDCLASSEX);
2458 win_class.style = CS_HREDRAW | CS_VREDRAW;
2459 win_class.lpfnWndProc = WndProc;
2460 win_class.cbClsExtra = 0;
2461 win_class.cbWndExtra = 0;
2462 win_class.hInstance = connection; // hInstance
2463 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2464 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2465 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2466 win_class.lpszMenuName = nullptr;
2467 win_class.lpszClassName = name;
2468 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2470 // Register window class:
2471 if (!RegisterClassEx(&win_class)) {
2472 // It didn't work, so try to give a useful error:
2473 printf("Unexpected error trying to start the application!\n");
2478 // Create window with the registered class:
2479 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2480 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2481 window = CreateWindowEx(0,
2484 WS_OVERLAPPEDWINDOW | // window style
2485 WS_VISIBLE | WS_SYSMENU,
2486 100, 100, // x/y coords
2487 wr.right - wr.left, // width
2488 wr.bottom - wr.top, // height
2489 nullptr, // handle to parent
2490 nullptr, // handle to menu
2491 connection, // hInstance
2492 nullptr); // no extra parameters
2495 // It didn't work, so try to give a useful error:
2496 printf("Cannot create a window in which to draw!\n");
2501 // Window client area size must be at least 1 pixel high, to prevent
2503 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2504 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2506 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2508 void Demo::create_xlib_window() {
2509 const char *display_envar = getenv("DISPLAY");
2510 if (display_envar == nullptr || display_envar[0] == '\0') {
2511 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2517 display = XOpenDisplay(nullptr);
2518 long visualMask = VisualScreenMask;
2519 int numberOfVisuals;
2520 XVisualInfo vInfoTemplate = {};
2521 vInfoTemplate.screen = DefaultScreen(display);
2522 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2524 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2526 XSetWindowAttributes windowAttributes = {};
2527 windowAttributes.colormap = colormap;
2528 windowAttributes.background_pixel = 0xFFFFFFFF;
2529 windowAttributes.border_pixel = 0;
2530 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2533 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2534 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2536 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2537 XMapWindow(display, xlib_window);
2539 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2542 void Demo::handle_xlib_event(const XEvent *event) {
2543 switch (event->type) {
2545 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2550 switch (event->xkey.keycode) {
2554 case 0x71: // left arrow key
2555 spin_angle -= spin_increment;
2557 case 0x72: // right arrow key
2558 spin_angle += spin_increment;
2560 case 0x41: // space bar
2565 case ConfigureNotify:
2566 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2567 width = event->xconfigure.width;
2568 height = event->xconfigure.height;
2577 void Demo::run_xlib() {
2582 XNextEvent(display, &event);
2583 handle_xlib_event(&event);
2585 while (XPending(display) > 0) {
2586 XNextEvent(display, &event);
2587 handle_xlib_event(&event);
2593 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2598 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2600 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2601 uint8_t event_code = event->response_type & 0x7f;
2602 switch (event_code) {
2604 // TODO: Resize window
2606 case XCB_CLIENT_MESSAGE:
2607 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2611 case XCB_KEY_RELEASE: {
2612 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2614 switch (key->detail) {
2618 case 0x71: // left arrow key
2619 spin_angle -= spin_increment;
2621 case 0x72: // right arrow key
2622 spin_angle += spin_increment;
2624 case 0x41: // space bar
2629 case XCB_CONFIGURE_NOTIFY: {
2630 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2631 if ((width != cfg->width) || (height != cfg->height)) {
2633 height = cfg->height;
2642 void Demo::run_xcb() {
2643 xcb_flush(connection);
2646 xcb_generic_event_t *event;
2649 event = xcb_wait_for_event(connection);
2651 event = xcb_poll_for_event(connection);
2654 handle_xcb_event(event);
2656 event = xcb_poll_for_event(connection);
2661 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2667 void Demo::create_xcb_window() {
2668 uint32_t value_mask, value_list[32];
2670 xcb_window = xcb_generate_id(connection);
2672 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2673 value_list[0] = screen->black_pixel;
2674 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2676 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2677 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2679 /* Magic code that will send notification when window is destroyed */
2680 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2681 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2683 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2684 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2686 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2690 xcb_map_window(connection, xcb_window);
2692 // Force the x/y coordinates to 100,100 results are identical in
2695 const uint32_t coords[] = {100, 100};
2696 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2698 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2703 wl_display_dispatch(display);
2705 wl_display_dispatch_pending(display);
2706 update_data_buffer();
2709 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2716 static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2717 Demo *demo = (Demo *)data;
2718 xdg_surface_ack_configure(xdg_surface, serial);
2719 if (demo->xdg_surface_has_been_configured) {
2722 demo->xdg_surface_has_been_configured = true;
2725 static const xdg_surface_listener surface_listener = {handle_surface_configure};
2727 static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2728 struct wl_array *states) {
2729 Demo *demo = (Demo *)data;
2730 demo->width = width;
2731 demo->height = height;
2732 // This will be followed by a surface configure
2735 static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2736 Demo *demo = (Demo *)data;
2740 static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2742 void Demo::create_window() {
2744 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2749 window = wl_compositor_create_surface(compositor);
2751 printf("Can not create wayland_surface from compositor!\n");
2756 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2757 if (!window_surface) {
2758 printf("Can not get xdg_surface from wayland_surface!\n");
2762 window_toplevel = xdg_surface_get_toplevel(window_surface);
2763 if (!window_toplevel) {
2764 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2768 xdg_surface_add_listener(window_surface, &surface_listener, this);
2769 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2770 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2771 if (xdg_decoration_mgr) {
2772 // if supported, let the compositor render titlebars for us
2773 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2774 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2777 wl_surface_commit(window);
2779 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
2783 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2787 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2789 vk::Result Demo::create_display_surface() {
2791 uint32_t display_count;
2792 uint32_t mode_count;
2793 uint32_t plane_count;
2794 vk::DisplayPropertiesKHR display_props;
2795 vk::DisplayKHR display;
2796 vk::DisplayModePropertiesKHR mode_props;
2797 vk::DisplayPlanePropertiesKHR *plane_props;
2798 vk::Bool32 found_plane = VK_FALSE;
2799 uint32_t plane_index;
2800 vk::Extent2D image_extent;
2802 // Get the first display
2803 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2804 VERIFY(result == vk::Result::eSuccess);
2806 if (display_count == 0) {
2807 printf("Cannot find any display!\n");
2813 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2814 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2816 display = display_props.display;
2818 // Get the first mode of the display
2819 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2820 VERIFY(result == vk::Result::eSuccess);
2822 if (mode_count == 0) {
2823 printf("Cannot find any mode for the display!\n");
2829 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2830 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2832 // Get the list of planes
2833 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2834 VERIFY(result == vk::Result::eSuccess);
2836 if (plane_count == 0) {
2837 printf("Cannot find any plane!\n");
2842 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2843 VERIFY(plane_props != nullptr);
2845 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2846 VERIFY(result == vk::Result::eSuccess);
2848 // Find a plane compatible with the display
2849 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2850 uint32_t supported_count;
2851 vk::DisplayKHR *supported_displays;
2853 // Disqualify planes that are bound to a different display
2854 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2858 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
2859 VERIFY(result == vk::Result::eSuccess);
2861 if (supported_count == 0) {
2865 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2866 VERIFY(supported_displays != nullptr);
2868 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
2869 VERIFY(result == vk::Result::eSuccess);
2871 for (uint32_t i = 0; i < supported_count; i++) {
2872 if (supported_displays[i] == display) {
2873 found_plane = VK_TRUE;
2878 free(supported_displays);
2886 printf("Cannot find a plane compatible with the display!\n");
2893 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2894 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2895 // Find a supported alpha mode
2896 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2897 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2898 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2899 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2900 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2901 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2903 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2904 if (planeCaps.supportedAlpha & alphaModes[i]) {
2905 alphaMode = alphaModes[i];
2910 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2911 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2913 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2914 .setDisplayMode(mode_props.displayMode)
2915 .setPlaneIndex(plane_index)
2916 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2917 .setGlobalAlpha(1.0f)
2918 .setAlphaMode(alphaMode)
2919 .setImageExtent(image_extent);
2921 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2924 void Demo::run_display() {
2929 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2937 // Include header required for parsing the command line options.
2938 #include <shellapi.h>
2942 // MS-Windows event handling function:
2943 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2946 PostQuitMessage(validation_error);
2951 case WM_GETMINMAXINFO: // set window's minimum size
2952 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2957 // Resize the application to the new window size, except when
2958 // it was minimized. Vulkan doesn't support images or swapchains
2959 // with width=0 and height=0.
2960 if (wParam != SIZE_MINIMIZED) {
2961 demo.width = lParam & 0xffff;
2962 demo.height = (lParam & 0xffff0000) >> 16;
2969 PostQuitMessage(validation_error);
2972 demo.spin_angle -= demo.spin_increment;
2975 demo.spin_angle += demo.spin_increment;
2978 demo.pause = !demo.pause;
2986 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2989 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
2990 // TODO: Gah.. refactor. This isn't 1989.
2992 bool done; // flag saying when app is complete
2996 // Ensure wParam is initialized.
2999 // Use the CommandLine functions to get the command line arguments.
3000 // Unfortunately, Microsoft outputs
3001 // this information as wide characters for Unicode, and we simply want the
3002 // Ascii version to be compatible
3003 // with the non-Windows side. So, we have to convert the information to
3004 // Ascii character strings.
3005 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3006 if (nullptr == commandLineArgs) {
3011 argv = (char **)malloc(sizeof(char *) * argc);
3012 if (argv == nullptr) {
3015 for (int iii = 0; iii < argc; iii++) {
3016 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3017 size_t numConverted = 0;
3019 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3020 if (argv[iii] != nullptr) {
3021 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3029 demo.init(argc, argv);
3031 // Free up the items we had to allocate for the command line arguments.
3032 if (argc > 0 && argv != nullptr) {
3033 for (int iii = 0; iii < argc; iii++) {
3034 if (argv[iii] != nullptr) {
3041 demo.connection = hInstance;
3042 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
3043 demo.create_window();
3044 demo.init_vk_swapchain();
3048 done = false; // initialize loop condition variable
3050 // main message loop
3053 const BOOL succ = WaitMessage();
3056 const auto &suppress_popups = demo.suppress_popups;
3057 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3061 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
3062 if (msg.message == WM_QUIT) // check for a quit message
3064 done = true; // if found, quit app
3066 /* Translate and dispatch to event queue*/
3067 TranslateMessage(&msg);
3068 DispatchMessage(&msg);
3070 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3075 return (int)msg.wParam;
3080 int main(int argc, char **argv) {
3083 demo.init(argc, argv);
3085 #if defined(VK_USE_PLATFORM_XCB_KHR)
3086 demo.create_xcb_window();
3087 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3088 demo.use_xlib = true;
3089 demo.create_xlib_window();
3090 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3091 demo.create_window();
3094 demo.init_vk_swapchain();
3098 #if defined(VK_USE_PLATFORM_XCB_KHR)
3100 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3102 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3104 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3110 return validation_error;
3113 #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3115 // Global function invoked from NS or UI views and controllers to create demo
3116 static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
3117 demo.init(argc, (char **)argv);
3119 demo.init_vk_swapchain();
3121 demo.spin_angle = 0.4f;
3125 #error "Platform not supported"