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_METAL_EXT)
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_METAL_EXT)
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);
853 float viewport_dimension;
854 float viewport_x = 0.0f;
855 float viewport_y = 0.0f;
856 if (width < height) {
857 viewport_dimension = (float)width;
858 viewport_y = (height - width) / 2.0f;
860 viewport_dimension = (float)height;
861 viewport_x = (width - height) / 2.0f;
863 auto const viewport = vk::Viewport()
866 .setWidth((float)viewport_dimension)
867 .setHeight((float)viewport_dimension)
868 .setMinDepth((float)0.0f)
869 .setMaxDepth((float)1.0f);
870 commandBuffer.setViewport(0, 1, &viewport);
872 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
873 commandBuffer.setScissor(0, 1, &scissor);
874 commandBuffer.draw(12 * 3, 1, 0, 0);
875 // Note that ending the renderpass changes the image's layout from
876 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
877 commandBuffer.endRenderPass();
879 if (separate_present_queue) {
880 // We have to transfer ownership from the graphics queue family to
882 // present queue family to be able to present. Note that we don't
884 // to transfer from present queue family back to graphics queue
886 // the start of the next frame because we don't care about the
888 // contents at that point.
889 auto const image_ownership_barrier =
890 vk::ImageMemoryBarrier()
891 .setSrcAccessMask(vk::AccessFlags())
892 .setDstAccessMask(vk::AccessFlags())
893 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
894 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
895 .setSrcQueueFamilyIndex(graphics_queue_family_index)
896 .setDstQueueFamilyIndex(present_queue_family_index)
897 .setImage(swapchain_image_resources[current_buffer].image)
898 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
900 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
901 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
904 result = commandBuffer.end();
905 VERIFY(result == vk::Result::eSuccess);
908 void Demo::flush_init_cmd() {
910 // This function could get called twice if the texture uses a staging
912 // In that case the second call should be ignored
917 auto result = cmd.end();
918 VERIFY(result == vk::Result::eSuccess);
920 auto const fenceInfo = vk::FenceCreateInfo();
922 result = device.createFence(&fenceInfo, nullptr, &fence);
923 VERIFY(result == vk::Result::eSuccess);
925 vk::CommandBuffer const commandBuffers[] = {cmd};
926 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
928 result = graphics_queue.submit(1, &submitInfo, fence);
929 VERIFY(result == vk::Result::eSuccess);
931 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
932 VERIFY(result == vk::Result::eSuccess);
934 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
935 device.destroyFence(fence, nullptr);
937 cmd = vk::CommandBuffer();
940 void Demo::init(int argc, char **argv) {
941 vec3 eye = {0.0f, 3.0f, 5.0f};
942 vec3 origin = {0, 0, 0};
943 vec3 up = {0.0f, 1.0f, 0.0};
945 presentMode = vk::PresentModeKHR::eFifo;
946 frameCount = UINT32_MAX;
949 for (int i = 1; i < argc; i++) {
950 if (strcmp(argv[i], "--use_staging") == 0) {
951 use_staging_buffer = true;
954 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
955 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
959 if (strcmp(argv[i], "--break") == 0) {
963 if (strcmp(argv[i], "--validate") == 0) {
967 if (strcmp(argv[i], "--xlib") == 0) {
968 fprintf(stderr, "--xlib is deprecated and no longer does anything");
971 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
972 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
976 if (strcmp(argv[i], "--suppress_popups") == 0) {
977 suppress_popups = true;
981 std::stringstream usage;
982 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
983 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
984 << "\t[--present_mode <present mode enum>]\n"
985 << "\t<present_mode_enum>\n"
986 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
987 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
988 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
989 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
992 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
994 std::cerr << usage.str();
1010 spin_increment = 0.2f;
1013 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1014 mat4x4_look_at(view_matrix, eye, origin, up);
1015 mat4x4_identity(model_matrix);
1017 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1020 void Demo::init_connection() {
1021 #if defined(VK_USE_PLATFORM_XCB_KHR)
1022 const xcb_setup_t *setup;
1023 xcb_screen_iterator_t iter;
1026 const char *display_envar = getenv("DISPLAY");
1027 if (display_envar == nullptr || display_envar[0] == '\0') {
1028 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1033 connection = xcb_connect(nullptr, &scr);
1034 if (xcb_connection_has_error(connection) > 0) {
1036 "Cannot find a compatible Vulkan installable client driver "
1037 "(ICD).\nExiting ...\n");
1042 setup = xcb_get_setup(connection);
1043 iter = xcb_setup_roots_iterator(setup);
1044 while (scr-- > 0) xcb_screen_next(&iter);
1047 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1048 display = wl_display_connect(nullptr);
1050 if (display == nullptr) {
1051 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1056 registry = wl_display_get_registry(display);
1057 wl_registry_add_listener(registry, ®istry_listener, this);
1058 wl_display_dispatch(display);
1062 void Demo::init_vk() {
1063 uint32_t instance_extension_count = 0;
1064 uint32_t instance_layer_count = 0;
1065 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
1066 enabled_extension_count = 0;
1067 enabled_layer_count = 0;
1069 // Look for validation layers
1070 vk::Bool32 validation_found = VK_FALSE;
1072 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
1073 VERIFY(result == vk::Result::eSuccess);
1075 if (instance_layer_count > 0) {
1076 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1077 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
1078 VERIFY(result == vk::Result::eSuccess);
1080 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
1081 instance_layer_count, instance_layers.get());
1082 if (validation_found) {
1083 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1084 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
1088 if (!validation_found) {
1090 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1091 "Please look at the Getting Started guide for additional information.\n",
1092 "vkCreateInstance Failure");
1096 /* Look for instance extensions */
1097 vk::Bool32 surfaceExtFound = VK_FALSE;
1098 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1099 memset(extension_names, 0, sizeof(extension_names));
1101 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1102 static_cast<vk::ExtensionProperties *>(nullptr));
1103 VERIFY(result == vk::Result::eSuccess);
1105 if (instance_extension_count > 0) {
1106 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1107 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1108 VERIFY(result == vk::Result::eSuccess);
1110 for (uint32_t i = 0; i < instance_extension_count; i++) {
1111 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1112 surfaceExtFound = 1;
1113 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1115 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1116 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1117 platformSurfaceExtFound = 1;
1118 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1120 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1121 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1122 platformSurfaceExtFound = 1;
1123 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1125 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1126 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1127 platformSurfaceExtFound = 1;
1128 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1130 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1131 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1132 platformSurfaceExtFound = 1;
1133 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1135 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1136 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1137 platformSurfaceExtFound = 1;
1138 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1140 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1141 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1142 platformSurfaceExtFound = 1;
1143 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
1147 assert(enabled_extension_count < 64);
1151 if (!surfaceExtFound) {
1152 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_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");
1159 if (!platformSurfaceExtFound) {
1160 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1161 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1163 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1164 "Please look at the Getting Started guide for additional information.\n",
1165 "vkCreateInstance Failure");
1166 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1167 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1169 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1170 "Please look at the Getting Started guide for additional information.\n",
1171 "vkCreateInstance Failure");
1172 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1173 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1175 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1176 "Please look at the Getting Started guide for additional information.\n",
1177 "vkCreateInstance Failure");
1178 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1179 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1181 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1182 "Please look at the Getting Started guide for additional information.\n",
1183 "vkCreateInstance Failure");
1184 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1185 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1187 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1188 "Please look at the Getting Started guide for additional information.\n",
1189 "vkCreateInstance Failure");
1190 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1191 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
1192 " extension.\n\nDo you have a compatible "
1193 "Vulkan installable client driver (ICD) installed?\nPlease "
1194 "look at the Getting Started guide for additional "
1196 "vkCreateInstance Failure");
1199 auto const app = vk::ApplicationInfo()
1200 .setPApplicationName(APP_SHORT_NAME)
1201 .setApplicationVersion(0)
1202 .setPEngineName(APP_SHORT_NAME)
1203 .setEngineVersion(0)
1204 .setApiVersion(VK_API_VERSION_1_0);
1205 auto const inst_info = vk::InstanceCreateInfo()
1206 .setPApplicationInfo(&app)
1207 .setEnabledLayerCount(enabled_layer_count)
1208 .setPpEnabledLayerNames(instance_validation_layers)
1209 .setEnabledExtensionCount(enabled_extension_count)
1210 .setPpEnabledExtensionNames(extension_names);
1212 result = vk::createInstance(&inst_info, nullptr, &inst);
1213 if (result == vk::Result::eErrorIncompatibleDriver) {
1215 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1216 "Please look at the Getting Started guide for additional information.\n",
1217 "vkCreateInstance Failure");
1218 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1220 "Cannot find a specified extension library.\n"
1221 "Make sure your layers path is set appropriately.\n",
1222 "vkCreateInstance Failure");
1223 } else if (result != vk::Result::eSuccess) {
1225 "vkCreateInstance failed.\n\n"
1226 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1227 "Please look at the Getting Started guide for additional information.\n",
1228 "vkCreateInstance Failure");
1231 /* Make initial call to query gpu_count, then second call for gpu info*/
1233 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
1234 VERIFY(result == vk::Result::eSuccess);
1236 if (gpu_count > 0) {
1237 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1238 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1239 VERIFY(result == vk::Result::eSuccess);
1240 /* For cube demo we just grab the first physical device */
1241 gpu = physical_devices[0];
1244 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1245 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1246 "Please look at the Getting Started guide for additional information.\n",
1247 "vkEnumeratePhysicalDevices Failure");
1250 /* Look for device extensions */
1251 uint32_t device_extension_count = 0;
1252 vk::Bool32 swapchainExtFound = VK_FALSE;
1253 enabled_extension_count = 0;
1254 memset(extension_names, 0, sizeof(extension_names));
1257 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
1258 VERIFY(result == vk::Result::eSuccess);
1260 if (device_extension_count > 0) {
1261 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1262 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1263 VERIFY(result == vk::Result::eSuccess);
1265 for (uint32_t i = 0; i < device_extension_count; i++) {
1266 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1267 swapchainExtFound = 1;
1268 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1270 assert(enabled_extension_count < 64);
1274 if (!swapchainExtFound) {
1275 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1277 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1278 "Please look at the Getting Started guide for additional information.\n",
1279 "vkCreateInstance Failure");
1282 gpu.getProperties(&gpu_props);
1284 /* Call with nullptr data to get count */
1285 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
1286 assert(queue_family_count >= 1);
1288 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1289 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1291 // Query fine-grained feature support for this device.
1292 // If app has specific feature requirements it should check supported
1293 // features based on this query
1294 vk::PhysicalDeviceFeatures physDevFeatures;
1295 gpu.getFeatures(&physDevFeatures);
1298 void Demo::create_surface() {
1299 // Create a WSI surface for the window:
1300 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1302 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1304 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1305 VERIFY(result == vk::Result::eSuccess);
1307 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1309 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1311 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1312 VERIFY(result == vk::Result::eSuccess);
1314 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1316 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1318 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1319 VERIFY(result == vk::Result::eSuccess);
1321 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1323 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1325 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1326 VERIFY(result == vk::Result::eSuccess);
1328 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1330 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
1332 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
1333 VERIFY(result == vk::Result::eSuccess);
1335 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1337 auto result = create_display_surface();
1338 VERIFY(result == vk::Result::eSuccess);
1343 void Demo::init_vk_swapchain() {
1345 // Iterate over each queue to learn whether it supports presenting:
1346 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1347 for (uint32_t i = 0; i < queue_family_count; i++) {
1348 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1351 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1352 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1353 for (uint32_t i = 0; i < queue_family_count; i++) {
1354 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1355 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1356 graphicsQueueFamilyIndex = i;
1359 if (supportsPresent[i] == VK_TRUE) {
1360 graphicsQueueFamilyIndex = i;
1361 presentQueueFamilyIndex = i;
1367 if (presentQueueFamilyIndex == UINT32_MAX) {
1368 // If didn't find a queue that supports both graphics and present,
1370 // find a separate present queue.
1371 for (uint32_t i = 0; i < queue_family_count; ++i) {
1372 if (supportsPresent[i] == VK_TRUE) {
1373 presentQueueFamilyIndex = i;
1379 // Generate error if could not find both a graphics and a present queue
1380 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1381 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1384 graphics_queue_family_index = graphicsQueueFamilyIndex;
1385 present_queue_family_index = presentQueueFamilyIndex;
1386 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1390 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1391 if (!separate_present_queue) {
1392 present_queue = graphics_queue;
1394 device.getQueue(present_queue_family_index, 0, &present_queue);
1397 // Get the list of VkFormat's that are supported:
1398 uint32_t formatCount;
1399 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
1400 VERIFY(result == vk::Result::eSuccess);
1402 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1403 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1404 VERIFY(result == vk::Result::eSuccess);
1406 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1407 // the surface has no preferred format. Otherwise, at least one
1408 // supported format will be returned.
1409 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1410 format = vk::Format::eB8G8R8A8Unorm;
1412 assert(formatCount >= 1);
1413 format = surfFormats[0].format;
1415 color_space = surfFormats[0].colorSpace;
1420 // Create semaphores to synchronize acquiring presentable buffers before
1421 // rendering and waiting for drawing to be complete before presenting
1422 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1424 // Create fences that we can use to throttle if we get too far
1425 // ahead of the image presents
1426 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1427 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1428 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1429 VERIFY(result == vk::Result::eSuccess);
1431 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1432 VERIFY(result == vk::Result::eSuccess);
1434 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1435 VERIFY(result == vk::Result::eSuccess);
1437 if (separate_present_queue) {
1438 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1439 VERIFY(result == vk::Result::eSuccess);
1444 // Get Memory information and properties
1445 gpu.getMemoryProperties(&memory_properties);
1448 void Demo::prepare() {
1449 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1450 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1451 VERIFY(result == vk::Result::eSuccess);
1453 auto const cmd = vk::CommandBufferAllocateInfo()
1454 .setCommandPool(cmd_pool)
1455 .setLevel(vk::CommandBufferLevel::ePrimary)
1456 .setCommandBufferCount(1);
1458 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1459 VERIFY(result == vk::Result::eSuccess);
1461 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1463 result = this->cmd.begin(&cmd_buf_info);
1464 VERIFY(result == vk::Result::eSuccess);
1469 prepare_cube_data_buffers();
1471 prepare_descriptor_layout();
1472 prepare_render_pass();
1475 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1476 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1477 VERIFY(result == vk::Result::eSuccess);
1480 if (separate_present_queue) {
1481 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1483 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1484 VERIFY(result == vk::Result::eSuccess);
1486 auto const present_cmd = vk::CommandBufferAllocateInfo()
1487 .setCommandPool(present_cmd_pool)
1488 .setLevel(vk::CommandBufferLevel::ePrimary)
1489 .setCommandBufferCount(1);
1491 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1492 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1493 VERIFY(result == vk::Result::eSuccess);
1495 build_image_ownership_cmd(i);
1499 prepare_descriptor_pool();
1500 prepare_descriptor_set();
1502 prepare_framebuffers();
1504 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1506 draw_build_cmd(swapchain_image_resources[i].cmd);
1510 * Prepare functions above may generate pipeline commands
1511 * that need to be flushed before beginning the render loop.
1514 if (staging_texture.buffer) {
1515 destroy_texture(&staging_texture);
1522 void Demo::prepare_buffers() {
1523 vk::SwapchainKHR oldSwapchain = swapchain;
1525 // Check the surface capabilities and formats
1526 vk::SurfaceCapabilitiesKHR surfCapabilities;
1527 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1528 VERIFY(result == vk::Result::eSuccess);
1530 uint32_t presentModeCount;
1531 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
1532 VERIFY(result == vk::Result::eSuccess);
1534 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1535 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1536 VERIFY(result == vk::Result::eSuccess);
1538 vk::Extent2D swapchainExtent;
1539 // width and height are either both -1, or both not -1.
1540 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1541 // If the surface size is undefined, the size is set to
1542 // the size of the images requested.
1543 swapchainExtent.width = width;
1544 swapchainExtent.height = height;
1546 // If the surface size is defined, the swap chain size must match
1547 swapchainExtent = surfCapabilities.currentExtent;
1548 width = surfCapabilities.currentExtent.width;
1549 height = surfCapabilities.currentExtent.height;
1552 // The FIFO present mode is guaranteed by the spec to be supported
1553 // and to have no tearing. It's a great default present mode to use.
1554 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1556 // There are times when you may wish to use another present mode. The
1557 // following code shows how to select them, and the comments provide some
1558 // reasons you may wish to use them.
1560 // It should be noted that Vulkan 1.0 doesn't provide a method for
1561 // synchronizing rendering with the presentation engine's display. There
1562 // is a method provided for throttling rendering with the display, but
1563 // there are some presentation engines for which this method will not work.
1564 // If an application doesn't throttle its rendering, and if it renders much
1565 // faster than the refresh rate of the display, this can waste power on
1566 // mobile devices. That is because power is being spent rendering images
1567 // that may never be seen.
1569 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1571 // tearing, or have some way of synchronizing their rendering with the
1573 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1574 // generally render a new presentable image every refresh cycle, but are
1575 // occasionally early. In this case, the application wants the new
1577 // to be displayed instead of the previously-queued-for-presentation
1579 // that has not yet been displayed.
1580 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1581 // render a new presentable image every refresh cycle, but are
1583 // late. In this case (perhaps because of stuttering/latency concerns),
1584 // the application wants the late image to be immediately displayed,
1586 // though that may mean some tearing.
1588 if (presentMode != swapchainPresentMode) {
1589 for (size_t i = 0; i < presentModeCount; ++i) {
1590 if (presentModes[i] == presentMode) {
1591 swapchainPresentMode = presentMode;
1597 if (swapchainPresentMode != presentMode) {
1598 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1601 // Determine the number of VkImages to use in the swap chain.
1602 // Application desires to acquire 3 images at a time for triple
1604 uint32_t desiredNumOfSwapchainImages = 3;
1605 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1606 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1609 // If maxImageCount is 0, we can ask for as many images as we want,
1611 // we're limited to maxImageCount
1612 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1613 // Application must settle for fewer images than desired:
1614 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1617 vk::SurfaceTransformFlagBitsKHR preTransform;
1618 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1619 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1621 preTransform = surfCapabilities.currentTransform;
1624 // Find a supported composite alpha mode - one of these is guaranteed to be set
1625 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1626 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1627 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1628 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1629 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1630 vk::CompositeAlphaFlagBitsKHR::eInherit,
1632 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1633 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1634 compositeAlpha = compositeAlphaFlags[i];
1639 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1640 .setSurface(surface)
1641 .setMinImageCount(desiredNumOfSwapchainImages)
1642 .setImageFormat(format)
1643 .setImageColorSpace(color_space)
1644 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1645 .setImageArrayLayers(1)
1646 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1647 .setImageSharingMode(vk::SharingMode::eExclusive)
1648 .setQueueFamilyIndexCount(0)
1649 .setPQueueFamilyIndices(nullptr)
1650 .setPreTransform(preTransform)
1651 .setCompositeAlpha(compositeAlpha)
1652 .setPresentMode(swapchainPresentMode)
1654 .setOldSwapchain(oldSwapchain);
1656 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1657 VERIFY(result == vk::Result::eSuccess);
1659 // If we just re-created an existing swapchain, we should destroy the
1661 // swapchain at this point.
1662 // Note: destroying the swapchain also cleans up all its associated
1663 // presentable images once the platform is done with them.
1665 device.destroySwapchainKHR(oldSwapchain, nullptr);
1668 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
1669 VERIFY(result == vk::Result::eSuccess);
1671 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1672 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1673 VERIFY(result == vk::Result::eSuccess);
1675 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1677 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1678 auto color_image_view = vk::ImageViewCreateInfo()
1679 .setViewType(vk::ImageViewType::e2D)
1681 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1683 swapchain_image_resources[i].image = swapchainImages[i];
1685 color_image_view.image = swapchain_image_resources[i].image;
1687 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1688 VERIFY(result == vk::Result::eSuccess);
1692 void Demo::prepare_cube_data_buffers() {
1694 mat4x4_mul(VP, projection_matrix, view_matrix);
1697 mat4x4_mul(MVP, VP, model_matrix);
1699 vktexcube_vs_uniform data;
1700 memcpy(data.mvp, MVP, sizeof(MVP));
1701 // dumpMatrix("MVP", MVP)
1703 for (int32_t i = 0; i < 12 * 3; i++) {
1704 data.position[i][0] = g_vertex_buffer_data[i * 3];
1705 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1706 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1707 data.position[i][3] = 1.0f;
1708 data.attr[i][0] = g_uv_buffer_data[2 * i];
1709 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1710 data.attr[i][2] = 0;
1711 data.attr[i][3] = 0;
1714 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1716 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1717 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
1718 VERIFY(result == vk::Result::eSuccess);
1720 vk::MemoryRequirements mem_reqs;
1721 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1723 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1725 bool const pass = memory_type_from_properties(
1726 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1727 &mem_alloc.memoryTypeIndex);
1730 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
1731 VERIFY(result == vk::Result::eSuccess);
1733 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1734 VERIFY(pData.result == vk::Result::eSuccess);
1736 memcpy(pData.value, &data, sizeof data);
1738 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1741 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
1742 VERIFY(result == vk::Result::eSuccess);
1746 void Demo::prepare_depth() {
1747 depth.format = vk::Format::eD16Unorm;
1749 auto const image = vk::ImageCreateInfo()
1750 .setImageType(vk::ImageType::e2D)
1751 .setFormat(depth.format)
1752 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1755 .setSamples(vk::SampleCountFlagBits::e1)
1756 .setTiling(vk::ImageTiling::eOptimal)
1757 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1758 .setSharingMode(vk::SharingMode::eExclusive)
1759 .setQueueFamilyIndexCount(0)
1760 .setPQueueFamilyIndices(nullptr)
1761 .setInitialLayout(vk::ImageLayout::eUndefined);
1763 auto result = device.createImage(&image, nullptr, &depth.image);
1764 VERIFY(result == vk::Result::eSuccess);
1766 vk::MemoryRequirements mem_reqs;
1767 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1769 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1770 depth.mem_alloc.setMemoryTypeIndex(0);
1772 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1773 &depth.mem_alloc.memoryTypeIndex);
1776 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1777 VERIFY(result == vk::Result::eSuccess);
1779 result = device.bindImageMemory(depth.image, depth.mem, 0);
1780 VERIFY(result == vk::Result::eSuccess);
1782 auto const view = vk::ImageViewCreateInfo()
1783 .setImage(depth.image)
1784 .setViewType(vk::ImageViewType::e2D)
1785 .setFormat(depth.format)
1786 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1787 result = device.createImageView(&view, nullptr, &depth.view);
1788 VERIFY(result == vk::Result::eSuccess);
1791 void Demo::prepare_descriptor_layout() {
1792 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1794 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1795 .setDescriptorCount(1)
1796 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1797 .setPImmutableSamplers(nullptr),
1798 vk::DescriptorSetLayoutBinding()
1800 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1801 .setDescriptorCount(texture_count)
1802 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1803 .setPImmutableSamplers(nullptr)};
1805 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1807 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1808 VERIFY(result == vk::Result::eSuccess);
1810 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1812 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1813 VERIFY(result == vk::Result::eSuccess);
1816 void Demo::prepare_descriptor_pool() {
1817 vk::DescriptorPoolSize const poolSizes[2] = {
1818 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1819 vk::DescriptorPoolSize()
1820 .setType(vk::DescriptorType::eCombinedImageSampler)
1821 .setDescriptorCount(swapchainImageCount * texture_count)};
1823 auto const descriptor_pool =
1824 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1826 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1827 VERIFY(result == vk::Result::eSuccess);
1830 void Demo::prepare_descriptor_set() {
1831 auto const alloc_info =
1832 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1834 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1836 vk::DescriptorImageInfo tex_descs[texture_count];
1837 for (uint32_t i = 0; i < texture_count; i++) {
1838 tex_descs[i].setSampler(textures[i].sampler);
1839 tex_descs[i].setImageView(textures[i].view);
1840 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1843 vk::WriteDescriptorSet writes[2];
1845 writes[0].setDescriptorCount(1);
1846 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1847 writes[0].setPBufferInfo(&buffer_info);
1849 writes[1].setDstBinding(1);
1850 writes[1].setDescriptorCount(texture_count);
1851 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1852 writes[1].setPImageInfo(tex_descs);
1854 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1855 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
1856 VERIFY(result == vk::Result::eSuccess);
1858 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1859 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1860 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1861 device.updateDescriptorSets(2, writes, 0, nullptr);
1865 void Demo::prepare_framebuffers() {
1866 vk::ImageView attachments[2];
1867 attachments[1] = depth.view;
1869 auto const fb_info = vk::FramebufferCreateInfo()
1870 .setRenderPass(render_pass)
1871 .setAttachmentCount(2)
1872 .setPAttachments(attachments)
1873 .setWidth((uint32_t)width)
1874 .setHeight((uint32_t)height)
1877 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1878 attachments[0] = swapchain_image_resources[i].view;
1879 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
1880 VERIFY(result == vk::Result::eSuccess);
1884 vk::ShaderModule Demo::prepare_fs() {
1885 const uint32_t fragShaderCode[] = {
1886 #include "cube.frag.inc"
1889 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
1891 return frag_shader_module;
1894 void Demo::prepare_pipeline() {
1895 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1896 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1897 VERIFY(result == vk::Result::eSuccess);
1899 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1900 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1901 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1903 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1905 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1907 // TODO: Where are pViewports and pScissors set?
1908 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1910 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1911 .setDepthClampEnable(VK_FALSE)
1912 .setRasterizerDiscardEnable(VK_FALSE)
1913 .setPolygonMode(vk::PolygonMode::eFill)
1914 .setCullMode(vk::CullModeFlagBits::eBack)
1915 .setFrontFace(vk::FrontFace::eCounterClockwise)
1916 .setDepthBiasEnable(VK_FALSE)
1917 .setLineWidth(1.0f);
1919 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1921 auto const stencilOp =
1922 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1924 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1925 .setDepthTestEnable(VK_TRUE)
1926 .setDepthWriteEnable(VK_TRUE)
1927 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1928 .setDepthBoundsTestEnable(VK_FALSE)
1929 .setStencilTestEnable(VK_FALSE)
1930 .setFront(stencilOp)
1931 .setBack(stencilOp);
1933 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1934 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1935 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1937 auto const colorBlendInfo =
1938 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1940 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1942 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1944 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1946 .setPStages(shaderStageInfo)
1947 .setPVertexInputState(&vertexInputInfo)
1948 .setPInputAssemblyState(&inputAssemblyInfo)
1949 .setPViewportState(&viewportInfo)
1950 .setPRasterizationState(&rasterizationInfo)
1951 .setPMultisampleState(&multisampleInfo)
1952 .setPDepthStencilState(&depthStencilInfo)
1953 .setPColorBlendState(&colorBlendInfo)
1954 .setPDynamicState(&dynamicStateInfo)
1955 .setLayout(pipeline_layout)
1956 .setRenderPass(render_pass);
1958 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1959 VERIFY(result == vk::Result::eSuccess);
1961 device.destroyShaderModule(frag_shader_module, nullptr);
1962 device.destroyShaderModule(vert_shader_module, nullptr);
1965 void Demo::prepare_render_pass() {
1966 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1967 // because at the start of the renderpass, we don't care about their contents.
1968 // At the start of the subpass, the color attachment's layout will be transitioned
1969 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1970 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1971 // the renderpass, the color attachment's layout will be transitioned to
1972 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1973 // the renderpass, no barriers are necessary.
1974 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1976 .setSamples(vk::SampleCountFlagBits::e1)
1977 .setLoadOp(vk::AttachmentLoadOp::eClear)
1978 .setStoreOp(vk::AttachmentStoreOp::eStore)
1979 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1980 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1981 .setInitialLayout(vk::ImageLayout::eUndefined)
1982 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1983 vk::AttachmentDescription()
1984 .setFormat(depth.format)
1985 .setSamples(vk::SampleCountFlagBits::e1)
1986 .setLoadOp(vk::AttachmentLoadOp::eClear)
1987 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1988 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1989 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1990 .setInitialLayout(vk::ImageLayout::eUndefined)
1991 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1993 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1995 auto const depth_reference =
1996 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1998 auto const subpass = vk::SubpassDescription()
1999 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2000 .setInputAttachmentCount(0)
2001 .setPInputAttachments(nullptr)
2002 .setColorAttachmentCount(1)
2003 .setPColorAttachments(&color_reference)
2004 .setPResolveAttachments(nullptr)
2005 .setPDepthStencilAttachment(&depth_reference)
2006 .setPreserveAttachmentCount(0)
2007 .setPPreserveAttachments(nullptr);
2009 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2010 vk::SubpassDependency const dependencies[2] = {
2011 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2012 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2014 .setSrcStageMask(stages)
2015 .setDstStageMask(stages)
2016 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2017 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2018 .setDependencyFlags(vk::DependencyFlags()),
2019 vk::SubpassDependency() // Image layout transition
2020 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2022 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2023 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2024 .setSrcAccessMask(vk::AccessFlagBits())
2025 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2026 .setDependencyFlags(vk::DependencyFlags()),
2029 auto const rp_info = vk::RenderPassCreateInfo()
2030 .setAttachmentCount(2)
2031 .setPAttachments(attachments)
2033 .setPSubpasses(&subpass)
2034 .setDependencyCount(2)
2035 .setPDependencies(dependencies);
2037 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2038 VERIFY(result == vk::Result::eSuccess);
2041 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2042 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2044 vk::ShaderModule module;
2045 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2046 VERIFY(result == vk::Result::eSuccess);
2051 void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2055 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2056 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2059 tex_obj->tex_width = tex_width;
2060 tex_obj->tex_height = tex_height;
2062 auto const buffer_create_info = vk::BufferCreateInfo()
2063 .setSize(tex_width * tex_height * 4)
2064 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2065 .setSharingMode(vk::SharingMode::eExclusive)
2066 .setQueueFamilyIndexCount(0)
2067 .setPQueueFamilyIndices(nullptr);
2069 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2070 VERIFY(result == vk::Result::eSuccess);
2072 vk::MemoryRequirements mem_reqs;
2073 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2075 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2076 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2078 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2079 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2080 VERIFY(pass == true);
2082 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2083 VERIFY(result == vk::Result::eSuccess);
2085 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2086 VERIFY(result == vk::Result::eSuccess);
2088 vk::SubresourceLayout layout;
2089 memset(&layout, 0, sizeof(layout));
2090 layout.rowPitch = tex_width * 4;
2091 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2092 VERIFY(data.result == vk::Result::eSuccess);
2094 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2095 fprintf(stderr, "Error loading texture: %s\n", filename);
2098 device.unmapMemory(tex_obj->mem);
2101 void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2102 vk::MemoryPropertyFlags required_props) {
2105 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2106 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2109 tex_obj->tex_width = tex_width;
2110 tex_obj->tex_height = tex_height;
2112 auto const image_create_info = vk::ImageCreateInfo()
2113 .setImageType(vk::ImageType::e2D)
2114 .setFormat(vk::Format::eR8G8B8A8Unorm)
2115 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2118 .setSamples(vk::SampleCountFlagBits::e1)
2121 .setSharingMode(vk::SharingMode::eExclusive)
2122 .setQueueFamilyIndexCount(0)
2123 .setPQueueFamilyIndices(nullptr)
2124 .setInitialLayout(vk::ImageLayout::ePreinitialized);
2126 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2127 VERIFY(result == vk::Result::eSuccess);
2129 vk::MemoryRequirements mem_reqs;
2130 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
2132 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2133 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2135 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2136 VERIFY(pass == true);
2138 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2139 VERIFY(result == vk::Result::eSuccess);
2141 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2142 VERIFY(result == vk::Result::eSuccess);
2144 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2145 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2146 vk::SubresourceLayout layout;
2147 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
2149 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2150 VERIFY(data.result == vk::Result::eSuccess);
2152 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2153 fprintf(stderr, "Error loading texture: %s\n", filename);
2156 device.unmapMemory(tex_obj->mem);
2159 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2162 void Demo::prepare_textures() {
2163 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2164 vk::FormatProperties props;
2165 gpu.getFormatProperties(tex_format, &props);
2167 for (uint32_t i = 0; i < texture_count; i++) {
2168 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2169 /* Device can texture using linear textures */
2170 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2171 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2172 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2173 // shader to run until layout transition completes
2174 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2175 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2176 vk::PipelineStageFlagBits::eFragmentShader);
2177 staging_texture.image = vk::Image();
2178 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2179 /* Must use staging buffer to copy linear texture to optimized */
2181 prepare_texture_buffer(tex_files[i], &staging_texture);
2183 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2184 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2185 vk::MemoryPropertyFlagBits::eDeviceLocal);
2187 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2188 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2189 vk::PipelineStageFlagBits::eTransfer);
2191 auto const subresource = vk::ImageSubresourceLayers()
2192 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2194 .setBaseArrayLayer(0)
2197 auto const copy_region =
2198 vk::BufferImageCopy()
2200 .setBufferRowLength(staging_texture.tex_width)
2201 .setBufferImageHeight(staging_texture.tex_height)
2202 .setImageSubresource(subresource)
2203 .setImageOffset({0, 0, 0})
2204 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2206 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, ©_region);
2208 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2209 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2210 vk::PipelineStageFlagBits::eFragmentShader);
2212 assert(!"No support for R8G8B8A8_UNORM as texture image format");
2215 auto const samplerInfo = vk::SamplerCreateInfo()
2216 .setMagFilter(vk::Filter::eNearest)
2217 .setMinFilter(vk::Filter::eNearest)
2218 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2219 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2220 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2221 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2222 .setMipLodBias(0.0f)
2223 .setAnisotropyEnable(VK_FALSE)
2224 .setMaxAnisotropy(1)
2225 .setCompareEnable(VK_FALSE)
2226 .setCompareOp(vk::CompareOp::eNever)
2229 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2230 .setUnnormalizedCoordinates(VK_FALSE);
2232 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2233 VERIFY(result == vk::Result::eSuccess);
2235 auto const viewInfo = vk::ImageViewCreateInfo()
2236 .setImage(textures[i].image)
2237 .setViewType(vk::ImageViewType::e2D)
2238 .setFormat(tex_format)
2239 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2241 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2242 VERIFY(result == vk::Result::eSuccess);
2246 vk::ShaderModule Demo::prepare_vs() {
2247 const uint32_t vertShaderCode[] = {
2248 #include "cube.vert.inc"
2251 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2253 return vert_shader_module;
2256 void Demo::resize() {
2259 // Don't react to resize until after first initialization.
2264 // In order to properly resize the window, we must re-create the
2266 // AND redo the command buffers, etc.
2268 // First, perform part of the cleanup() function:
2270 auto result = device.waitIdle();
2271 VERIFY(result == vk::Result::eSuccess);
2273 for (i = 0; i < swapchainImageCount; i++) {
2274 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2277 device.destroyDescriptorPool(desc_pool, nullptr);
2279 device.destroyPipeline(pipeline, nullptr);
2280 device.destroyPipelineCache(pipelineCache, nullptr);
2281 device.destroyRenderPass(render_pass, nullptr);
2282 device.destroyPipelineLayout(pipeline_layout, nullptr);
2283 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2285 for (i = 0; i < texture_count; i++) {
2286 device.destroyImageView(textures[i].view, nullptr);
2287 device.destroyImage(textures[i].image, nullptr);
2288 device.freeMemory(textures[i].mem, nullptr);
2289 device.destroySampler(textures[i].sampler, nullptr);
2292 device.destroyImageView(depth.view, nullptr);
2293 device.destroyImage(depth.image, nullptr);
2294 device.freeMemory(depth.mem, nullptr);
2296 for (i = 0; i < swapchainImageCount; i++) {
2297 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2298 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2299 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2300 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2303 device.destroyCommandPool(cmd_pool, nullptr);
2304 if (separate_present_queue) {
2305 device.destroyCommandPool(present_cmd_pool, nullptr);
2308 // Second, re-perform the prepare() function, which will re-create the
2313 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2314 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2317 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2318 vk::AccessFlags flags;
2321 case vk::ImageLayout::eTransferDstOptimal:
2322 // Make sure anything that was copying from this image has
2324 flags = vk::AccessFlagBits::eTransferWrite;
2326 case vk::ImageLayout::eColorAttachmentOptimal:
2327 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2329 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2330 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2332 case vk::ImageLayout::eShaderReadOnlyOptimal:
2333 // Make sure any Copy or CPU writes to image are flushed
2334 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2336 case vk::ImageLayout::eTransferSrcOptimal:
2337 flags = vk::AccessFlagBits::eTransferRead;
2339 case vk::ImageLayout::ePresentSrcKHR:
2340 flags = vk::AccessFlagBits::eMemoryRead;
2349 auto const barrier = vk::ImageMemoryBarrier()
2350 .setSrcAccessMask(srcAccessMask)
2351 .setDstAccessMask(DstAccessMask(newLayout))
2352 .setOldLayout(oldLayout)
2353 .setNewLayout(newLayout)
2354 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2355 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2357 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2359 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2362 void Demo::update_data_buffer() {
2364 mat4x4_mul(VP, projection_matrix, view_matrix);
2366 // Rotate around the Y axis
2368 mat4x4_dup(Model, model_matrix);
2369 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2372 mat4x4_mul(MVP, VP, model_matrix);
2374 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2375 VERIFY(data.result == vk::Result::eSuccess);
2377 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2379 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2382 /* Convert ppm image data from header file into RGBA texture image */
2383 #include "lunarg.ppm.h"
2384 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
2387 cPtr = (char *)lunarg_ppm;
2388 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2391 while (strncmp(cPtr++, "\n", 1))
2393 sscanf(cPtr, "%u %u", width, height);
2394 if (rgba_data == NULL) {
2397 while (strncmp(cPtr++, "\n", 1))
2399 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2402 while (strncmp(cPtr++, "\n", 1))
2404 for (int y = 0; y < *height; y++) {
2405 uint8_t *rowPtr = rgba_data;
2406 for (int x = 0; x < *width; x++) {
2407 memcpy(rowPtr, cPtr, 3);
2408 rowPtr[3] = 255; /* Alpha of 1 */
2412 rgba_data += layout->rowPitch;
2417 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2418 // Search memtypes to find first index with those properties
2419 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2420 if ((typeBits & 1) == 1) {
2421 // Type is available, does it match user properties?
2422 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2430 // No memory types matched, return failure
2434 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2443 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2444 PostQuitMessage(validation_error);
2448 void Demo::create_window() {
2449 WNDCLASSEX win_class;
2451 // Initialize the window class structure:
2452 win_class.cbSize = sizeof(WNDCLASSEX);
2453 win_class.style = CS_HREDRAW | CS_VREDRAW;
2454 win_class.lpfnWndProc = WndProc;
2455 win_class.cbClsExtra = 0;
2456 win_class.cbWndExtra = 0;
2457 win_class.hInstance = connection; // hInstance
2458 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2459 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2460 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2461 win_class.lpszMenuName = nullptr;
2462 win_class.lpszClassName = name;
2463 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2465 // Register window class:
2466 if (!RegisterClassEx(&win_class)) {
2467 // It didn't work, so try to give a useful error:
2468 printf("Unexpected error trying to start the application!\n");
2473 // Create window with the registered class:
2474 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2475 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2476 window = CreateWindowEx(0,
2479 WS_OVERLAPPEDWINDOW | // window style
2480 WS_VISIBLE | WS_SYSMENU,
2481 100, 100, // x/y coords
2482 wr.right - wr.left, // width
2483 wr.bottom - wr.top, // height
2484 nullptr, // handle to parent
2485 nullptr, // handle to menu
2486 connection, // hInstance
2487 nullptr); // no extra parameters
2490 // It didn't work, so try to give a useful error:
2491 printf("Cannot create a window in which to draw!\n");
2496 // Window client area size must be at least 1 pixel high, to prevent
2498 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2499 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2501 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2503 void Demo::create_xlib_window() {
2504 const char *display_envar = getenv("DISPLAY");
2505 if (display_envar == nullptr || display_envar[0] == '\0') {
2506 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2512 display = XOpenDisplay(nullptr);
2513 long visualMask = VisualScreenMask;
2514 int numberOfVisuals;
2515 XVisualInfo vInfoTemplate = {};
2516 vInfoTemplate.screen = DefaultScreen(display);
2517 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2519 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2521 XSetWindowAttributes windowAttributes = {};
2522 windowAttributes.colormap = colormap;
2523 windowAttributes.background_pixel = 0xFFFFFFFF;
2524 windowAttributes.border_pixel = 0;
2525 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2528 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2529 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2531 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2532 XMapWindow(display, xlib_window);
2534 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2537 void Demo::handle_xlib_event(const XEvent *event) {
2538 switch (event->type) {
2540 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2545 switch (event->xkey.keycode) {
2549 case 0x71: // left arrow key
2550 spin_angle -= spin_increment;
2552 case 0x72: // right arrow key
2553 spin_angle += spin_increment;
2555 case 0x41: // space bar
2560 case ConfigureNotify:
2561 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2562 width = event->xconfigure.width;
2563 height = event->xconfigure.height;
2572 void Demo::run_xlib() {
2577 XNextEvent(display, &event);
2578 handle_xlib_event(&event);
2580 while (XPending(display) > 0) {
2581 XNextEvent(display, &event);
2582 handle_xlib_event(&event);
2588 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2593 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2595 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2596 uint8_t event_code = event->response_type & 0x7f;
2597 switch (event_code) {
2599 // TODO: Resize window
2601 case XCB_CLIENT_MESSAGE:
2602 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2606 case XCB_KEY_RELEASE: {
2607 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2609 switch (key->detail) {
2613 case 0x71: // left arrow key
2614 spin_angle -= spin_increment;
2616 case 0x72: // right arrow key
2617 spin_angle += spin_increment;
2619 case 0x41: // space bar
2624 case XCB_CONFIGURE_NOTIFY: {
2625 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2626 if ((width != cfg->width) || (height != cfg->height)) {
2628 height = cfg->height;
2637 void Demo::run_xcb() {
2638 xcb_flush(connection);
2641 xcb_generic_event_t *event;
2644 event = xcb_wait_for_event(connection);
2646 event = xcb_poll_for_event(connection);
2649 handle_xcb_event(event);
2651 event = xcb_poll_for_event(connection);
2656 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2662 void Demo::create_xcb_window() {
2663 uint32_t value_mask, value_list[32];
2665 xcb_window = xcb_generate_id(connection);
2667 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2668 value_list[0] = screen->black_pixel;
2669 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2671 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2672 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2674 /* Magic code that will send notification when window is destroyed */
2675 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2676 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2678 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2679 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2681 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2685 xcb_map_window(connection, xcb_window);
2687 // Force the x/y coordinates to 100,100 results are identical in
2690 const uint32_t coords[] = {100, 100};
2691 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2693 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2698 wl_display_dispatch(display);
2700 wl_display_dispatch_pending(display);
2701 update_data_buffer();
2704 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2711 static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2712 Demo *demo = (Demo *)data;
2713 xdg_surface_ack_configure(xdg_surface, serial);
2714 if (demo->xdg_surface_has_been_configured) {
2717 demo->xdg_surface_has_been_configured = true;
2720 static const xdg_surface_listener surface_listener = {handle_surface_configure};
2722 static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2723 struct wl_array *states) {
2724 Demo *demo = (Demo *)data;
2725 demo->width = width;
2726 demo->height = height;
2727 // This will be followed by a surface configure
2730 static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2731 Demo *demo = (Demo *)data;
2735 static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2737 void Demo::create_window() {
2739 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2744 window = wl_compositor_create_surface(compositor);
2746 printf("Can not create wayland_surface from compositor!\n");
2751 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2752 if (!window_surface) {
2753 printf("Can not get xdg_surface from wayland_surface!\n");
2757 window_toplevel = xdg_surface_get_toplevel(window_surface);
2758 if (!window_toplevel) {
2759 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2763 xdg_surface_add_listener(window_surface, &surface_listener, this);
2764 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2765 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2766 if (xdg_decoration_mgr) {
2767 // if supported, let the compositor render titlebars for us
2768 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2769 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2772 wl_surface_commit(window);
2774 #elif defined(VK_USE_PLATFORM_METAL_EXT)
2778 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2782 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2784 vk::Result Demo::create_display_surface() {
2786 uint32_t display_count;
2787 uint32_t mode_count;
2788 uint32_t plane_count;
2789 vk::DisplayPropertiesKHR display_props;
2790 vk::DisplayKHR display;
2791 vk::DisplayModePropertiesKHR mode_props;
2792 vk::DisplayPlanePropertiesKHR *plane_props;
2793 vk::Bool32 found_plane = VK_FALSE;
2794 uint32_t plane_index;
2795 vk::Extent2D image_extent;
2797 // Get the first display
2798 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2799 VERIFY(result == vk::Result::eSuccess);
2801 if (display_count == 0) {
2802 printf("Cannot find any display!\n");
2808 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2809 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2811 display = display_props.display;
2813 // Get the first mode of the display
2814 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2815 VERIFY(result == vk::Result::eSuccess);
2817 if (mode_count == 0) {
2818 printf("Cannot find any mode for the display!\n");
2824 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2825 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2827 // Get the list of planes
2828 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2829 VERIFY(result == vk::Result::eSuccess);
2831 if (plane_count == 0) {
2832 printf("Cannot find any plane!\n");
2837 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2838 VERIFY(plane_props != nullptr);
2840 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2841 VERIFY(result == vk::Result::eSuccess);
2843 // Find a plane compatible with the display
2844 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2845 uint32_t supported_count;
2846 vk::DisplayKHR *supported_displays;
2848 // Disqualify planes that are bound to a different display
2849 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2853 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
2854 VERIFY(result == vk::Result::eSuccess);
2856 if (supported_count == 0) {
2860 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2861 VERIFY(supported_displays != nullptr);
2863 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
2864 VERIFY(result == vk::Result::eSuccess);
2866 for (uint32_t i = 0; i < supported_count; i++) {
2867 if (supported_displays[i] == display) {
2868 found_plane = VK_TRUE;
2873 free(supported_displays);
2881 printf("Cannot find a plane compatible with the display!\n");
2888 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2889 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2890 // Find a supported alpha mode
2891 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2892 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2893 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2894 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2895 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2896 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2898 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2899 if (planeCaps.supportedAlpha & alphaModes[i]) {
2900 alphaMode = alphaModes[i];
2905 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2906 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2908 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2909 .setDisplayMode(mode_props.displayMode)
2910 .setPlaneIndex(plane_index)
2911 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2912 .setGlobalAlpha(1.0f)
2913 .setAlphaMode(alphaMode)
2914 .setImageExtent(image_extent);
2916 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2919 void Demo::run_display() {
2924 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2932 // Include header required for parsing the command line options.
2933 #include <shellapi.h>
2937 // MS-Windows event handling function:
2938 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2941 PostQuitMessage(validation_error);
2946 case WM_GETMINMAXINFO: // set window's minimum size
2947 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2952 // Resize the application to the new window size, except when
2953 // it was minimized. Vulkan doesn't support images or swapchains
2954 // with width=0 and height=0.
2955 if (wParam != SIZE_MINIMIZED) {
2956 demo.width = lParam & 0xffff;
2957 demo.height = (lParam & 0xffff0000) >> 16;
2964 PostQuitMessage(validation_error);
2967 demo.spin_angle -= demo.spin_increment;
2970 demo.spin_angle += demo.spin_increment;
2973 demo.pause = !demo.pause;
2981 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2984 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
2985 // TODO: Gah.. refactor. This isn't 1989.
2987 bool done; // flag saying when app is complete
2991 // Ensure wParam is initialized.
2994 // Use the CommandLine functions to get the command line arguments.
2995 // Unfortunately, Microsoft outputs
2996 // this information as wide characters for Unicode, and we simply want the
2997 // Ascii version to be compatible
2998 // with the non-Windows side. So, we have to convert the information to
2999 // Ascii character strings.
3000 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3001 if (nullptr == commandLineArgs) {
3006 argv = (char **)malloc(sizeof(char *) * argc);
3007 if (argv == nullptr) {
3010 for (int iii = 0; iii < argc; iii++) {
3011 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3012 size_t numConverted = 0;
3014 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3015 if (argv[iii] != nullptr) {
3016 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3024 demo.init(argc, argv);
3026 // Free up the items we had to allocate for the command line arguments.
3027 if (argc > 0 && argv != nullptr) {
3028 for (int iii = 0; iii < argc; iii++) {
3029 if (argv[iii] != nullptr) {
3036 demo.connection = hInstance;
3037 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
3038 demo.create_window();
3039 demo.init_vk_swapchain();
3043 done = false; // initialize loop condition variable
3045 // main message loop
3048 const BOOL succ = WaitMessage();
3051 const auto &suppress_popups = demo.suppress_popups;
3052 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3056 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
3057 if (msg.message == WM_QUIT) // check for a quit message
3059 done = true; // if found, quit app
3061 /* Translate and dispatch to event queue*/
3062 TranslateMessage(&msg);
3063 DispatchMessage(&msg);
3065 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3070 return (int)msg.wParam;
3075 int main(int argc, char **argv) {
3078 demo.init(argc, argv);
3080 #if defined(VK_USE_PLATFORM_XCB_KHR)
3081 demo.create_xcb_window();
3082 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3083 demo.use_xlib = true;
3084 demo.create_xlib_window();
3085 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3086 demo.create_window();
3089 demo.init_vk_swapchain();
3093 #if defined(VK_USE_PLATFORM_XCB_KHR)
3095 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3097 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3099 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3105 return validation_error;
3108 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3110 // Global function invoked from NS or UI views and controllers to create demo
3111 static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
3112 demo.init(argc, (char **)argv);
3113 demo.caMetalLayer = caMetalLayer;
3114 demo.init_vk_swapchain();
3116 demo.spin_angle = 0.4f;
3120 #error "Platform not supported"