2 * Copyright (c) 2015-2016 The Khronos Group Inc.
3 * Copyright (c) 2015-2016 Valve Corporation
4 * Copyright (c) 2015-2016 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>
37 #define VULKAN_HPP_NO_SMART_HANDLE
38 #define VULKAN_HPP_NO_EXCEPTIONS
39 #define VULKAN_HPP_TYPESAFE_CONVERSION
40 #include <vulkan/vulkan.hpp>
41 #include <vulkan/vk_sdk_platform.h>
46 #define VERIFY(x) assert(x)
48 #define VERIFY(x) ((void)(x))
51 #define APP_SHORT_NAME "vkcube"
53 #define APP_NAME_STR_LEN 80
56 // Allow a maximum of two outstanding presentation operations.
59 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
62 #define ERR_EXIT(err_msg, err_class) \
64 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
68 #define ERR_EXIT(err_msg, err_class) \
70 printf("%s\n", err_msg); \
76 struct texture_object {
81 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
83 vk::MemoryAllocateInfo mem_alloc;
88 int32_t tex_height{0};
91 static char const *const tex_files[] = {"lunarg.ppm"};
93 static int validation_error = 0;
95 struct vkcube_vs_uniform {
96 // Must start with MVP
98 float position[12 * 3][4];
99 float color[12 * 3][4];
102 struct vktexcube_vs_uniform {
103 // Must start with MVP
105 float position[12 * 3][4];
106 float attr[12 * 3][4];
109 //--------------------------------------------------------------------------------------
110 // Mesh and VertexFormat Data
111 //--------------------------------------------------------------------------------------
113 static const float g_vertex_buffer_data[] = {
114 -1.0f,-1.0f,-1.0f, // -X side
121 -1.0f,-1.0f,-1.0f, // -Z side
128 -1.0f,-1.0f,-1.0f, // -Y side
135 -1.0f, 1.0f,-1.0f, // +Y side
142 1.0f, 1.0f,-1.0f, // +X side
149 -1.0f, 1.0f, 1.0f, // +Z side
157 static const float g_uv_buffer_data[] = {
158 0.0f, 1.0f, // -X side
165 1.0f, 1.0f, // -Z side
172 1.0f, 0.0f, // -Y side
179 1.0f, 0.0f, // +Y side
186 1.0f, 0.0f, // +X side
193 0.0f, 0.0f, // +Z side
204 vk::CommandBuffer cmd;
205 vk::CommandBuffer graphics_to_present_cmd;
207 vk::Buffer uniform_buffer;
208 vk::DeviceMemory uniform_memory;
209 vk::Framebuffer framebuffer;
210 vk::DescriptorSet descriptor_set;
211 } SwapchainImageResources;
215 void build_image_ownership_cmd(uint32_t const &);
216 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
218 void create_device();
219 void destroy_texture(texture_object *);
221 void draw_build_cmd(vk::CommandBuffer);
222 void flush_init_cmd();
223 void init(int, char **);
224 void init_connection();
226 void init_vk_swapchain();
228 void prepare_buffers();
229 void prepare_cube_data_buffers();
230 void prepare_depth();
231 void prepare_descriptor_layout();
232 void prepare_descriptor_pool();
233 void prepare_descriptor_set();
234 void prepare_framebuffers();
235 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
236 vk::ShaderModule prepare_vs();
237 vk::ShaderModule prepare_fs();
238 void prepare_pipeline();
239 void prepare_render_pass();
240 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
241 void prepare_texture_buffer(const char *, texture_object *);
242 void prepare_textures();
245 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
246 vk::PipelineStageFlags, vk::PipelineStageFlags);
247 void update_data_buffer();
248 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
249 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
251 #if defined(VK_USE_PLATFORM_WIN32_KHR)
253 void create_window();
254 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
255 void create_xlib_window();
256 void handle_xlib_event(const XEvent *);
258 #elif defined(VK_USE_PLATFORM_XCB_KHR)
259 void handle_xcb_event(const xcb_generic_event_t *);
261 void create_xcb_window();
262 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
264 void create_window();
265 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
267 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
268 vk::Result create_display_surface();
272 #if defined(VK_USE_PLATFORM_WIN32_KHR)
273 HINSTANCE connection; // hInstance - Windows Instance
274 HWND window; // hWnd - window handle
275 POINT minsize; // minimum window size
276 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
277 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
279 Atom xlib_wm_delete_window;
281 #elif defined(VK_USE_PLATFORM_XCB_KHR)
282 xcb_window_t xcb_window;
283 xcb_screen_t *screen;
284 xcb_connection_t *connection;
285 xcb_intern_atom_reply_t *atom_wm_delete_window;
286 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
288 wl_registry *registry;
289 wl_compositor *compositor;
292 wl_shell_surface *shell_surface;
295 wl_keyboard *keyboard;
296 #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
300 vk::SurfaceKHR surface;
302 bool use_staging_buffer;
304 bool separate_present_queue;
307 vk::PhysicalDevice gpu;
309 vk::Queue graphics_queue;
310 vk::Queue present_queue;
311 uint32_t graphics_queue_family_index;
312 uint32_t present_queue_family_index;
313 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
314 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
315 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
316 vk::PhysicalDeviceProperties gpu_props;
317 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
318 vk::PhysicalDeviceMemoryProperties memory_properties;
320 uint32_t enabled_extension_count;
321 uint32_t enabled_layer_count;
322 char const *extension_names[64];
323 char const *enabled_layers[64];
328 vk::ColorSpaceKHR color_space;
330 uint32_t swapchainImageCount;
331 vk::SwapchainKHR swapchain;
332 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
333 vk::PresentModeKHR presentMode;
334 vk::Fence fences[FRAME_LAG];
335 uint32_t frame_index;
337 vk::CommandPool cmd_pool;
338 vk::CommandPool present_cmd_pool;
343 vk::MemoryAllocateInfo mem_alloc;
344 vk::DeviceMemory mem;
348 static int32_t const texture_count = 1;
349 texture_object textures[texture_count];
350 texture_object staging_texture;
354 vk::MemoryAllocateInfo mem_alloc;
355 vk::DeviceMemory mem;
356 vk::DescriptorBufferInfo buffer_info;
359 vk::CommandBuffer cmd; // Buffer for initialization commands
360 vk::PipelineLayout pipeline_layout;
361 vk::DescriptorSetLayout desc_layout;
362 vk::PipelineCache pipelineCache;
363 vk::RenderPass render_pass;
364 vk::Pipeline pipeline;
366 mat4x4 projection_matrix;
371 float spin_increment;
374 vk::ShaderModule vert_shader_module;
375 vk::ShaderModule frag_shader_module;
377 vk::DescriptorPool desc_pool;
378 vk::DescriptorSet desc_set;
380 std::unique_ptr<vk::Framebuffer[]> framebuffers;
387 bool suppress_popups;
389 uint32_t current_buffer;
390 uint32_t queue_family_count;
394 // MS-Windows event handling function:
395 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
398 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
399 static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
400 wl_shell_surface_pong(shell_surface, serial);
403 static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
405 static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
407 static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
409 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
412 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
414 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
416 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
418 Demo *demo = (Demo *)data;
419 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
420 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
424 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
426 static const struct wl_pointer_listener pointer_listener = {
427 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
430 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
432 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
433 struct wl_array *keys) {}
435 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
437 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
439 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
440 Demo *demo = (Demo *)data;
442 case KEY_ESC: // Escape
445 case KEY_LEFT: // left arrow key
446 demo->spin_angle -= demo->spin_increment;
448 case KEY_RIGHT: // right arrow key
449 demo->spin_angle += demo->spin_increment;
451 case KEY_SPACE: // space bar
452 demo->pause = !demo->pause;
457 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
458 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
460 static const struct wl_keyboard_listener keyboard_listener = {
461 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
464 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
465 // Subscribe to pointer events
466 Demo *demo = (Demo *)data;
467 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
468 demo->pointer = wl_seat_get_pointer(seat);
469 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
470 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
471 wl_pointer_destroy(demo->pointer);
472 demo->pointer = NULL;
474 // Subscribe to keyboard events
475 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
476 demo->keyboard = wl_seat_get_keyboard(seat);
477 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
478 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
479 wl_keyboard_destroy(demo->keyboard);
480 demo->keyboard = NULL;
484 static const wl_seat_listener seat_listener = {
485 seat_handle_capabilities,
488 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
489 Demo *demo = (Demo *)data;
490 // pickup wayland objects when they appear
491 if (strcmp(interface, "wl_compositor") == 0) {
492 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
493 } else if (strcmp(interface, "wl_shell") == 0) {
494 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
495 } else if (strcmp(interface, "wl_seat") == 0) {
496 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
497 wl_seat_add_listener(demo->seat, &seat_listener, demo);
501 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
503 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
508 #if defined(VK_USE_PLATFORM_WIN32_KHR)
511 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
514 #if defined(VK_USE_PLATFORM_XLIB_KHR)
516 xlib_wm_delete_window{0},
518 #elif defined(VK_USE_PLATFORM_XCB_KHR)
522 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
528 shell_surface{nullptr},
534 use_staging_buffer{false},
536 graphics_queue_family_index{0},
537 present_queue_family_index{0},
538 enabled_extension_count{0},
539 enabled_layer_count{0},
542 swapchainImageCount{0},
543 presentMode{vk::PresentModeKHR::eFifo},
546 spin_increment{0.0f},
553 suppress_popups{false},
555 queue_family_count{0} {
556 #if defined(VK_USE_PLATFORM_WIN32_KHR)
557 memset(name, '\0', APP_NAME_STR_LEN);
559 memset(projection_matrix, 0, sizeof(projection_matrix));
560 memset(view_matrix, 0, sizeof(view_matrix));
561 memset(model_matrix, 0, sizeof(model_matrix));
564 void Demo::build_image_ownership_cmd(uint32_t const &i) {
565 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
566 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
567 VERIFY(result == vk::Result::eSuccess);
569 auto const image_ownership_barrier =
570 vk::ImageMemoryBarrier()
571 .setSrcAccessMask(vk::AccessFlags())
572 .setDstAccessMask(vk::AccessFlags())
573 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
574 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
575 .setSrcQueueFamilyIndex(graphics_queue_family_index)
576 .setDstQueueFamilyIndex(present_queue_family_index)
577 .setImage(swapchain_image_resources[i].image)
578 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
580 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
581 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
582 nullptr, 1, &image_ownership_barrier);
584 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
585 VERIFY(result == vk::Result::eSuccess);
588 vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
589 vk::LayerProperties *layers) {
590 for (uint32_t i = 0; i < check_count; i++) {
591 vk::Bool32 found = VK_FALSE;
592 for (uint32_t j = 0; j < layer_count; j++) {
593 if (!strcmp(check_names[i], layers[j].layerName)) {
599 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
606 void Demo::cleanup() {
610 // Wait for fences from present operations
611 for (uint32_t i = 0; i < FRAME_LAG; i++) {
612 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
613 device.destroyFence(fences[i], nullptr);
614 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
615 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
616 if (separate_present_queue) {
617 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
621 for (uint32_t i = 0; i < swapchainImageCount; i++) {
622 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
624 device.destroyDescriptorPool(desc_pool, nullptr);
626 device.destroyPipeline(pipeline, nullptr);
627 device.destroyPipelineCache(pipelineCache, nullptr);
628 device.destroyRenderPass(render_pass, nullptr);
629 device.destroyPipelineLayout(pipeline_layout, nullptr);
630 device.destroyDescriptorSetLayout(desc_layout, nullptr);
632 for (uint32_t i = 0; i < texture_count; i++) {
633 device.destroyImageView(textures[i].view, nullptr);
634 device.destroyImage(textures[i].image, nullptr);
635 device.freeMemory(textures[i].mem, nullptr);
636 device.destroySampler(textures[i].sampler, nullptr);
638 device.destroySwapchainKHR(swapchain, nullptr);
640 device.destroyImageView(depth.view, nullptr);
641 device.destroyImage(depth.image, nullptr);
642 device.freeMemory(depth.mem, nullptr);
644 for (uint32_t i = 0; i < swapchainImageCount; i++) {
645 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
646 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
647 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
648 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
651 device.destroyCommandPool(cmd_pool, nullptr);
653 if (separate_present_queue) {
654 device.destroyCommandPool(present_cmd_pool, nullptr);
657 device.destroy(nullptr);
658 inst.destroySurfaceKHR(surface, nullptr);
660 #if defined(VK_USE_PLATFORM_XLIB_KHR)
661 XDestroyWindow(display, xlib_window);
662 XCloseDisplay(display);
663 #elif defined(VK_USE_PLATFORM_XCB_KHR)
664 xcb_destroy_window(connection, xcb_window);
665 xcb_disconnect(connection);
666 free(atom_wm_delete_window);
667 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
668 wl_keyboard_destroy(keyboard);
669 wl_pointer_destroy(pointer);
670 wl_seat_destroy(seat);
671 wl_shell_surface_destroy(shell_surface);
672 wl_surface_destroy(window);
673 wl_shell_destroy(shell);
674 wl_compositor_destroy(compositor);
675 wl_registry_destroy(registry);
676 wl_display_disconnect(display);
679 inst.destroy(nullptr);
682 void Demo::create_device() {
683 float const priorities[1] = {0.0};
685 vk::DeviceQueueCreateInfo queues[2];
686 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
687 queues[0].setQueueCount(1);
688 queues[0].setPQueuePriorities(priorities);
690 auto deviceInfo = vk::DeviceCreateInfo()
691 .setQueueCreateInfoCount(1)
692 .setPQueueCreateInfos(queues)
693 .setEnabledLayerCount(0)
694 .setPpEnabledLayerNames(nullptr)
695 .setEnabledExtensionCount(enabled_extension_count)
696 .setPpEnabledExtensionNames((const char *const *)extension_names)
697 .setPEnabledFeatures(nullptr);
699 if (separate_present_queue) {
700 queues[1].setQueueFamilyIndex(present_queue_family_index);
701 queues[1].setQueueCount(1);
702 queues[1].setPQueuePriorities(priorities);
703 deviceInfo.setQueueCreateInfoCount(2);
706 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
707 VERIFY(result == vk::Result::eSuccess);
710 void Demo::destroy_texture(texture_object *tex_objs) {
711 // clean up staging resources
712 device.freeMemory(tex_objs->mem, nullptr);
713 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
714 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
718 // Ensure no more than FRAME_LAG renderings are outstanding
719 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
720 device.resetFences(1, &fences[frame_index]);
725 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer);
726 if (result == vk::Result::eErrorOutOfDateKHR) {
727 // demo->swapchain is out of date (e.g. the window was resized) and
728 // must be recreated:
730 } else if (result == vk::Result::eSuboptimalKHR) {
731 // swapchain is not as optimal as it could be, but the platform's
732 // presentation engine will still present the image correctly.
735 VERIFY(result == vk::Result::eSuccess);
737 } while (result != vk::Result::eSuccess);
739 update_data_buffer();
741 // Wait for the image acquired semaphore to be signaled to ensure
742 // that the image won't be rendered to until the presentation
743 // engine has fully released ownership to the application, and it is
744 // okay to render to the image.
745 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
746 auto const submit_info = vk::SubmitInfo()
747 .setPWaitDstStageMask(&pipe_stage_flags)
748 .setWaitSemaphoreCount(1)
749 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
750 .setCommandBufferCount(1)
751 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
752 .setSignalSemaphoreCount(1)
753 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
755 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
756 VERIFY(result == vk::Result::eSuccess);
758 if (separate_present_queue) {
759 // If we are using separate queues, change image ownership to the
760 // present queue before presenting, waiting for the draw complete
761 // semaphore and signalling the ownership released semaphore when
763 auto const present_submit_info = vk::SubmitInfo()
764 .setPWaitDstStageMask(&pipe_stage_flags)
765 .setWaitSemaphoreCount(1)
766 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
767 .setCommandBufferCount(1)
768 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
769 .setSignalSemaphoreCount(1)
770 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
772 result = present_queue.submit(1, &present_submit_info, vk::Fence());
773 VERIFY(result == vk::Result::eSuccess);
776 // If we are using separate queues we have to wait for image ownership,
777 // otherwise wait for draw complete
778 auto const presentInfo = vk::PresentInfoKHR()
779 .setWaitSemaphoreCount(1)
780 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
781 : &draw_complete_semaphores[frame_index])
782 .setSwapchainCount(1)
783 .setPSwapchains(&swapchain)
784 .setPImageIndices(¤t_buffer);
786 result = present_queue.presentKHR(&presentInfo);
788 frame_index %= FRAME_LAG;
789 if (result == vk::Result::eErrorOutOfDateKHR) {
790 // swapchain is out of date (e.g. the window was resized) and
791 // must be recreated:
793 } else if (result == vk::Result::eSuboptimalKHR) {
794 // swapchain is not as optimal as it could be, but the platform's
795 // presentation engine will still present the image correctly.
797 VERIFY(result == vk::Result::eSuccess);
801 void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
802 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
804 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
805 vk::ClearDepthStencilValue(1.0f, 0u)};
807 auto const passInfo = vk::RenderPassBeginInfo()
808 .setRenderPass(render_pass)
809 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
810 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
811 .setClearValueCount(2)
812 .setPClearValues(clearValues);
814 auto result = commandBuffer.begin(&commandInfo);
815 VERIFY(result == vk::Result::eSuccess);
817 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
818 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
819 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
820 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
822 auto const viewport =
823 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
824 commandBuffer.setViewport(0, 1, &viewport);
826 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
827 commandBuffer.setScissor(0, 1, &scissor);
828 commandBuffer.draw(12 * 3, 1, 0, 0);
829 // Note that ending the renderpass changes the image's layout from
830 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
831 commandBuffer.endRenderPass();
833 if (separate_present_queue) {
834 // We have to transfer ownership from the graphics queue family to
836 // present queue family to be able to present. Note that we don't
838 // to transfer from present queue family back to graphics queue
840 // the start of the next frame because we don't care about the
842 // contents at that point.
843 auto const image_ownership_barrier =
844 vk::ImageMemoryBarrier()
845 .setSrcAccessMask(vk::AccessFlags())
846 .setDstAccessMask(vk::AccessFlags())
847 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
848 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
849 .setSrcQueueFamilyIndex(graphics_queue_family_index)
850 .setDstQueueFamilyIndex(present_queue_family_index)
851 .setImage(swapchain_image_resources[current_buffer].image)
852 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
854 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
855 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
858 result = commandBuffer.end();
859 VERIFY(result == vk::Result::eSuccess);
862 void Demo::flush_init_cmd() {
864 // This function could get called twice if the texture uses a staging
866 // In that case the second call should be ignored
871 auto result = cmd.end();
872 VERIFY(result == vk::Result::eSuccess);
874 auto const fenceInfo = vk::FenceCreateInfo();
876 result = device.createFence(&fenceInfo, nullptr, &fence);
877 VERIFY(result == vk::Result::eSuccess);
879 vk::CommandBuffer const commandBuffers[] = {cmd};
880 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
882 result = graphics_queue.submit(1, &submitInfo, fence);
883 VERIFY(result == vk::Result::eSuccess);
885 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
886 VERIFY(result == vk::Result::eSuccess);
888 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
889 device.destroyFence(fence, nullptr);
891 cmd = vk::CommandBuffer();
894 void Demo::init(int argc, char **argv) {
895 vec3 eye = {0.0f, 3.0f, 5.0f};
896 vec3 origin = {0, 0, 0};
897 vec3 up = {0.0f, 1.0f, 0.0};
899 presentMode = vk::PresentModeKHR::eFifo;
900 frameCount = UINT32_MAX;
903 for (int i = 1; i < argc; i++) {
904 if (strcmp(argv[i], "--use_staging") == 0) {
905 use_staging_buffer = true;
908 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
909 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
913 if (strcmp(argv[i], "--break") == 0) {
917 if (strcmp(argv[i], "--validate") == 0) {
921 if (strcmp(argv[i], "--xlib") == 0) {
922 fprintf(stderr, "--xlib is deprecated and no longer does anything");
925 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
926 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
930 if (strcmp(argv[i], "--suppress_popups") == 0) {
931 suppress_popups = true;
935 std::stringstream usage;
936 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
937 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
938 << "\t[--present_mode <present mode enum>]\n"
939 << "\t<present_mode_enum>\n"
940 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
941 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
942 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
943 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
946 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
948 std::cerr << usage.str();
964 spin_increment = 0.2f;
967 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
968 mat4x4_look_at(view_matrix, eye, origin, up);
969 mat4x4_identity(model_matrix);
971 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
974 void Demo::init_connection() {
975 #if defined(VK_USE_PLATFORM_XCB_KHR)
976 const xcb_setup_t *setup;
977 xcb_screen_iterator_t iter;
980 const char *display_envar = getenv("DISPLAY");
981 if (display_envar == nullptr || display_envar[0] == '\0') {
982 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
987 connection = xcb_connect(nullptr, &scr);
988 if (xcb_connection_has_error(connection) > 0) {
990 "Cannot find a compatible Vulkan installable client driver "
991 "(ICD).\nExiting ...\n");
996 setup = xcb_get_setup(connection);
997 iter = xcb_setup_roots_iterator(setup);
998 while (scr-- > 0) xcb_screen_next(&iter);
1001 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1002 display = wl_display_connect(nullptr);
1004 if (display == nullptr) {
1005 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1010 registry = wl_display_get_registry(display);
1011 wl_registry_add_listener(registry, ®istry_listener, this);
1012 wl_display_dispatch(display);
1016 void Demo::init_vk() {
1017 uint32_t instance_extension_count = 0;
1018 uint32_t instance_layer_count = 0;
1019 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
1020 enabled_extension_count = 0;
1021 enabled_layer_count = 0;
1023 // Look for validation layers
1024 vk::Bool32 validation_found = VK_FALSE;
1026 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
1027 VERIFY(result == vk::Result::eSuccess);
1029 if (instance_layer_count > 0) {
1030 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1031 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
1032 VERIFY(result == vk::Result::eSuccess);
1034 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
1035 instance_layer_count, instance_layers.get());
1036 if (validation_found) {
1037 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1038 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
1042 if (!validation_found) {
1044 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1045 "Please look at the Getting Started guide for additional information.\n",
1046 "vkCreateInstance Failure");
1050 /* Look for instance extensions */
1051 vk::Bool32 surfaceExtFound = VK_FALSE;
1052 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1053 memset(extension_names, 0, sizeof(extension_names));
1055 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1056 static_cast<vk::ExtensionProperties *>(nullptr));
1057 VERIFY(result == vk::Result::eSuccess);
1059 if (instance_extension_count > 0) {
1060 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1061 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1062 VERIFY(result == vk::Result::eSuccess);
1064 for (uint32_t i = 0; i < instance_extension_count; i++) {
1065 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1066 surfaceExtFound = 1;
1067 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1069 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1070 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1071 platformSurfaceExtFound = 1;
1072 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1074 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1075 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1076 platformSurfaceExtFound = 1;
1077 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1079 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1080 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1081 platformSurfaceExtFound = 1;
1082 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1084 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1085 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1086 platformSurfaceExtFound = 1;
1087 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1089 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1090 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1091 platformSurfaceExtFound = 1;
1092 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1094 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1095 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1096 platformSurfaceExtFound = 1;
1097 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1099 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1100 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1101 platformSurfaceExtFound = 1;
1102 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1106 assert(enabled_extension_count < 64);
1110 if (!surfaceExtFound) {
1111 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1113 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1114 "Please look at the Getting Started guide for additional information.\n",
1115 "vkCreateInstance Failure");
1118 if (!platformSurfaceExtFound) {
1119 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1120 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1122 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1123 "Please look at the Getting Started guide for additional information.\n",
1124 "vkCreateInstance Failure");
1125 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1126 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1128 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1129 "Please look at the Getting Started guide for additional information.\n",
1130 "vkCreateInstance Failure");
1131 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1132 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1134 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1135 "Please look at the Getting Started guide for additional information.\n",
1136 "vkCreateInstance Failure");
1137 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1141 "Please look at the Getting Started guide for additional information.\n",
1142 "vkCreateInstance Failure");
1143 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1144 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1146 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1147 "Please look at the Getting Started guide for additional information.\n",
1148 "vkCreateInstance Failure");
1149 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1150 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1151 " extension.\n\nDo you have a compatible "
1152 "Vulkan installable client driver (ICD) installed?\nPlease "
1153 "look at the Getting Started guide for additional "
1155 "vkCreateInstance Failure");
1156 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1157 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1158 " extension.\n\nDo you have a compatible "
1159 "Vulkan installable client driver (ICD) installed?\nPlease "
1160 "look at the Getting Started guide for additional "
1162 "vkCreateInstance Failure");
1165 auto const app = vk::ApplicationInfo()
1166 .setPApplicationName(APP_SHORT_NAME)
1167 .setApplicationVersion(0)
1168 .setPEngineName(APP_SHORT_NAME)
1169 .setEngineVersion(0)
1170 .setApiVersion(VK_API_VERSION_1_0);
1171 auto const inst_info = vk::InstanceCreateInfo()
1172 .setPApplicationInfo(&app)
1173 .setEnabledLayerCount(enabled_layer_count)
1174 .setPpEnabledLayerNames(instance_validation_layers)
1175 .setEnabledExtensionCount(enabled_extension_count)
1176 .setPpEnabledExtensionNames(extension_names);
1178 result = vk::createInstance(&inst_info, nullptr, &inst);
1179 if (result == vk::Result::eErrorIncompatibleDriver) {
1181 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1182 "Please look at the Getting Started guide for additional information.\n",
1183 "vkCreateInstance Failure");
1184 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1186 "Cannot find a specified extension library.\n"
1187 "Make sure your layers path is set appropriately.\n",
1188 "vkCreateInstance Failure");
1189 } else if (result != vk::Result::eSuccess) {
1191 "vkCreateInstance failed.\n\n"
1192 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1193 "Please look at the Getting Started guide for additional information.\n",
1194 "vkCreateInstance Failure");
1197 /* Make initial call to query gpu_count, then second call for gpu info*/
1199 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
1200 VERIFY(result == vk::Result::eSuccess);
1202 if (gpu_count > 0) {
1203 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1204 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1205 VERIFY(result == vk::Result::eSuccess);
1206 /* For cube demo we just grab the first physical device */
1207 gpu = physical_devices[0];
1210 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1211 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1212 "Please look at the Getting Started guide for additional information.\n",
1213 "vkEnumeratePhysicalDevices Failure");
1216 /* Look for device extensions */
1217 uint32_t device_extension_count = 0;
1218 vk::Bool32 swapchainExtFound = VK_FALSE;
1219 enabled_extension_count = 0;
1220 memset(extension_names, 0, sizeof(extension_names));
1223 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
1224 VERIFY(result == vk::Result::eSuccess);
1226 if (device_extension_count > 0) {
1227 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1228 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1229 VERIFY(result == vk::Result::eSuccess);
1231 for (uint32_t i = 0; i < device_extension_count; i++) {
1232 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1233 swapchainExtFound = 1;
1234 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1236 assert(enabled_extension_count < 64);
1240 if (!swapchainExtFound) {
1241 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1243 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1244 "Please look at the Getting Started guide for additional information.\n",
1245 "vkCreateInstance Failure");
1248 gpu.getProperties(&gpu_props);
1250 /* Call with nullptr data to get count */
1251 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
1252 assert(queue_family_count >= 1);
1254 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1255 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1257 // Query fine-grained feature support for this device.
1258 // If app has specific feature requirements it should check supported
1259 // features based on this query
1260 vk::PhysicalDeviceFeatures physDevFeatures;
1261 gpu.getFeatures(&physDevFeatures);
1264 void Demo::init_vk_swapchain() {
1265 // Create a WSI surface for the window:
1266 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1268 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1270 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1271 VERIFY(result == vk::Result::eSuccess);
1273 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1275 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1277 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1278 VERIFY(result == vk::Result::eSuccess);
1280 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1282 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1284 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1285 VERIFY(result == vk::Result::eSuccess);
1287 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1289 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1291 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1292 VERIFY(result == vk::Result::eSuccess);
1294 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1296 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1298 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1299 VERIFY(result == vk::Result::eSuccess);
1301 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1303 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1305 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1306 VERIFY(result == vk::Result::eSuccess);
1308 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1310 auto result = create_display_surface();
1311 VERIFY(result == vk::Result::eSuccess);
1314 // Iterate over each queue to learn whether it supports presenting:
1315 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1316 for (uint32_t i = 0; i < queue_family_count; i++) {
1317 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1320 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1321 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1322 for (uint32_t i = 0; i < queue_family_count; i++) {
1323 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1324 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1325 graphicsQueueFamilyIndex = i;
1328 if (supportsPresent[i] == VK_TRUE) {
1329 graphicsQueueFamilyIndex = i;
1330 presentQueueFamilyIndex = i;
1336 if (presentQueueFamilyIndex == UINT32_MAX) {
1337 // If didn't find a queue that supports both graphics and present,
1339 // find a separate present queue.
1340 for (uint32_t i = 0; i < queue_family_count; ++i) {
1341 if (supportsPresent[i] == VK_TRUE) {
1342 presentQueueFamilyIndex = i;
1348 // Generate error if could not find both a graphics and a present queue
1349 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1350 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1353 graphics_queue_family_index = graphicsQueueFamilyIndex;
1354 present_queue_family_index = presentQueueFamilyIndex;
1355 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1359 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1360 if (!separate_present_queue) {
1361 present_queue = graphics_queue;
1363 device.getQueue(present_queue_family_index, 0, &present_queue);
1366 // Get the list of VkFormat's that are supported:
1367 uint32_t formatCount;
1368 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
1369 VERIFY(result == vk::Result::eSuccess);
1371 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1372 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1373 VERIFY(result == vk::Result::eSuccess);
1375 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1376 // the surface has no preferred format. Otherwise, at least one
1377 // supported format will be returned.
1378 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1379 format = vk::Format::eB8G8R8A8Unorm;
1381 assert(formatCount >= 1);
1382 format = surfFormats[0].format;
1384 color_space = surfFormats[0].colorSpace;
1389 // Create semaphores to synchronize acquiring presentable buffers before
1390 // rendering and waiting for drawing to be complete before presenting
1391 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1393 // Create fences that we can use to throttle if we get too far
1394 // ahead of the image presents
1395 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1396 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1397 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1398 VERIFY(result == vk::Result::eSuccess);
1400 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1401 VERIFY(result == vk::Result::eSuccess);
1403 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1404 VERIFY(result == vk::Result::eSuccess);
1406 if (separate_present_queue) {
1407 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1408 VERIFY(result == vk::Result::eSuccess);
1413 // Get Memory information and properties
1414 gpu.getMemoryProperties(&memory_properties);
1417 void Demo::prepare() {
1418 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1419 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1420 VERIFY(result == vk::Result::eSuccess);
1422 auto const cmd = vk::CommandBufferAllocateInfo()
1423 .setCommandPool(cmd_pool)
1424 .setLevel(vk::CommandBufferLevel::ePrimary)
1425 .setCommandBufferCount(1);
1427 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1428 VERIFY(result == vk::Result::eSuccess);
1430 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1432 result = this->cmd.begin(&cmd_buf_info);
1433 VERIFY(result == vk::Result::eSuccess);
1438 prepare_cube_data_buffers();
1440 prepare_descriptor_layout();
1441 prepare_render_pass();
1444 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1445 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1446 VERIFY(result == vk::Result::eSuccess);
1449 if (separate_present_queue) {
1450 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1452 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1453 VERIFY(result == vk::Result::eSuccess);
1455 auto const present_cmd = vk::CommandBufferAllocateInfo()
1456 .setCommandPool(present_cmd_pool)
1457 .setLevel(vk::CommandBufferLevel::ePrimary)
1458 .setCommandBufferCount(1);
1460 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1461 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1462 VERIFY(result == vk::Result::eSuccess);
1464 build_image_ownership_cmd(i);
1468 prepare_descriptor_pool();
1469 prepare_descriptor_set();
1471 prepare_framebuffers();
1473 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1475 draw_build_cmd(swapchain_image_resources[i].cmd);
1479 * Prepare functions above may generate pipeline commands
1480 * that need to be flushed before beginning the render loop.
1483 if (staging_texture.buffer) {
1484 destroy_texture(&staging_texture);
1491 void Demo::prepare_buffers() {
1492 vk::SwapchainKHR oldSwapchain = swapchain;
1494 // Check the surface capabilities and formats
1495 vk::SurfaceCapabilitiesKHR surfCapabilities;
1496 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1497 VERIFY(result == vk::Result::eSuccess);
1499 uint32_t presentModeCount;
1500 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
1501 VERIFY(result == vk::Result::eSuccess);
1503 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1504 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1505 VERIFY(result == vk::Result::eSuccess);
1507 vk::Extent2D swapchainExtent;
1508 // width and height are either both -1, or both not -1.
1509 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1510 // If the surface size is undefined, the size is set to
1511 // the size of the images requested.
1512 swapchainExtent.width = width;
1513 swapchainExtent.height = height;
1515 // If the surface size is defined, the swap chain size must match
1516 swapchainExtent = surfCapabilities.currentExtent;
1517 width = surfCapabilities.currentExtent.width;
1518 height = surfCapabilities.currentExtent.height;
1521 // The FIFO present mode is guaranteed by the spec to be supported
1522 // and to have no tearing. It's a great default present mode to use.
1523 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1525 // There are times when you may wish to use another present mode. The
1526 // following code shows how to select them, and the comments provide some
1527 // reasons you may wish to use them.
1529 // It should be noted that Vulkan 1.0 doesn't provide a method for
1530 // synchronizing rendering with the presentation engine's display. There
1531 // is a method provided for throttling rendering with the display, but
1532 // there are some presentation engines for which this method will not work.
1533 // If an application doesn't throttle its rendering, and if it renders much
1534 // faster than the refresh rate of the display, this can waste power on
1535 // mobile devices. That is because power is being spent rendering images
1536 // that may never be seen.
1538 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1540 // tearing, or have some way of synchronizing their rendering with the
1542 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1543 // generally render a new presentable image every refresh cycle, but are
1544 // occasionally early. In this case, the application wants the new
1546 // to be displayed instead of the previously-queued-for-presentation
1548 // that has not yet been displayed.
1549 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1550 // render a new presentable image every refresh cycle, but are
1552 // late. In this case (perhaps because of stuttering/latency concerns),
1553 // the application wants the late image to be immediately displayed,
1555 // though that may mean some tearing.
1557 if (presentMode != swapchainPresentMode) {
1558 for (size_t i = 0; i < presentModeCount; ++i) {
1559 if (presentModes[i] == presentMode) {
1560 swapchainPresentMode = presentMode;
1566 if (swapchainPresentMode != presentMode) {
1567 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1570 // Determine the number of VkImages to use in the swap chain.
1571 // Application desires to acquire 3 images at a time for triple
1573 uint32_t desiredNumOfSwapchainImages = 3;
1574 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1575 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1578 // If maxImageCount is 0, we can ask for as many images as we want,
1580 // we're limited to maxImageCount
1581 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1582 // Application must settle for fewer images than desired:
1583 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1586 vk::SurfaceTransformFlagBitsKHR preTransform;
1587 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1588 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1590 preTransform = surfCapabilities.currentTransform;
1593 // Find a supported composite alpha mode - one of these is guaranteed to be set
1594 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1595 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1596 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1597 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1598 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1599 vk::CompositeAlphaFlagBitsKHR::eInherit,
1601 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1602 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1603 compositeAlpha = compositeAlphaFlags[i];
1608 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1609 .setSurface(surface)
1610 .setMinImageCount(desiredNumOfSwapchainImages)
1611 .setImageFormat(format)
1612 .setImageColorSpace(color_space)
1613 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1614 .setImageArrayLayers(1)
1615 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1616 .setImageSharingMode(vk::SharingMode::eExclusive)
1617 .setQueueFamilyIndexCount(0)
1618 .setPQueueFamilyIndices(nullptr)
1619 .setPreTransform(preTransform)
1620 .setCompositeAlpha(compositeAlpha)
1621 .setPresentMode(swapchainPresentMode)
1623 .setOldSwapchain(oldSwapchain);
1625 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1626 VERIFY(result == vk::Result::eSuccess);
1628 // If we just re-created an existing swapchain, we should destroy the
1630 // swapchain at this point.
1631 // Note: destroying the swapchain also cleans up all its associated
1632 // presentable images once the platform is done with them.
1634 device.destroySwapchainKHR(oldSwapchain, nullptr);
1637 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
1638 VERIFY(result == vk::Result::eSuccess);
1640 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1641 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1642 VERIFY(result == vk::Result::eSuccess);
1644 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1646 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1647 auto color_image_view = vk::ImageViewCreateInfo()
1648 .setViewType(vk::ImageViewType::e2D)
1650 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1652 swapchain_image_resources[i].image = swapchainImages[i];
1654 color_image_view.image = swapchain_image_resources[i].image;
1656 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1657 VERIFY(result == vk::Result::eSuccess);
1661 void Demo::prepare_cube_data_buffers() {
1663 mat4x4_mul(VP, projection_matrix, view_matrix);
1666 mat4x4_mul(MVP, VP, model_matrix);
1668 vktexcube_vs_uniform data;
1669 memcpy(data.mvp, MVP, sizeof(MVP));
1670 // dumpMatrix("MVP", MVP)
1672 for (int32_t i = 0; i < 12 * 3; i++) {
1673 data.position[i][0] = g_vertex_buffer_data[i * 3];
1674 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1675 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1676 data.position[i][3] = 1.0f;
1677 data.attr[i][0] = g_uv_buffer_data[2 * i];
1678 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1679 data.attr[i][2] = 0;
1680 data.attr[i][3] = 0;
1683 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1685 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1686 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
1687 VERIFY(result == vk::Result::eSuccess);
1689 vk::MemoryRequirements mem_reqs;
1690 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1692 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1694 bool const pass = memory_type_from_properties(
1695 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1696 &mem_alloc.memoryTypeIndex);
1699 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
1700 VERIFY(result == vk::Result::eSuccess);
1702 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1703 VERIFY(pData.result == vk::Result::eSuccess);
1705 memcpy(pData.value, &data, sizeof data);
1707 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1710 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
1711 VERIFY(result == vk::Result::eSuccess);
1715 void Demo::prepare_depth() {
1716 depth.format = vk::Format::eD16Unorm;
1718 auto const image = vk::ImageCreateInfo()
1719 .setImageType(vk::ImageType::e2D)
1720 .setFormat(depth.format)
1721 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1724 .setSamples(vk::SampleCountFlagBits::e1)
1725 .setTiling(vk::ImageTiling::eOptimal)
1726 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1727 .setSharingMode(vk::SharingMode::eExclusive)
1728 .setQueueFamilyIndexCount(0)
1729 .setPQueueFamilyIndices(nullptr)
1730 .setInitialLayout(vk::ImageLayout::eUndefined);
1732 auto result = device.createImage(&image, nullptr, &depth.image);
1733 VERIFY(result == vk::Result::eSuccess);
1735 vk::MemoryRequirements mem_reqs;
1736 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1738 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1739 depth.mem_alloc.setMemoryTypeIndex(0);
1741 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1742 &depth.mem_alloc.memoryTypeIndex);
1745 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1746 VERIFY(result == vk::Result::eSuccess);
1748 result = device.bindImageMemory(depth.image, depth.mem, 0);
1749 VERIFY(result == vk::Result::eSuccess);
1751 auto const view = vk::ImageViewCreateInfo()
1752 .setImage(depth.image)
1753 .setViewType(vk::ImageViewType::e2D)
1754 .setFormat(depth.format)
1755 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1756 result = device.createImageView(&view, nullptr, &depth.view);
1757 VERIFY(result == vk::Result::eSuccess);
1760 void Demo::prepare_descriptor_layout() {
1761 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1763 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1764 .setDescriptorCount(1)
1765 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1766 .setPImmutableSamplers(nullptr),
1767 vk::DescriptorSetLayoutBinding()
1769 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1770 .setDescriptorCount(texture_count)
1771 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1772 .setPImmutableSamplers(nullptr)};
1774 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1776 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1777 VERIFY(result == vk::Result::eSuccess);
1779 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1781 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1782 VERIFY(result == vk::Result::eSuccess);
1785 void Demo::prepare_descriptor_pool() {
1786 vk::DescriptorPoolSize const poolSizes[2] = {
1787 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1788 vk::DescriptorPoolSize()
1789 .setType(vk::DescriptorType::eCombinedImageSampler)
1790 .setDescriptorCount(swapchainImageCount * texture_count)};
1792 auto const descriptor_pool =
1793 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1795 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1796 VERIFY(result == vk::Result::eSuccess);
1799 void Demo::prepare_descriptor_set() {
1800 auto const alloc_info =
1801 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1803 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1805 vk::DescriptorImageInfo tex_descs[texture_count];
1806 for (uint32_t i = 0; i < texture_count; i++) {
1807 tex_descs[i].setSampler(textures[i].sampler);
1808 tex_descs[i].setImageView(textures[i].view);
1809 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1812 vk::WriteDescriptorSet writes[2];
1814 writes[0].setDescriptorCount(1);
1815 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1816 writes[0].setPBufferInfo(&buffer_info);
1818 writes[1].setDstBinding(1);
1819 writes[1].setDescriptorCount(texture_count);
1820 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1821 writes[1].setPImageInfo(tex_descs);
1823 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1824 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
1825 VERIFY(result == vk::Result::eSuccess);
1827 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1828 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1829 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1830 device.updateDescriptorSets(2, writes, 0, nullptr);
1834 void Demo::prepare_framebuffers() {
1835 vk::ImageView attachments[2];
1836 attachments[1] = depth.view;
1838 auto const fb_info = vk::FramebufferCreateInfo()
1839 .setRenderPass(render_pass)
1840 .setAttachmentCount(2)
1841 .setPAttachments(attachments)
1842 .setWidth((uint32_t)width)
1843 .setHeight((uint32_t)height)
1846 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1847 attachments[0] = swapchain_image_resources[i].view;
1848 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
1849 VERIFY(result == vk::Result::eSuccess);
1853 vk::ShaderModule Demo::prepare_fs() {
1854 const uint32_t fragShaderCode[] = {
1855 #include "cube.frag.inc"
1858 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
1860 return frag_shader_module;
1863 void Demo::prepare_pipeline() {
1864 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1865 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1866 VERIFY(result == vk::Result::eSuccess);
1868 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1869 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1870 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1872 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1874 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1876 // TODO: Where are pViewports and pScissors set?
1877 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1879 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1880 .setDepthClampEnable(VK_FALSE)
1881 .setRasterizerDiscardEnable(VK_FALSE)
1882 .setPolygonMode(vk::PolygonMode::eFill)
1883 .setCullMode(vk::CullModeFlagBits::eBack)
1884 .setFrontFace(vk::FrontFace::eCounterClockwise)
1885 .setDepthBiasEnable(VK_FALSE)
1886 .setLineWidth(1.0f);
1888 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1890 auto const stencilOp =
1891 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1893 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1894 .setDepthTestEnable(VK_TRUE)
1895 .setDepthWriteEnable(VK_TRUE)
1896 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1897 .setDepthBoundsTestEnable(VK_FALSE)
1898 .setStencilTestEnable(VK_FALSE)
1899 .setFront(stencilOp)
1900 .setBack(stencilOp);
1902 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1903 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1904 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1906 auto const colorBlendInfo =
1907 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1909 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1911 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1913 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1915 .setPStages(shaderStageInfo)
1916 .setPVertexInputState(&vertexInputInfo)
1917 .setPInputAssemblyState(&inputAssemblyInfo)
1918 .setPViewportState(&viewportInfo)
1919 .setPRasterizationState(&rasterizationInfo)
1920 .setPMultisampleState(&multisampleInfo)
1921 .setPDepthStencilState(&depthStencilInfo)
1922 .setPColorBlendState(&colorBlendInfo)
1923 .setPDynamicState(&dynamicStateInfo)
1924 .setLayout(pipeline_layout)
1925 .setRenderPass(render_pass);
1927 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1928 VERIFY(result == vk::Result::eSuccess);
1930 device.destroyShaderModule(frag_shader_module, nullptr);
1931 device.destroyShaderModule(vert_shader_module, nullptr);
1934 void Demo::prepare_render_pass() {
1935 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1936 // because at the start of the renderpass, we don't care about their contents.
1937 // At the start of the subpass, the color attachment's layout will be transitioned
1938 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1939 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1940 // the renderpass, the color attachment's layout will be transitioned to
1941 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1942 // the renderpass, no barriers are necessary.
1943 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1945 .setSamples(vk::SampleCountFlagBits::e1)
1946 .setLoadOp(vk::AttachmentLoadOp::eClear)
1947 .setStoreOp(vk::AttachmentStoreOp::eStore)
1948 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1949 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1950 .setInitialLayout(vk::ImageLayout::eUndefined)
1951 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1952 vk::AttachmentDescription()
1953 .setFormat(depth.format)
1954 .setSamples(vk::SampleCountFlagBits::e1)
1955 .setLoadOp(vk::AttachmentLoadOp::eClear)
1956 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1957 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1958 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1959 .setInitialLayout(vk::ImageLayout::eUndefined)
1960 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1962 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1964 auto const depth_reference =
1965 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1967 auto const subpass = vk::SubpassDescription()
1968 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1969 .setInputAttachmentCount(0)
1970 .setPInputAttachments(nullptr)
1971 .setColorAttachmentCount(1)
1972 .setPColorAttachments(&color_reference)
1973 .setPResolveAttachments(nullptr)
1974 .setPDepthStencilAttachment(&depth_reference)
1975 .setPreserveAttachmentCount(0)
1976 .setPPreserveAttachments(nullptr);
1978 auto const rp_info = vk::RenderPassCreateInfo()
1979 .setAttachmentCount(2)
1980 .setPAttachments(attachments)
1982 .setPSubpasses(&subpass)
1983 .setDependencyCount(0)
1984 .setPDependencies(nullptr);
1986 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
1987 VERIFY(result == vk::Result::eSuccess);
1990 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
1991 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
1993 vk::ShaderModule module;
1994 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
1995 VERIFY(result == vk::Result::eSuccess);
2000 void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2004 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2005 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2008 tex_obj->tex_width = tex_width;
2009 tex_obj->tex_height = tex_height;
2011 auto const buffer_create_info = vk::BufferCreateInfo()
2012 .setSize(tex_width * tex_height * 4)
2013 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2014 .setSharingMode(vk::SharingMode::eExclusive)
2015 .setQueueFamilyIndexCount(0)
2016 .setPQueueFamilyIndices(nullptr);
2018 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2019 VERIFY(result == vk::Result::eSuccess);
2021 vk::MemoryRequirements mem_reqs;
2022 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2024 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2025 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2027 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2028 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2029 VERIFY(pass == true);
2031 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2032 VERIFY(result == vk::Result::eSuccess);
2034 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2035 VERIFY(result == vk::Result::eSuccess);
2037 vk::SubresourceLayout layout;
2038 memset(&layout, 0, sizeof(layout));
2039 layout.rowPitch = tex_width * 4;
2040 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2041 VERIFY(data.result == vk::Result::eSuccess);
2043 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2044 fprintf(stderr, "Error loading texture: %s\n", filename);
2047 device.unmapMemory(tex_obj->mem);
2050 void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2051 vk::MemoryPropertyFlags required_props) {
2054 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2055 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2058 tex_obj->tex_width = tex_width;
2059 tex_obj->tex_height = tex_height;
2061 auto const image_create_info = vk::ImageCreateInfo()
2062 .setImageType(vk::ImageType::e2D)
2063 .setFormat(vk::Format::eR8G8B8A8Unorm)
2064 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2067 .setSamples(vk::SampleCountFlagBits::e1)
2070 .setSharingMode(vk::SharingMode::eExclusive)
2071 .setQueueFamilyIndexCount(0)
2072 .setPQueueFamilyIndices(nullptr)
2073 .setInitialLayout(vk::ImageLayout::ePreinitialized);
2075 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2076 VERIFY(result == vk::Result::eSuccess);
2078 vk::MemoryRequirements mem_reqs;
2079 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
2081 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2082 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2084 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2085 VERIFY(pass == true);
2087 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2088 VERIFY(result == vk::Result::eSuccess);
2090 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2091 VERIFY(result == vk::Result::eSuccess);
2093 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2094 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2095 vk::SubresourceLayout layout;
2096 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
2098 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2099 VERIFY(data.result == vk::Result::eSuccess);
2101 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2102 fprintf(stderr, "Error loading texture: %s\n", filename);
2105 device.unmapMemory(tex_obj->mem);
2108 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2111 void Demo::prepare_textures() {
2112 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2113 vk::FormatProperties props;
2114 gpu.getFormatProperties(tex_format, &props);
2116 for (uint32_t i = 0; i < texture_count; i++) {
2117 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2118 /* Device can texture using linear textures */
2119 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2120 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2121 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2122 // shader to run until layout transition completes
2123 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2124 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2125 vk::PipelineStageFlagBits::eFragmentShader);
2126 staging_texture.image = vk::Image();
2127 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2128 /* Must use staging buffer to copy linear texture to optimized */
2130 prepare_texture_buffer(tex_files[i], &staging_texture);
2132 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2133 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2134 vk::MemoryPropertyFlagBits::eDeviceLocal);
2136 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2137 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2138 vk::PipelineStageFlagBits::eTransfer);
2140 auto const subresource = vk::ImageSubresourceLayers()
2141 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2143 .setBaseArrayLayer(0)
2146 auto const copy_region =
2147 vk::BufferImageCopy()
2149 .setBufferRowLength(staging_texture.tex_width)
2150 .setBufferImageHeight(staging_texture.tex_height)
2151 .setImageSubresource(subresource)
2152 .setImageOffset({0, 0, 0})
2153 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2155 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, ©_region);
2157 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2158 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2159 vk::PipelineStageFlagBits::eFragmentShader);
2161 assert(!"No support for R8G8B8A8_UNORM as texture image format");
2164 auto const samplerInfo = vk::SamplerCreateInfo()
2165 .setMagFilter(vk::Filter::eNearest)
2166 .setMinFilter(vk::Filter::eNearest)
2167 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2168 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2169 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2170 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2171 .setMipLodBias(0.0f)
2172 .setAnisotropyEnable(VK_FALSE)
2173 .setMaxAnisotropy(1)
2174 .setCompareEnable(VK_FALSE)
2175 .setCompareOp(vk::CompareOp::eNever)
2178 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2179 .setUnnormalizedCoordinates(VK_FALSE);
2181 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2182 VERIFY(result == vk::Result::eSuccess);
2184 auto const viewInfo = vk::ImageViewCreateInfo()
2185 .setImage(textures[i].image)
2186 .setViewType(vk::ImageViewType::e2D)
2187 .setFormat(tex_format)
2188 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2190 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2191 VERIFY(result == vk::Result::eSuccess);
2195 vk::ShaderModule Demo::prepare_vs() {
2196 const uint32_t vertShaderCode[] = {
2197 #include "cube.vert.inc"
2200 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2202 return vert_shader_module;
2205 void Demo::resize() {
2208 // Don't react to resize until after first initialization.
2213 // In order to properly resize the window, we must re-create the
2215 // AND redo the command buffers, etc.
2217 // First, perform part of the cleanup() function:
2219 auto result = device.waitIdle();
2220 VERIFY(result == vk::Result::eSuccess);
2222 for (i = 0; i < swapchainImageCount; i++) {
2223 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2226 device.destroyDescriptorPool(desc_pool, nullptr);
2228 device.destroyPipeline(pipeline, nullptr);
2229 device.destroyPipelineCache(pipelineCache, nullptr);
2230 device.destroyRenderPass(render_pass, nullptr);
2231 device.destroyPipelineLayout(pipeline_layout, nullptr);
2232 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2234 for (i = 0; i < texture_count; i++) {
2235 device.destroyImageView(textures[i].view, nullptr);
2236 device.destroyImage(textures[i].image, nullptr);
2237 device.freeMemory(textures[i].mem, nullptr);
2238 device.destroySampler(textures[i].sampler, nullptr);
2241 device.destroyImageView(depth.view, nullptr);
2242 device.destroyImage(depth.image, nullptr);
2243 device.freeMemory(depth.mem, nullptr);
2245 for (i = 0; i < swapchainImageCount; i++) {
2246 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2247 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2248 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2249 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2252 device.destroyCommandPool(cmd_pool, nullptr);
2253 if (separate_present_queue) {
2254 device.destroyCommandPool(present_cmd_pool, nullptr);
2257 // Second, re-perform the prepare() function, which will re-create the
2262 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2263 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2266 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2267 vk::AccessFlags flags;
2270 case vk::ImageLayout::eTransferDstOptimal:
2271 // Make sure anything that was copying from this image has
2273 flags = vk::AccessFlagBits::eTransferWrite;
2275 case vk::ImageLayout::eColorAttachmentOptimal:
2276 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2278 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2279 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2281 case vk::ImageLayout::eShaderReadOnlyOptimal:
2282 // Make sure any Copy or CPU writes to image are flushed
2283 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2285 case vk::ImageLayout::eTransferSrcOptimal:
2286 flags = vk::AccessFlagBits::eTransferRead;
2288 case vk::ImageLayout::ePresentSrcKHR:
2289 flags = vk::AccessFlagBits::eMemoryRead;
2298 auto const barrier = vk::ImageMemoryBarrier()
2299 .setSrcAccessMask(srcAccessMask)
2300 .setDstAccessMask(DstAccessMask(newLayout))
2301 .setOldLayout(oldLayout)
2302 .setNewLayout(newLayout)
2303 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2304 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2306 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2308 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2311 void Demo::update_data_buffer() {
2313 mat4x4_mul(VP, projection_matrix, view_matrix);
2315 // Rotate around the Y axis
2317 mat4x4_dup(Model, model_matrix);
2318 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2321 mat4x4_mul(MVP, VP, model_matrix);
2323 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2324 VERIFY(data.result == vk::Result::eSuccess);
2326 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2328 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2331 /* Convert ppm image data from header file into RGBA texture image */
2332 #include "lunarg.ppm.h"
2333 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
2336 cPtr = (char *)lunarg_ppm;
2337 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2340 while (strncmp(cPtr++, "\n", 1))
2342 sscanf(cPtr, "%u %u", width, height);
2343 if (rgba_data == NULL) {
2346 while (strncmp(cPtr++, "\n", 1))
2348 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2351 while (strncmp(cPtr++, "\n", 1))
2353 for (int y = 0; y < *height; y++) {
2354 uint8_t *rowPtr = rgba_data;
2355 for (int x = 0; x < *width; x++) {
2356 memcpy(rowPtr, cPtr, 3);
2357 rowPtr[3] = 255; /* Alpha of 1 */
2361 rgba_data += layout->rowPitch;
2366 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2367 // Search memtypes to find first index with those properties
2368 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2369 if ((typeBits & 1) == 1) {
2370 // Type is available, does it match user properties?
2371 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2379 // No memory types matched, return failure
2383 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2392 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2393 PostQuitMessage(validation_error);
2397 void Demo::create_window() {
2398 WNDCLASSEX win_class;
2400 // Initialize the window class structure:
2401 win_class.cbSize = sizeof(WNDCLASSEX);
2402 win_class.style = CS_HREDRAW | CS_VREDRAW;
2403 win_class.lpfnWndProc = WndProc;
2404 win_class.cbClsExtra = 0;
2405 win_class.cbWndExtra = 0;
2406 win_class.hInstance = connection; // hInstance
2407 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2408 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2409 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2410 win_class.lpszMenuName = nullptr;
2411 win_class.lpszClassName = name;
2412 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2414 // Register window class:
2415 if (!RegisterClassEx(&win_class)) {
2416 // It didn't work, so try to give a useful error:
2417 printf("Unexpected error trying to start the application!\n");
2422 // Create window with the registered class:
2423 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2424 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2425 window = CreateWindowEx(0,
2428 WS_OVERLAPPEDWINDOW | // window style
2429 WS_VISIBLE | WS_SYSMENU,
2430 100, 100, // x/y coords
2431 wr.right - wr.left, // width
2432 wr.bottom - wr.top, // height
2433 nullptr, // handle to parent
2434 nullptr, // handle to menu
2435 connection, // hInstance
2436 nullptr); // no extra parameters
2439 // It didn't work, so try to give a useful error:
2440 printf("Cannot create a window in which to draw!\n");
2445 // Window client area size must be at least 1 pixel high, to prevent
2447 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2448 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2450 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2452 void Demo::create_xlib_window() {
2453 const char *display_envar = getenv("DISPLAY");
2454 if (display_envar == nullptr || display_envar[0] == '\0') {
2455 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2461 display = XOpenDisplay(nullptr);
2462 long visualMask = VisualScreenMask;
2463 int numberOfVisuals;
2464 XVisualInfo vInfoTemplate = {};
2465 vInfoTemplate.screen = DefaultScreen(display);
2466 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2468 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2470 XSetWindowAttributes windowAttributes = {};
2471 windowAttributes.colormap = colormap;
2472 windowAttributes.background_pixel = 0xFFFFFFFF;
2473 windowAttributes.border_pixel = 0;
2474 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2477 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2478 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2480 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2481 XMapWindow(display, xlib_window);
2483 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2486 void Demo::handle_xlib_event(const XEvent *event) {
2487 switch (event->type) {
2489 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2494 switch (event->xkey.keycode) {
2498 case 0x71: // left arrow key
2499 spin_angle -= spin_increment;
2501 case 0x72: // right arrow key
2502 spin_angle += spin_increment;
2504 case 0x41: // space bar
2509 case ConfigureNotify:
2510 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2511 width = event->xconfigure.width;
2512 height = event->xconfigure.height;
2521 void Demo::run_xlib() {
2526 XNextEvent(display, &event);
2527 handle_xlib_event(&event);
2529 while (XPending(display) > 0) {
2530 XNextEvent(display, &event);
2531 handle_xlib_event(&event);
2537 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2542 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2544 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2545 uint8_t event_code = event->response_type & 0x7f;
2546 switch (event_code) {
2548 // TODO: Resize window
2550 case XCB_CLIENT_MESSAGE:
2551 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2555 case XCB_KEY_RELEASE: {
2556 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2558 switch (key->detail) {
2562 case 0x71: // left arrow key
2563 spin_angle -= spin_increment;
2565 case 0x72: // right arrow key
2566 spin_angle += spin_increment;
2568 case 0x41: // space bar
2573 case XCB_CONFIGURE_NOTIFY: {
2574 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2575 if ((width != cfg->width) || (height != cfg->height)) {
2577 height = cfg->height;
2586 void Demo::run_xcb() {
2587 xcb_flush(connection);
2590 xcb_generic_event_t *event;
2593 event = xcb_wait_for_event(connection);
2595 event = xcb_poll_for_event(connection);
2598 handle_xcb_event(event);
2600 event = xcb_poll_for_event(connection);
2605 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2611 void Demo::create_xcb_window() {
2612 uint32_t value_mask, value_list[32];
2614 xcb_window = xcb_generate_id(connection);
2616 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2617 value_list[0] = screen->black_pixel;
2618 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2620 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2621 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2623 /* Magic code that will send notification when window is destroyed */
2624 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2625 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2627 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2628 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2630 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2634 xcb_map_window(connection, xcb_window);
2636 // Force the x/y coordinates to 100,100 results are identical in
2639 const uint32_t coords[] = {100, 100};
2640 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2642 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2647 wl_display_dispatch(display);
2649 wl_display_dispatch_pending(display);
2650 update_data_buffer();
2653 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2660 void Demo::create_window() {
2661 window = wl_compositor_create_surface(compositor);
2663 printf("Can not create wayland_surface from compositor!\n");
2668 shell_surface = wl_shell_get_shell_surface(shell, window);
2669 if (!shell_surface) {
2670 printf("Can not get shell_surface from wayland_surface!\n");
2675 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2676 wl_shell_surface_set_toplevel(shell_surface);
2677 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2679 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
2683 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2687 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2689 vk::Result Demo::create_display_surface() {
2691 uint32_t display_count;
2692 uint32_t mode_count;
2693 uint32_t plane_count;
2694 vk::DisplayPropertiesKHR display_props;
2695 vk::DisplayKHR display;
2696 vk::DisplayModePropertiesKHR mode_props;
2697 vk::DisplayPlanePropertiesKHR *plane_props;
2698 vk::Bool32 found_plane = VK_FALSE;
2699 uint32_t plane_index;
2700 vk::Extent2D image_extent;
2702 // Get the first display
2703 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2704 VERIFY(result == vk::Result::eSuccess);
2706 if (display_count == 0) {
2707 printf("Cannot find any display!\n");
2713 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2714 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2716 display = display_props.display;
2718 // Get the first mode of the display
2719 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2720 VERIFY(result == vk::Result::eSuccess);
2722 if (mode_count == 0) {
2723 printf("Cannot find any mode for the display!\n");
2729 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2730 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2732 // Get the list of planes
2733 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2734 VERIFY(result == vk::Result::eSuccess);
2736 if (plane_count == 0) {
2737 printf("Cannot find any plane!\n");
2742 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2743 VERIFY(plane_props != nullptr);
2745 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2746 VERIFY(result == vk::Result::eSuccess);
2748 // Find a plane compatible with the display
2749 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2750 uint32_t supported_count;
2751 vk::DisplayKHR *supported_displays;
2753 // Disqualify planes that are bound to a different display
2754 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2758 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
2759 VERIFY(result == vk::Result::eSuccess);
2761 if (supported_count == 0) {
2765 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2766 VERIFY(supported_displays != nullptr);
2768 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
2769 VERIFY(result == vk::Result::eSuccess);
2771 for (uint32_t i = 0; i < supported_count; i++) {
2772 if (supported_displays[i] == display) {
2773 found_plane = VK_TRUE;
2778 free(supported_displays);
2786 printf("Cannot find a plane compatible with the display!\n");
2793 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2794 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2795 // Find a supported alpha mode
2796 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2797 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2798 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2799 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2800 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2801 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2803 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2804 if (planeCaps.supportedAlpha & alphaModes[i]) {
2805 alphaMode = alphaModes[i];
2810 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2811 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2813 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2814 .setDisplayMode(mode_props.displayMode)
2815 .setPlaneIndex(plane_index)
2816 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2817 .setGlobalAlpha(1.0f)
2818 .setAlphaMode(alphaMode)
2819 .setImageExtent(image_extent);
2821 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2824 void Demo::run_display() {
2829 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2837 // Include header required for parsing the command line options.
2838 #include <shellapi.h>
2842 // MS-Windows event handling function:
2843 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2846 PostQuitMessage(validation_error);
2851 case WM_GETMINMAXINFO: // set window's minimum size
2852 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2857 // Resize the application to the new window size, except when
2858 // it was minimized. Vulkan doesn't support images or swapchains
2859 // with width=0 and height=0.
2860 if (wParam != SIZE_MINIMIZED) {
2861 demo.width = lParam & 0xffff;
2862 demo.height = (lParam & 0xffff0000) >> 16;
2869 PostQuitMessage(validation_error);
2872 demo.spin_angle -= demo.spin_increment;
2875 demo.spin_angle += demo.spin_increment;
2878 demo.pause = !demo.pause;
2886 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2889 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
2890 // TODO: Gah.. refactor. This isn't 1989.
2892 bool done; // flag saying when app is complete
2896 // Ensure wParam is initialized.
2899 // Use the CommandLine functions to get the command line arguments.
2900 // Unfortunately, Microsoft outputs
2901 // this information as wide characters for Unicode, and we simply want the
2902 // Ascii version to be compatible
2903 // with the non-Windows side. So, we have to convert the information to
2904 // Ascii character strings.
2905 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
2906 if (nullptr == commandLineArgs) {
2911 argv = (char **)malloc(sizeof(char *) * argc);
2912 if (argv == nullptr) {
2915 for (int iii = 0; iii < argc; iii++) {
2916 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2917 size_t numConverted = 0;
2919 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
2920 if (argv[iii] != nullptr) {
2921 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
2929 demo.init(argc, argv);
2931 // Free up the items we had to allocate for the command line arguments.
2932 if (argc > 0 && argv != nullptr) {
2933 for (int iii = 0; iii < argc; iii++) {
2934 if (argv[iii] != nullptr) {
2941 demo.connection = hInstance;
2942 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
2943 demo.create_window();
2944 demo.init_vk_swapchain();
2948 done = false; // initialize loop condition variable
2950 // main message loop
2953 const BOOL succ = WaitMessage();
2956 const auto &suppress_popups = demo.suppress_popups;
2957 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2961 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
2962 if (msg.message == WM_QUIT) // check for a quit message
2964 done = true; // if found, quit app
2966 /* Translate and dispatch to event queue*/
2967 TranslateMessage(&msg);
2968 DispatchMessage(&msg);
2970 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2975 return (int)msg.wParam;
2980 int main(int argc, char **argv) {
2983 demo.init(argc, argv);
2985 #if defined(VK_USE_PLATFORM_XCB_KHR)
2986 demo.create_xcb_window();
2987 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2988 demo.use_xlib = true;
2989 demo.create_xlib_window();
2990 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2991 demo.create_window();
2994 demo.init_vk_swapchain();
2998 #if defined(VK_USE_PLATFORM_XCB_KHR)
3000 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3002 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3004 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3010 return validation_error;
3013 #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3015 // Global function invoked from NS or UI views and controllers to create demo
3016 static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
3017 demo.init(argc, (char **)argv);
3019 demo.init_vk_swapchain();
3021 demo.spin_angle = 0.4f;
3025 #error "Platform not supported"