diff options
| author | Karl Schultz <karl@lunarg.com> | 2016-02-02 15:37:51 -0700 |
|---|---|---|
| committer | Karl Schultz <karl@lunarg.com> | 2016-02-02 15:37:51 -0700 |
| commit | e4dc75caaa206144837a6d8a08773f2c40ae30cd (patch) | |
| tree | b7a314e946a6e6601dc4d7e479f1207e694cff87 | |
| parent | e4850518e0183680143742ef4e3e0ac798e19c3f (diff) | |
| download | usermoji-e4dc75caaa206144837a6d8a08773f2c40ae30cd.tar.xz | |
demos: Update copyright and apply clang-format
| -rw-r--r-- | demos/cube.c | 1436 | ||||
| -rw-r--r-- | demos/cube.frag | 28 | ||||
| -rw-r--r-- | demos/cube.vert | 28 | ||||
| -rw-r--r-- | demos/linmath.h | 1052 | ||||
| -rw-r--r-- | demos/tri.c | 1193 | ||||
| -rw-r--r-- | demos/tri.frag | 28 | ||||
| -rw-r--r-- | demos/tri.vert | 28 | ||||
| -rw-r--r-- | demos/vulkaninfo.c | 762 |
8 files changed, 2291 insertions, 2264 deletions
diff --git a/demos/cube.c b/demos/cube.c index 47473717..0801bfda 100644 --- a/demos/cube.c +++ b/demos/cube.c @@ -1,31 +1,37 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. * - * Copyright (C) 2015 Valve Corporation - * Copyright (C) 2015 Google Inc. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. * * Author: Chia-I Wu <olv@lunarg.com> * Author: Courtney Goeltzenleuchter <courtney@LunarG.com> * Author: Ian Elliott <ian@LunarG.com> * Author: Jon Ashburn <jon@lunarg.com> */ + #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> @@ -58,43 +64,46 @@ #endif #ifdef _WIN32 -#define ERR_EXIT(err_msg, err_class) \ - do { \ - MessageBox(NULL, err_msg, err_class, MB_OK); \ - exit(1); \ - } while (0) - -#else // _WIN32 - -#define ERR_EXIT(err_msg, err_class) \ - do { \ - printf(err_msg); \ - fflush(stdout); \ - exit(1); \ - } while (0) +#define ERR_EXIT(err_msg, err_class) \ + do { \ + MessageBox(NULL, err_msg, err_class, MB_OK); \ + exit(1); \ + } while (0) + +#else // _WIN32 + +#define ERR_EXIT(err_msg, err_class) \ + do { \ + printf(err_msg); \ + fflush(stdout); \ + exit(1); \ + } while (0) #endif // _WIN32 -#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \ -{ \ - demo->fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \ - if (demo->fp##entrypoint == NULL) { \ - ERR_EXIT("vkGetInstanceProcAddr failed to find vk"#entrypoint, \ - "vkGetInstanceProcAddr Failure"); \ - } \ -} +#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \ + { \ + demo->fp##entrypoint = \ + (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \ + if (demo->fp##entrypoint == NULL) { \ + ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, \ + "vkGetInstanceProcAddr Failure"); \ + } \ + } static PFN_vkGetDeviceProcAddr g_gdpa = NULL; -#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ -{ \ - if(!g_gdpa) \ - g_gdpa = (PFN_vkGetDeviceProcAddr) vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \ - demo->fp##entrypoint = (PFN_vk##entrypoint) g_gdpa(dev, "vk"#entrypoint); \ - if (demo->fp##entrypoint == NULL) { \ - ERR_EXIT("vkGetDeviceProcAddr failed to find vk"#entrypoint, \ - "vkGetDeviceProcAddr Failure"); \ - } \ -} +#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ + { \ + if (!g_gdpa) \ + g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr( \ + demo->inst, "vkGetDeviceProcAddr"); \ + demo->fp##entrypoint = \ + (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \ + if (demo->fp##entrypoint == NULL) { \ + ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, \ + "vkGetDeviceProcAddr Failure"); \ + } \ + } /* * structure to track all objects related to a texture. @@ -111,27 +120,26 @@ struct texture_object { int32_t tex_width, tex_height; }; -static char *tex_files[] = { - "lunarg.ppm" -}; +static char *tex_files[] = {"lunarg.ppm"}; struct vkcube_vs_uniform { // Must start with MVP - float mvp[4][4]; - float position[12*3][4]; - float color[12*3][4]; + float mvp[4][4]; + float position[12 * 3][4]; + float color[12 * 3][4]; }; struct vktexcube_vs_uniform { // Must start with MVP - float mvp[4][4]; - float position[12*3][4]; - float attr[12*3][4]; + float mvp[4][4]; + float position[12 * 3][4]; + float attr[12 * 3][4]; }; //-------------------------------------------------------------------------------------- // Mesh and VertexFormat Data //-------------------------------------------------------------------------------------- +// clang-format off struct Vertex { float posX, posY, posZ, posW; // Position data @@ -234,49 +242,46 @@ static const float g_uv_buffer_data[] = { 1.0f, 0.0f, 1.0f, 1.0f, }; +// clang-format on -void dumpMatrix(const char *note, mat4x4 MVP) -{ +void dumpMatrix(const char *note, mat4x4 MVP) { int i; printf("%s: \n", note); - for (i=0; i<4; i++) { + for (i = 0; i < 4; i++) { printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]); } printf("\n"); fflush(stdout); } -void dumpVec4(const char *note, vec4 vector) -{ +void dumpVec4(const char *note, vec4 vector) { printf("%s: \n", note); - printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]); + printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]); printf("\n"); fflush(stdout); } -VKAPI_ATTR VkBool32 VKAPI_CALL dbgFunc( - VkFlags msgFlags, - VkDebugReportObjectTypeEXT objType, - uint64_t srcObject, - size_t location, - int32_t msgCode, - const char* pLayerPrefix, - const char* pMsg, - void* pUserData) -{ - char *message = (char *) malloc(strlen(pMsg)+100); +VKAPI_ATTR VkBool32 VKAPI_CALL +dbgFunc(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, + uint64_t srcObject, size_t location, int32_t msgCode, + const char *pLayerPrefix, const char *pMsg, void *pUserData) { + char *message = (char *)malloc(strlen(pMsg) + 100); - assert (message); + assert(message); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { - sprintf(message,"ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else if (msgFlags & VK_DEBUG_REPORT_WARN_BIT_EXT) { - // We know that we're submitting queues without fences, ignore this warning - if (strstr(pMsg, "vkQueueSubmit parameter, VkFence fence, is null pointer")){ + // We know that we're submitting queues without fences, ignore this + // warning + if (strstr(pMsg, + "vkQueueSubmit parameter, VkFence fence, is null pointer")) { return false; } - sprintf(message,"WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else { return false; } @@ -284,7 +289,7 @@ VKAPI_ATTR VkBool32 VKAPI_CALL dbgFunc( #ifdef _WIN32 MessageBox(NULL, message, "Alert", MB_OK); #else - printf("%s\n",message); + printf("%s\n", message); fflush(stdout); #endif free(message); @@ -299,16 +304,10 @@ VKAPI_ATTR VkBool32 VKAPI_CALL dbgFunc( return false; } -VkBool32 BreakCallback( - VkFlags msgFlags, - VkDebugReportObjectTypeEXT objType, - uint64_t srcObject, - size_t location, - int32_t msgCode, - const char* pLayerPrefix, - const char* pMsg, - void* pUserData) -{ +VkBool32 BreakCallback(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, + uint64_t srcObject, size_t location, int32_t msgCode, + const char *pLayerPrefix, const char *pMsg, + void *pUserData) { #ifndef WIN32 raise(SIGTRAP); #else @@ -329,13 +328,13 @@ struct demo { #define APP_NAME_STR_LEN 80 HINSTANCE connection; // hInstance - Windows Instance char name[APP_NAME_STR_LEN]; // Name to put on the window/icon - HWND window; // hWnd - window handle -#else // _WIN32 + HWND window; // hWnd - window handle +#else // _WIN32 xcb_connection_t *connection; xcb_screen_t *screen; xcb_window_t window; xcb_intern_atom_reply_t *atom_wm_delete_window; -#endif // _WIN32 +#endif // _WIN32 VkSurfaceKHR surface; bool prepared; bool use_staging_buffer; @@ -358,10 +357,14 @@ struct demo { VkFormat format; VkColorSpaceKHR color_space; - PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR; - PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR; - PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR; - PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR; + PFN_vkGetPhysicalDeviceSurfaceSupportKHR + fpGetPhysicalDeviceSurfaceSupportKHR; + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR + fpGetPhysicalDeviceSurfaceCapabilitiesKHR; + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR + fpGetPhysicalDeviceSurfaceFormatsKHR; + PFN_vkGetPhysicalDeviceSurfacePresentModesKHR + fpGetPhysicalDeviceSurfacePresentModesKHR; PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR; PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR; PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR; @@ -391,7 +394,7 @@ struct demo { VkDescriptorBufferInfo buffer_info; } uniform_data; - VkCommandBuffer cmd; // Buffer for initialization commands + VkCommandBuffer cmd; // Buffer for initialization commands VkPipelineLayout pipeline_layout; VkDescriptorSetLayout desc_layout; VkPipelineCache pipelineCache; @@ -431,25 +434,26 @@ struct demo { // Forward declaration: static void demo_resize(struct demo *demo); -static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) -{ - // Search memtypes to find first index with those properties - for (uint32_t i = 0; i < 32; i++) { - if ((typeBits & 1) == 1) { - // Type is available, does it match user properties? - if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { - *typeIndex = i; - return true; - } - } - typeBits >>= 1; - } - // No memory types matched, return failure - return false; +static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, + VkFlags requirements_mask, + uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < 32; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((demo->memory_properties.memoryTypes[i].propertyFlags & + requirements_mask) == requirements_mask) { + *typeIndex = i; + return true; + } + } + typeBits >>= 1; + } + // No memory types matched, return failure + return false; } -static void demo_flush_init_cmd(struct demo *demo) -{ +static void demo_flush_init_cmd(struct demo *demo) { VkResult U_ASSERT_ONLY err; if (demo->cmd == VK_NULL_HANDLE) @@ -458,19 +462,17 @@ static void demo_flush_init_cmd(struct demo *demo) err = vkEndCommandBuffer(demo->cmd); assert(!err); - const VkCommandBuffer cmd_bufs[] = { demo->cmd }; + const VkCommandBuffer cmd_bufs[] = {demo->cmd}; VkFence nullFence = VK_NULL_HANDLE; - VkSubmitInfo submit_info = { - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .pNext = NULL, - .waitSemaphoreCount = 0, - .pWaitSemaphores = NULL, - .pWaitDstStageMask = NULL, - .commandBufferCount = 1, - .pCommandBuffers = cmd_bufs, - .signalSemaphoreCount = 0, - .pSignalSemaphores = NULL - }; + VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = NULL, + .waitSemaphoreCount = 0, + .pWaitSemaphores = NULL, + .pWaitDstStageMask = NULL, + .commandBufferCount = 1, + .pCommandBuffers = cmd_bufs, + .signalSemaphoreCount = 0, + .pSignalSemaphores = NULL}; err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence); assert(!err); @@ -482,13 +484,10 @@ static void demo_flush_init_cmd(struct demo *demo) demo->cmd = VK_NULL_HANDLE; } -static void demo_set_image_layout( - struct demo *demo, - VkImage image, - VkImageAspectFlags aspectMask, - VkImageLayout old_image_layout, - VkImageLayout new_image_layout) -{ +static void demo_set_image_layout(struct demo *demo, VkImage image, + VkImageAspectFlags aspectMask, + VkImageLayout old_image_layout, + VkImageLayout new_image_layout) { VkResult U_ASSERT_ONLY err; if (demo->cmd == VK_NULL_HANDLE) { @@ -531,8 +530,7 @@ static void demo_set_image_layout( .oldLayout = old_image_layout, .newLayout = new_image_layout, .image = image, - .subresourceRange = { aspectMask, 0, 1, 0, 1 } - }; + .subresourceRange = {aspectMask, 0, 1, 0, 1}}; if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { /* Make sure anything that was copying from this image has completed */ @@ -540,16 +538,19 @@ static void demo_set_image_layout( } if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { - image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + image_memory_barrier.dstAccessMask = + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { - image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + image_memory_barrier.dstAccessMask = + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; } if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { /* Make sure any Copy or CPU writes to image are flushed */ - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; + image_memory_barrier.dstAccessMask = + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; } VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier; @@ -557,11 +558,11 @@ static void demo_set_image_layout( VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier); + vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, + NULL, 1, pmemory_barrier); } -static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) -{ +static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) { VkCommandBufferInheritanceInfo cmd_buf_hinfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, .pNext = NULL, @@ -579,8 +580,8 @@ static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) .pInheritanceInfo = &cmd_buf_hinfo, }; const VkClearValue clear_values[2] = { - [0] = { .color.float32 = { 0.2f, 0.2f, 0.2f, 0.2f } }, - [1] = { .depthStencil = { 1.0f, 0 } }, + [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}}, + [1] = {.depthStencil = {1.0f, 0}}, }; const VkRenderPassBeginInfo rp_begin = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, @@ -601,17 +602,17 @@ static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, - demo->pipeline); - vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, - 0, 1, &demo->desc_set, 0, NULL); + vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline); + vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, + demo->pipeline_layout, 0, 1, &demo->desc_set, 0, + NULL); VkViewport viewport; memset(&viewport, 0, sizeof(viewport)); - viewport.height = (float) demo->height; - viewport.width = (float) demo->width; - viewport.minDepth = (float) 0.0f; - viewport.maxDepth = (float) 1.0f; + viewport.height = (float)demo->height; + viewport.width = (float)demo->width; + viewport.minDepth = (float)0.0f; + viewport.maxDepth = (float)1.0f; vkCmdSetViewport(cmd_buf, 0, 1, &viewport); VkRect2D scissor; @@ -634,22 +635,19 @@ static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } - }; + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; prePresentBarrier.image = demo->buffers[demo->current_buffer].image; VkImageMemoryBarrier *pmemory_barrier = &prePresentBarrier; - vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, pmemory_barrier); - + vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, + NULL, 1, pmemory_barrier); err = vkEndCommandBuffer(cmd_buf); assert(!err); } - -void demo_update_data_buffer(struct demo *demo) -{ +void demo_update_data_buffer(struct demo *demo) { mat4x4 MVP, Model, VP; int matrixSize = sizeof(MVP); uint8_t *pData; @@ -659,19 +657,21 @@ void demo_update_data_buffer(struct demo *demo) // Rotate 22.5 degrees around the Y axis mat4x4_dup(Model, demo->model_matrix); - mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(demo->spin_angle)); + mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, + (float)degreesToRadians(demo->spin_angle)); mat4x4_mul(MVP, VP, demo->model_matrix); - err = vkMapMemory(demo->device, demo->uniform_data.mem, 0, demo->uniform_data.mem_alloc.allocationSize, 0, (void **) &pData); + err = vkMapMemory(demo->device, demo->uniform_data.mem, 0, + demo->uniform_data.mem_alloc.allocationSize, 0, + (void **)&pData); assert(!err); - memcpy(pData, (const void*) &MVP[0][0], matrixSize); + memcpy(pData, (const void *)&MVP[0][0], matrixSize); vkUnmapMemory(demo->device, demo->uniform_data.mem); } -static void demo_draw(struct demo *demo) -{ +static void demo_draw(struct demo *demo) { VkResult U_ASSERT_ONLY err; VkSemaphore presentCompleteSemaphore; VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo = { @@ -681,17 +681,14 @@ static void demo_draw(struct demo *demo) }; VkFence nullFence = VK_NULL_HANDLE; - err = vkCreateSemaphore(demo->device, - &presentCompleteSemaphoreCreateInfo, - NULL, - &presentCompleteSemaphore); + err = vkCreateSemaphore(demo->device, &presentCompleteSemaphoreCreateInfo, + NULL, &presentCompleteSemaphore); assert(!err); // Get the index of the next available swapchain image: - err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, - UINT64_MAX, + err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX, presentCompleteSemaphore, - (VkFence)0,// TODO: Show use of fence + (VkFence)0, // TODO: Show use of fence &demo->current_buffer); if (err == VK_ERROR_OUT_OF_DATE_KHR) { // demo->swapchain is out of date (e.g. the window was resized) and @@ -710,9 +707,9 @@ static void demo_draw(struct demo *demo) // Assume the command buffer has been run on current_buffer before so // we need to set the image layout back to COLOR_ATTACHMENT_OPTIMAL demo_set_image_layout(demo, demo->buffers[demo->current_buffer].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); demo_flush_init_cmd(demo); // Wait for the present complete semaphore to be signaled to ensure @@ -720,19 +717,19 @@ static void demo_draw(struct demo *demo) // engine has fully released ownership to the application, and it is // okay to render to the image. -// FIXME/TODO: DEAL WITH VK_IMAGE_LAYOUT_PRESENT_SRC_KHR - VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - VkSubmitInfo submit_info = { - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .pNext = NULL, - .waitSemaphoreCount = 1, - .pWaitSemaphores = &presentCompleteSemaphore, - .pWaitDstStageMask = &pipe_stage_flags, - .commandBufferCount = 1, - .pCommandBuffers = &demo->buffers[demo->current_buffer].cmd, - .signalSemaphoreCount = 0, - .pSignalSemaphores = NULL - }; + // FIXME/TODO: DEAL WITH VK_IMAGE_LAYOUT_PRESENT_SRC_KHR + VkPipelineStageFlags pipe_stage_flags = + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = NULL, + .waitSemaphoreCount = 1, + .pWaitSemaphores = &presentCompleteSemaphore, + .pWaitDstStageMask = &pipe_stage_flags, + .commandBufferCount = 1, + .pCommandBuffers = + &demo->buffers[demo->current_buffer].cmd, + .signalSemaphoreCount = 0, + .pSignalSemaphores = NULL}; err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence); assert(!err); @@ -745,7 +742,7 @@ static void demo_draw(struct demo *demo) .pImageIndices = &demo->current_buffer, }; -// TBD/TODO: SHOULD THE "present" PARAMETER BE "const" IN THE HEADER? + // TBD/TODO: SHOULD THE "present" PARAMETER BE "const" IN THE HEADER? err = demo->fpQueuePresentKHR(demo->queue, &present); if (err == VK_ERROR_OUT_OF_DATE_KHR) { // demo->swapchain is out of date (e.g. the window was resized) and @@ -764,42 +761,35 @@ static void demo_draw(struct demo *demo) vkDestroySemaphore(demo->device, presentCompleteSemaphore, NULL); } -static void demo_prepare_buffers(struct demo *demo) -{ +static void demo_prepare_buffers(struct demo *demo) { VkResult U_ASSERT_ONLY err; VkSwapchainKHR oldSwapchain = demo->swapchain; // Check the surface capabilities and formats VkSurfaceCapabilitiesKHR surfCapabilities; - err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, - demo->surface, - &surfCapabilities); + err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR( + demo->gpu, demo->surface, &surfCapabilities); assert(!err); uint32_t presentModeCount; - err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, - demo->surface, - &presentModeCount, NULL); + err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( + demo->gpu, demo->surface, &presentModeCount, NULL); assert(!err); VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); assert(presentModes); - err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, - demo->surface, - &presentModeCount, presentModes); + err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( + demo->gpu, demo->surface, &presentModeCount, presentModes); assert(!err); VkExtent2D swapchainExtent; // width and height are either both -1, or both not -1. - if (surfCapabilities.currentExtent.width == (uint32_t) -1) - { + if (surfCapabilities.currentExtent.width == (uint32_t)-1) { // If the surface size is undefined, the size is set to // the size of the images requested. swapchainExtent.width = demo->width; swapchainExtent.height = demo->height; - } - else - { + } else { // If the surface size is defined, the swap chain size must match swapchainExtent = surfCapabilities.currentExtent; demo->width = surfCapabilities.currentExtent.width; @@ -825,16 +815,17 @@ static void demo_prepare_buffers(struct demo *demo) // Determine the number of VkImage's to use in the swap chain (we desire to // own only 1 image at a time, besides the images being displayed and // queued for display): - uint32_t desiredNumberOfSwapchainImages = surfCapabilities.minImageCount + 1; + uint32_t desiredNumberOfSwapchainImages = + surfCapabilities.minImageCount + 1; if ((surfCapabilities.maxImageCount > 0) && - (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount)) - { + (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount)) { // Application must settle for fewer images than desired: desiredNumberOfSwapchainImages = surfCapabilities.maxImageCount; } VkSurfaceTransformFlagsKHR preTransform; - if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { + if (surfCapabilities.supportedTransforms & + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; } else { preTransform = surfCapabilities.currentTransform; @@ -847,10 +838,10 @@ static void demo_prepare_buffers(struct demo *demo) .minImageCount = desiredNumberOfSwapchainImages, .imageFormat = demo->format, .imageColorSpace = demo->color_space, - .imageExtent = { - .width = swapchainExtent.width, - .height = swapchainExtent.height, - }, + .imageExtent = + { + .width = swapchainExtent.width, .height = swapchainExtent.height, + }, .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .preTransform = preTransform, .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, @@ -864,7 +855,8 @@ static void demo_prepare_buffers(struct demo *demo) }; uint32_t i; - err = demo->fpCreateSwapchainKHR(demo->device, &swapchain, NULL, &demo->swapchain); + err = demo->fpCreateSwapchainKHR(demo->device, &swapchain, NULL, + &demo->swapchain); assert(!err); // If we just re-created an existing swapchain, we should destroy the old @@ -879,15 +871,16 @@ static void demo_prepare_buffers(struct demo *demo) &demo->swapchainImageCount, NULL); assert(!err); - VkImage* swapchainImages = - (VkImage*)malloc(demo->swapchainImageCount * sizeof(VkImage)); + VkImage *swapchainImages = + (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage)); assert(swapchainImages); err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages); assert(!err); - demo->buffers = (SwapchainBuffers*)malloc(sizeof(SwapchainBuffers)*demo->swapchainImageCount); + demo->buffers = (SwapchainBuffers *)malloc(sizeof(SwapchainBuffers) * + demo->swapchainImageCount); assert(demo->buffers); for (i = 0; i < demo->swapchainImageCount; i++) { @@ -895,53 +888,52 @@ static void demo_prepare_buffers(struct demo *demo) .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .pNext = NULL, .format = demo->format, - .components = { - .r = VK_COMPONENT_SWIZZLE_R, - .g = VK_COMPONENT_SWIZZLE_G, - .b = VK_COMPONENT_SWIZZLE_B, - .a = VK_COMPONENT_SWIZZLE_A, - }, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1 - }, + .components = + { + .r = VK_COMPONENT_SWIZZLE_R, + .g = VK_COMPONENT_SWIZZLE_G, + .b = VK_COMPONENT_SWIZZLE_B, + .a = VK_COMPONENT_SWIZZLE_A, + }, + .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, .viewType = VK_IMAGE_VIEW_TYPE_2D, .flags = 0, }; demo->buffers[i].image = swapchainImages[i]; - // Render loop will expect image to have been used before and in VK_IMAGE_LAYOUT_PRESENT_SRC_KHR - // layout and will change to COLOR_ATTACHMENT_OPTIMAL, so init the image to that state - demo_set_image_layout(demo, demo->buffers[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); + // Render loop will expect image to have been used before and in + // VK_IMAGE_LAYOUT_PRESENT_SRC_KHR + // layout and will change to COLOR_ATTACHMENT_OPTIMAL, so init the image + // to that state + demo_set_image_layout( + demo, demo->buffers[i].image, VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); color_image_view.image = demo->buffers[i].image; - err = vkCreateImageView(demo->device, - &color_image_view, NULL, &demo->buffers[i].view); + err = vkCreateImageView(demo->device, &color_image_view, NULL, + &demo->buffers[i].view); assert(!err); } - + if (NULL != presentModes) { free(presentModes); } } -static void demo_prepare_depth(struct demo *demo) -{ +static void demo_prepare_depth(struct demo *demo) { const VkFormat depth_format = VK_FORMAT_D16_UNORM; const VkImageCreateInfo image = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = NULL, .imageType = VK_IMAGE_TYPE_2D, .format = depth_format, - .extent = { demo->width, demo->height, 1 }, + .extent = {demo->width, demo->height, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -955,13 +947,11 @@ static void demo_prepare_depth(struct demo *demo) .pNext = NULL, .image = VK_NULL_HANDLE, .format = depth_format, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1 - }, + .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, .flags = 0, .viewType = VK_IMAGE_VIEW_TYPE_2D, }; @@ -973,12 +963,10 @@ static void demo_prepare_depth(struct demo *demo) demo->depth.format = depth_format; /* create image */ - err = vkCreateImage(demo->device, &image, NULL, - &demo->depth.image); + err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image); assert(!err); - vkGetImageMemoryRequirements(demo->device, - demo->depth.image, &mem_reqs); + vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs); assert(!err); demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; @@ -986,26 +974,24 @@ static void demo_prepare_depth(struct demo *demo) demo->depth.mem_alloc.allocationSize = mem_reqs.size; demo->depth.mem_alloc.memoryTypeIndex = 0; - pass = memory_type_from_properties(demo, - mem_reqs.memoryTypeBits, - 0, /* No requirements */ - &demo->depth.mem_alloc.memoryTypeIndex); + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, + 0, /* No requirements */ + &demo->depth.mem_alloc.memoryTypeIndex); assert(pass); /* allocate memory */ - err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, - NULL, &demo->depth.mem); + err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, + &demo->depth.mem); assert(!err); /* bind memory */ - err = vkBindImageMemory(demo->device, demo->depth.image, - demo->depth.mem, 0); + err = + vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0); assert(!err); - demo_set_image_layout(demo, demo->depth.image, - VK_IMAGE_ASPECT_DEPTH_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + demo_set_image_layout(demo, demo->depth.image, VK_IMAGE_ASPECT_DEPTH_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); /* create image view */ view.image = demo->depth.image; @@ -1015,10 +1001,8 @@ static void demo_prepare_depth(struct demo *demo) /* Load a ppm file into memory */ bool loadTexture(const char *filename, uint8_t *rgba_data, - VkSubresourceLayout *layout, - int32_t *width, int32_t *height) -{ - FILE *fPtr = fopen(filename,"rb"); + VkSubresourceLayout *layout, int32_t *width, int32_t *height) { + FILE *fPtr = fopen(filename, "rb"); char header[256], *cPtr, *tmp; if (!fPtr) @@ -1036,7 +1020,7 @@ bool loadTexture(const char *filename, uint8_t *rgba_data, fclose(fPtr); return false; } - } while ( !strncmp(header, "#", 1) ); + } while (!strncmp(header, "#", 1)); sscanf(header, "%u %u", height, width); if (rgba_data == NULL) { @@ -1044,19 +1028,17 @@ bool loadTexture(const char *filename, uint8_t *rgba_data, return true; } tmp = fgets(header, 256, fPtr); // Format - (void) tmp; + (void)tmp; if (cPtr == NULL || strncmp(header, "255\n", 3)) { fclose(fPtr); return false; } - for(int y = 0; y < *height; y++) - { + for (int y = 0; y < *height; y++) { uint8_t *rowPtr = rgba_data; - for(int x = 0; x < *width; x++) - { + for (int x = 0; x < *width; x++) { size_t s = fread(rowPtr, 3, 1, fPtr); - (void) s; + (void)s; rowPtr[3] = 255; /* Alpha of 1 */ rowPtr += 4; } @@ -1066,21 +1048,18 @@ bool loadTexture(const char *filename, uint8_t *rgba_data, return true; } -static void demo_prepare_texture_image(struct demo *demo, - const char *filename, +static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj, VkImageTiling tiling, VkImageUsageFlags usage, - VkFlags required_props) -{ + VkFlags required_props) { const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM; int32_t tex_width; int32_t tex_height; VkResult U_ASSERT_ONLY err; bool U_ASSERT_ONLY pass; - if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) - { + if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) { printf("Failed to load textures\n"); fflush(stdout); exit(1); @@ -1094,7 +1073,7 @@ static void demo_prepare_texture_image(struct demo *demo, .pNext = NULL, .imageType = VK_IMAGE_TYPE_2D, .format = tex_format, - .extent = { tex_width, tex_height, 1 }, + .extent = {tex_width, tex_height, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -1105,8 +1084,8 @@ static void demo_prepare_texture_image(struct demo *demo, VkMemoryRequirements mem_reqs; - err = vkCreateImage(demo->device, &image_create_info, NULL, - &tex_obj->image); + err = + vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image); assert(!err); vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs); @@ -1116,17 +1095,18 @@ static void demo_prepare_texture_image(struct demo *demo, tex_obj->mem_alloc.allocationSize = mem_reqs.size; tex_obj->mem_alloc.memoryTypeIndex = 0; - pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex); + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, + required_props, + &tex_obj->mem_alloc.memoryTypeIndex); assert(pass); /* allocate memory */ err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, - &(tex_obj->mem)); + &(tex_obj->mem)); assert(!err); /* bind memory */ - err = vkBindImageMemory(demo->device, tex_obj->image, - tex_obj->mem, 0); + err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0); assert(!err); if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { @@ -1138,9 +1118,11 @@ static void demo_prepare_texture_image(struct demo *demo, VkSubresourceLayout layout; void *data; - vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout); + vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, + &layout); - err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data); + err = vkMapMemory(demo->device, tex_obj->mem, 0, + tex_obj->mem_alloc.allocationSize, 0, &data); assert(!err); if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) { @@ -1151,22 +1133,20 @@ static void demo_prepare_texture_image(struct demo *demo, } tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - demo_set_image_layout(demo, tex_obj->image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - tex_obj->imageLayout); - /* setting the image layout does not reference the actual memory so no need to add a mem ref */ + demo_set_image_layout(demo, tex_obj->image, VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, tex_obj->imageLayout); + /* setting the image layout does not reference the actual memory so no need + * to add a mem ref */ } -static void demo_destroy_texture_image(struct demo *demo, struct texture_object *tex_objs) -{ +static void demo_destroy_texture_image(struct demo *demo, + struct texture_object *tex_objs) { /* clean up staging resources */ vkFreeMemory(demo->device, tex_objs->mem, NULL); vkDestroyImage(demo->device, tex_objs->image, NULL); } -static void demo_prepare_textures(struct demo *demo) -{ +static void demo_prepare_textures(struct demo *demo) { const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM; VkFormatProperties props; uint32_t i; @@ -1176,49 +1156,57 @@ static void demo_prepare_textures(struct demo *demo) for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { VkResult U_ASSERT_ONLY err; - if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) { + if ((props.linearTilingFeatures & + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && + !demo->use_staging_buffer) { /* Device can texture using linear textures */ demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], - VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); - } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { + VK_IMAGE_TILING_LINEAR, + VK_IMAGE_USAGE_SAMPLED_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); + } else if (props.optimalTilingFeatures & + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { /* Must use staging buffer to copy linear texture to optimized */ struct texture_object staging_texture; memset(&staging_texture, 0, sizeof(staging_texture)); demo_prepare_texture_image(demo, tex_files[i], &staging_texture, - VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); + VK_IMAGE_TILING_LINEAR, + VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); - demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], - VK_IMAGE_TILING_OPTIMAL, - (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + demo_prepare_texture_image( + demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL, + (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); demo_set_image_layout(demo, staging_texture.image, - VK_IMAGE_ASPECT_COLOR_BIT, - staging_texture.imageLayout, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + VK_IMAGE_ASPECT_COLOR_BIT, + staging_texture.imageLayout, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); demo_set_image_layout(demo, demo->textures[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - demo->textures[i].imageLayout, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + VK_IMAGE_ASPECT_COLOR_BIT, + demo->textures[i].imageLayout, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkImageCopy copy_region = { - .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, - .srcOffset = { 0, 0, 0 }, - .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, - .dstOffset = { 0, 0, 0 }, - .extent = { staging_texture.tex_width, staging_texture.tex_height, 1 }, + .srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffset = {0, 0, 0}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstOffset = {0, 0, 0}, + .extent = {staging_texture.tex_width, + staging_texture.tex_height, 1}, }; - vkCmdCopyImage(demo->cmd, - staging_texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - demo->textures[i].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, ©_region); + vkCmdCopyImage( + demo->cmd, staging_texture.image, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); demo_set_image_layout(demo, demo->textures[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - demo->textures[i].imageLayout); + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + demo->textures[i].imageLayout); demo_flush_init_cmd(demo); @@ -1253,29 +1241,29 @@ static void demo_prepare_textures(struct demo *demo) .image = VK_NULL_HANDLE, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = tex_format, - .components = { VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A, }, - .subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }, + .components = + { + VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, + VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, + }, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, .flags = 0, }; /* create sampler */ err = vkCreateSampler(demo->device, &sampler, NULL, - &demo->textures[i].sampler); + &demo->textures[i].sampler); assert(!err); /* create image view */ view.image = demo->textures[i].image; err = vkCreateImageView(demo->device, &view, NULL, - &demo->textures[i].view); + &demo->textures[i].view); assert(!err); } } -void demo_prepare_cube_data_buffer(struct demo *demo) -{ +void demo_prepare_cube_data_buffer(struct demo *demo) { VkBufferCreateInfo buf_info; VkMemoryRequirements mem_reqs; uint8_t *pData; @@ -1288,15 +1276,15 @@ void demo_prepare_cube_data_buffer(struct demo *demo) mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix); mat4x4_mul(MVP, VP, demo->model_matrix); memcpy(data.mvp, MVP, sizeof(MVP)); -// dumpMatrix("MVP", MVP); + // dumpMatrix("MVP", MVP); - for (i=0; i<12*3; i++) { - data.position[i][0] = g_vertex_buffer_data[i*3]; - data.position[i][1] = g_vertex_buffer_data[i*3+1]; - data.position[i][2] = g_vertex_buffer_data[i*3+2]; + for (i = 0; i < 12 * 3; i++) { + data.position[i][0] = g_vertex_buffer_data[i * 3]; + data.position[i][1] = g_vertex_buffer_data[i * 3 + 1]; + data.position[i][2] = g_vertex_buffer_data[i * 3 + 2]; data.position[i][3] = 1.0f; - data.attr[i][0] = g_uv_buffer_data[2*i]; - data.attr[i][1] = g_uv_buffer_data[2*i + 1]; + data.attr[i][0] = g_uv_buffer_data[2 * i]; + data.attr[i][1] = g_uv_buffer_data[2 * i + 1]; data.attr[i][2] = 0; data.attr[i][3] = 0; } @@ -1305,37 +1293,38 @@ void demo_prepare_cube_data_buffer(struct demo *demo) buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; buf_info.size = sizeof(data); - err = vkCreateBuffer(demo->device, &buf_info, NULL, - &demo->uniform_data.buf); + err = + vkCreateBuffer(demo->device, &buf_info, NULL, &demo->uniform_data.buf); assert(!err); - vkGetBufferMemoryRequirements(demo->device, demo->uniform_data.buf, &mem_reqs); + vkGetBufferMemoryRequirements(demo->device, demo->uniform_data.buf, + &mem_reqs); demo->uniform_data.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; demo->uniform_data.mem_alloc.pNext = NULL; demo->uniform_data.mem_alloc.allocationSize = mem_reqs.size; demo->uniform_data.mem_alloc.memoryTypeIndex = 0; - pass = memory_type_from_properties(demo, - mem_reqs.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, - &demo->uniform_data.mem_alloc.memoryTypeIndex); + pass = memory_type_from_properties( + demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, + &demo->uniform_data.mem_alloc.memoryTypeIndex); assert(pass); - err = vkAllocateMemory(demo->device, &demo->uniform_data.mem_alloc, - NULL, &(demo->uniform_data.mem)); + err = vkAllocateMemory(demo->device, &demo->uniform_data.mem_alloc, NULL, + &(demo->uniform_data.mem)); assert(!err); - err = vkMapMemory(demo->device, demo->uniform_data.mem, 0, demo->uniform_data.mem_alloc.allocationSize, 0, (void **) &pData); + err = vkMapMemory(demo->device, demo->uniform_data.mem, 0, + demo->uniform_data.mem_alloc.allocationSize, 0, + (void **)&pData); assert(!err); memcpy(pData, &data, sizeof data); vkUnmapMemory(demo->device, demo->uniform_data.mem); - err = vkBindBufferMemory(demo->device, - demo->uniform_data.buf, - demo->uniform_data.mem, 0); + err = vkBindBufferMemory(demo->device, demo->uniform_data.buf, + demo->uniform_data.mem, 0); assert(!err); demo->uniform_data.buffer_info.buffer = demo->uniform_data.buf; @@ -1343,23 +1332,24 @@ void demo_prepare_cube_data_buffer(struct demo *demo) demo->uniform_data.buffer_info.range = sizeof(data); } -static void demo_prepare_descriptor_layout(struct demo *demo) -{ +static void demo_prepare_descriptor_layout(struct demo *demo) { const VkDescriptorSetLayoutBinding layout_bindings[2] = { - [0] = { - .binding = 0, - .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .descriptorCount = 1, - .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, - .pImmutableSamplers = NULL, - }, - [1] = { - .binding = 1, - .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = DEMO_TEXTURE_COUNT, - .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, - .pImmutableSamplers = NULL, - }, + [0] = + { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, + .pImmutableSamplers = NULL, + }, + [1] = + { + .binding = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = DEMO_TEXTURE_COUNT, + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + .pImmutableSamplers = NULL, + }, }; const VkDescriptorSetLayoutCreateInfo descriptor_layout = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, @@ -1369,51 +1359,51 @@ static void demo_prepare_descriptor_layout(struct demo *demo) }; VkResult U_ASSERT_ONLY err; - err = vkCreateDescriptorSetLayout(demo->device, - &descriptor_layout, NULL, &demo->desc_layout); + err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, + &demo->desc_layout); assert(!err); const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = { - .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, - .pNext = NULL, + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .pNext = NULL, .setLayoutCount = 1, - .pSetLayouts = &demo->desc_layout, + .pSetLayouts = &demo->desc_layout, }; - err = vkCreatePipelineLayout(demo->device, - &pPipelineLayoutCreateInfo, - NULL, + err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout); assert(!err); } -static void demo_prepare_render_pass(struct demo *demo) -{ +static void demo_prepare_render_pass(struct demo *demo) { const VkAttachmentDescription attachments[2] = { - [0] = { - .format = demo->format, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - }, - [1] = { - .format = demo->depth.format, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - }, + [0] = + { + .format = demo->format, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + }, + [1] = + { + .format = demo->depth.format, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + .finalLayout = + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + }, }; const VkAttachmentReference color_reference = { - .attachment = 0, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }; const VkAttachmentReference depth_reference = { .attachment = 1, @@ -1447,10 +1437,8 @@ static void demo_prepare_render_pass(struct demo *demo) assert(!err); } -static VkShaderModule demo_prepare_shader_module(struct demo* demo, - const void* code, - size_t size) -{ +static VkShaderModule +demo_prepare_shader_module(struct demo *demo, const void *code, size_t size) { VkShaderModule module; VkShaderModuleCreateInfo moduleCreateInfo; VkResult U_ASSERT_ONLY err; @@ -1467,14 +1455,14 @@ static VkShaderModule demo_prepare_shader_module(struct demo* demo, return module; } -char *demo_read_spv(const char *filename, size_t *psize) -{ +char *demo_read_spv(const char *filename, size_t *psize) { long int size; size_t U_ASSERT_ONLY retval; void *shader_code; FILE *fp = fopen(filename, "rb"); - if (!fp) return NULL; + if (!fp) + return NULL; fseek(fp, 0L, SEEK_END); size = ftell(fp); @@ -1491,47 +1479,46 @@ char *demo_read_spv(const char *filename, size_t *psize) return shader_code; } -static VkShaderModule demo_prepare_vs(struct demo *demo) -{ +static VkShaderModule demo_prepare_vs(struct demo *demo) { void *vertShaderCode; size_t size; vertShaderCode = demo_read_spv("cube-vert.spv", &size); - demo->vert_shader_module = demo_prepare_shader_module(demo, vertShaderCode, size); + demo->vert_shader_module = + demo_prepare_shader_module(demo, vertShaderCode, size); free(vertShaderCode); return demo->vert_shader_module; } -static VkShaderModule demo_prepare_fs(struct demo *demo) -{ +static VkShaderModule demo_prepare_fs(struct demo *demo) { void *fragShaderCode; size_t size; fragShaderCode = demo_read_spv("cube-frag.spv", &size); - demo->frag_shader_module = demo_prepare_shader_module(demo, fragShaderCode, size); + demo->frag_shader_module = + demo_prepare_shader_module(demo, fragShaderCode, size); free(fragShaderCode); return demo->frag_shader_module; } -static void demo_prepare_pipeline(struct demo *demo) -{ +static void demo_prepare_pipeline(struct demo *demo) { VkGraphicsPipelineCreateInfo pipeline; VkPipelineCacheCreateInfo pipelineCache; - VkPipelineVertexInputStateCreateInfo vi; + VkPipelineVertexInputStateCreateInfo vi; VkPipelineInputAssemblyStateCreateInfo ia; - VkPipelineRasterizationStateCreateInfo rs; - VkPipelineColorBlendStateCreateInfo cb; - VkPipelineDepthStencilStateCreateInfo ds; - VkPipelineViewportStateCreateInfo vp; - VkPipelineMultisampleStateCreateInfo ms; - VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE]; - VkPipelineDynamicStateCreateInfo dynamicState; + VkPipelineRasterizationStateCreateInfo rs; + VkPipelineColorBlendStateCreateInfo cb; + VkPipelineDepthStencilStateCreateInfo ds; + VkPipelineViewportStateCreateInfo vp; + VkPipelineMultisampleStateCreateInfo ms; + VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE]; + VkPipelineDynamicStateCreateInfo dynamicState; VkResult U_ASSERT_ONLY err; memset(dynamicStateEnables, 0, sizeof dynamicStateEnables); @@ -1571,9 +1558,11 @@ static void demo_prepare_pipeline(struct demo *demo) memset(&vp, 0, sizeof(vp)); vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vp.viewportCount = 1; - dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT; + dynamicStateEnables[dynamicState.dynamicStateCount++] = + VK_DYNAMIC_STATE_VIEWPORT; vp.scissorCount = 1; - dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR; + dynamicStateEnables[dynamicState.dynamicStateCount++] = + VK_DYNAMIC_STATE_SCISSOR; memset(&ds, 0, sizeof(ds)); ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; @@ -1597,54 +1586,56 @@ static void demo_prepare_pipeline(struct demo *demo) VkPipelineShaderStageCreateInfo shaderStages[2]; memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo)); - shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = demo_prepare_vs(demo); - shaderStages[0].pName = "main"; + shaderStages[0].pName = "main"; - shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = demo_prepare_fs(demo); - shaderStages[1].pName = "main"; + shaderStages[1].pName = "main"; memset(&pipelineCache, 0, sizeof(pipelineCache)); pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; - err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache); + err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, + &demo->pipelineCache); assert(!err); - pipeline.pVertexInputState = &vi; + pipeline.pVertexInputState = &vi; pipeline.pInputAssemblyState = &ia; - pipeline.pRasterizationState = &rs; - pipeline.pColorBlendState = &cb; - pipeline.pMultisampleState = &ms; - pipeline.pViewportState = &vp; - pipeline.pDepthStencilState = &ds; - pipeline.pStages = shaderStages; - pipeline.renderPass = demo->render_pass; - pipeline.pDynamicState = &dynamicState; + pipeline.pRasterizationState = &rs; + pipeline.pColorBlendState = &cb; + pipeline.pMultisampleState = &ms; + pipeline.pViewportState = &vp; + pipeline.pDepthStencilState = &ds; + pipeline.pStages = shaderStages; + pipeline.renderPass = demo->render_pass; + pipeline.pDynamicState = &dynamicState; pipeline.renderPass = demo->render_pass; - err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, - 1, &pipeline, NULL, &demo->pipeline); + err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, + &pipeline, NULL, &demo->pipeline); assert(!err); vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL); vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL); } -static void demo_prepare_descriptor_pool(struct demo *demo) -{ +static void demo_prepare_descriptor_pool(struct demo *demo) { const VkDescriptorPoolSize type_counts[2] = { - [0] = { - .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .descriptorCount = 1, - }, - [1] = { - .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = DEMO_TEXTURE_COUNT, - }, + [0] = + { + .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + .descriptorCount = 1, + }, + [1] = + { + .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = DEMO_TEXTURE_COUNT, + }, }; const VkDescriptorPoolCreateInfo descriptor_pool = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, @@ -1655,13 +1646,12 @@ static void demo_prepare_descriptor_pool(struct demo *demo) }; VkResult U_ASSERT_ONLY err; - err = vkCreateDescriptorPool(demo->device, - &descriptor_pool, NULL, &demo->desc_pool); + err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, + &demo->desc_pool); assert(!err); } -static void demo_prepare_descriptor_set(struct demo *demo) -{ +static void demo_prepare_descriptor_set(struct demo *demo) { VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT]; VkWriteDescriptorSet writes[2]; VkResult U_ASSERT_ONLY err; @@ -1672,8 +1662,7 @@ static void demo_prepare_descriptor_set(struct demo *demo) .pNext = NULL, .descriptorPool = demo->desc_pool, .descriptorSetCount = 1, - .pSetLayouts = &demo->desc_layout - }; + .pSetLayouts = &demo->desc_layout}; err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->desc_set); assert(!err); @@ -1702,36 +1691,36 @@ static void demo_prepare_descriptor_set(struct demo *demo) vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL); } -static void demo_prepare_framebuffers(struct demo *demo) -{ +static void demo_prepare_framebuffers(struct demo *demo) { VkImageView attachments[2]; attachments[1] = demo->depth.view; const VkFramebufferCreateInfo fb_info = { - .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .pNext = NULL, - .renderPass = demo->render_pass, - .attachmentCount = 2, - .pAttachments = attachments, - .width = demo->width, - .height = demo->height, - .layers = 1, + .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .pNext = NULL, + .renderPass = demo->render_pass, + .attachmentCount = 2, + .pAttachments = attachments, + .width = demo->width, + .height = demo->height, + .layers = 1, }; VkResult U_ASSERT_ONLY err; uint32_t i; - demo->framebuffers = (VkFramebuffer *)malloc(demo->swapchainImageCount * sizeof(VkFramebuffer)); + demo->framebuffers = (VkFramebuffer *)malloc(demo->swapchainImageCount * + sizeof(VkFramebuffer)); assert(demo->framebuffers); for (i = 0; i < demo->swapchainImageCount; i++) { attachments[0] = demo->buffers[i].view; - err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->framebuffers[i]); + err = vkCreateFramebuffer(demo->device, &fb_info, NULL, + &demo->framebuffers[i]); assert(!err); } } -static void demo_prepare(struct demo *demo) -{ +static void demo_prepare(struct demo *demo) { VkResult U_ASSERT_ONLY err; const VkCommandPoolCreateInfo cmd_pool_info = { @@ -1740,7 +1729,8 @@ static void demo_prepare(struct demo *demo) .queueFamilyIndex = demo->graphics_queue_node_index, .flags = 0, }; - err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool); + err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, + &demo->cmd_pool); assert(!err); const VkCommandBufferAllocateInfo cmd = { @@ -1761,7 +1751,8 @@ static void demo_prepare(struct demo *demo) demo_prepare_pipeline(demo); for (uint32_t i = 0; i < demo->swapchainImageCount; i++) { - err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->buffers[i].cmd); + err = + vkAllocateCommandBuffers(demo->device, &cmd, &demo->buffers[i].cmd); assert(!err); } @@ -1785,8 +1776,7 @@ static void demo_prepare(struct demo *demo) demo->prepared = true; } -static void demo_cleanup(struct demo *demo) -{ +static void demo_cleanup(struct demo *demo) { uint32_t i; demo->prepared = false; @@ -1820,7 +1810,8 @@ static void demo_cleanup(struct demo *demo) for (i = 0; i < demo->swapchainImageCount; i++) { vkDestroyImageView(demo->device, demo->buffers[i].view, NULL); - vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->buffers[i].cmd); + vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, + &demo->buffers[i].cmd); } free(demo->buffers); @@ -1841,8 +1832,7 @@ static void demo_cleanup(struct demo *demo) #endif // _WIN32 } -static void demo_resize(struct demo *demo) -{ +static void demo_resize(struct demo *demo) { uint32_t i; // Don't react to resize until after first initialization. @@ -1883,7 +1873,8 @@ static void demo_resize(struct demo *demo) for (i = 0; i < demo->swapchainImageCount; i++) { vkDestroyImageView(demo->device, demo->buffers[i].view, NULL); - vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->buffers[i].cmd); + vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, + &demo->buffers[i].cmd); } vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL); free(demo->buffers); @@ -1897,8 +1888,7 @@ static void demo_resize(struct demo *demo) struct demo demo; #ifdef _WIN32 -static void demo_run(struct demo *demo) -{ +static void demo_run(struct demo *demo) { if (!demo->prepared) return; // Wait for work to finish before updating MVP. @@ -1912,23 +1902,16 @@ static void demo_run(struct demo *demo) demo->curFrame++; - if (demo->frameCount != INT_MAX && demo->curFrame == demo->frameCount) - { - demo->quit=true; + if (demo->frameCount != INT_MAX && demo->curFrame == demo->frameCount) { + demo->quit = true; demo_cleanup(demo); ExitProcess(0); } - } // MS-Windows event handling function: -LRESULT CALLBACK WndProc(HWND hWnd, - UINT uMsg, - WPARAM wParam, - LPARAM lParam) -{ - switch(uMsg) - { +LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + switch (uMsg) { case WM_CLOSE: PostQuitMessage(0); break; @@ -1946,9 +1929,8 @@ LRESULT CALLBACK WndProc(HWND hWnd, return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } -static void demo_create_window(struct demo *demo) -{ - WNDCLASSEX win_class; +static void demo_create_window(struct demo *demo) { + WNDCLASSEX win_class; // Initialize the window class structure: win_class.cbSize = sizeof(WNDCLASSEX); @@ -1971,21 +1953,20 @@ static void demo_create_window(struct demo *demo) exit(1); } // Create window with the registered class: - RECT wr = { 0, 0, demo->width, demo->height }; + RECT wr = {0, 0, demo->width, demo->height}; AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); demo->window = CreateWindowEx(0, demo->name, // class name demo->name, // app name WS_OVERLAPPEDWINDOW | // window style - WS_VISIBLE | - WS_SYSMENU, - 100,100, // x/y coords - wr.right-wr.left, // width - wr.bottom-wr.top, // height - NULL, // handle to parent - NULL, // handle to menu - demo->connection, // hInstance - NULL); // no extra parameters + WS_VISIBLE | WS_SYSMENU, + 100, 100, // x/y coords + wr.right - wr.left, // width + wr.bottom - wr.top, // height + NULL, // handle to parent + NULL, // handle to menu + demo->connection, // hInstance + NULL); // no extra parameters if (!demo->window) { // It didn't work, so try to give a useful error: printf("Cannot create a window in which to draw!\n"); @@ -1995,56 +1976,50 @@ static void demo_create_window(struct demo *demo) } #else // _WIN32 static void demo_handle_event(struct demo *demo, - const xcb_generic_event_t *event) -{ + const xcb_generic_event_t *event) { uint8_t event_code = event->response_type & 0x7f; switch (event_code) { case XCB_EXPOSE: // TODO: Resize window break; case XCB_CLIENT_MESSAGE: - if((*(xcb_client_message_event_t*)event).data.data32[0] == - (*demo->atom_wm_delete_window).atom) { + if ((*(xcb_client_message_event_t *)event).data.data32[0] == + (*demo->atom_wm_delete_window).atom) { demo->quit = true; } break; - case XCB_KEY_RELEASE: - { - const xcb_key_release_event_t *key = - (const xcb_key_release_event_t *) event; + case XCB_KEY_RELEASE: { + const xcb_key_release_event_t *key = + (const xcb_key_release_event_t *)event; - switch (key->detail) { - case 0x9: // Escape - demo->quit = true; - break; - case 0x71: // left arrow key - demo->spin_angle += demo->spin_increment; - break; - case 0x72: // right arrow key - demo->spin_angle -= demo->spin_increment; - break; - case 0x41: - demo->pause = !demo->pause; - break; - } + switch (key->detail) { + case 0x9: // Escape + demo->quit = true; + break; + case 0x71: // left arrow key + demo->spin_angle += demo->spin_increment; + break; + case 0x72: // right arrow key + demo->spin_angle -= demo->spin_increment; + break; + case 0x41: + demo->pause = !demo->pause; + break; } - break; - case XCB_CONFIGURE_NOTIFY: - { - const xcb_configure_notify_event_t *cfg = - (const xcb_configure_notify_event_t *) event; - if ((demo->width != cfg->width) || (demo->height != cfg->height)) { - demo_resize(demo); - } + } break; + case XCB_CONFIGURE_NOTIFY: { + const xcb_configure_notify_event_t *cfg = + (const xcb_configure_notify_event_t *)event; + if ((demo->width != cfg->width) || (demo->height != cfg->height)) { + demo_resize(demo); } - break; + } break; default: break; } } -static void demo_run(struct demo *demo) -{ +static void demo_run(struct demo *demo) { xcb_flush(demo->connection); while (!demo->quit) { @@ -2071,47 +2046,45 @@ static void demo_run(struct demo *demo) demo->curFrame++; if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true; - } } -static void demo_create_window(struct demo *demo) -{ +static void demo_create_window(struct demo *demo) { uint32_t value_mask, value_list[32]; demo->window = xcb_generate_id(demo->connection); value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; value_list[0] = demo->screen->black_pixel; - value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | - XCB_EVENT_MASK_EXPOSURE | + value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY; - xcb_create_window(demo->connection, - XCB_COPY_FROM_PARENT, - demo->window, demo->screen->root, - 0, 0, demo->width, demo->height, 0, - XCB_WINDOW_CLASS_INPUT_OUTPUT, - demo->screen->root_visual, - value_mask, value_list); + xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->window, + demo->screen->root, 0, 0, demo->width, demo->height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, + value_mask, value_list); /* Magic code that will send notification when window is destroyed */ - xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, - "WM_PROTOCOLS"); - xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(demo->connection, cookie, 0); - - xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); - demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0); - - xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, - demo->window, (*reply).atom, 4, 32, 1, + xcb_intern_atom_cookie_t cookie = + xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS"); + xcb_intern_atom_reply_t *reply = + xcb_intern_atom_reply(demo->connection, cookie, 0); + + xcb_intern_atom_cookie_t cookie2 = + xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); + demo->atom_wm_delete_window = + xcb_intern_atom_reply(demo->connection, cookie2, 0); + + xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->window, + (*reply).atom, 4, 32, 1, &(*demo->atom_wm_delete_window).atom); free(reply); xcb_map_window(demo->connection, demo->window); - // Force the x/y coordinates to 100,100 results are identical in consecutive runs - const uint32_t coords[] = {100, 100}; + // Force the x/y coordinates to 100,100 results are identical in consecutive + // runs + const uint32_t coords[] = {100, 100}; xcb_configure_window(demo->connection, demo->window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); } @@ -2122,8 +2095,8 @@ static void demo_create_window(struct demo *demo) * can be found in given layer properties. */ static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, - uint32_t layer_count, VkLayerProperties *layers) -{ + uint32_t layer_count, + VkLayerProperties *layers) { for (uint32_t i = 0; i < check_count; i++) { VkBool32 found = 0; for (uint32_t j = 0; j < layer_count; j++) { @@ -2139,8 +2112,7 @@ static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, return 1; } -static void demo_init_vk(struct demo *demo) -{ +static void demo_init_vk(struct demo *demo) { VkResult err; char *extension_names[64]; VkExtensionProperties *instance_extensions; @@ -2154,14 +2126,10 @@ static void demo_init_vk(struct demo *demo) uint32_t enabled_layer_count = 0; char *instance_validation_layers[] = { - "VK_LAYER_LUNARG_threading", - "VK_LAYER_LUNARG_mem_tracker", - "VK_LAYER_LUNARG_object_tracker", - "VK_LAYER_LUNARG_draw_state", - "VK_LAYER_LUNARG_param_checker", - "VK_LAYER_LUNARG_swapchain", - "VK_LAYER_LUNARG_device_limits", - "VK_LAYER_LUNARG_image", + "VK_LAYER_LUNARG_threading", "VK_LAYER_LUNARG_mem_tracker", + "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_draw_state", + "VK_LAYER_LUNARG_param_checker", "VK_LAYER_LUNARG_swapchain", + "VK_LAYER_LUNARG_device_limits", "VK_LAYER_LUNARG_image", }; demo->device_validation_layers[0] = "VK_LAYER_LUNARG_threading"; @@ -2180,12 +2148,14 @@ static void demo_init_vk(struct demo *demo) assert(!err); instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count); - err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers); + err = vkEnumerateInstanceLayerProperties(&instance_layer_count, + instance_layers); assert(!err); if (demo->validate) { - validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers, - instance_layer_count, instance_layers); + validation_found = demo_check_layers( + ARRAY_SIZE(instance_validation_layers), instance_validation_layers, + instance_layer_count, instance_layers); if (!validation_found) { ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find" "required validation layer.\n\n" @@ -2196,41 +2166,53 @@ static void demo_init_vk(struct demo *demo) enabled_layer_count = ARRAY_SIZE(instance_validation_layers); } - err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL); + err = vkEnumerateInstanceExtensionProperties( + NULL, &instance_extension_count, NULL); assert(!err); VkBool32 surfaceExtFound = 0; VkBool32 platformSurfaceExtFound = 0; memset(extension_names, 0, sizeof(extension_names)); - instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count); - err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions); + instance_extensions = + malloc(sizeof(VkExtensionProperties) * instance_extension_count); + err = vkEnumerateInstanceExtensionProperties( + NULL, &instance_extension_count, instance_extensions); assert(!err); for (uint32_t i = 0; i < instance_extension_count; i++) { - if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, + instance_extensions[i].extensionName)) { surfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME; + extension_names[enabled_extension_count++] = + VK_KHR_SURFACE_EXTENSION_NAME; } #ifdef _WIN32 - if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, + instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME; + extension_names[enabled_extension_count++] = + VK_KHR_WIN32_SURFACE_EXTENSION_NAME; } #else // _WIN32 - if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, + instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME; + extension_names[enabled_extension_count++] = + VK_KHR_XCB_SURFACE_EXTENSION_NAME; } #endif // _WIN32 - if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, + instance_extensions[i].extensionName)) { if (demo->validate) { - extension_names[enabled_extension_count++] = VK_EXT_DEBUG_REPORT_EXTENSION_NAME; + extension_names[enabled_extension_count++] = + VK_EXT_DEBUG_REPORT_EXTENSION_NAME; } } assert(enabled_extension_count < 64); } if (!surfaceExtFound) { - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_KHR_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " + "the " VK_KHR_SURFACE_EXTENSION_NAME + " extension.\n\nDo you have a compatible " "Vulkan installable client driver (ICD) installed?\nPlease " "look at the Getting Started guide for additional " "information.\n", @@ -2238,15 +2220,17 @@ static void demo_init_vk(struct demo *demo) } if (!platformSurfaceExtFound) { #ifdef _WIN32 - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_KHR_WIN32_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " + "the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME + " extension.\n\nDo you have a compatible " "Vulkan installable client driver (ICD) installed?\nPlease " "look at the Getting Started guide for additional " "information.\n", "vkCreateInstance Failure"); #else // _WIN32 - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_KHR_XCB_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " + "the " VK_KHR_XCB_SURFACE_EXTENSION_NAME + " extension.\n\nDo you have a compatible " "Vulkan installable client driver (ICD) installed?\nPlease " "look at the Getting Started guide for additional " "information.\n", @@ -2267,9 +2251,11 @@ static void demo_init_vk(struct demo *demo) .pNext = NULL, .pApplicationInfo = &app, .enabledLayerCount = enabled_layer_count, - .ppEnabledLayerNames = (const char *const*) ((demo->validate) ? instance_validation_layers : NULL), + .ppEnabledLayerNames = + (const char *const *)((demo->validate) ? instance_validation_layers + : NULL), .enabledExtensionCount = enabled_extension_count, - .ppEnabledExtensionNames = (const char *const*) extension_names, + .ppEnabledExtensionNames = (const char *const *)extension_names, }; uint32_t gpu_count; @@ -2308,15 +2294,18 @@ static void demo_init_vk(struct demo *demo) validation_found = 0; demo->enabled_layer_count = 0; uint32_t device_layer_count = 0; - err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, NULL); + err = + vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, NULL); assert(!err); device_layers = malloc(sizeof(VkLayerProperties) * device_layer_count); - err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, device_layers); + err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, + device_layers); assert(!err); if (demo->validate) { - validation_found = demo_check_layers(device_validation_layer_count, demo->device_validation_layers, + validation_found = demo_check_layers(device_validation_layer_count, + demo->device_validation_layers, device_layer_count, device_layers); if (!validation_found) { ERR_EXIT("vkEnumerateDeviceLayerProperties failed to find" @@ -2330,28 +2319,32 @@ static void demo_init_vk(struct demo *demo) uint32_t device_extension_count = 0; VkExtensionProperties *device_extensions = NULL; - err = vkEnumerateDeviceExtensionProperties( - demo->gpu, NULL, &device_extension_count, NULL); + err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, + &device_extension_count, NULL); assert(!err); VkBool32 swapchainExtFound = 0; demo->enabled_extension_count = 0; memset(extension_names, 0, sizeof(extension_names)); - device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count); + device_extensions = + malloc(sizeof(VkExtensionProperties) * device_extension_count); err = vkEnumerateDeviceExtensionProperties( - demo->gpu, NULL, &device_extension_count, device_extensions); + demo->gpu, NULL, &device_extension_count, device_extensions); assert(!err); for (uint32_t i = 0; i < device_extension_count; i++) { - if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, + device_extensions[i].extensionName)) { swapchainExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = + VK_KHR_SWAPCHAIN_EXTENSION_NAME; } assert(demo->enabled_extension_count < 64); } if (!swapchainExtFound) { - ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " - VK_KHR_SWAPCHAIN_EXTENSION_NAME" extension.\n\nDo you have a compatible " + ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find " + "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME + " extension.\n\nDo you have a compatible " "Vulkan installable client driver (ICD) installed?\nPlease " "look at the Getting Started guide for additional " "information.\n", @@ -2359,17 +2352,25 @@ static void demo_init_vk(struct demo *demo) } if (demo->validate) { - demo->CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(demo->inst, "vkCreateDebugReportCallbackEXT"); - demo->DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugReportCallbackEXT"); + demo->CreateDebugReportCallback = + (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr( + demo->inst, "vkCreateDebugReportCallbackEXT"); + demo->DestroyDebugReportCallback = + (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr( + demo->inst, "vkDestroyDebugReportCallbackEXT"); if (!demo->CreateDebugReportCallback) { - ERR_EXIT("GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", - "vkGetProcAddr Failure"); + ERR_EXIT( + "GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", + "vkGetProcAddr Failure"); } if (!demo->DestroyDebugReportCallback) { - ERR_EXIT("GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT\n", - "vkGetProcAddr Failure"); + ERR_EXIT( + "GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT\n", + "vkGetProcAddr Failure"); } - demo->DebugReportMessage = (PFN_vkDebugReportMessageEXT) vkGetInstanceProcAddr(demo->inst, "vkDebugReportMessageEXT"); + demo->DebugReportMessage = + (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr( + demo->inst, "vkDebugReportMessageEXT"); if (!demo->DebugReportMessage) { ERR_EXIT("GetProcAddr: Unable to find vkDebugReportMessageEXT\n", "vkGetProcAddr Failure"); @@ -2381,7 +2382,8 @@ static void demo_init_vk(struct demo *demo) callback = dbgFunc; } else { callback = dbgFunc; - // TODO add a break callback defined locally since there is no longer + // TODO add a break callback defined locally since there is no + // longer // one included in the loader } VkDebugReportCallbackCreateInfoEXT dbgCreateInfo; @@ -2389,12 +2391,10 @@ static void demo_init_vk(struct demo *demo) dbgCreateInfo.pNext = NULL; dbgCreateInfo.pfnCallback = callback; dbgCreateInfo.pUserData = NULL; - dbgCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARN_BIT_EXT; - err = demo->CreateDebugReportCallback( - demo->inst, - &dbgCreateInfo, - NULL, - &demo->msg_callback); + dbgCreateInfo.flags = + VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARN_BIT_EXT; + err = demo->CreateDebugReportCallback(demo->inst, &dbgCreateInfo, NULL, + &demo->msg_callback); switch (err) { case VK_SUCCESS: break; @@ -2411,20 +2411,25 @@ static void demo_init_vk(struct demo *demo) vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props); /* Call with NULL data to get count */ - vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, NULL); + vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, + NULL); assert(demo->queue_count >= 1); - demo->queue_props = (VkQueueFamilyProperties *) malloc(demo->queue_count * sizeof(VkQueueFamilyProperties)); - vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, demo->queue_props); + demo->queue_props = (VkQueueFamilyProperties *)malloc( + demo->queue_count * sizeof(VkQueueFamilyProperties)); + vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, + demo->queue_props); // Find a queue that supports gfx uint32_t gfx_queue_idx = 0; - for (gfx_queue_idx = 0; gfx_queue_idx<demo->queue_count; gfx_queue_idx++) { + for (gfx_queue_idx = 0; gfx_queue_idx < demo->queue_count; + gfx_queue_idx++) { if (demo->queue_props[gfx_queue_idx].queueFlags & VK_QUEUE_GRAPHICS_BIT) break; } assert(gfx_queue_idx < demo->queue_count); // Query fine-grained feature support for this device. - // If app has specific feature requirements it should check supported features based on this query + // If app has specific feature requirements it should check supported + // features based on this query VkPhysicalDeviceFeatures physDevFeatures; vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures); @@ -2437,17 +2442,15 @@ static void demo_init_vk(struct demo *demo) GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR); } -static void demo_create_device(struct demo *demo) -{ +static void demo_create_device(struct demo *demo) { VkResult U_ASSERT_ONLY err; - float queue_priorities[1] = { 0.0 }; + float queue_priorities[1] = {0.0}; const VkDeviceQueueCreateInfo queue = { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .pNext = NULL, .queueFamilyIndex = demo->graphics_queue_node_index, .queueCount = 1, - .pQueuePriorities = queue_priorities - }; + .pQueuePriorities = queue_priorities}; VkDeviceCreateInfo device = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, @@ -2455,23 +2458,25 @@ static void demo_create_device(struct demo *demo) .queueCreateInfoCount = 1, .pQueueCreateInfos = &queue, .enabledLayerCount = demo->enabled_layer_count, - .ppEnabledLayerNames = (const char *const*) ((demo->validate) ? demo->device_validation_layers : NULL), + .ppEnabledLayerNames = + (const char *const *)((demo->validate) + ? demo->device_validation_layers + : NULL), .enabledExtensionCount = demo->enabled_extension_count, - .ppEnabledExtensionNames = (const char *const*) demo->extension_names, - .pEnabledFeatures = NULL, // If specific features are required, pass them in here + .ppEnabledExtensionNames = (const char *const *)demo->extension_names, + .pEnabledFeatures = + NULL, // If specific features are required, pass them in here }; err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device); assert(!err); - } -static void demo_init_vk_swapchain(struct demo *demo) -{ +static void demo_init_vk_swapchain(struct demo *demo) { VkResult U_ASSERT_ONLY err; uint32_t i; - // Create a WSI surface for the window: +// Create a WSI surface for the window: #ifdef _WIN32 VkWin32SurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; @@ -2480,8 +2485,8 @@ static void demo_init_vk_swapchain(struct demo *demo) createInfo.hinstance = demo->connection; createInfo.hwnd = demo->window; - err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, - NULL, &demo->surface); + err = + vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #else // _WIN32 VkXcbSurfaceCreateInfoKHR createInfo; @@ -2491,28 +2496,27 @@ static void demo_init_vk_swapchain(struct demo *demo) createInfo.connection = demo->connection; createInfo.window = demo->window; - err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, - NULL, &demo->surface); + err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #endif // _WIN32 // Iterate over each queue to learn whether it supports presenting: - VkBool32* supportsPresent = (VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32)); + VkBool32 *supportsPresent = + (VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32)); for (i = 0; i < demo->queue_count; i++) { - demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, - demo->surface, + demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]); } // Search for a graphics and a present queue in the array of queue // families, try to find one that supports both uint32_t graphicsQueueNodeIndex = UINT32_MAX; - uint32_t presentQueueNodeIndex = UINT32_MAX; + uint32_t presentQueueNodeIndex = UINT32_MAX; for (i = 0; i < demo->queue_count; i++) { if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { if (graphicsQueueNodeIndex == UINT32_MAX) { graphicsQueueNodeIndex = i; } - + if (supportsPresent[i] == VK_TRUE) { graphicsQueueNodeIndex = i; presentQueueNodeIndex = i; @@ -2533,7 +2537,8 @@ static void demo_init_vk_swapchain(struct demo *demo) free(supportsPresent); // Generate error if could not find both a graphics and a present queue - if (graphicsQueueNodeIndex == UINT32_MAX || presentQueueNodeIndex == UINT32_MAX) { + if (graphicsQueueNodeIndex == UINT32_MAX || + presentQueueNodeIndex == UINT32_MAX) { ERR_EXIT("Could not find a graphics and a present queue\n", "Swapchain Initialization Failure"); } @@ -2558,30 +2563,25 @@ static void demo_init_vk_swapchain(struct demo *demo) GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR); GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR); - vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, - 0, &demo->queue); + vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, 0, + &demo->queue); // Get the list of VkFormat's that are supported: uint32_t formatCount; - err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, - demo->surface, + err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL); assert(!err); VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); - err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, - demo->surface, + err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats); assert(!err); // If the format list includes just one entry of VK_FORMAT_UNDEFINED, // the surface has no preferred format. Otherwise, at least one // supported format will be returned. - if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) - { + if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { demo->format = VK_FORMAT_B8G8R8A8_UNORM; - } - else - { + } else { assert(formatCount >= 1); demo->format = surfFormats[0].format; } @@ -2594,8 +2594,7 @@ static void demo_init_vk_swapchain(struct demo *demo) vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties); } -static void demo_init_connection(struct demo *demo) -{ +static void demo_init_connection(struct demo *demo) { #ifndef _WIN32 const xcb_setup_t *setup; xcb_screen_iterator_t iter; @@ -2618,8 +2617,7 @@ static void demo_init_connection(struct demo *demo) #endif // _WIN32 } -static void demo_init(struct demo *demo, int argc, char **argv) -{ +static void demo_init(struct demo *demo, int argc, char **argv) { vec3 eye = {0.0f, 3.0f, 5.0f}; vec3 origin = {0, 0, 0}; vec3 up = {0.0f, 1.0f, 0.0}; @@ -2640,17 +2638,16 @@ static void demo_init(struct demo *demo, int argc, char **argv) demo->validate = true; continue; } - if (strcmp(argv[i], "--c") == 0 && - demo->frameCount == INT32_MAX && - i < argc-1 && - sscanf(argv[i+1],"%d", &demo->frameCount) == 1 && - demo->frameCount >= 0) - { + if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && + i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && + demo->frameCount >= 0) { i++; continue; } - fprintf(stderr, "Usage:\n %s [--use_staging] [--validate] [--break] [--c <framecount>]\n", APP_SHORT_NAME); + fprintf(stderr, "Usage:\n %s [--use_staging] [--validate] [--break] " + "[--c <framecount>]\n", + APP_SHORT_NAME); fflush(stderr); exit(1); } @@ -2665,71 +2662,60 @@ static void demo_init(struct demo *demo, int argc, char **argv) demo->spin_increment = 0.01f; demo->pause = false; - mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f); + mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), + 1.0f, 0.1f, 100.0f); mat4x4_look_at(demo->view_matrix, eye, origin, up); mat4x4_identity(demo->model_matrix); } - #ifdef _WIN32 // Include header required for parsing the command line options. #include <shellapi.h> -int WINAPI WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR pCmdLine, - int nCmdShow) -{ - MSG msg; // message - bool done; // flag saying when app is complete +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, + int nCmdShow) { + MSG msg; // message + bool done; // flag saying when app is complete int argc; - char** argv; - - // Use the CommandLine functions to get the command line arguments. Unfortunately, Microsoft outputs - // this information as wide characters for Unicode, and we simply want the Ascii version to be compatible - // with the non-Windows side. So, we have to convert the information to Ascii character strings. - LPWSTR* commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc); - if (NULL == commandLineArgs) - { + char **argv; + + // Use the CommandLine functions to get the command line arguments. + // Unfortunately, Microsoft outputs + // this information as wide characters for Unicode, and we simply want the + // Ascii version to be compatible + // with the non-Windows side. So, we have to convert the information to + // Ascii character strings. + LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc); + if (NULL == commandLineArgs) { argc = 0; } - if (argc > 0) - { - argv = (char**)malloc(sizeof(char*) * argc); - if (argv == NULL) - { + if (argc > 0) { + argv = (char **)malloc(sizeof(char *) * argc); + if (argv == NULL) { argc = 0; - } - else - { - for (int iii = 0; iii < argc; iii++) - { - size_t wideCharLen = wcslen(commandLineArgs[iii]); + } else { + for (int iii = 0; iii < argc; iii++) { + size_t wideCharLen = wcslen(commandLineArgs[iii]); size_t numConverted = 0; - argv[iii] = (char*)malloc(sizeof(char) * (wideCharLen + 1)); - if (argv[iii] != NULL) - { - wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1); + argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1)); + if (argv[iii] != NULL) { + wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, + commandLineArgs[iii], wideCharLen + 1); } } } - } - else - { + } else { argv = NULL; } demo_init(&demo, argc, argv); // Free up the items we had to allocate for the command line arguments. - if (argc > 0 && argv != NULL) - { - for (int iii = 0; iii < argc; iii++) - { - if (argv[iii] != NULL) - { + if (argc > 0 && argv != NULL) { + for (int iii = 0; iii < argc; iii++) { + if (argv[iii] != NULL) { free(argv[iii]); } } @@ -2743,20 +2729,17 @@ int WINAPI WinMain(HINSTANCE hInstance, demo_prepare(&demo); - done = false; //initialize loop condition variable + done = false; // initialize loop condition variable // main message loop - while(!done) - { + while (!done) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); - if (msg.message == WM_QUIT) //check for a quit message - { - done = true; //if found, quit app - } - else + if (msg.message == WM_QUIT) // check for a quit message { + done = true; // if found, quit app + } else { /* Translate and dispatch to event queue*/ - TranslateMessage(&msg); + TranslateMessage(&msg); DispatchMessage(&msg); } RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT); @@ -2764,11 +2747,10 @@ int WINAPI WinMain(HINSTANCE hInstance, demo_cleanup(&demo); - return (int) msg.wParam; + return (int)msg.wParam; } #else // _WIN32 -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { struct demo demo; demo_init(&demo, argc, argv); diff --git a/demos/cube.frag b/demos/cube.frag index c0c29055..226e4fe4 100644 --- a/demos/cube.frag +++ b/demos/cube.frag @@ -1,4 +1,32 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: + * + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. + * + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. + */ +/* * Fragment shader for cube demo */ #version 400 diff --git a/demos/cube.vert b/demos/cube.vert index 87729e5f..7f47e8c3 100644 --- a/demos/cube.vert +++ b/demos/cube.vert @@ -1,4 +1,32 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: + * + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. + * + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. + */ +/* * Vertex shader used by Cube demo. */ #version 400 diff --git a/demos/linmath.h b/demos/linmath.h index 5de34e93..b60da859 100644 --- a/demos/linmath.h +++ b/demos/linmath.h @@ -11,7 +11,7 @@ DO WHAT THE **** YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - 0. You just DO WHAT THE FUCK YOU WANT TO. + 0. You just DO WHAT THE **** YOU WANT TO. */ #ifndef LINMATH_H @@ -26,572 +26,520 @@ #define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI) typedef float vec3[3]; -static inline void vec3_add(vec3 r, vec3 const a, vec3 const b) -{ - int i; - for(i=0; i<3; ++i) - r[i] = a[i] + b[i]; -} -static inline void vec3_sub(vec3 r, vec3 const a, vec3 const b) -{ - int i; - for(i=0; i<3; ++i) - r[i] = a[i] - b[i]; -} -static inline void vec3_scale(vec3 r, vec3 const v, float const s) -{ - int i; - for(i=0; i<3; ++i) - r[i] = v[i] * s; -} -static inline float vec3_mul_inner(vec3 const a, vec3 const b) -{ - float p = 0.f; - int i; - for(i=0; i<3; ++i) - p += b[i]*a[i]; - return p; -} -static inline void vec3_mul_cross(vec3 r, vec3 const a, vec3 const b) -{ - r[0] = a[1]*b[2] - a[2]*b[1]; - r[1] = a[2]*b[0] - a[0]*b[2]; - r[2] = a[0]*b[1] - a[1]*b[0]; -} -static inline float vec3_len(vec3 const v) -{ - return sqrtf(vec3_mul_inner(v, v)); -} -static inline void vec3_norm(vec3 r, vec3 const v) -{ - float k = 1.f / vec3_len(v); - vec3_scale(r, v, k); -} -static inline void vec3_reflect(vec3 r, vec3 const v, vec3 const n) -{ - float p = 2.f*vec3_mul_inner(v, n); - int i; - for(i=0;i<3;++i) - r[i] = v[i] - p*n[i]; +static inline void vec3_add(vec3 r, vec3 const a, vec3 const b) { + int i; + for (i = 0; i < 3; ++i) + r[i] = a[i] + b[i]; +} +static inline void vec3_sub(vec3 r, vec3 const a, vec3 const b) { + int i; + for (i = 0; i < 3; ++i) + r[i] = a[i] - b[i]; +} +static inline void vec3_scale(vec3 r, vec3 const v, float const s) { + int i; + for (i = 0; i < 3; ++i) + r[i] = v[i] * s; +} +static inline float vec3_mul_inner(vec3 const a, vec3 const b) { + float p = 0.f; + int i; + for (i = 0; i < 3; ++i) + p += b[i] * a[i]; + return p; +} +static inline void vec3_mul_cross(vec3 r, vec3 const a, vec3 const b) { + r[0] = a[1] * b[2] - a[2] * b[1]; + r[1] = a[2] * b[0] - a[0] * b[2]; + r[2] = a[0] * b[1] - a[1] * b[0]; +} +static inline float vec3_len(vec3 const v) { + return sqrtf(vec3_mul_inner(v, v)); +} +static inline void vec3_norm(vec3 r, vec3 const v) { + float k = 1.f / vec3_len(v); + vec3_scale(r, v, k); +} +static inline void vec3_reflect(vec3 r, vec3 const v, vec3 const n) { + float p = 2.f * vec3_mul_inner(v, n); + int i; + for (i = 0; i < 3; ++i) + r[i] = v[i] - p * n[i]; } typedef float vec4[4]; -static inline void vec4_add(vec4 r, vec4 const a, vec4 const b) -{ - int i; - for(i=0; i<4; ++i) - r[i] = a[i] + b[i]; -} -static inline void vec4_sub(vec4 r, vec4 const a, vec4 const b) -{ - int i; - for(i=0; i<4; ++i) - r[i] = a[i] - b[i]; -} -static inline void vec4_scale(vec4 r, vec4 v, float s) -{ - int i; - for(i=0; i<4; ++i) - r[i] = v[i] * s; -} -static inline float vec4_mul_inner(vec4 a, vec4 b) -{ - float p = 0.f; - int i; - for(i=0; i<4; ++i) - p += b[i]*a[i]; - return p; -} -static inline void vec4_mul_cross(vec4 r, vec4 a, vec4 b) -{ - r[0] = a[1]*b[2] - a[2]*b[1]; - r[1] = a[2]*b[0] - a[0]*b[2]; - r[2] = a[0]*b[1] - a[1]*b[0]; - r[3] = 1.f; -} -static inline float vec4_len(vec4 v) -{ - return sqrtf(vec4_mul_inner(v, v)); -} -static inline void vec4_norm(vec4 r, vec4 v) -{ - float k = 1.f / vec4_len(v); - vec4_scale(r, v, k); -} -static inline void vec4_reflect(vec4 r, vec4 v, vec4 n) -{ - float p = 2.f*vec4_mul_inner(v, n); - int i; - for(i=0;i<4;++i) - r[i] = v[i] - p*n[i]; +static inline void vec4_add(vec4 r, vec4 const a, vec4 const b) { + int i; + for (i = 0; i < 4; ++i) + r[i] = a[i] + b[i]; +} +static inline void vec4_sub(vec4 r, vec4 const a, vec4 const b) { + int i; + for (i = 0; i < 4; ++i) + r[i] = a[i] - b[i]; +} +static inline void vec4_scale(vec4 r, vec4 v, float s) { + int i; + for (i = 0; i < 4; ++i) + r[i] = v[i] * s; +} +static inline float vec4_mul_inner(vec4 a, vec4 b) { + float p = 0.f; + int i; + for (i = 0; i < 4; ++i) + p += b[i] * a[i]; + return p; +} +static inline void vec4_mul_cross(vec4 r, vec4 a, vec4 b) { + r[0] = a[1] * b[2] - a[2] * b[1]; + r[1] = a[2] * b[0] - a[0] * b[2]; + r[2] = a[0] * b[1] - a[1] * b[0]; + r[3] = 1.f; +} +static inline float vec4_len(vec4 v) { return sqrtf(vec4_mul_inner(v, v)); } +static inline void vec4_norm(vec4 r, vec4 v) { + float k = 1.f / vec4_len(v); + vec4_scale(r, v, k); +} +static inline void vec4_reflect(vec4 r, vec4 v, vec4 n) { + float p = 2.f * vec4_mul_inner(v, n); + int i; + for (i = 0; i < 4; ++i) + r[i] = v[i] - p * n[i]; } typedef vec4 mat4x4[4]; -static inline void mat4x4_identity(mat4x4 M) -{ - int i, j; - for(i=0; i<4; ++i) - for(j=0; j<4; ++j) - M[i][j] = i==j ? 1.f : 0.f; -} -static inline void mat4x4_dup(mat4x4 M, mat4x4 N) -{ - int i, j; - for(i=0; i<4; ++i) - for(j=0; j<4; ++j) - M[i][j] = N[i][j]; -} -static inline void mat4x4_row(vec4 r, mat4x4 M, int i) -{ - int k; - for(k=0; k<4; ++k) - r[k] = M[k][i]; -} -static inline void mat4x4_col(vec4 r, mat4x4 M, int i) -{ - int k; - for(k=0; k<4; ++k) - r[k] = M[i][k]; -} -static inline void mat4x4_transpose(mat4x4 M, mat4x4 N) -{ - int i, j; - for(j=0; j<4; ++j) - for(i=0; i<4; ++i) - M[i][j] = N[j][i]; -} -static inline void mat4x4_add(mat4x4 M, mat4x4 a, mat4x4 b) -{ - int i; - for(i=0; i<4; ++i) - vec4_add(M[i], a[i], b[i]); -} -static inline void mat4x4_sub(mat4x4 M, mat4x4 a, mat4x4 b) -{ - int i; - for(i=0; i<4; ++i) - vec4_sub(M[i], a[i], b[i]); -} -static inline void mat4x4_scale(mat4x4 M, mat4x4 a, float k) -{ - int i; - for(i=0; i<4; ++i) - vec4_scale(M[i], a[i], k); -} -static inline void mat4x4_scale_aniso(mat4x4 M, mat4x4 a, float x, float y, float z) -{ - int i; - vec4_scale(M[0], a[0], x); - vec4_scale(M[1], a[1], y); - vec4_scale(M[2], a[2], z); - for(i = 0; i < 4; ++i) { - M[3][i] = a[3][i]; +static inline void mat4x4_identity(mat4x4 M) { + int i, j; + for (i = 0; i < 4; ++i) + for (j = 0; j < 4; ++j) + M[i][j] = i == j ? 1.f : 0.f; +} +static inline void mat4x4_dup(mat4x4 M, mat4x4 N) { + int i, j; + for (i = 0; i < 4; ++i) + for (j = 0; j < 4; ++j) + M[i][j] = N[i][j]; +} +static inline void mat4x4_row(vec4 r, mat4x4 M, int i) { + int k; + for (k = 0; k < 4; ++k) + r[k] = M[k][i]; +} +static inline void mat4x4_col(vec4 r, mat4x4 M, int i) { + int k; + for (k = 0; k < 4; ++k) + r[k] = M[i][k]; +} +static inline void mat4x4_transpose(mat4x4 M, mat4x4 N) { + int i, j; + for (j = 0; j < 4; ++j) + for (i = 0; i < 4; ++i) + M[i][j] = N[j][i]; +} +static inline void mat4x4_add(mat4x4 M, mat4x4 a, mat4x4 b) { + int i; + for (i = 0; i < 4; ++i) + vec4_add(M[i], a[i], b[i]); +} +static inline void mat4x4_sub(mat4x4 M, mat4x4 a, mat4x4 b) { + int i; + for (i = 0; i < 4; ++i) + vec4_sub(M[i], a[i], b[i]); +} +static inline void mat4x4_scale(mat4x4 M, mat4x4 a, float k) { + int i; + for (i = 0; i < 4; ++i) + vec4_scale(M[i], a[i], k); +} +static inline void mat4x4_scale_aniso(mat4x4 M, mat4x4 a, float x, float y, + float z) { + int i; + vec4_scale(M[0], a[0], x); + vec4_scale(M[1], a[1], y); + vec4_scale(M[2], a[2], z); + for (i = 0; i < 4; ++i) { + M[3][i] = a[3][i]; + } +} +static inline void mat4x4_mul(mat4x4 M, mat4x4 a, mat4x4 b) { + int k, r, c; + for (c = 0; c < 4; ++c) + for (r = 0; r < 4; ++r) { + M[c][r] = 0.f; + for (k = 0; k < 4; ++k) + M[c][r] += a[k][r] * b[c][k]; } } -static inline void mat4x4_mul(mat4x4 M, mat4x4 a, mat4x4 b) -{ - int k, r, c; - for(c=0; c<4; ++c) for(r=0; r<4; ++r) { - M[c][r] = 0.f; - for(k=0; k<4; ++k) - M[c][r] += a[k][r] * b[c][k]; - } -} -static inline void mat4x4_mul_vec4(vec4 r, mat4x4 M, vec4 v) -{ - int i, j; - for(j=0; j<4; ++j) { - r[j] = 0.f; - for(i=0; i<4; ++i) - r[j] += M[i][j] * v[i]; - } -} -static inline void mat4x4_translate(mat4x4 T, float x, float y, float z) -{ - mat4x4_identity(T); - T[3][0] = x; - T[3][1] = y; - T[3][2] = z; -} -static inline void mat4x4_translate_in_place(mat4x4 M, float x, float y, float z) -{ - vec4 t = {x, y, z, 0}; - vec4 r; - int i; - for (i = 0; i < 4; ++i) { - mat4x4_row(r, M, i); - M[3][i] += vec4_mul_inner(r, t); - } -} -static inline void mat4x4_from_vec3_mul_outer(mat4x4 M, vec3 a, vec3 b) -{ - int i, j; - for(i=0; i<4; ++i) for(j=0; j<4; ++j) - M[i][j] = i<3 && j<3 ? a[i] * b[j] : 0.f; -} -static inline void mat4x4_rotate(mat4x4 R, mat4x4 M, float x, float y, float z, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - vec3 u = {x, y, z}; - - if(vec3_len(u) > 1e-4) { - vec3_norm(u, u); - mat4x4 T; - mat4x4_from_vec3_mul_outer(T, u, u); - - mat4x4 S = { - { 0, u[2], -u[1], 0}, - {-u[2], 0, u[0], 0}, - { u[1], -u[0], 0, 0}, - { 0, 0, 0, 0} - }; - mat4x4_scale(S, S, s); - - mat4x4 C; - mat4x4_identity(C); - mat4x4_sub(C, C, T); - - mat4x4_scale(C, C, c); - - mat4x4_add(T, T, C); - mat4x4_add(T, T, S); - - T[3][3] = 1.; - mat4x4_mul(R, M, T); - } else { - mat4x4_dup(R, M); - } -} -static inline void mat4x4_rotate_X(mat4x4 Q, mat4x4 M, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = { - {1.f, 0.f, 0.f, 0.f}, - {0.f, c, s, 0.f}, - {0.f, -s, c, 0.f}, - {0.f, 0.f, 0.f, 1.f} - }; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_rotate_Y(mat4x4 Q, mat4x4 M, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = { - { c, 0.f, s, 0.f}, - { 0.f, 1.f, 0.f, 0.f}, - { -s, 0.f, c, 0.f}, - { 0.f, 0.f, 0.f, 1.f} - }; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = { - { c, s, 0.f, 0.f}, - { -s, c, 0.f, 0.f}, - { 0.f, 0.f, 1.f, 0.f}, - { 0.f, 0.f, 0.f, 1.f} - }; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_invert(mat4x4 T, mat4x4 M) -{ - float s[6]; - float c[6]; - s[0] = M[0][0]*M[1][1] - M[1][0]*M[0][1]; - s[1] = M[0][0]*M[1][2] - M[1][0]*M[0][2]; - s[2] = M[0][0]*M[1][3] - M[1][0]*M[0][3]; - s[3] = M[0][1]*M[1][2] - M[1][1]*M[0][2]; - s[4] = M[0][1]*M[1][3] - M[1][1]*M[0][3]; - s[5] = M[0][2]*M[1][3] - M[1][2]*M[0][3]; - - c[0] = M[2][0]*M[3][1] - M[3][0]*M[2][1]; - c[1] = M[2][0]*M[3][2] - M[3][0]*M[2][2]; - c[2] = M[2][0]*M[3][3] - M[3][0]*M[2][3]; - c[3] = M[2][1]*M[3][2] - M[3][1]*M[2][2]; - c[4] = M[2][1]*M[3][3] - M[3][1]*M[2][3]; - c[5] = M[2][2]*M[3][3] - M[3][2]*M[2][3]; - - /* Assumes it is invertible */ - float idet = 1.0f/( s[0]*c[5]-s[1]*c[4]+s[2]*c[3]+s[3]*c[2]-s[4]*c[1]+s[5]*c[0] ); - - T[0][0] = ( M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; - T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; - T[0][2] = ( M[3][1] * s[5] - M[3][2] * s[4] + M[3][3] * s[3]) * idet; - T[0][3] = (-M[2][1] * s[5] + M[2][2] * s[4] - M[2][3] * s[3]) * idet; - - T[1][0] = (-M[1][0] * c[5] + M[1][2] * c[2] - M[1][3] * c[1]) * idet; - T[1][1] = ( M[0][0] * c[5] - M[0][2] * c[2] + M[0][3] * c[1]) * idet; - T[1][2] = (-M[3][0] * s[5] + M[3][2] * s[2] - M[3][3] * s[1]) * idet; - T[1][3] = ( M[2][0] * s[5] - M[2][2] * s[2] + M[2][3] * s[1]) * idet; - - T[2][0] = ( M[1][0] * c[4] - M[1][1] * c[2] + M[1][3] * c[0]) * idet; - T[2][1] = (-M[0][0] * c[4] + M[0][1] * c[2] - M[0][3] * c[0]) * idet; - T[2][2] = ( M[3][0] * s[4] - M[3][1] * s[2] + M[3][3] * s[0]) * idet; - T[2][3] = (-M[2][0] * s[4] + M[2][1] * s[2] - M[2][3] * s[0]) * idet; - - T[3][0] = (-M[1][0] * c[3] + M[1][1] * c[1] - M[1][2] * c[0]) * idet; - T[3][1] = ( M[0][0] * c[3] - M[0][1] * c[1] + M[0][2] * c[0]) * idet; - T[3][2] = (-M[3][0] * s[3] + M[3][1] * s[1] - M[3][2] * s[0]) * idet; - T[3][3] = ( M[2][0] * s[3] - M[2][1] * s[1] + M[2][2] * s[0]) * idet; -} -static inline void mat4x4_orthonormalize(mat4x4 R, mat4x4 M) -{ +static inline void mat4x4_mul_vec4(vec4 r, mat4x4 M, vec4 v) { + int i, j; + for (j = 0; j < 4; ++j) { + r[j] = 0.f; + for (i = 0; i < 4; ++i) + r[j] += M[i][j] * v[i]; + } +} +static inline void mat4x4_translate(mat4x4 T, float x, float y, float z) { + mat4x4_identity(T); + T[3][0] = x; + T[3][1] = y; + T[3][2] = z; +} +static inline void mat4x4_translate_in_place(mat4x4 M, float x, float y, + float z) { + vec4 t = {x, y, z, 0}; + vec4 r; + int i; + for (i = 0; i < 4; ++i) { + mat4x4_row(r, M, i); + M[3][i] += vec4_mul_inner(r, t); + } +} +static inline void mat4x4_from_vec3_mul_outer(mat4x4 M, vec3 a, vec3 b) { + int i, j; + for (i = 0; i < 4; ++i) + for (j = 0; j < 4; ++j) + M[i][j] = i < 3 && j < 3 ? a[i] * b[j] : 0.f; +} +static inline void mat4x4_rotate(mat4x4 R, mat4x4 M, float x, float y, float z, + float angle) { + float s = sinf(angle); + float c = cosf(angle); + vec3 u = {x, y, z}; + + if (vec3_len(u) > 1e-4) { + vec3_norm(u, u); + mat4x4 T; + mat4x4_from_vec3_mul_outer(T, u, u); + + mat4x4 S = {{0, u[2], -u[1], 0}, + {-u[2], 0, u[0], 0}, + {u[1], -u[0], 0, 0}, + {0, 0, 0, 0}}; + mat4x4_scale(S, S, s); + + mat4x4 C; + mat4x4_identity(C); + mat4x4_sub(C, C, T); + + mat4x4_scale(C, C, c); + + mat4x4_add(T, T, C); + mat4x4_add(T, T, S); + + T[3][3] = 1.; + mat4x4_mul(R, M, T); + } else { mat4x4_dup(R, M); - float s = 1.; - vec3 h; - - vec3_norm(R[2], R[2]); - - s = vec3_mul_inner(R[1], R[2]); - vec3_scale(h, R[2], s); - vec3_sub(R[1], R[1], h); - vec3_norm(R[2], R[2]); - - s = vec3_mul_inner(R[1], R[2]); - vec3_scale(h, R[2], s); - vec3_sub(R[1], R[1], h); - vec3_norm(R[1], R[1]); - - s = vec3_mul_inner(R[0], R[1]); - vec3_scale(h, R[1], s); - vec3_sub(R[0], R[0], h); - vec3_norm(R[0], R[0]); -} - -static inline void mat4x4_frustum(mat4x4 M, float l, float r, float b, float t, float n, float f) -{ - M[0][0] = 2.f*n/(r-l); - M[0][1] = M[0][2] = M[0][3] = 0.f; - - M[1][1] = 2.f*n/(t-b); - M[1][0] = M[1][2] = M[1][3] = 0.f; - - M[2][0] = (r+l)/(r-l); - M[2][1] = (t+b)/(t-b); - M[2][2] = -(f+n)/(f-n); - M[2][3] = -1.f; - - M[3][2] = -2.f*(f*n)/(f-n); - M[3][0] = M[3][1] = M[3][3] = 0.f; -} -static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, float n, float f) -{ - M[0][0] = 2.f/(r-l); - M[0][1] = M[0][2] = M[0][3] = 0.f; - - M[1][1] = 2.f/(t-b); - M[1][0] = M[1][2] = M[1][3] = 0.f; - - M[2][2] = -2.f/(f-n); - M[2][0] = M[2][1] = M[2][3] = 0.f; - - M[3][0] = -(r+l)/(r-l); - M[3][1] = -(t+b)/(t-b); - M[3][2] = -(f+n)/(f-n); - M[3][3] = 1.f; -} -static inline void mat4x4_perspective(mat4x4 m, float y_fov, float aspect, float n, float f) -{ - /* NOTE: Degrees are an unhandy unit to work with. - * linmath.h uses radians for everything! */ - float const a = (float)(1.f / tan(y_fov / 2.f)); - - m[0][0] = a / aspect; - m[0][1] = 0.f; - m[0][2] = 0.f; - m[0][3] = 0.f; - - m[1][0] = 0.f; - m[1][1] = a; - m[1][2] = 0.f; - m[1][3] = 0.f; - - m[2][0] = 0.f; - m[2][1] = 0.f; - m[2][2] = -((f + n) / (f - n)); - m[2][3] = -1.f; - - m[3][0] = 0.f; - m[3][1] = 0.f; - m[3][2] = -((2.f * f * n) / (f - n)); - m[3][3] = 0.f; -} -static inline void mat4x4_look_at(mat4x4 m, vec3 eye, vec3 center, vec3 up) -{ - /* Adapted from Android's OpenGL Matrix.java. */ - /* See the OpenGL GLUT documentation for gluLookAt for a description */ - /* of the algorithm. We implement it in a straightforward way: */ - - /* TODO: The negation of of can be spared by swapping the order of - * operands in the following cross products in the right way. */ - vec3 f; - vec3_sub(f, center, eye); - vec3_norm(f, f); - - vec3 s; - vec3_mul_cross(s, f, up); - vec3_norm(s, s); - - vec3 t; - vec3_mul_cross(t, s, f); - - m[0][0] = s[0]; - m[0][1] = t[0]; - m[0][2] = -f[0]; - m[0][3] = 0.f; + } +} +static inline void mat4x4_rotate_X(mat4x4 Q, mat4x4 M, float angle) { + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = {{1.f, 0.f, 0.f, 0.f}, + {0.f, c, s, 0.f}, + {0.f, -s, c, 0.f}, + {0.f, 0.f, 0.f, 1.f}}; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_rotate_Y(mat4x4 Q, mat4x4 M, float angle) { + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = {{c, 0.f, s, 0.f}, + {0.f, 1.f, 0.f, 0.f}, + {-s, 0.f, c, 0.f}, + {0.f, 0.f, 0.f, 1.f}}; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle) { + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = {{c, s, 0.f, 0.f}, + {-s, c, 0.f, 0.f}, + {0.f, 0.f, 1.f, 0.f}, + {0.f, 0.f, 0.f, 1.f}}; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_invert(mat4x4 T, mat4x4 M) { + float s[6]; + float c[6]; + s[0] = M[0][0] * M[1][1] - M[1][0] * M[0][1]; + s[1] = M[0][0] * M[1][2] - M[1][0] * M[0][2]; + s[2] = M[0][0] * M[1][3] - M[1][0] * M[0][3]; + s[3] = M[0][1] * M[1][2] - M[1][1] * M[0][2]; + s[4] = M[0][1] * M[1][3] - M[1][1] * M[0][3]; + s[5] = M[0][2] * M[1][3] - M[1][2] * M[0][3]; + + c[0] = M[2][0] * M[3][1] - M[3][0] * M[2][1]; + c[1] = M[2][0] * M[3][2] - M[3][0] * M[2][2]; + c[2] = M[2][0] * M[3][3] - M[3][0] * M[2][3]; + c[3] = M[2][1] * M[3][2] - M[3][1] * M[2][2]; + c[4] = M[2][1] * M[3][3] - M[3][1] * M[2][3]; + c[5] = M[2][2] * M[3][3] - M[3][2] * M[2][3]; + + /* Assumes it is invertible */ + float idet = 1.0f / (s[0] * c[5] - s[1] * c[4] + s[2] * c[3] + s[3] * c[2] - + s[4] * c[1] + s[5] * c[0]); + + T[0][0] = (M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; + T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; + T[0][2] = (M[3][1] * s[5] - M[3][2] * s[4] + M[3][3] * s[3]) * idet; + T[0][3] = (-M[2][1] * s[5] + M[2][2] * s[4] - M[2][3] * s[3]) * idet; + + T[1][0] = (-M[1][0] * c[5] + M[1][2] * c[2] - M[1][3] * c[1]) * idet; + T[1][1] = (M[0][0] * c[5] - M[0][2] * c[2] + M[0][3] * c[1]) * idet; + T[1][2] = (-M[3][0] * s[5] + M[3][2] * s[2] - M[3][3] * s[1]) * idet; + T[1][3] = (M[2][0] * s[5] - M[2][2] * s[2] + M[2][3] * s[1]) * idet; + + T[2][0] = (M[1][0] * c[4] - M[1][1] * c[2] + M[1][3] * c[0]) * idet; + T[2][1] = (-M[0][0] * c[4] + M[0][1] * c[2] - M[0][3] * c[0]) * idet; + T[2][2] = (M[3][0] * s[4] - M[3][1] * s[2] + M[3][3] * s[0]) * idet; + T[2][3] = (-M[2][0] * s[4] + M[2][1] * s[2] - M[2][3] * s[0]) * idet; + + T[3][0] = (-M[1][0] * c[3] + M[1][1] * c[1] - M[1][2] * c[0]) * idet; + T[3][1] = (M[0][0] * c[3] - M[0][1] * c[1] + M[0][2] * c[0]) * idet; + T[3][2] = (-M[3][0] * s[3] + M[3][1] * s[1] - M[3][2] * s[0]) * idet; + T[3][3] = (M[2][0] * s[3] - M[2][1] * s[1] + M[2][2] * s[0]) * idet; +} +static inline void mat4x4_orthonormalize(mat4x4 R, mat4x4 M) { + mat4x4_dup(R, M); + float s = 1.; + vec3 h; + + vec3_norm(R[2], R[2]); + + s = vec3_mul_inner(R[1], R[2]); + vec3_scale(h, R[2], s); + vec3_sub(R[1], R[1], h); + vec3_norm(R[2], R[2]); + + s = vec3_mul_inner(R[1], R[2]); + vec3_scale(h, R[2], s); + vec3_sub(R[1], R[1], h); + vec3_norm(R[1], R[1]); + + s = vec3_mul_inner(R[0], R[1]); + vec3_scale(h, R[1], s); + vec3_sub(R[0], R[0], h); + vec3_norm(R[0], R[0]); +} + +static inline void mat4x4_frustum(mat4x4 M, float l, float r, float b, float t, + float n, float f) { + M[0][0] = 2.f * n / (r - l); + M[0][1] = M[0][2] = M[0][3] = 0.f; + + M[1][1] = 2.f * n / (t - b); + M[1][0] = M[1][2] = M[1][3] = 0.f; + + M[2][0] = (r + l) / (r - l); + M[2][1] = (t + b) / (t - b); + M[2][2] = -(f + n) / (f - n); + M[2][3] = -1.f; + + M[3][2] = -2.f * (f * n) / (f - n); + M[3][0] = M[3][1] = M[3][3] = 0.f; +} +static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, + float n, float f) { + M[0][0] = 2.f / (r - l); + M[0][1] = M[0][2] = M[0][3] = 0.f; + + M[1][1] = 2.f / (t - b); + M[1][0] = M[1][2] = M[1][3] = 0.f; + + M[2][2] = -2.f / (f - n); + M[2][0] = M[2][1] = M[2][3] = 0.f; + + M[3][0] = -(r + l) / (r - l); + M[3][1] = -(t + b) / (t - b); + M[3][2] = -(f + n) / (f - n); + M[3][3] = 1.f; +} +static inline void mat4x4_perspective(mat4x4 m, float y_fov, float aspect, + float n, float f) { + /* NOTE: Degrees are an unhandy unit to work with. + * linmath.h uses radians for everything! */ + float const a = (float)(1.f / tan(y_fov / 2.f)); + + m[0][0] = a / aspect; + m[0][1] = 0.f; + m[0][2] = 0.f; + m[0][3] = 0.f; + + m[1][0] = 0.f; + m[1][1] = a; + m[1][2] = 0.f; + m[1][3] = 0.f; + + m[2][0] = 0.f; + m[2][1] = 0.f; + m[2][2] = -((f + n) / (f - n)); + m[2][3] = -1.f; + + m[3][0] = 0.f; + m[3][1] = 0.f; + m[3][2] = -((2.f * f * n) / (f - n)); + m[3][3] = 0.f; +} +static inline void mat4x4_look_at(mat4x4 m, vec3 eye, vec3 center, vec3 up) { + /* Adapted from Android's OpenGL Matrix.java. */ + /* See the OpenGL GLUT documentation for gluLookAt for a description */ + /* of the algorithm. We implement it in a straightforward way: */ + + /* TODO: The negation of of can be spared by swapping the order of + * operands in the following cross products in the right way. */ + vec3 f; + vec3_sub(f, center, eye); + vec3_norm(f, f); + + vec3 s; + vec3_mul_cross(s, f, up); + vec3_norm(s, s); + + vec3 t; + vec3_mul_cross(t, s, f); + + m[0][0] = s[0]; + m[0][1] = t[0]; + m[0][2] = -f[0]; + m[0][3] = 0.f; - m[1][0] = s[1]; - m[1][1] = t[1]; - m[1][2] = -f[1]; - m[1][3] = 0.f; - - m[2][0] = s[2]; - m[2][1] = t[2]; - m[2][2] = -f[2]; - m[2][3] = 0.f; - - m[3][0] = 0.f; - m[3][1] = 0.f; - m[3][2] = 0.f; - m[3][3] = 1.f; - - mat4x4_translate_in_place(m, -eye[0], -eye[1], -eye[2]); + m[1][0] = s[1]; + m[1][1] = t[1]; + m[1][2] = -f[1]; + m[1][3] = 0.f; + + m[2][0] = s[2]; + m[2][1] = t[2]; + m[2][2] = -f[2]; + m[2][3] = 0.f; + + m[3][0] = 0.f; + m[3][1] = 0.f; + m[3][2] = 0.f; + m[3][3] = 1.f; + + mat4x4_translate_in_place(m, -eye[0], -eye[1], -eye[2]); } typedef float quat[4]; -static inline void quat_identity(quat q) -{ - q[0] = q[1] = q[2] = 0.f; - q[3] = 1.f; -} -static inline void quat_add(quat r, quat a, quat b) -{ - int i; - for(i=0; i<4; ++i) - r[i] = a[i] + b[i]; -} -static inline void quat_sub(quat r, quat a, quat b) -{ - int i; - for(i=0; i<4; ++i) - r[i] = a[i] - b[i]; -} -static inline void quat_mul(quat r, quat p, quat q) -{ - vec3 w; - vec3_mul_cross(r, p, q); - vec3_scale(w, p, q[3]); - vec3_add(r, r, w); - vec3_scale(w, q, p[3]); - vec3_add(r, r, w); - r[3] = p[3]*q[3] - vec3_mul_inner(p, q); -} -static inline void quat_scale(quat r, quat v, float s) -{ - int i; - for(i=0; i<4; ++i) - r[i] = v[i] * s; -} -static inline float quat_inner_product(quat a, quat b) -{ - float p = 0.f; - int i; - for(i=0; i<4; ++i) - p += b[i]*a[i]; - return p; -} -static inline void quat_conj(quat r, quat q) -{ - int i; - for(i=0; i<3; ++i) - r[i] = -q[i]; - r[3] = q[3]; +static inline void quat_identity(quat q) { + q[0] = q[1] = q[2] = 0.f; + q[3] = 1.f; +} +static inline void quat_add(quat r, quat a, quat b) { + int i; + for (i = 0; i < 4; ++i) + r[i] = a[i] + b[i]; +} +static inline void quat_sub(quat r, quat a, quat b) { + int i; + for (i = 0; i < 4; ++i) + r[i] = a[i] - b[i]; +} +static inline void quat_mul(quat r, quat p, quat q) { + vec3 w; + vec3_mul_cross(r, p, q); + vec3_scale(w, p, q[3]); + vec3_add(r, r, w); + vec3_scale(w, q, p[3]); + vec3_add(r, r, w); + r[3] = p[3] * q[3] - vec3_mul_inner(p, q); +} +static inline void quat_scale(quat r, quat v, float s) { + int i; + for (i = 0; i < 4; ++i) + r[i] = v[i] * s; +} +static inline float quat_inner_product(quat a, quat b) { + float p = 0.f; + int i; + for (i = 0; i < 4; ++i) + p += b[i] * a[i]; + return p; +} +static inline void quat_conj(quat r, quat q) { + int i; + for (i = 0; i < 3; ++i) + r[i] = -q[i]; + r[3] = q[3]; } #define quat_norm vec4_norm -static inline void quat_mul_vec3(vec3 r, quat q, vec3 v) -{ - quat v_ = {v[0], v[1], v[2], 0.f}; - - quat_conj(r, q); - quat_norm(r, r); - quat_mul(r, v_, r); - quat_mul(r, q, r); -} -static inline void mat4x4_from_quat(mat4x4 M, quat q) -{ - float a = q[3]; - float b = q[0]; - float c = q[1]; - float d = q[2]; - float a2 = a*a; - float b2 = b*b; - float c2 = c*c; - float d2 = d*d; - - M[0][0] = a2 + b2 - c2 - d2; - M[0][1] = 2.f*(b*c + a*d); - M[0][2] = 2.f*(b*d - a*c); - M[0][3] = 0.f; - - M[1][0] = 2*(b*c - a*d); - M[1][1] = a2 - b2 + c2 - d2; - M[1][2] = 2.f*(c*d + a*b); - M[1][3] = 0.f; - - M[2][0] = 2.f*(b*d + a*c); - M[2][1] = 2.f*(c*d - a*b); - M[2][2] = a2 - b2 - c2 + d2; - M[2][3] = 0.f; - - M[3][0] = M[3][1] = M[3][2] = 0.f; - M[3][3] = 1.f; -} - -static inline void mat4x4o_mul_quat(mat4x4 R, mat4x4 M, quat q) -{ -/* XXX: The way this is written only works for othogonal matrices. */ -/* TODO: Take care of non-orthogonal case. */ - quat_mul_vec3(R[0], q, M[0]); - quat_mul_vec3(R[1], q, M[1]); - quat_mul_vec3(R[2], q, M[2]); - - R[3][0] = R[3][1] = R[3][2] = 0.f; - R[3][3] = 1.f; -} -static inline void quat_from_mat4x4(quat q, mat4x4 M) -{ - float r=0.f; - int i; - - int perm[] = { 0, 1, 2, 0, 1 }; - int *p = perm; - - for(i = 0; i<3; i++) { - float m = M[i][i]; - if( m < r ) - continue; - m = r; - p = &perm[i]; - } - - r = sqrtf(1.f + M[p[0]][p[0]] - M[p[1]][p[1]] - M[p[2]][p[2]] ); - - if(r < 1e-6) { - q[0] = 1.f; - q[1] = q[2] = q[3] = 0.f; - return; - } - - q[0] = r/2.f; - q[1] = (M[p[0]][p[1]] - M[p[1]][p[0]])/(2.f*r); - q[2] = (M[p[2]][p[0]] - M[p[0]][p[2]])/(2.f*r); - q[3] = (M[p[2]][p[1]] - M[p[1]][p[2]])/(2.f*r); +static inline void quat_mul_vec3(vec3 r, quat q, vec3 v) { + quat v_ = {v[0], v[1], v[2], 0.f}; + + quat_conj(r, q); + quat_norm(r, r); + quat_mul(r, v_, r); + quat_mul(r, q, r); +} +static inline void mat4x4_from_quat(mat4x4 M, quat q) { + float a = q[3]; + float b = q[0]; + float c = q[1]; + float d = q[2]; + float a2 = a * a; + float b2 = b * b; + float c2 = c * c; + float d2 = d * d; + + M[0][0] = a2 + b2 - c2 - d2; + M[0][1] = 2.f * (b * c + a * d); + M[0][2] = 2.f * (b * d - a * c); + M[0][3] = 0.f; + + M[1][0] = 2 * (b * c - a * d); + M[1][1] = a2 - b2 + c2 - d2; + M[1][2] = 2.f * (c * d + a * b); + M[1][3] = 0.f; + + M[2][0] = 2.f * (b * d + a * c); + M[2][1] = 2.f * (c * d - a * b); + M[2][2] = a2 - b2 - c2 + d2; + M[2][3] = 0.f; + + M[3][0] = M[3][1] = M[3][2] = 0.f; + M[3][3] = 1.f; +} + +static inline void mat4x4o_mul_quat(mat4x4 R, mat4x4 M, quat q) { + /* XXX: The way this is written only works for othogonal matrices. */ + /* TODO: Take care of non-orthogonal case. */ + quat_mul_vec3(R[0], q, M[0]); + quat_mul_vec3(R[1], q, M[1]); + quat_mul_vec3(R[2], q, M[2]); + + R[3][0] = R[3][1] = R[3][2] = 0.f; + R[3][3] = 1.f; +} +static inline void quat_from_mat4x4(quat q, mat4x4 M) { + float r = 0.f; + int i; + + int perm[] = {0, 1, 2, 0, 1}; + int *p = perm; + + for (i = 0; i < 3; i++) { + float m = M[i][i]; + if (m < r) + continue; + m = r; + p = &perm[i]; + } + + r = sqrtf(1.f + M[p[0]][p[0]] - M[p[1]][p[1]] - M[p[2]][p[2]]); + + if (r < 1e-6) { + q[0] = 1.f; + q[1] = q[2] = q[3] = 0.f; + return; + } + + q[0] = r / 2.f; + q[1] = (M[p[0]][p[1]] - M[p[1]][p[0]]) / (2.f * r); + q[2] = (M[p[2]][p[0]] - M[p[0]][p[2]]) / (2.f * r); + q[3] = (M[p[2]][p[1]] - M[p[1]][p[2]]) / (2.f * r); } #endif diff --git a/demos/tri.c b/demos/tri.c index ec8e6e07..990a470e 100644 --- a/demos/tri.c +++ b/demos/tri.c @@ -1,24 +1,30 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. * - * Copyright (C) 2015 Valve Corporation + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. * * Author: Chia-I Wu <olvaffe@gmail.com> * Author: Cody Northrop <cody@lunarg.com> @@ -65,38 +71,40 @@ #endif #ifdef _WIN32 -#define ERR_EXIT(err_msg, err_class) \ - do { \ - MessageBox(NULL, err_msg, err_class, MB_OK); \ - exit(1); \ - } while (0) -#else // _WIN32 - -#define ERR_EXIT(err_msg, err_class) \ - do { \ - printf(err_msg); \ - fflush(stdout); \ - exit(1); \ - } while (0) +#define ERR_EXIT(err_msg, err_class) \ + do { \ + MessageBox(NULL, err_msg, err_class, MB_OK); \ + exit(1); \ + } while (0) +#else // _WIN32 + +#define ERR_EXIT(err_msg, err_class) \ + do { \ + printf(err_msg); \ + fflush(stdout); \ + exit(1); \ + } while (0) #endif // _WIN32 -#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \ -{ \ - demo->fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \ - if (demo->fp##entrypoint == NULL) { \ - ERR_EXIT("vkGetInstanceProcAddr failed to find vk"#entrypoint, \ - "vkGetInstanceProcAddr Failure"); \ - } \ -} +#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \ + { \ + demo->fp##entrypoint = \ + (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \ + if (demo->fp##entrypoint == NULL) { \ + ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, \ + "vkGetInstanceProcAddr Failure"); \ + } \ + } -#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ -{ \ - demo->fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint); \ - if (demo->fp##entrypoint == NULL) { \ - ERR_EXIT("vkGetDeviceProcAddr failed to find vk"#entrypoint, \ - "vkGetDeviceProcAddr Failure"); \ - } \ -} +#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ + { \ + demo->fp##entrypoint = \ + (PFN_vk##entrypoint)vkGetDeviceProcAddr(dev, "vk" #entrypoint); \ + if (demo->fp##entrypoint == NULL) { \ + ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, \ + "vkGetDeviceProcAddr Failure"); \ + } \ + } struct texture_object { VkSampler sampler; @@ -109,24 +117,20 @@ struct texture_object { int32_t tex_width, tex_height; }; -VKAPI_ATTR VkBool32 VKAPI_CALL dbgFunc( - VkFlags msgFlags, - VkDebugReportObjectTypeEXT objType, - uint64_t srcObject, - size_t location, - int32_t msgCode, - const char* pLayerPrefix, - const char* pMsg, - void* pUserData) -{ - char *message = (char *) malloc(strlen(pMsg)+100); +VKAPI_ATTR VkBool32 VKAPI_CALL +dbgFunc(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, + uint64_t srcObject, size_t location, int32_t msgCode, + const char *pLayerPrefix, const char *pMsg, void *pUserData) { + char *message = (char *)malloc(strlen(pMsg) + 100); - assert (message); + assert(message); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { - sprintf(message,"ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else if (msgFlags & VK_DEBUG_REPORT_WARN_BIT_EXT) { - sprintf(message,"WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else { return false; } @@ -134,7 +138,7 @@ VKAPI_ATTR VkBool32 VKAPI_CALL dbgFunc( #ifdef _WIN32 MessageBox(NULL, message, "Alert", MB_OK); #else - printf("%s\n",message); + printf("%s\n", message); fflush(stdout); #endif free(message); @@ -160,13 +164,13 @@ struct demo { #define APP_NAME_STR_LEN 80 HINSTANCE connection; // hInstance - Windows Instance char name[APP_NAME_STR_LEN]; // Name to put on the window/icon - HWND window; // hWnd - window handle -#else // _WIN32 + HWND window; // hWnd - window handle +#else // _WIN32 xcb_connection_t *connection; xcb_screen_t *screen; xcb_window_t window; xcb_intern_atom_reply_t *atom_wm_delete_window; -#endif // _WIN32 +#endif // _WIN32 VkSurfaceKHR surface; bool prepared; bool use_staging_buffer; @@ -186,15 +190,18 @@ struct demo { char *extension_names[64]; char *device_validation_layers[64]; - int width, height; VkFormat format; VkColorSpaceKHR color_space; - PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR; - PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR; - PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR; - PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR; + PFN_vkGetPhysicalDeviceSurfaceSupportKHR + fpGetPhysicalDeviceSurfaceSupportKHR; + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR + fpGetPhysicalDeviceSurfaceCapabilitiesKHR; + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR + fpGetPhysicalDeviceSurfaceFormatsKHR; + PFN_vkGetPhysicalDeviceSurfacePresentModesKHR + fpGetPhysicalDeviceSurfacePresentModesKHR; PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR; PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR; PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR; @@ -225,7 +232,7 @@ struct demo { VkVertexInputAttributeDescription vi_attrs[2]; } vertices; - VkCommandBuffer setup_cmd; // Command Buffer for initialization commands + VkCommandBuffer setup_cmd; // Command Buffer for initialization commands VkCommandBuffer draw_cmd; // Command Buffer for drawing commands VkPipelineLayout pipeline_layout; VkDescriptorSetLayout desc_layout; @@ -259,25 +266,26 @@ struct demo { // Forward declaration: static void demo_resize(struct demo *demo); -static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) -{ - // Search memtypes to find first index with those properties - for (uint32_t i = 0; i < 32; i++) { - if ((typeBits & 1) == 1) { - // Type is available, does it match user properties? - if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { - *typeIndex = i; - return true; - } - } - typeBits >>= 1; - } - // No memory types matched, return failure - return false; +static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, + VkFlags requirements_mask, + uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < 32; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((demo->memory_properties.memoryTypes[i].propertyFlags & + requirements_mask) == requirements_mask) { + *typeIndex = i; + return true; + } + } + typeBits >>= 1; + } + // No memory types matched, return failure + return false; } -static void demo_flush_init_cmd(struct demo *demo) -{ +static void demo_flush_init_cmd(struct demo *demo) { VkResult U_ASSERT_ONLY err; if (demo->setup_cmd == VK_NULL_HANDLE) @@ -286,19 +294,17 @@ static void demo_flush_init_cmd(struct demo *demo) err = vkEndCommandBuffer(demo->setup_cmd); assert(!err); - const VkCommandBuffer cmd_bufs[] = { demo->setup_cmd }; + const VkCommandBuffer cmd_bufs[] = {demo->setup_cmd}; VkFence nullFence = {VK_NULL_HANDLE}; - VkSubmitInfo submit_info = { - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .pNext = NULL, - .waitSemaphoreCount = 0, - .pWaitSemaphores = NULL, - .pWaitDstStageMask = NULL, - .commandBufferCount = 1, - .pCommandBuffers = cmd_bufs, - .signalSemaphoreCount = 0, - .pSignalSemaphores = NULL - }; + VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = NULL, + .waitSemaphoreCount = 0, + .pWaitSemaphores = NULL, + .pWaitDstStageMask = NULL, + .commandBufferCount = 1, + .pCommandBuffers = cmd_bufs, + .signalSemaphoreCount = 0, + .pSignalSemaphores = NULL}; err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence); assert(!err); @@ -310,13 +316,10 @@ static void demo_flush_init_cmd(struct demo *demo) demo->setup_cmd = VK_NULL_HANDLE; } -static void demo_set_image_layout( - struct demo *demo, - VkImage image, - VkImageAspectFlags aspectMask, - VkImageLayout old_image_layout, - VkImageLayout new_image_layout) -{ +static void demo_set_image_layout(struct demo *demo, VkImage image, + VkImageAspectFlags aspectMask, + VkImageLayout old_image_layout, + VkImageLayout new_image_layout) { VkResult U_ASSERT_ONLY err; if (demo->setup_cmd == VK_NULL_HANDLE) { @@ -359,8 +362,7 @@ static void demo_set_image_layout( .oldLayout = old_image_layout, .newLayout = new_image_layout, .image = image, - .subresourceRange = { aspectMask, 0, 1, 0, 1 } - }; + .subresourceRange = {aspectMask, 0, 1, 0, 1}}; if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { /* Make sure anything that was copying from this image has completed */ @@ -368,16 +370,19 @@ static void demo_set_image_layout( } if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { - image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - } + image_memory_barrier.dstAccessMask = + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + } if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { - image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + image_memory_barrier.dstAccessMask = + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; } if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { /* Make sure any Copy or CPU writes to image are flushed */ - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; + image_memory_barrier.dstAccessMask = + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; } VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier; @@ -385,21 +390,21 @@ static void demo_set_image_layout( VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - vkCmdPipelineBarrier(demo->setup_cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier); + vkCmdPipelineBarrier(demo->setup_cmd, src_stages, dest_stages, 0, 0, NULL, + 0, NULL, 1, pmemory_barrier); } -static void demo_draw_build_cmd(struct demo *demo) -{ - const VkCommandBufferInheritanceInfo cmd_buf_hinfo = { - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, - .pNext = NULL, - .renderPass = VK_NULL_HANDLE, - .subpass = 0, - .framebuffer = VK_NULL_HANDLE, - .occlusionQueryEnable = VK_FALSE, - .queryFlags = 0, - .pipelineStatistics = 0, - }; +static void demo_draw_build_cmd(struct demo *demo) { + const VkCommandBufferInheritanceInfo cmd_buf_hinfo = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, + .pNext = NULL, + .renderPass = VK_NULL_HANDLE, + .subpass = 0, + .framebuffer = VK_NULL_HANDLE, + .occlusionQueryEnable = VK_FALSE, + .queryFlags = 0, + .pipelineStatistics = 0, + }; const VkCommandBufferBeginInfo cmd_buf_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .pNext = NULL, @@ -407,8 +412,8 @@ static void demo_draw_build_cmd(struct demo *demo) .pInheritanceInfo = &cmd_buf_hinfo, }; const VkClearValue clear_values[2] = { - [0] = { .color.float32 = { 0.2f, 0.2f, 0.2f, 0.2f } }, - [1] = { .depthStencil = { demo->depthStencil, 0 } }, + [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}}, + [1] = {.depthStencil = {demo->depthStencil, 0}}, }; const VkRenderPassBeginInfo rp_begin = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, @@ -429,16 +434,17 @@ static void demo_draw_build_cmd(struct demo *demo) vkCmdBeginRenderPass(demo->draw_cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, - demo->pipeline); - vkCmdBindDescriptorSets(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, - 0, 1, & demo->desc_set, 0, NULL); + demo->pipeline); + vkCmdBindDescriptorSets(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, + demo->pipeline_layout, 0, 1, &demo->desc_set, 0, + NULL); VkViewport viewport; memset(&viewport, 0, sizeof(viewport)); - viewport.height = (float) demo->height; - viewport.width = (float) demo->width; - viewport.minDepth = (float) 0.0f; - viewport.maxDepth = (float) 1.0f; + viewport.height = (float)demo->height; + viewport.width = (float)demo->width; + viewport.minDepth = (float)0.0f; + viewport.maxDepth = (float)1.0f; vkCmdSetViewport(demo->draw_cmd, 0, 1, &viewport); VkRect2D scissor; @@ -450,7 +456,8 @@ static void demo_draw_build_cmd(struct demo *demo) vkCmdSetScissor(demo->draw_cmd, 0, 1, &scissor); VkDeviceSize offsets[1] = {0}; - vkCmdBindVertexBuffers(demo->draw_cmd, VERTEX_BUFFER_BIND_ID, 1, &demo->vertices.buf, offsets); + vkCmdBindVertexBuffers(demo->draw_cmd, VERTEX_BUFFER_BIND_ID, 1, + &demo->vertices.buf, offsets); vkCmdDraw(demo->draw_cmd, 3, 1, 0, 0); vkCmdEndRenderPass(demo->draw_cmd); @@ -464,20 +471,19 @@ static void demo_draw_build_cmd(struct demo *demo) .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } - }; + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; prePresentBarrier.image = demo->buffers[demo->current_buffer].image; VkImageMemoryBarrier *pmemory_barrier = &prePresentBarrier; - vkCmdPipelineBarrier(demo->draw_cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, pmemory_barrier); + vkCmdPipelineBarrier(demo->draw_cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, + NULL, 1, pmemory_barrier); err = vkEndCommandBuffer(demo->draw_cmd); assert(!err); } -static void demo_draw(struct demo *demo) -{ +static void demo_draw(struct demo *demo) { VkResult U_ASSERT_ONLY err; VkSemaphore presentCompleteSemaphore; VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo = { @@ -486,17 +492,14 @@ static void demo_draw(struct demo *demo) .flags = 0, }; - err = vkCreateSemaphore(demo->device, - &presentCompleteSemaphoreCreateInfo, - NULL, - &presentCompleteSemaphore); + err = vkCreateSemaphore(demo->device, &presentCompleteSemaphoreCreateInfo, + NULL, &presentCompleteSemaphore); assert(!err); // Get the index of the next available swapchain image: - err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, - UINT64_MAX, + err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX, presentCompleteSemaphore, - (VkFence)0,// TODO: Show use of fence + (VkFence)0, // TODO: Show use of fence &demo->current_buffer); if (err == VK_ERROR_OUT_OF_DATE_KHR) { // demo->swapchain is out of date (e.g. the window was resized) and @@ -515,9 +518,9 @@ static void demo_draw(struct demo *demo) // Assume the command buffer has been run on current_buffer before so // we need to set the image layout back to COLOR_ATTACHMENT_OPTIMAL demo_set_image_layout(demo, demo->buffers[demo->current_buffer].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); demo_flush_init_cmd(demo); // Wait for the present complete semaphore to be signaled to ensure @@ -525,21 +528,20 @@ static void demo_draw(struct demo *demo) // engine has fully released ownership to the application, and it is // okay to render to the image. -// FIXME/TODO: DEAL WITH VK_IMAGE_LAYOUT_PRESENT_SRC_KHR + // FIXME/TODO: DEAL WITH VK_IMAGE_LAYOUT_PRESENT_SRC_KHR demo_draw_build_cmd(demo); VkFence nullFence = VK_NULL_HANDLE; - VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - VkSubmitInfo submit_info = { - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .pNext = NULL, - .waitSemaphoreCount = 1, - .pWaitSemaphores = &presentCompleteSemaphore, - .pWaitDstStageMask = &pipe_stage_flags, - .commandBufferCount = 1, - .pCommandBuffers = &demo->draw_cmd, - .signalSemaphoreCount = 0, - .pSignalSemaphores = NULL - }; + VkPipelineStageFlags pipe_stage_flags = + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = NULL, + .waitSemaphoreCount = 1, + .pWaitSemaphores = &presentCompleteSemaphore, + .pWaitDstStageMask = &pipe_stage_flags, + .commandBufferCount = 1, + .pCommandBuffers = &demo->draw_cmd, + .signalSemaphoreCount = 0, + .pSignalSemaphores = NULL}; err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence); assert(!err); @@ -552,7 +554,7 @@ static void demo_draw(struct demo *demo) .pImageIndices = &demo->current_buffer, }; -// TBD/TODO: SHOULD THE "present" PARAMETER BE "const" IN THE HEADER? + // TBD/TODO: SHOULD THE "present" PARAMETER BE "const" IN THE HEADER? err = demo->fpQueuePresentKHR(demo->queue, &present); if (err == VK_ERROR_OUT_OF_DATE_KHR) { // demo->swapchain is out of date (e.g. the window was resized) and @@ -571,42 +573,35 @@ static void demo_draw(struct demo *demo) vkDestroySemaphore(demo->device, presentCompleteSemaphore, NULL); } -static void demo_prepare_buffers(struct demo *demo) -{ +static void demo_prepare_buffers(struct demo *demo) { VkResult U_ASSERT_ONLY err; VkSwapchainKHR oldSwapchain = demo->swapchain; // Check the surface capabilities and formats VkSurfaceCapabilitiesKHR surfCapabilities; - err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, - demo->surface, - &surfCapabilities); + err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR( + demo->gpu, demo->surface, &surfCapabilities); assert(!err); uint32_t presentModeCount; - err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, - demo->surface, - &presentModeCount, NULL); + err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( + demo->gpu, demo->surface, &presentModeCount, NULL); assert(!err); VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); assert(presentModes); - err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, - demo->surface, - &presentModeCount, presentModes); + err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( + demo->gpu, demo->surface, &presentModeCount, presentModes); assert(!err); VkExtent2D swapchainExtent; // width and height are either both -1, or both not -1. - if (surfCapabilities.currentExtent.width == (uint32_t) -1) - { + if (surfCapabilities.currentExtent.width == (uint32_t)-1) { // If the surface size is undefined, the size is set to // the size of the images requested. swapchainExtent.width = demo->width; swapchainExtent.height = demo->height; - } - else - { + } else { // If the surface size is defined, the swap chain size must match swapchainExtent = surfCapabilities.currentExtent; demo->width = surfCapabilities.currentExtent.width; @@ -618,16 +613,17 @@ static void demo_prepare_buffers(struct demo *demo) // Determine the number of VkImage's to use in the swap chain (we desire to // own only 1 image at a time, besides the images being displayed and // queued for display): - uint32_t desiredNumberOfSwapchainImages = surfCapabilities.minImageCount + 1; + uint32_t desiredNumberOfSwapchainImages = + surfCapabilities.minImageCount + 1; if ((surfCapabilities.maxImageCount > 0) && - (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount)) - { + (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount)) { // Application must settle for fewer images than desired: desiredNumberOfSwapchainImages = surfCapabilities.maxImageCount; } VkSurfaceTransformFlagsKHR preTransform; - if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { + if (surfCapabilities.supportedTransforms & + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; } else { preTransform = surfCapabilities.currentTransform; @@ -640,10 +636,10 @@ static void demo_prepare_buffers(struct demo *demo) .minImageCount = desiredNumberOfSwapchainImages, .imageFormat = demo->format, .imageColorSpace = demo->color_space, - .imageExtent = { - .width = swapchainExtent.width, - .height = swapchainExtent.height, - }, + .imageExtent = + { + .width = swapchainExtent.width, .height = swapchainExtent.height, + }, .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .preTransform = preTransform, .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, @@ -657,7 +653,8 @@ static void demo_prepare_buffers(struct demo *demo) }; uint32_t i; - err = demo->fpCreateSwapchainKHR(demo->device, &swapchain, NULL, &demo->swapchain); + err = demo->fpCreateSwapchainKHR(demo->device, &swapchain, NULL, + &demo->swapchain); assert(!err); // If we just re-created an existing swapchain, we should destroy the old @@ -672,15 +669,16 @@ static void demo_prepare_buffers(struct demo *demo) &demo->swapchainImageCount, NULL); assert(!err); - VkImage* swapchainImages = - (VkImage*)malloc(demo->swapchainImageCount * sizeof(VkImage)); + VkImage *swapchainImages = + (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage)); assert(swapchainImages); err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages); assert(!err); - demo->buffers = (SwapchainBuffers*)malloc(sizeof(SwapchainBuffers)*demo->swapchainImageCount); + demo->buffers = (SwapchainBuffers *)malloc(sizeof(SwapchainBuffers) * + demo->swapchainImageCount); assert(demo->buffers); for (i = 0; i < demo->swapchainImageCount; i++) { @@ -688,55 +686,54 @@ static void demo_prepare_buffers(struct demo *demo) .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .pNext = NULL, .format = demo->format, - .components = { - .r = VK_COMPONENT_SWIZZLE_R, - .g = VK_COMPONENT_SWIZZLE_G, - .b = VK_COMPONENT_SWIZZLE_B, - .a = VK_COMPONENT_SWIZZLE_A, - }, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1 - }, + .components = + { + .r = VK_COMPONENT_SWIZZLE_R, + .g = VK_COMPONENT_SWIZZLE_G, + .b = VK_COMPONENT_SWIZZLE_B, + .a = VK_COMPONENT_SWIZZLE_A, + }, + .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, .viewType = VK_IMAGE_VIEW_TYPE_2D, .flags = 0, }; demo->buffers[i].image = swapchainImages[i]; - // Render loop will expect image to have been used before and in VK_IMAGE_LAYOUT_PRESENT_SRC_KHR - // layout and will change to COLOR_ATTACHMENT_OPTIMAL, so init the image to that state - demo_set_image_layout(demo, demo->buffers[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); + // Render loop will expect image to have been used before and in + // VK_IMAGE_LAYOUT_PRESENT_SRC_KHR + // layout and will change to COLOR_ATTACHMENT_OPTIMAL, so init the image + // to that state + demo_set_image_layout( + demo, demo->buffers[i].image, VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); color_attachment_view.image = demo->buffers[i].image; - err = vkCreateImageView(demo->device, - &color_attachment_view, NULL, &demo->buffers[i].view); + err = vkCreateImageView(demo->device, &color_attachment_view, NULL, + &demo->buffers[i].view); assert(!err); } demo->current_buffer = 0; - + if (NULL != presentModes) { free(presentModes); } } -static void demo_prepare_depth(struct demo *demo) -{ +static void demo_prepare_depth(struct demo *demo) { const VkFormat depth_format = VK_FORMAT_D16_UNORM; const VkImageCreateInfo image = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = NULL, .imageType = VK_IMAGE_TYPE_2D, .format = depth_format, - .extent = { demo->width, demo->height, 1 }, + .extent = {demo->width, demo->height, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -755,13 +752,11 @@ static void demo_prepare_depth(struct demo *demo) .pNext = NULL, .image = VK_NULL_HANDLE, .format = depth_format, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1 - }, + .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, .flags = 0, .viewType = VK_IMAGE_VIEW_TYPE_2D, }; @@ -773,20 +768,17 @@ static void demo_prepare_depth(struct demo *demo) demo->depth.format = depth_format; /* create image */ - err = vkCreateImage(demo->device, &image, NULL, - &demo->depth.image); + err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image); assert(!err); /* get memory requirements for this object */ - vkGetImageMemoryRequirements(demo->device, demo->depth.image, - &mem_reqs); + vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs); /* select memory size and type */ mem_alloc.allocationSize = mem_reqs.size; - pass = memory_type_from_properties(demo, - mem_reqs.memoryTypeBits, - 0, /* No requirements */ - &mem_alloc.memoryTypeIndex); + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, + 0, /* No requirements */ + &mem_alloc.memoryTypeIndex); assert(pass); /* allocate memory */ @@ -794,14 +786,13 @@ static void demo_prepare_depth(struct demo *demo) assert(!err); /* bind memory */ - err = vkBindImageMemory(demo->device, demo->depth.image, - demo->depth.mem, 0); + err = + vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0); assert(!err); - demo_set_image_layout(demo, demo->depth.image, - VK_IMAGE_ASPECT_DEPTH_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + demo_set_image_layout(demo, demo->depth.image, VK_IMAGE_ASPECT_DEPTH_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); /* create image view */ view.image = demo->depth.image; @@ -809,13 +800,10 @@ static void demo_prepare_depth(struct demo *demo) assert(!err); } -static void demo_prepare_texture_image(struct demo *demo, - const uint32_t *tex_colors, - struct texture_object *tex_obj, - VkImageTiling tiling, - VkImageUsageFlags usage, - VkFlags required_props) -{ +static void +demo_prepare_texture_image(struct demo *demo, const uint32_t *tex_colors, + struct texture_object *tex_obj, VkImageTiling tiling, + VkImageUsageFlags usage, VkFlags required_props) { const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM; const int32_t tex_width = 2; const int32_t tex_height = 2; @@ -830,7 +818,7 @@ static void demo_prepare_texture_image(struct demo *demo, .pNext = NULL, .imageType = VK_IMAGE_TYPE_2D, .format = tex_format, - .extent = { tex_width, tex_height, 1 }, + .extent = {tex_width, tex_height, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -847,14 +835,16 @@ static void demo_prepare_texture_image(struct demo *demo, VkMemoryRequirements mem_reqs; - err = vkCreateImage(demo->device, &image_create_info, NULL, - &tex_obj->image); + err = + vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image); assert(!err); vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs); - mem_alloc.allocationSize = mem_reqs.size; - pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &mem_alloc.memoryTypeIndex); + mem_alloc.allocationSize = mem_reqs.size; + pass = + memory_type_from_properties(demo, mem_reqs.memoryTypeBits, + required_props, &mem_alloc.memoryTypeIndex); assert(pass); /* allocate memory */ @@ -862,8 +852,7 @@ static void demo_prepare_texture_image(struct demo *demo, assert(!err); /* bind memory */ - err = vkBindImageMemory(demo->device, tex_obj->image, - tex_obj->mem, 0); + err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0); assert(!err); if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { @@ -876,13 +865,15 @@ static void demo_prepare_texture_image(struct demo *demo, void *data; int32_t x, y; - vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout); + vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, + &layout); - err = vkMapMemory(demo->device, tex_obj->mem, 0, mem_alloc.allocationSize, 0, &data); + err = vkMapMemory(demo->device, tex_obj->mem, 0, + mem_alloc.allocationSize, 0, &data); assert(!err); for (y = 0; y < tex_height; y++) { - uint32_t *row = (uint32_t *) ((char *) data + layout.rowPitch * y); + uint32_t *row = (uint32_t *)((char *)data + layout.rowPitch * y); for (x = 0; x < tex_width; x++) row[x] = tex_colors[(x & 1) ^ (y & 1)]; } @@ -891,26 +882,24 @@ static void demo_prepare_texture_image(struct demo *demo, } tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - demo_set_image_layout(demo, tex_obj->image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - tex_obj->imageLayout); - /* setting the image layout does not reference the actual memory so no need to add a mem ref */ + demo_set_image_layout(demo, tex_obj->image, VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, tex_obj->imageLayout); + /* setting the image layout does not reference the actual memory so no need + * to add a mem ref */ } -static void demo_destroy_texture_image(struct demo *demo, struct texture_object *tex_obj) -{ +static void demo_destroy_texture_image(struct demo *demo, + struct texture_object *tex_obj) { /* clean up staging resources */ vkDestroyImage(demo->device, tex_obj->image, NULL); vkFreeMemory(demo->device, tex_obj->mem, NULL); } -static void demo_prepare_textures(struct demo *demo) -{ +static void demo_prepare_textures(struct demo *demo) { const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM; VkFormatProperties props; const uint32_t tex_colors[DEMO_TEXTURE_COUNT][2] = { - { 0xffff0000, 0xff00ff00 }, + {0xffff0000, 0xff00ff00}, }; uint32_t i; VkResult U_ASSERT_ONLY err; @@ -918,49 +907,58 @@ static void demo_prepare_textures(struct demo *demo) vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props); for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { - if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) { + if ((props.linearTilingFeatures & + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && + !demo->use_staging_buffer) { /* Device can texture using linear textures */ demo_prepare_texture_image(demo, tex_colors[i], &demo->textures[i], - VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); - } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT){ + VK_IMAGE_TILING_LINEAR, + VK_IMAGE_USAGE_SAMPLED_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); + } else if (props.optimalTilingFeatures & + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { /* Must use staging buffer to copy linear texture to optimized */ struct texture_object staging_texture; memset(&staging_texture, 0, sizeof(staging_texture)); demo_prepare_texture_image(demo, tex_colors[i], &staging_texture, - VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); + VK_IMAGE_TILING_LINEAR, + VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); - demo_prepare_texture_image(demo, tex_colors[i], &demo->textures[i], - VK_IMAGE_TILING_OPTIMAL, - (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + demo_prepare_texture_image( + demo, tex_colors[i], &demo->textures[i], + VK_IMAGE_TILING_OPTIMAL, + (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); demo_set_image_layout(demo, staging_texture.image, - VK_IMAGE_ASPECT_COLOR_BIT, - staging_texture.imageLayout, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + VK_IMAGE_ASPECT_COLOR_BIT, + staging_texture.imageLayout, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); demo_set_image_layout(demo, demo->textures[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - demo->textures[i].imageLayout, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + VK_IMAGE_ASPECT_COLOR_BIT, + demo->textures[i].imageLayout, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkImageCopy copy_region = { - .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, - .srcOffset = { 0, 0, 0 }, - .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, - .dstOffset = { 0, 0, 0 }, - .extent = { staging_texture.tex_width, staging_texture.tex_height, 1 }, + .srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffset = {0, 0, 0}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstOffset = {0, 0, 0}, + .extent = {staging_texture.tex_width, + staging_texture.tex_height, 1}, }; - vkCmdCopyImage(demo->setup_cmd, - staging_texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - demo->textures[i].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, ©_region); + vkCmdCopyImage( + demo->setup_cmd, staging_texture.image, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); demo_set_image_layout(demo, demo->textures[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - demo->textures[i].imageLayout); + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + demo->textures[i].imageLayout); demo_flush_init_cmd(demo); @@ -994,35 +992,37 @@ static void demo_prepare_textures(struct demo *demo) .image = VK_NULL_HANDLE, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = tex_format, - .components = { VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A, }, - .subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }, + .components = + { + VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, + VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, + }, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, .flags = 0, }; /* create sampler */ err = vkCreateSampler(demo->device, &sampler, NULL, - &demo->textures[i].sampler); + &demo->textures[i].sampler); assert(!err); /* create image view */ view.image = demo->textures[i].image; err = vkCreateImageView(demo->device, &view, NULL, - &demo->textures[i].view); + &demo->textures[i].view); assert(!err); } } -static void demo_prepare_vertices(struct demo *demo) -{ +static void demo_prepare_vertices(struct demo *demo) { + // clang-format off const float vb[3][5] = { /* position texcoord */ { -1.0f, -1.0f, 0.25f, 0.0f, 0.0f }, { 1.0f, -1.0f, 0.25f, 1.0f, 0.0f }, { 0.0f, 1.0f, 1.0f, 0.5f, 1.0f }, }; + // clang-format on const VkBufferCreateInfo buf_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = NULL, @@ -1046,21 +1046,20 @@ static void demo_prepare_vertices(struct demo *demo) err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->vertices.buf); assert(!err); - vkGetBufferMemoryRequirements(demo->device, - demo->vertices.buf, &mem_reqs); + vkGetBufferMemoryRequirements(demo->device, demo->vertices.buf, &mem_reqs); assert(!err); - mem_alloc.allocationSize = mem_reqs.size; - pass = memory_type_from_properties(demo, - mem_reqs.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, - &mem_alloc.memoryTypeIndex); + mem_alloc.allocationSize = mem_reqs.size; + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, + &mem_alloc.memoryTypeIndex); assert(pass); err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->vertices.mem); assert(!err); - err = vkMapMemory(demo->device, demo->vertices.mem, 0, mem_alloc.allocationSize, 0, &data); + err = vkMapMemory(demo->device, demo->vertices.mem, 0, + mem_alloc.allocationSize, 0, &data); assert(!err); memcpy(data, vb, sizeof(vb)); @@ -1068,10 +1067,11 @@ static void demo_prepare_vertices(struct demo *demo) vkUnmapMemory(demo->device, demo->vertices.mem); err = vkBindBufferMemory(demo->device, demo->vertices.buf, - demo->vertices.mem, 0); + demo->vertices.mem, 0); assert(!err); - demo->vertices.vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + demo->vertices.vi.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; demo->vertices.vi.pNext = NULL; demo->vertices.vi.vertexBindingDescriptionCount = 1; demo->vertices.vi.pVertexBindingDescriptions = demo->vertices.vi_bindings; @@ -1093,8 +1093,7 @@ static void demo_prepare_vertices(struct demo *demo) demo->vertices.vi_attrs[1].offset = sizeof(float) * 3; } -static void demo_prepare_descriptor_layout(struct demo *demo) -{ +static void demo_prepare_descriptor_layout(struct demo *demo) { const VkDescriptorSetLayoutBinding layout_binding = { .binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, @@ -1110,51 +1109,51 @@ static void demo_prepare_descriptor_layout(struct demo *demo) }; VkResult U_ASSERT_ONLY err; - err = vkCreateDescriptorSetLayout(demo->device, - &descriptor_layout, NULL, &demo->desc_layout); + err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, + &demo->desc_layout); assert(!err); const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = { - .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, - .pNext = NULL, + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .pNext = NULL, .setLayoutCount = 1, - .pSetLayouts = &demo->desc_layout, + .pSetLayouts = &demo->desc_layout, }; - err = vkCreatePipelineLayout(demo->device, - &pPipelineLayoutCreateInfo, - NULL, + err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout); assert(!err); } -static void demo_prepare_render_pass(struct demo *demo) -{ +static void demo_prepare_render_pass(struct demo *demo) { const VkAttachmentDescription attachments[2] = { - [0] = { - .format = demo->format, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - }, - [1] = { - .format = demo->depth.format, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - }, + [0] = + { + .format = demo->format, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + }, + [1] = + { + .format = demo->depth.format, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + .finalLayout = + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + }, }; const VkAttachmentReference color_reference = { - .attachment = 0, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }; const VkAttachmentReference depth_reference = { .attachment = 1, @@ -1188,10 +1187,8 @@ static void demo_prepare_render_pass(struct demo *demo) assert(!err); } -static VkShaderModule demo_prepare_shader_module(struct demo *demo, - const void *code, - size_t size) -{ +static VkShaderModule +demo_prepare_shader_module(struct demo *demo, const void *code, size_t size) { VkShaderModuleCreateInfo moduleCreateInfo; VkShaderModule module; VkResult U_ASSERT_ONLY err; @@ -1208,14 +1205,14 @@ static VkShaderModule demo_prepare_shader_module(struct demo *demo, return module; } -char *demo_read_spv(const char *filename, size_t *psize) -{ +char *demo_read_spv(const char *filename, size_t *psize) { long int size; void *shader_code; size_t retVal; FILE *fp = fopen(filename, "rb"); - if (!fp) return NULL; + if (!fp) + return NULL; fseek(fp, 0L, SEEK_END); size = ftell(fp); @@ -1224,7 +1221,8 @@ char *demo_read_spv(const char *filename, size_t *psize) shader_code = malloc(size); retVal = fread(shader_code, size, 1, fp); - if (!retVal) return NULL; + if (!retVal) + return NULL; *psize = size; @@ -1232,48 +1230,47 @@ char *demo_read_spv(const char *filename, size_t *psize) return shader_code; } -static VkShaderModule demo_prepare_vs(struct demo *demo) -{ +static VkShaderModule demo_prepare_vs(struct demo *demo) { void *vertShaderCode; size_t size; vertShaderCode = demo_read_spv("tri-vert.spv", &size); - demo->vert_shader_module = demo_prepare_shader_module(demo, vertShaderCode, size); + demo->vert_shader_module = + demo_prepare_shader_module(demo, vertShaderCode, size); free(vertShaderCode); return demo->vert_shader_module; } -static VkShaderModule demo_prepare_fs(struct demo *demo) -{ +static VkShaderModule demo_prepare_fs(struct demo *demo) { void *fragShaderCode; size_t size; fragShaderCode = demo_read_spv("tri-frag.spv", &size); - demo->frag_shader_module = demo_prepare_shader_module(demo, fragShaderCode, size); + demo->frag_shader_module = + demo_prepare_shader_module(demo, fragShaderCode, size); free(fragShaderCode); return demo->frag_shader_module; } -static void demo_prepare_pipeline(struct demo *demo) -{ +static void demo_prepare_pipeline(struct demo *demo) { VkGraphicsPipelineCreateInfo pipeline; VkPipelineCacheCreateInfo pipelineCache; - VkPipelineVertexInputStateCreateInfo vi; + VkPipelineVertexInputStateCreateInfo vi; VkPipelineInputAssemblyStateCreateInfo ia; - VkPipelineRasterizationStateCreateInfo rs; - VkPipelineColorBlendStateCreateInfo cb; - VkPipelineDepthStencilStateCreateInfo ds; - VkPipelineViewportStateCreateInfo vp; - VkPipelineMultisampleStateCreateInfo ms; - VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE]; - VkPipelineDynamicStateCreateInfo dynamicState; + VkPipelineRasterizationStateCreateInfo rs; + VkPipelineColorBlendStateCreateInfo cb; + VkPipelineDepthStencilStateCreateInfo ds; + VkPipelineViewportStateCreateInfo vp; + VkPipelineMultisampleStateCreateInfo ms; + VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE]; + VkPipelineDynamicStateCreateInfo dynamicState; VkResult U_ASSERT_ONLY err; @@ -1313,9 +1310,11 @@ static void demo_prepare_pipeline(struct demo *demo) memset(&vp, 0, sizeof(vp)); vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vp.viewportCount = 1; - dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT; + dynamicStateEnables[dynamicState.dynamicStateCount++] = + VK_DYNAMIC_STATE_VIEWPORT; vp.scissorCount = 1; - dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR; + dynamicStateEnables[dynamicState.dynamicStateCount++] = + VK_DYNAMIC_STATE_SCISSOR; memset(&ds, 0, sizeof(ds)); ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; @@ -1339,34 +1338,35 @@ static void demo_prepare_pipeline(struct demo *demo) VkPipelineShaderStageCreateInfo shaderStages[2]; memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo)); - shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = demo_prepare_vs(demo); - shaderStages[0].pName = "main"; + shaderStages[0].pName = "main"; - shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = demo_prepare_fs(demo); - shaderStages[1].pName = "main"; + shaderStages[1].pName = "main"; - pipeline.pVertexInputState = &vi; + pipeline.pVertexInputState = &vi; pipeline.pInputAssemblyState = &ia; - pipeline.pRasterizationState = &rs; - pipeline.pColorBlendState = &cb; - pipeline.pMultisampleState = &ms; - pipeline.pViewportState = &vp; - pipeline.pDepthStencilState = &ds; - pipeline.pStages = shaderStages; - pipeline.renderPass = demo->render_pass; - pipeline.pDynamicState = &dynamicState; + pipeline.pRasterizationState = &rs; + pipeline.pColorBlendState = &cb; + pipeline.pMultisampleState = &ms; + pipeline.pViewportState = &vp; + pipeline.pDepthStencilState = &ds; + pipeline.pStages = shaderStages; + pipeline.renderPass = demo->render_pass; + pipeline.pDynamicState = &dynamicState; memset(&pipelineCache, 0, sizeof(pipelineCache)); pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; - err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache); + err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, + &demo->pipelineCache); assert(!err); - err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, - 1, &pipeline, NULL, &demo->pipeline); + err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, + &pipeline, NULL, &demo->pipeline); assert(!err); vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL); @@ -1375,8 +1375,7 @@ static void demo_prepare_pipeline(struct demo *demo) vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL); } -static void demo_prepare_descriptor_pool(struct demo *demo) -{ +static void demo_prepare_descriptor_pool(struct demo *demo) { const VkDescriptorPoolSize type_count = { .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = DEMO_TEXTURE_COUNT, @@ -1390,13 +1389,12 @@ static void demo_prepare_descriptor_pool(struct demo *demo) }; VkResult U_ASSERT_ONLY err; - err = vkCreateDescriptorPool(demo->device, - &descriptor_pool, NULL, &demo->desc_pool); + err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, + &demo->desc_pool); assert(!err); } -static void demo_prepare_descriptor_set(struct demo *demo) -{ +static void demo_prepare_descriptor_set(struct demo *demo) { VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT]; VkWriteDescriptorSet write; VkResult U_ASSERT_ONLY err; @@ -1407,8 +1405,7 @@ static void demo_prepare_descriptor_set(struct demo *demo) .pNext = NULL, .descriptorPool = demo->desc_pool, .descriptorSetCount = 1, - .pSetLayouts = &demo->desc_layout - }; + .pSetLayouts = &demo->desc_layout}; err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->desc_set); assert(!err); @@ -1429,36 +1426,36 @@ static void demo_prepare_descriptor_set(struct demo *demo) vkUpdateDescriptorSets(demo->device, 1, &write, 0, NULL); } -static void demo_prepare_framebuffers(struct demo *demo) -{ +static void demo_prepare_framebuffers(struct demo *demo) { VkImageView attachments[2]; attachments[1] = demo->depth.view; const VkFramebufferCreateInfo fb_info = { - .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .pNext = NULL, - .renderPass = demo->render_pass, - .attachmentCount = 2, - .pAttachments = attachments, - .width = demo->width, - .height = demo->height, - .layers = 1, + .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .pNext = NULL, + .renderPass = demo->render_pass, + .attachmentCount = 2, + .pAttachments = attachments, + .width = demo->width, + .height = demo->height, + .layers = 1, }; VkResult U_ASSERT_ONLY err; uint32_t i; - demo->framebuffers = (VkFramebuffer *) malloc(demo->swapchainImageCount * sizeof(VkFramebuffer)); + demo->framebuffers = (VkFramebuffer *)malloc(demo->swapchainImageCount * + sizeof(VkFramebuffer)); assert(demo->framebuffers); for (i = 0; i < demo->swapchainImageCount; i++) { - attachments[0]= demo->buffers[i].view; - err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->framebuffers[i]); + attachments[0] = demo->buffers[i].view; + err = vkCreateFramebuffer(demo->device, &fb_info, NULL, + &demo->framebuffers[i]); assert(!err); } } -static void demo_prepare(struct demo *demo) -{ +static void demo_prepare(struct demo *demo) { VkResult U_ASSERT_ONLY err; const VkCommandPoolCreateInfo cmd_pool_info = { @@ -1467,7 +1464,8 @@ static void demo_prepare(struct demo *demo) .queueFamilyIndex = demo->graphics_queue_node_index, .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, }; - err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool); + err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, + &demo->cmd_pool); assert(!err); const VkCommandBufferAllocateInfo cmd = { @@ -1497,8 +1495,7 @@ static void demo_prepare(struct demo *demo) } #ifdef _WIN32 -static void demo_run(struct demo *demo) -{ +static void demo_run(struct demo *demo) { if (!demo->prepared) return; demo_draw(demo); @@ -1515,15 +1512,10 @@ static void demo_run(struct demo *demo) struct demo demo; // MS-Windows event handling function: -LRESULT CALLBACK WndProc(HWND hWnd, - UINT uMsg, - WPARAM wParam, - LPARAM lParam) -{ +LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { char tmp_str[] = APP_LONG_NAME; - switch(uMsg) - { + switch (uMsg) { case WM_CREATE: return 0; case WM_CLOSE: @@ -1545,9 +1537,8 @@ LRESULT CALLBACK WndProc(HWND hWnd, return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } -static void demo_create_window(struct demo *demo) -{ - WNDCLASSEX win_class; +static void demo_create_window(struct demo *demo) { + WNDCLASSEX win_class; // Initialize the window class structure: win_class.cbSize = sizeof(WNDCLASSEX); @@ -1570,21 +1561,20 @@ static void demo_create_window(struct demo *demo) exit(1); } // Create window with the registered class: - RECT wr = { 0, 0, demo->width, demo->height }; + RECT wr = {0, 0, demo->width, demo->height}; AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); demo->window = CreateWindowEx(0, demo->name, // class name demo->name, // app name WS_OVERLAPPEDWINDOW | // window style - WS_VISIBLE | - WS_SYSMENU, - 100,100, // x/y coords - wr.right-wr.left, // width - wr.bottom-wr.top, // height - NULL, // handle to parent - NULL, // handle to menu - demo->connection, // hInstance - NULL); // no extra parameters + WS_VISIBLE | WS_SYSMENU, + 100, 100, // x/y coords + wr.right - wr.left, // width + wr.bottom - wr.top, // height + NULL, // handle to parent + NULL, // handle to menu + demo->connection, // hInstance + NULL); // no extra parameters if (!demo->window) { // It didn't work, so try to give a useful error: printf("Cannot create a window in which to draw!\n"); @@ -1595,46 +1585,40 @@ static void demo_create_window(struct demo *demo) #else // _WIN32 static void demo_handle_event(struct demo *demo, - const xcb_generic_event_t *event) -{ + const xcb_generic_event_t *event) { switch (event->response_type & 0x7f) { case XCB_EXPOSE: demo_draw(demo); break; case XCB_CLIENT_MESSAGE: - if((*(xcb_client_message_event_t*)event).data.data32[0] == - (*demo->atom_wm_delete_window).atom) { + if ((*(xcb_client_message_event_t *)event).data.data32[0] == + (*demo->atom_wm_delete_window).atom) { demo->quit = true; } break; - case XCB_KEY_RELEASE: - { - const xcb_key_release_event_t *key = - (const xcb_key_release_event_t *) event; + case XCB_KEY_RELEASE: { + const xcb_key_release_event_t *key = + (const xcb_key_release_event_t *)event; - if (key->detail == 0x9) - demo->quit = true; - } - break; + if (key->detail == 0x9) + demo->quit = true; + } break; case XCB_DESTROY_NOTIFY: demo->quit = true; break; - case XCB_CONFIGURE_NOTIFY: - { - const xcb_configure_notify_event_t *cfg = - (const xcb_configure_notify_event_t *) event; - if ((demo->width != cfg->width) || (demo->height != cfg->height)) { - demo_resize(demo); - } + case XCB_CONFIGURE_NOTIFY: { + const xcb_configure_notify_event_t *cfg = + (const xcb_configure_notify_event_t *)event; + if ((demo->width != cfg->width) || (demo->height != cfg->height)) { + demo_resize(demo); } - break; + } break; default: break; } } -static void demo_run(struct demo *demo) -{ +static void demo_run(struct demo *demo) { xcb_flush(demo->connection); while (!demo->quit) { @@ -1660,36 +1644,34 @@ static void demo_run(struct demo *demo) } } -static void demo_create_window(struct demo *demo) -{ +static void demo_create_window(struct demo *demo) { uint32_t value_mask, value_list[32]; demo->window = xcb_generate_id(demo->connection); value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; value_list[0] = demo->screen->black_pixel; - value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | - XCB_EVENT_MASK_EXPOSURE | + value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY; - xcb_create_window(demo->connection, - XCB_COPY_FROM_PARENT, - demo->window, demo->screen->root, - 0, 0, demo->width, demo->height, 0, - XCB_WINDOW_CLASS_INPUT_OUTPUT, - demo->screen->root_visual, - value_mask, value_list); + xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->window, + demo->screen->root, 0, 0, demo->width, demo->height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, + value_mask, value_list); /* Magic code that will send notification when window is destroyed */ - xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, - "WM_PROTOCOLS"); - xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(demo->connection, cookie, 0); - - xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); - demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0); - - xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, - demo->window, (*reply).atom, 4, 32, 1, + xcb_intern_atom_cookie_t cookie = + xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS"); + xcb_intern_atom_reply_t *reply = + xcb_intern_atom_reply(demo->connection, cookie, 0); + + xcb_intern_atom_cookie_t cookie2 = + xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); + demo->atom_wm_delete_window = + xcb_intern_atom_reply(demo->connection, cookie2, 0); + + xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->window, + (*reply).atom, 4, 32, 1, &(*demo->atom_wm_delete_window).atom); free(reply); @@ -1702,8 +1684,8 @@ static void demo_create_window(struct demo *demo) * can be found in given layer properties. */ static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, - uint32_t layer_count, VkLayerProperties *layers) -{ + uint32_t layer_count, + VkLayerProperties *layers) { for (uint32_t i = 0; i < check_count; i++) { VkBool32 found = 0; for (uint32_t j = 0; j < layer_count; j++) { @@ -1719,22 +1701,15 @@ static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, return 1; } -VKAPI_ATTR void* VKAPI_CALL myrealloc( - void* pUserData, - void* pOriginal, - size_t size, - size_t alignment, - VkSystemAllocationScope allocationScope) -{ +VKAPI_ATTR void *VKAPI_CALL myrealloc(void *pUserData, void *pOriginal, + size_t size, size_t alignment, + VkSystemAllocationScope allocationScope) { return realloc(pOriginal, size); } -VKAPI_ATTR void* VKAPI_CALL myalloc( - void* pUserData, - size_t size, - size_t alignment, - VkSystemAllocationScope allocationScope) -{ +VKAPI_ATTR void *VKAPI_CALL myalloc(void *pUserData, size_t size, + size_t alignment, + VkSystemAllocationScope allocationScope) { #ifdef _MSC_VER return _aligned_malloc(size, alignment); #else @@ -1742,10 +1717,7 @@ VKAPI_ATTR void* VKAPI_CALL myalloc( #endif } -VKAPI_ATTR void VKAPI_CALL myfree( - void* pUserData, - void* pMemory) -{ +VKAPI_ATTR void VKAPI_CALL myfree(void *pUserData, void *pMemory) { #ifdef _MSC_VER _aligned_free(pMemory); #else @@ -1753,8 +1725,7 @@ VKAPI_ATTR void VKAPI_CALL myfree( #endif } -static void demo_init_vk(struct demo *demo) -{ +static void demo_init_vk(struct demo *demo) { VkResult err; VkExtensionProperties *instance_extensions; VkPhysicalDevice *physical_devices; @@ -1779,12 +1750,14 @@ static void demo_init_vk(struct demo *demo) assert(!err); instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count); - err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers); + err = vkEnumerateInstanceLayerProperties(&instance_layer_count, + instance_layers); assert(!err); if (demo->validate) { - validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers, - instance_layer_count, instance_layers); + validation_found = demo_check_layers( + ARRAY_SIZE(instance_validation_layers), instance_validation_layers, + instance_layer_count, instance_layers); if (!validation_found) { ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find" "required validation layer.\n\n" @@ -1795,41 +1768,53 @@ static void demo_init_vk(struct demo *demo) demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers); } - err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL); + err = vkEnumerateInstanceExtensionProperties( + NULL, &instance_extension_count, NULL); assert(!err); VkBool32 surfaceExtFound = 0; VkBool32 platformSurfaceExtFound = 0; memset(demo->extension_names, 0, sizeof(demo->extension_names)); - instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count); - err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions); + instance_extensions = + malloc(sizeof(VkExtensionProperties) * instance_extension_count); + err = vkEnumerateInstanceExtensionProperties( + NULL, &instance_extension_count, instance_extensions); assert(!err); for (uint32_t i = 0; i < instance_extension_count; i++) { - if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, + instance_extensions[i].extensionName)) { surfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = + VK_KHR_SURFACE_EXTENSION_NAME; } #ifdef _WIN32 - if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, + instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = + VK_KHR_WIN32_SURFACE_EXTENSION_NAME; } #else // _WIN32 - if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, + instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = + VK_KHR_XCB_SURFACE_EXTENSION_NAME; } #endif // _WIN32 - if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instance_extensions[i].extensionName)) { + if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, + instance_extensions[i].extensionName)) { if (demo->validate) { - demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_REPORT_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = + VK_EXT_DEBUG_REPORT_EXTENSION_NAME; } } assert(demo->enabled_extension_count < 64); } if (!surfaceExtFound) { - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_KHR_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " + "the " VK_KHR_SURFACE_EXTENSION_NAME + " extension.\n\nDo you have a compatible " "Vulkan installable client driver (ICD) installed?\nPlease " "look at the Getting Started guide for additional " "information.\n", @@ -1837,19 +1822,21 @@ static void demo_init_vk(struct demo *demo) } if (!platformSurfaceExtFound) { #ifdef _WIN32 - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_KHR_WIN32_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " + "the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME + " extension.\n\nDo you have a compatible " + "Vulkan installable client driver (ICD) installed?\nPlease " + "look at the Getting Started guide for additional " + "information.\n", + "vkCreateInstance Failure"); #else // _WIN32 - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_KHR_XCB_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " + "the " VK_KHR_XCB_SURFACE_EXTENSION_NAME + " extension.\n\nDo you have a compatible " + "Vulkan installable client driver (ICD) installed?\nPlease " + "look at the Getting Started guide for additional " + "information.\n", + "vkCreateInstance Failure"); #endif // _WIN32 } const VkApplicationInfo app = { @@ -1866,9 +1853,9 @@ static void demo_init_vk(struct demo *demo) .pNext = NULL, .pApplicationInfo = &app, .enabledLayerCount = demo->enabled_layer_count, - .ppEnabledLayerNames = (const char *const*) instance_validation_layers, + .ppEnabledLayerNames = (const char *const *)instance_validation_layers, .enabledExtensionCount = demo->enabled_extension_count, - .ppEnabledExtensionNames = (const char *const*) demo->extension_names, + .ppEnabledExtensionNames = (const char *const *)demo->extension_names, }; uint32_t gpu_count; @@ -1911,15 +1898,18 @@ static void demo_init_vk(struct demo *demo) validation_found = 0; demo->enabled_layer_count = 0; uint32_t device_layer_count = 0; - err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, NULL); + err = + vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, NULL); assert(!err); device_layers = malloc(sizeof(VkLayerProperties) * device_layer_count); - err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, device_layers); + err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, + device_layers); assert(!err); if (demo->validate) { - validation_found = demo_check_layers(device_validation_layer_count, demo->device_validation_layers, + validation_found = demo_check_layers(device_validation_layer_count, + demo->device_validation_layers, device_layer_count, device_layers); if (!validation_found) { ERR_EXIT("vkEnumerateDeviceLayerProperties failed to find " @@ -1933,28 +1923,32 @@ static void demo_init_vk(struct demo *demo) uint32_t device_extension_count = 0; VkExtensionProperties *device_extensions = NULL; - err = vkEnumerateDeviceExtensionProperties( - demo->gpu, NULL, &device_extension_count, NULL); + err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, + &device_extension_count, NULL); assert(!err); VkBool32 swapchainExtFound = 0; demo->enabled_extension_count = 0; memset(demo->extension_names, 0, sizeof(demo->extension_names)); - device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count); + device_extensions = + malloc(sizeof(VkExtensionProperties) * device_extension_count); err = vkEnumerateDeviceExtensionProperties( - demo->gpu, NULL, &device_extension_count, device_extensions); + demo->gpu, NULL, &device_extension_count, device_extensions); assert(!err); for (uint32_t i = 0; i < device_extension_count; i++) { - if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, + device_extensions[i].extensionName)) { swapchainExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = + VK_KHR_SWAPCHAIN_EXTENSION_NAME; } assert(demo->enabled_extension_count < 64); } if (!swapchainExtFound) { - ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " - VK_KHR_SWAPCHAIN_EXTENSION_NAME" extension.\n\nDo you have a compatible " + ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find " + "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME + " extension.\n\nDo you have a compatible " "Vulkan installable client driver (ICD) installed?\nPlease " "look at the Getting Started guide for additional " "information.\n", @@ -1962,22 +1956,23 @@ static void demo_init_vk(struct demo *demo) } if (demo->validate) { - demo->CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(demo->inst, "vkCreateDebugReportCallbackEXT"); + demo->CreateDebugReportCallback = + (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr( + demo->inst, "vkCreateDebugReportCallbackEXT"); if (!demo->CreateDebugReportCallback) { - ERR_EXIT("GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", - "vkGetProcAddr Failure"); + ERR_EXIT( + "GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", + "vkGetProcAddr Failure"); } VkDebugReportCallbackCreateInfoEXT dbgCreateInfo; dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; - dbgCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARN_BIT_EXT; + dbgCreateInfo.flags = + VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARN_BIT_EXT; dbgCreateInfo.pfnCallback = dbgFunc; dbgCreateInfo.pUserData = NULL; dbgCreateInfo.pNext = NULL; - err = demo->CreateDebugReportCallback( - demo->inst, - &dbgCreateInfo, - NULL, - &demo->msg_callback); + err = demo->CreateDebugReportCallback(demo->inst, &dbgCreateInfo, NULL, + &demo->msg_callback); switch (err) { case VK_SUCCESS: break; @@ -2007,10 +2002,13 @@ static void demo_init_vk(struct demo *demo) vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props); // Query with NULL data to get count - vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, NULL); + vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, + NULL); - demo->queue_props = (VkQueueFamilyProperties *) malloc(demo->queue_count * sizeof(VkQueueFamilyProperties)); - vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, demo->queue_props); + demo->queue_props = (VkQueueFamilyProperties *)malloc( + demo->queue_count * sizeof(VkQueueFamilyProperties)); + vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, + demo->queue_props); assert(demo->queue_count >= 1); // Graphics queue and MemMgr queue can be separate. @@ -2018,18 +2016,16 @@ static void demo_init_vk(struct demo *demo) // and appropriate tracking for QueueSubmit } -static void demo_init_device(struct demo *demo) -{ +static void demo_init_device(struct demo *demo) { VkResult U_ASSERT_ONLY err; - float queue_priorities[1] = { 0.0 }; + float queue_priorities[1] = {0.0}; const VkDeviceQueueCreateInfo queue = { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .pNext = NULL, .queueFamilyIndex = demo->graphics_queue_node_index, .queueCount = 1, - .pQueuePriorities = queue_priorities - }; + .pQueuePriorities = queue_priorities}; VkDeviceCreateInfo device = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, @@ -2037,21 +2033,23 @@ static void demo_init_device(struct demo *demo) .queueCreateInfoCount = 1, .pQueueCreateInfos = &queue, .enabledLayerCount = demo->enabled_layer_count, - .ppEnabledLayerNames = (const char *const*) ((demo->validate) ? demo->device_validation_layers : NULL), + .ppEnabledLayerNames = + (const char *const *)((demo->validate) + ? demo->device_validation_layers + : NULL), .enabledExtensionCount = demo->enabled_extension_count, - .ppEnabledExtensionNames = (const char *const*) demo->extension_names, + .ppEnabledExtensionNames = (const char *const *)demo->extension_names, }; err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device); assert(!err); } -static void demo_init_vk_swapchain(struct demo *demo) -{ +static void demo_init_vk_swapchain(struct demo *demo) { VkResult U_ASSERT_ONLY err; uint32_t i; - // Create a WSI surface for the window: +// Create a WSI surface for the window: #ifdef _WIN32 VkWin32SurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; @@ -2060,8 +2058,8 @@ static void demo_init_vk_swapchain(struct demo *demo) createInfo.hinstance = demo->connection; createInfo.hwnd = demo->window; - err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, - NULL, &demo->surface); + err = + vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #else // _WIN32 VkXcbSurfaceCreateInfoKHR createInfo; @@ -2071,28 +2069,27 @@ static void demo_init_vk_swapchain(struct demo *demo) createInfo.connection = demo->connection; createInfo.window = demo->window; - err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, - NULL, &demo->surface); + err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #endif // _WIN32 // Iterate over each queue to learn whether it supports presenting: - VkBool32* supportsPresent = (VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32)); + VkBool32 *supportsPresent = + (VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32)); for (i = 0; i < demo->queue_count; i++) { - demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, - demo->surface, + demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]); } // Search for a graphics and a present queue in the array of queue // families, try to find one that supports both uint32_t graphicsQueueNodeIndex = UINT32_MAX; - uint32_t presentQueueNodeIndex = UINT32_MAX; + uint32_t presentQueueNodeIndex = UINT32_MAX; for (i = 0; i < demo->queue_count; i++) { if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { if (graphicsQueueNodeIndex == UINT32_MAX) { graphicsQueueNodeIndex = i; } - + if (supportsPresent[i] == VK_TRUE) { graphicsQueueNodeIndex = i; presentQueueNodeIndex = i; @@ -2113,7 +2110,8 @@ static void demo_init_vk_swapchain(struct demo *demo) free(supportsPresent); // Generate error if could not find both a graphics and a present queue - if (graphicsQueueNodeIndex == UINT32_MAX || presentQueueNodeIndex == UINT32_MAX) { + if (graphicsQueueNodeIndex == UINT32_MAX || + presentQueueNodeIndex == UINT32_MAX) { ERR_EXIT("Could not find a graphics and a present queue\n", "Swapchain Initialization Failure"); } @@ -2132,30 +2130,25 @@ static void demo_init_vk_swapchain(struct demo *demo) demo_init_device(demo); - vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, - 0, &demo->queue); + vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, 0, + &demo->queue); // Get the list of VkFormat's that are supported: uint32_t formatCount; - err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, - demo->surface, + err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL); assert(!err); VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); - err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, - demo->surface, + err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats); assert(!err); // If the format list includes just one entry of VK_FORMAT_UNDEFINED, // the surface has no preferred format. Otherwise, at least one // supported format will be returned. - if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) - { + if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { demo->format = VK_FORMAT_B8G8R8A8_UNORM; - } - else - { + } else { assert(formatCount >= 1); demo->format = surfFormats[0].format; } @@ -2165,8 +2158,7 @@ static void demo_init_vk_swapchain(struct demo *demo) vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties); } -static void demo_init_connection(struct demo *demo) -{ +static void demo_init_connection(struct demo *demo) { #ifndef _WIN32 const xcb_setup_t *setup; xcb_screen_iterator_t iter; @@ -2230,8 +2222,7 @@ static void demo_init(struct demo *demo, const int argc, const char *argv[]) demo->depthIncrement = -0.01f; } -static void demo_cleanup(struct demo *demo) -{ +static void demo_cleanup(struct demo *demo) { uint32_t i; demo->prepared = false; @@ -2287,8 +2278,7 @@ static void demo_cleanup(struct demo *demo) #endif // _WIN32 } -static void demo_resize(struct demo *demo) -{ +static void demo_resize(struct demo *demo) { uint32_t i; // Don't react to resize until after first initialization. @@ -2344,13 +2334,10 @@ static void demo_resize(struct demo *demo) } #ifdef _WIN32 -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR pCmdLine, - int nCmdShow) -{ - MSG msg; // message - bool done; // flag saying when app is complete +int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, + LPSTR pCmdLine, int nCmdShow) { + MSG msg; // message + bool done; // flag saying when app is complete demo_init(&demo, hInstance, pCmdLine); demo_create_window(&demo); @@ -2358,19 +2345,16 @@ int APIENTRY WinMain(HINSTANCE hInstance, demo_prepare(&demo); - done = false; //initialize loop condition variable + done = false; // initialize loop condition variable /* main message loop*/ - while(!done) - { + while (!done) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); - if (msg.message == WM_QUIT) //check for a quit message - { - done = true; //if found, quit app - } - else + if (msg.message == WM_QUIT) // check for a quit message { + done = true; // if found, quit app + } else { /* Translate and dispatch to event queue*/ - TranslateMessage(&msg); + TranslateMessage(&msg); DispatchMessage(&msg); } RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT); @@ -2378,11 +2362,10 @@ int APIENTRY WinMain(HINSTANCE hInstance, demo_cleanup(&demo); - return (int) msg.wParam; + return (int)msg.wParam; } #else // _WIN32 -int main(const int argc, const char *argv[]) -{ +int main(const int argc, const char *argv[]) { struct demo demo; demo_init(&demo, argc, argv); diff --git a/demos/tri.frag b/demos/tri.frag index 564abe88..02fd0ee9 100644 --- a/demos/tri.frag +++ b/demos/tri.frag @@ -1,4 +1,32 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: + * + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. + * + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. + */ +/* * Fragment shader for tri demo */ #version 400 diff --git a/demos/tri.vert b/demos/tri.vert index 2d731395..7fc5a217 100644 --- a/demos/tri.vert +++ b/demos/tri.vert @@ -1,4 +1,32 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: + * + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. + * + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. + */ +/* * Vertex shader used by tri demo. */ #version 400 diff --git a/demos/vulkaninfo.c b/demos/vulkaninfo.c index 8b13ab4d..983288c1 100644 --- a/demos/vulkaninfo.c +++ b/demos/vulkaninfo.c @@ -1,25 +1,30 @@ /* + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. * - * Copyright (C) 2015 Valve Corporation - * Copyright (C) 2015 Google Inc. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. + * The Materials are Confidential Information as defined by the Khronos + * Membership Agreement until designated non-confidential by Khronos, at which + * point this condition clause shall be removed. * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. * * Author: Courtney Goeltzenleuchter <courtney@LunarG.com> * Author: David Pinedo <david@lunarg.com> @@ -37,12 +42,12 @@ #include <io.h> #endif // _WIN32 - #include <vulkan/vulkan.h> #include <vulkan/vk_ext_debug_report.h> -#define ERR(err) printf("%s:%d: failed with %s\n", \ - __FILE__, __LINE__, vk_result_string(err)); +#define ERR(err) \ + printf("%s:%d: failed with %s\n", __FILE__, __LINE__, \ + vk_result_string(err)); #ifdef _WIN32 @@ -50,23 +55,22 @@ bool consoleCreated = false; -#define WAIT_FOR_CONSOLE_DESTROY \ - do { \ - if (consoleCreated) \ - Sleep(INFINITE); \ +#define WAIT_FOR_CONSOLE_DESTROY \ + do { \ + if (consoleCreated) \ + Sleep(INFINITE); \ } while (0) #else - #define WAIT_FOR_CONSOLE_DESTROY +#define WAIT_FOR_CONSOLE_DESTROY #endif - -#define ERR_EXIT(err) \ - do { \ - ERR(err); \ - fflush(stdout); \ - WAIT_FOR_CONSOLE_DESTROY; \ - exit(-1); \ - } while (0) +#define ERR_EXIT(err) \ + do { \ + ERR(err); \ + fflush(stdout); \ + WAIT_FOR_CONSOLE_DESTROY; \ + exit(-1); \ + } while (0) #if defined(NDEBUG) && defined(__GNUC__) #define U_ASSERT_ONLY __attribute__((unused)) @@ -88,7 +92,6 @@ struct app_dev { VkDevice obj; - VkFormatProperties format_props[VK_FORMAT_RANGE_SIZE]; }; @@ -99,7 +102,7 @@ struct layer_extension_list { }; struct app_instance { - VkInstance instance; + VkInstance instance; uint32_t global_layer_count; struct layer_extension_list *global_layers; uint32_t global_extension_count; @@ -129,32 +132,29 @@ struct app_gpu { struct app_dev dev; }; -static VKAPI_ATTR VkBool32 VKAPI_CALL dbg_callback( - VkFlags msgFlags, - VkDebugReportObjectTypeEXT objType, - uint64_t srcObject, - size_t location, - int32_t msgCode, - const char* pLayerPrefix, - const char* pMsg, - void* pUserData) -{ - char *message = (char *) malloc(strlen(pMsg)+100); +static VKAPI_ATTR VkBool32 VKAPI_CALL +dbg_callback(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, + uint64_t srcObject, size_t location, int32_t msgCode, + const char *pLayerPrefix, const char *pMsg, void *pUserData) { + char *message = (char *)malloc(strlen(pMsg) + 100); - assert (message); + assert(message); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { - sprintf(message,"ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else if (msgFlags & VK_DEBUG_REPORT_WARN_BIT_EXT) { - sprintf(message,"WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else if (msgFlags & VK_DEBUG_REPORT_INFO_BIT_EXT) { - sprintf(message,"INFO: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "INFO: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { - sprintf(message,"DEBUG: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg); + sprintf(message, "DEBUG: [%s] Code %d : %s", pLayerPrefix, msgCode, + pMsg); } - - printf("%s\n",message); + printf("%s\n", message); fflush(stdout); free(message); @@ -168,268 +168,273 @@ static VKAPI_ATTR VkBool32 VKAPI_CALL dbg_callback( return false; } -static const char *vk_result_string(VkResult err) -{ +static const char *vk_result_string(VkResult err) { switch (err) { -#define STR(r) case r: return #r - STR(VK_SUCCESS); - STR(VK_NOT_READY); - STR(VK_TIMEOUT); - STR(VK_EVENT_SET); - STR(VK_EVENT_RESET); - STR(VK_ERROR_INITIALIZATION_FAILED); - STR(VK_ERROR_OUT_OF_HOST_MEMORY); - STR(VK_ERROR_OUT_OF_DEVICE_MEMORY); - STR(VK_ERROR_DEVICE_LOST); - STR(VK_ERROR_LAYER_NOT_PRESENT); - STR(VK_ERROR_EXTENSION_NOT_PRESENT); - STR(VK_ERROR_MEMORY_MAP_FAILED); - STR(VK_ERROR_INCOMPATIBLE_DRIVER); +#define STR(r) \ + case r: \ + return #r + STR(VK_SUCCESS); + STR(VK_NOT_READY); + STR(VK_TIMEOUT); + STR(VK_EVENT_SET); + STR(VK_EVENT_RESET); + STR(VK_ERROR_INITIALIZATION_FAILED); + STR(VK_ERROR_OUT_OF_HOST_MEMORY); + STR(VK_ERROR_OUT_OF_DEVICE_MEMORY); + STR(VK_ERROR_DEVICE_LOST); + STR(VK_ERROR_LAYER_NOT_PRESENT); + STR(VK_ERROR_EXTENSION_NOT_PRESENT); + STR(VK_ERROR_MEMORY_MAP_FAILED); + STR(VK_ERROR_INCOMPATIBLE_DRIVER); #undef STR - default: return "UNKNOWN_RESULT"; + default: + return "UNKNOWN_RESULT"; } } -static const char *vk_physical_device_type_string(VkPhysicalDeviceType type) -{ +static const char *vk_physical_device_type_string(VkPhysicalDeviceType type) { switch (type) { -#define STR(r) case VK_PHYSICAL_DEVICE_TYPE_ ##r: return #r - STR(OTHER); - STR(INTEGRATED_GPU); - STR(DISCRETE_GPU); - STR(VIRTUAL_GPU); +#define STR(r) \ + case VK_PHYSICAL_DEVICE_TYPE_##r: \ + return #r + STR(OTHER); + STR(INTEGRATED_GPU); + STR(DISCRETE_GPU); + STR(VIRTUAL_GPU); #undef STR - default: return "UNKNOWN_DEVICE"; + default: + return "UNKNOWN_DEVICE"; } } -static const char *vk_format_string(VkFormat fmt) -{ +static const char *vk_format_string(VkFormat fmt) { switch (fmt) { -#define STR(r) case VK_FORMAT_ ##r: return #r - STR(UNDEFINED); - STR(R4G4_UNORM_PACK8); - STR(R4G4B4A4_UNORM_PACK16); - STR(B4G4R4A4_UNORM_PACK16); - STR(R5G6B5_UNORM_PACK16); - STR(B5G6R5_UNORM_PACK16); - STR(R5G5B5A1_UNORM_PACK16); - STR(B5G5R5A1_UNORM_PACK16); - STR(A1R5G5B5_UNORM_PACK16); - STR(R8_UNORM); - STR(R8_SNORM); - STR(R8_USCALED); - STR(R8_SSCALED); - STR(R8_UINT); - STR(R8_SINT); - STR(R8_SRGB); - STR(R8G8_UNORM); - STR(R8G8_SNORM); - STR(R8G8_USCALED); - STR(R8G8_SSCALED); - STR(R8G8_UINT); - STR(R8G8_SINT); - STR(R8G8_SRGB); - STR(R8G8B8_UNORM); - STR(R8G8B8_SNORM); - STR(R8G8B8_USCALED); - STR(R8G8B8_SSCALED); - STR(R8G8B8_UINT); - STR(R8G8B8_SINT); - STR(R8G8B8_SRGB); - STR(B8G8R8_UNORM); - STR(B8G8R8_SNORM); - STR(B8G8R8_USCALED); - STR(B8G8R8_SSCALED); - STR(B8G8R8_UINT); - STR(B8G8R8_SINT); - STR(B8G8R8_SRGB); - STR(R8G8B8A8_UNORM); - STR(R8G8B8A8_SNORM); - STR(R8G8B8A8_USCALED); - STR(R8G8B8A8_SSCALED); - STR(R8G8B8A8_UINT); - STR(R8G8B8A8_SINT); - STR(R8G8B8A8_SRGB); - STR(B8G8R8A8_UNORM); - STR(B8G8R8A8_SNORM); - STR(B8G8R8A8_USCALED); - STR(B8G8R8A8_SSCALED); - STR(B8G8R8A8_UINT); - STR(B8G8R8A8_SINT); - STR(B8G8R8A8_SRGB); - STR(A8B8G8R8_UNORM_PACK32); - STR(A8B8G8R8_SNORM_PACK32); - STR(A8B8G8R8_USCALED_PACK32); - STR(A8B8G8R8_SSCALED_PACK32); - STR(A8B8G8R8_UINT_PACK32); - STR(A8B8G8R8_SINT_PACK32); - STR(A8B8G8R8_SRGB_PACK32); - STR(A2R10G10B10_UNORM_PACK32); - STR(A2R10G10B10_SNORM_PACK32); - STR(A2R10G10B10_USCALED_PACK32); - STR(A2R10G10B10_SSCALED_PACK32); - STR(A2R10G10B10_UINT_PACK32); - STR(A2R10G10B10_SINT_PACK32); - STR(A2B10G10R10_UNORM_PACK32); - STR(A2B10G10R10_SNORM_PACK32); - STR(A2B10G10R10_USCALED_PACK32); - STR(A2B10G10R10_SSCALED_PACK32); - STR(A2B10G10R10_UINT_PACK32); - STR(A2B10G10R10_SINT_PACK32); - STR(R16_UNORM); - STR(R16_SNORM); - STR(R16_USCALED); - STR(R16_SSCALED); - STR(R16_UINT); - STR(R16_SINT); - STR(R16_SFLOAT); - STR(R16G16_UNORM); - STR(R16G16_SNORM); - STR(R16G16_USCALED); - STR(R16G16_SSCALED); - STR(R16G16_UINT); - STR(R16G16_SINT); - STR(R16G16_SFLOAT); - STR(R16G16B16_UNORM); - STR(R16G16B16_SNORM); - STR(R16G16B16_USCALED); - STR(R16G16B16_SSCALED); - STR(R16G16B16_UINT); - STR(R16G16B16_SINT); - STR(R16G16B16_SFLOAT); - STR(R16G16B16A16_UNORM); - STR(R16G16B16A16_SNORM); - STR(R16G16B16A16_USCALED); - STR(R16G16B16A16_SSCALED); - STR(R16G16B16A16_UINT); - STR(R16G16B16A16_SINT); - STR(R16G16B16A16_SFLOAT); - STR(R32_UINT); - STR(R32_SINT); - STR(R32_SFLOAT); - STR(R32G32_UINT); - STR(R32G32_SINT); - STR(R32G32_SFLOAT); - STR(R32G32B32_UINT); - STR(R32G32B32_SINT); - STR(R32G32B32_SFLOAT); - STR(R32G32B32A32_UINT); - STR(R32G32B32A32_SINT); - STR(R32G32B32A32_SFLOAT); - STR(R64_UINT); - STR(R64_SINT); - STR(R64_SFLOAT); - STR(R64G64_UINT); - STR(R64G64_SINT); - STR(R64G64_SFLOAT); - STR(R64G64B64_UINT); - STR(R64G64B64_SINT); - STR(R64G64B64_SFLOAT); - STR(R64G64B64A64_UINT); - STR(R64G64B64A64_SINT); - STR(R64G64B64A64_SFLOAT); - STR(B10G11R11_UFLOAT_PACK32); - STR(E5B9G9R9_UFLOAT_PACK32); - STR(D16_UNORM); - STR(X8_D24_UNORM_PACK32); - STR(D32_SFLOAT); - STR(S8_UINT); - STR(D16_UNORM_S8_UINT); - STR(D24_UNORM_S8_UINT); - STR(D32_SFLOAT_S8_UINT); - STR(BC1_RGB_UNORM_BLOCK); - STR(BC1_RGB_SRGB_BLOCK); - STR(BC2_UNORM_BLOCK); - STR(BC2_SRGB_BLOCK); - STR(BC3_UNORM_BLOCK); - STR(BC3_SRGB_BLOCK); - STR(BC4_UNORM_BLOCK); - STR(BC4_SNORM_BLOCK); - STR(BC5_UNORM_BLOCK); - STR(BC5_SNORM_BLOCK); - STR(BC6H_UFLOAT_BLOCK); - STR(BC6H_SFLOAT_BLOCK); - STR(BC7_UNORM_BLOCK); - STR(BC7_SRGB_BLOCK); - STR(ETC2_R8G8B8_UNORM_BLOCK); - STR(ETC2_R8G8B8A1_UNORM_BLOCK); - STR(ETC2_R8G8B8A8_UNORM_BLOCK); - STR(EAC_R11_UNORM_BLOCK); - STR(EAC_R11_SNORM_BLOCK); - STR(EAC_R11G11_UNORM_BLOCK); - STR(EAC_R11G11_SNORM_BLOCK); - STR(ASTC_4x4_UNORM_BLOCK); - STR(ASTC_4x4_SRGB_BLOCK); - STR(ASTC_5x4_UNORM_BLOCK); - STR(ASTC_5x4_SRGB_BLOCK); - STR(ASTC_5x5_UNORM_BLOCK); - STR(ASTC_5x5_SRGB_BLOCK); - STR(ASTC_6x5_UNORM_BLOCK); - STR(ASTC_6x5_SRGB_BLOCK); - STR(ASTC_6x6_UNORM_BLOCK); - STR(ASTC_6x6_SRGB_BLOCK); - STR(ASTC_8x5_UNORM_BLOCK); - STR(ASTC_8x5_SRGB_BLOCK); - STR(ASTC_8x6_UNORM_BLOCK); - STR(ASTC_8x6_SRGB_BLOCK); - STR(ASTC_8x8_UNORM_BLOCK); - STR(ASTC_8x8_SRGB_BLOCK); - STR(ASTC_10x5_UNORM_BLOCK); - STR(ASTC_10x5_SRGB_BLOCK); - STR(ASTC_10x6_UNORM_BLOCK); - STR(ASTC_10x6_SRGB_BLOCK); - STR(ASTC_10x8_UNORM_BLOCK); - STR(ASTC_10x8_SRGB_BLOCK); - STR(ASTC_10x10_UNORM_BLOCK); - STR(ASTC_10x10_SRGB_BLOCK); - STR(ASTC_12x10_UNORM_BLOCK); - STR(ASTC_12x10_SRGB_BLOCK); - STR(ASTC_12x12_UNORM_BLOCK); - STR(ASTC_12x12_SRGB_BLOCK); +#define STR(r) \ + case VK_FORMAT_##r: \ + return #r + STR(UNDEFINED); + STR(R4G4_UNORM_PACK8); + STR(R4G4B4A4_UNORM_PACK16); + STR(B4G4R4A4_UNORM_PACK16); + STR(R5G6B5_UNORM_PACK16); + STR(B5G6R5_UNORM_PACK16); + STR(R5G5B5A1_UNORM_PACK16); + STR(B5G5R5A1_UNORM_PACK16); + STR(A1R5G5B5_UNORM_PACK16); + STR(R8_UNORM); + STR(R8_SNORM); + STR(R8_USCALED); + STR(R8_SSCALED); + STR(R8_UINT); + STR(R8_SINT); + STR(R8_SRGB); + STR(R8G8_UNORM); + STR(R8G8_SNORM); + STR(R8G8_USCALED); + STR(R8G8_SSCALED); + STR(R8G8_UINT); + STR(R8G8_SINT); + STR(R8G8_SRGB); + STR(R8G8B8_UNORM); + STR(R8G8B8_SNORM); + STR(R8G8B8_USCALED); + STR(R8G8B8_SSCALED); + STR(R8G8B8_UINT); + STR(R8G8B8_SINT); + STR(R8G8B8_SRGB); + STR(B8G8R8_UNORM); + STR(B8G8R8_SNORM); + STR(B8G8R8_USCALED); + STR(B8G8R8_SSCALED); + STR(B8G8R8_UINT); + STR(B8G8R8_SINT); + STR(B8G8R8_SRGB); + STR(R8G8B8A8_UNORM); + STR(R8G8B8A8_SNORM); + STR(R8G8B8A8_USCALED); + STR(R8G8B8A8_SSCALED); + STR(R8G8B8A8_UINT); + STR(R8G8B8A8_SINT); + STR(R8G8B8A8_SRGB); + STR(B8G8R8A8_UNORM); + STR(B8G8R8A8_SNORM); + STR(B8G8R8A8_USCALED); + STR(B8G8R8A8_SSCALED); + STR(B8G8R8A8_UINT); + STR(B8G8R8A8_SINT); + STR(B8G8R8A8_SRGB); + STR(A8B8G8R8_UNORM_PACK32); + STR(A8B8G8R8_SNORM_PACK32); + STR(A8B8G8R8_USCALED_PACK32); + STR(A8B8G8R8_SSCALED_PACK32); + STR(A8B8G8R8_UINT_PACK32); + STR(A8B8G8R8_SINT_PACK32); + STR(A8B8G8R8_SRGB_PACK32); + STR(A2R10G10B10_UNORM_PACK32); + STR(A2R10G10B10_SNORM_PACK32); + STR(A2R10G10B10_USCALED_PACK32); + STR(A2R10G10B10_SSCALED_PACK32); + STR(A2R10G10B10_UINT_PACK32); + STR(A2R10G10B10_SINT_PACK32); + STR(A2B10G10R10_UNORM_PACK32); + STR(A2B10G10R10_SNORM_PACK32); + STR(A2B10G10R10_USCALED_PACK32); + STR(A2B10G10R10_SSCALED_PACK32); + STR(A2B10G10R10_UINT_PACK32); + STR(A2B10G10R10_SINT_PACK32); + STR(R16_UNORM); + STR(R16_SNORM); + STR(R16_USCALED); + STR(R16_SSCALED); + STR(R16_UINT); + STR(R16_SINT); + STR(R16_SFLOAT); + STR(R16G16_UNORM); + STR(R16G16_SNORM); + STR(R16G16_USCALED); + STR(R16G16_SSCALED); + STR(R16G16_UINT); + STR(R16G16_SINT); + STR(R16G16_SFLOAT); + STR(R16G16B16_UNORM); + STR(R16G16B16_SNORM); + STR(R16G16B16_USCALED); + STR(R16G16B16_SSCALED); + STR(R16G16B16_UINT); + STR(R16G16B16_SINT); + STR(R16G16B16_SFLOAT); + STR(R16G16B16A16_UNORM); + STR(R16G16B16A16_SNORM); + STR(R16G16B16A16_USCALED); + STR(R16G16B16A16_SSCALED); + STR(R16G16B16A16_UINT); + STR(R16G16B16A16_SINT); + STR(R16G16B16A16_SFLOAT); + STR(R32_UINT); + STR(R32_SINT); + STR(R32_SFLOAT); + STR(R32G32_UINT); + STR(R32G32_SINT); + STR(R32G32_SFLOAT); + STR(R32G32B32_UINT); + STR(R32G32B32_SINT); + STR(R32G32B32_SFLOAT); + STR(R32G32B32A32_UINT); + STR(R32G32B32A32_SINT); + STR(R32G32B32A32_SFLOAT); + STR(R64_UINT); + STR(R64_SINT); + STR(R64_SFLOAT); + STR(R64G64_UINT); + STR(R64G64_SINT); + STR(R64G64_SFLOAT); + STR(R64G64B64_UINT); + STR(R64G64B64_SINT); + STR(R64G64B64_SFLOAT); + STR(R64G64B64A64_UINT); + STR(R64G64B64A64_SINT); + STR(R64G64B64A64_SFLOAT); + STR(B10G11R11_UFLOAT_PACK32); + STR(E5B9G9R9_UFLOAT_PACK32); + STR(D16_UNORM); + STR(X8_D24_UNORM_PACK32); + STR(D32_SFLOAT); + STR(S8_UINT); + STR(D16_UNORM_S8_UINT); + STR(D24_UNORM_S8_UINT); + STR(D32_SFLOAT_S8_UINT); + STR(BC1_RGB_UNORM_BLOCK); + STR(BC1_RGB_SRGB_BLOCK); + STR(BC2_UNORM_BLOCK); + STR(BC2_SRGB_BLOCK); + STR(BC3_UNORM_BLOCK); + STR(BC3_SRGB_BLOCK); + STR(BC4_UNORM_BLOCK); + STR(BC4_SNORM_BLOCK); + STR(BC5_UNORM_BLOCK); + STR(BC5_SNORM_BLOCK); + STR(BC6H_UFLOAT_BLOCK); + STR(BC6H_SFLOAT_BLOCK); + STR(BC7_UNORM_BLOCK); + STR(BC7_SRGB_BLOCK); + STR(ETC2_R8G8B8_UNORM_BLOCK); + STR(ETC2_R8G8B8A1_UNORM_BLOCK); + STR(ETC2_R8G8B8A8_UNORM_BLOCK); + STR(EAC_R11_UNORM_BLOCK); + STR(EAC_R11_SNORM_BLOCK); + STR(EAC_R11G11_UNORM_BLOCK); + STR(EAC_R11G11_SNORM_BLOCK); + STR(ASTC_4x4_UNORM_BLOCK); + STR(ASTC_4x4_SRGB_BLOCK); + STR(ASTC_5x4_UNORM_BLOCK); + STR(ASTC_5x4_SRGB_BLOCK); + STR(ASTC_5x5_UNORM_BLOCK); + STR(ASTC_5x5_SRGB_BLOCK); + STR(ASTC_6x5_UNORM_BLOCK); + STR(ASTC_6x5_SRGB_BLOCK); + STR(ASTC_6x6_UNORM_BLOCK); + STR(ASTC_6x6_SRGB_BLOCK); + STR(ASTC_8x5_UNORM_BLOCK); + STR(ASTC_8x5_SRGB_BLOCK); + STR(ASTC_8x6_UNORM_BLOCK); + STR(ASTC_8x6_SRGB_BLOCK); + STR(ASTC_8x8_UNORM_BLOCK); + STR(ASTC_8x8_SRGB_BLOCK); + STR(ASTC_10x5_UNORM_BLOCK); + STR(ASTC_10x5_SRGB_BLOCK); + STR(ASTC_10x6_UNORM_BLOCK); + STR(ASTC_10x6_SRGB_BLOCK); + STR(ASTC_10x8_UNORM_BLOCK); + STR(ASTC_10x8_SRGB_BLOCK); + STR(ASTC_10x10_UNORM_BLOCK); + STR(ASTC_10x10_SRGB_BLOCK); + STR(ASTC_12x10_UNORM_BLOCK); + STR(ASTC_12x10_SRGB_BLOCK); + STR(ASTC_12x12_UNORM_BLOCK); + STR(ASTC_12x12_SRGB_BLOCK); #undef STR - default: return "UNKNOWN_FORMAT"; + default: + return "UNKNOWN_FORMAT"; } } -static void app_dev_init_formats(struct app_dev *dev) -{ +static void app_dev_init_formats(struct app_dev *dev) { VkFormat f; for (f = 0; f < VK_FORMAT_RANGE_SIZE; f++) { const VkFormat fmt = f; - vkGetPhysicalDeviceFormatProperties(dev->gpu->obj, fmt, &dev->format_props[f]); + vkGetPhysicalDeviceFormatProperties(dev->gpu->obj, fmt, + &dev->format_props[f]); } } -static void extract_version(uint32_t version, uint32_t *major, uint32_t *minor, uint32_t *patch) -{ +static void extract_version(uint32_t version, uint32_t *major, uint32_t *minor, + uint32_t *patch) { *major = version >> 22; *minor = (version >> 12) & 0x3ff; *patch = version & 0xfff; } static void app_get_physical_device_layer_extensions( - struct app_gpu *gpu, - char *layer_name, - uint32_t *extension_count, - VkExtensionProperties **extension_properties) -{ + struct app_gpu *gpu, char *layer_name, uint32_t *extension_count, + VkExtensionProperties **extension_properties) { VkResult err; uint32_t ext_count = 0; VkExtensionProperties *ext_ptr = NULL; /* repeat get until VK_INCOMPLETE goes away */ do { - err = vkEnumerateDeviceExtensionProperties(gpu->obj, layer_name, &ext_count, NULL); + err = vkEnumerateDeviceExtensionProperties(gpu->obj, layer_name, + &ext_count, NULL); assert(!err); if (ext_ptr) { free(ext_ptr); } ext_ptr = malloc(ext_count * sizeof(VkExtensionProperties)); - err = vkEnumerateDeviceExtensionProperties(gpu->obj, layer_name, &ext_count, ext_ptr); + err = vkEnumerateDeviceExtensionProperties(gpu->obj, layer_name, + &ext_count, ext_ptr); } while (err == VK_INCOMPLETE); assert(!err); @@ -437,8 +442,7 @@ static void app_get_physical_device_layer_extensions( *extension_properties = ext_ptr; } -static void app_dev_init(struct app_dev *dev, struct app_gpu *gpu) -{ +static void app_dev_init(struct app_dev *dev, struct app_gpu *gpu) { VkDeviceCreateInfo info = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = NULL, @@ -477,7 +481,8 @@ static void app_dev_init(struct app_dev *dev, struct app_gpu *gpu) device_layers = malloc(sizeof(struct layer_extension_list) * count); assert(device_layers); - err = vkEnumerateDeviceLayerProperties(gpu->obj, &count, device_layer_properties); + err = vkEnumerateDeviceLayerProperties(gpu->obj, &count, + device_layer_properties); } while (err == VK_INCOMPLETE); assert(!err); @@ -487,22 +492,18 @@ static void app_dev_init(struct app_dev *dev, struct app_gpu *gpu) for (uint32_t i = 0; i < gpu->device_layer_count; i++) { VkLayerProperties *src_info = &device_layer_properties[i]; struct layer_extension_list *dst_info = &gpu->device_layers[i]; - memcpy(&dst_info->layer_properties, src_info, sizeof(VkLayerProperties)); + memcpy(&dst_info->layer_properties, src_info, + sizeof(VkLayerProperties)); /* Save away layer extension info for report */ app_get_physical_device_layer_extensions( - gpu, - src_info->layerName, - &dst_info->extension_count, - &dst_info->extension_properties); + gpu, src_info->layerName, &dst_info->extension_count, + &dst_info->extension_properties); } free(device_layer_properties); app_get_physical_device_layer_extensions( - gpu, - NULL, - &gpu->device_extension_count, - &gpu->device_extensions); + gpu, NULL, &gpu->device_extension_count, &gpu->device_extensions); fflush(stdout); @@ -532,38 +533,36 @@ static void app_dev_init(struct app_dev *dev, struct app_gpu *gpu) info.enabledLayerCount = 0; info.ppEnabledLayerNames = NULL; info.enabledExtensionCount = enabled_extension_count; - info.ppEnabledExtensionNames = (const char*const*) known_extensions; + info.ppEnabledExtensionNames = (const char *const *)known_extensions; dev->gpu = gpu; err = vkCreateDevice(gpu->obj, &info, NULL, &dev->obj); if (err) ERR_EXIT(err); - } -static void app_dev_destroy(struct app_dev *dev) -{ +static void app_dev_destroy(struct app_dev *dev) { vkDestroyDevice(dev->obj, NULL); } -static void app_get_global_layer_extensions( - char *layer_name, - uint32_t *extension_count, - VkExtensionProperties **extension_properties) -{ +static void +app_get_global_layer_extensions(char *layer_name, uint32_t *extension_count, + VkExtensionProperties **extension_properties) { VkResult err; uint32_t ext_count = 0; VkExtensionProperties *ext_ptr = NULL; /* repeat get until VK_INCOMPLETE goes away */ do { - err = vkEnumerateInstanceExtensionProperties(layer_name, &ext_count, NULL); + err = vkEnumerateInstanceExtensionProperties(layer_name, &ext_count, + NULL); assert(!err); if (ext_ptr) { free(ext_ptr); } ext_ptr = malloc(ext_count * sizeof(VkExtensionProperties)); - err = vkEnumerateInstanceExtensionProperties(layer_name, &ext_count, ext_ptr); + err = vkEnumerateInstanceExtensionProperties(layer_name, &ext_count, + ext_ptr); } while (err == VK_INCOMPLETE); assert(!err); @@ -571,8 +570,7 @@ static void app_get_global_layer_extensions( *extension_properties = ext_ptr; } -static void app_create_instance(struct app_instance *inst) -{ +static void app_create_instance(struct app_instance *inst) { const VkApplicationInfo app_info = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pNext = NULL, @@ -638,7 +636,8 @@ static void app_create_instance(struct app_instance *inst) global_layers = malloc(sizeof(struct layer_extension_list) * count); assert(global_layers); - err = vkEnumerateInstanceLayerProperties(&count, global_layer_properties); + err = + vkEnumerateInstanceLayerProperties(&count, global_layer_properties); } while (err == VK_INCOMPLETE); assert(!err); @@ -648,22 +647,20 @@ static void app_create_instance(struct app_instance *inst) for (uint32_t i = 0; i < inst->global_layer_count; i++) { VkLayerProperties *src_info = &global_layer_properties[i]; struct layer_extension_list *dst_info = &inst->global_layers[i]; - memcpy(&dst_info->layer_properties, src_info, sizeof(VkLayerProperties)); + memcpy(&dst_info->layer_properties, src_info, + sizeof(VkLayerProperties)); /* Save away layer extension info for report */ - app_get_global_layer_extensions( - src_info->layerName, - &dst_info->extension_count, - &dst_info->extension_properties); + app_get_global_layer_extensions(src_info->layerName, + &dst_info->extension_count, + &dst_info->extension_properties); } free(global_layer_properties); /* Collect global extensions */ inst->global_extension_count = 0; - app_get_global_layer_extensions( - NULL, - &inst->global_extension_count, - &inst->global_extensions); + app_get_global_layer_extensions(NULL, &inst->global_extension_count, + &inst->global_extensions); for (uint32_t i = 0; i < ARRAY_SIZE(known_extensions); i++) { VkBool32 extension_found = 0; @@ -682,12 +679,14 @@ static void app_create_instance(struct app_instance *inst) } inst_info.enabledExtensionCount = global_extension_count; - inst_info.ppEnabledExtensionNames = (const char * const *) known_extensions; + inst_info.ppEnabledExtensionNames = (const char *const *)known_extensions; VkDebugReportCallbackCreateInfoEXT dbg_info; memset(&dbg_info, 0, sizeof(dbg_info)); dbg_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; - dbg_info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARN_BIT_EXT | VK_DEBUG_REPORT_INFO_BIT_EXT; + dbg_info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | + VK_DEBUG_REPORT_WARN_BIT_EXT | + VK_DEBUG_REPORT_INFO_BIT_EXT; dbg_info.pfnCallback = dbg_callback; inst_info.pNext = &dbg_info; @@ -700,15 +699,13 @@ static void app_create_instance(struct app_instance *inst) } } -static void app_destroy_instance(struct app_instance *inst) -{ +static void app_destroy_instance(struct app_instance *inst) { free(inst->global_extensions); vkDestroyInstance(inst->instance, NULL); } - -static void app_gpu_init(struct app_gpu *gpu, uint32_t id, VkPhysicalDevice obj) -{ +static void app_gpu_init(struct app_gpu *gpu, uint32_t id, + VkPhysicalDevice obj) { uint32_t i; memset(gpu, 0, sizeof(*gpu)); @@ -721,20 +718,22 @@ static void app_gpu_init(struct app_gpu *gpu, uint32_t id, VkPhysicalDevice obj) /* get queue count */ vkGetPhysicalDeviceQueueFamilyProperties(gpu->obj, &gpu->queue_count, NULL); - gpu->queue_props = - malloc(sizeof(gpu->queue_props[0]) * gpu->queue_count); + gpu->queue_props = malloc(sizeof(gpu->queue_props[0]) * gpu->queue_count); if (!gpu->queue_props) ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY); - vkGetPhysicalDeviceQueueFamilyProperties(gpu->obj, &gpu->queue_count, gpu->queue_props); + vkGetPhysicalDeviceQueueFamilyProperties(gpu->obj, &gpu->queue_count, + gpu->queue_props); /* set up queue requests */ gpu->queue_reqs = malloc(sizeof(*gpu->queue_reqs) * gpu->queue_count); if (!gpu->queue_reqs) ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY); for (i = 0; i < gpu->queue_count; i++) { - float *queue_priorities = malloc(gpu->queue_props[i].queueCount * sizeof(float)); - memset(queue_priorities, 0, gpu->queue_props[i].queueCount * sizeof(float)); + float *queue_priorities = + malloc(gpu->queue_props[i].queueCount * sizeof(float)); + memset(queue_priorities, 0, + gpu->queue_props[i].queueCount * sizeof(float)); gpu->queue_reqs[i].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; gpu->queue_reqs[i].pNext = NULL; gpu->queue_reqs[i].queueFamilyIndex = i; @@ -750,18 +749,18 @@ static void app_gpu_init(struct app_gpu *gpu, uint32_t id, VkPhysicalDevice obj) app_dev_init_formats(&gpu->dev); } -static void app_gpu_destroy(struct app_gpu *gpu) -{ +static void app_gpu_destroy(struct app_gpu *gpu) { app_dev_destroy(&gpu->dev); free(gpu->device_extensions); for (uint32_t i = 0; i < gpu->queue_count; i++) { - free((void *) gpu->queue_reqs[i].pQueuePriorities); + free((void *)gpu->queue_reqs[i].pQueuePriorities); } free(gpu->queue_reqs); free(gpu->queue_props); } +// clang-format off static void app_dev_dump_format_props(const struct app_dev *dev, VkFormat fmt) { const VkFormatProperties *props = &dev->format_props[fmt]; @@ -847,7 +846,7 @@ static void app_gpu_dump_features(const struct app_gpu *gpu) printf("\ttextureCompressionETC2 = %u\n", features->textureCompressionETC2 ); printf("\ttextureCompressionASTC_LDR = %u\n", features->textureCompressionASTC_LDR ); printf("\ttextureCompressionBC = %u\n", features->textureCompressionBC ); - printf("\tocclusionQueryPrecise = %u\n", features->occlusionQueryPrecise ); + printf("\tocclusionQueryPrecise = %u\n", features->occlusionQueryPrecise ); printf("\tpipelineStatisticsQuery = %u\n", features->pipelineStatisticsQuery ); printf("\tvertexSideEffects = %u\n", features->vertexPipelineStoresAndAtomics ); printf("\ttessellationSideEffects = %u\n", features->fragmentStoresAndAtomics ); @@ -888,11 +887,11 @@ static void app_dump_sparse_props(const VkPhysicalDeviceSparseProperties *sparse printf("\tVkPhysicalDeviceSparseProperties:\n"); printf("\t---------------------------------\n"); - printf("\t\tresidencyStandard2DBlockShape = %u\n", sparseProps->residencyStandard2DBlockShape ); + printf("\t\tresidencyStandard2DBlockShape = %u\n", sparseProps->residencyStandard2DBlockShape ); printf("\t\tresidencyStandard2DMultisampleBlockShape = %u\n", sparseProps->residencyStandard2DMultisampleBlockShape); - printf("\t\tresidencyStandard3DBlockShape = %u\n", sparseProps->residencyStandard3DBlockShape ); - printf("\t\tresidencyAlignedMipSize = %u\n", sparseProps->residencyAlignedMipSize ); - printf("\t\tresidencyNonResidentStrict = %u\n", sparseProps->residencyNonResidentStrict ); + printf("\t\tresidencyStandard3DBlockShape = %u\n", sparseProps->residencyStandard3DBlockShape ); + printf("\t\tresidencyAlignedMipSize = %u\n", sparseProps->residencyAlignedMipSize ); + printf("\t\tresidencyNonResidentStrict = %u\n", sparseProps->residencyNonResidentStrict ); } static void app_dump_limits(const VkPhysicalDeviceLimits *limits) @@ -906,8 +905,8 @@ static void app_dump_limits(const VkPhysicalDeviceLimits *limits) printf("\t\tmaxImageDimensionCube = 0x%" PRIxLEAST32 "\n", limits->maxImageDimensionCube ); printf("\t\tmaxImageArrayLayers = 0x%" PRIxLEAST32 "\n", limits->maxImageArrayLayers ); printf("\t\tmaxTexelBufferElements = 0x%" PRIxLEAST32 "\n", limits->maxTexelBufferElements ); - printf("\t\tmaxUniformBufferRange = 0x%" PRIxLEAST32 "\n", limits->maxUniformBufferRange ); - printf("\t\tmaxStorageBufferRange = 0x%" PRIxLEAST32 "\n", limits->maxStorageBufferRange ); + printf("\t\tmaxUniformBufferRange = 0x%" PRIxLEAST32 "\n", limits->maxUniformBufferRange ); + printf("\t\tmaxStorageBufferRange = 0x%" PRIxLEAST32 "\n", limits->maxStorageBufferRange ); printf("\t\tmaxPushConstantsSize = 0x%" PRIxLEAST32 "\n", limits->maxPushConstantsSize ); printf("\t\tmaxMemoryAllocationCount = 0x%" PRIxLEAST32 "\n", limits->maxMemoryAllocationCount ); printf("\t\tmaxSamplerAllocationCount = 0x%" PRIxLEAST32 "\n", limits->maxSamplerAllocationCount ); @@ -934,7 +933,7 @@ static void app_dump_limits(const VkPhysicalDeviceLimits *limits) printf("\t\tmaxVertexInputAttributeOffset = 0x%" PRIxLEAST32 "\n", limits->maxVertexInputAttributeOffset ); printf("\t\tmaxVertexInputBindingStride = 0x%" PRIxLEAST32 "\n", limits->maxVertexInputBindingStride ); printf("\t\tmaxVertexOutputComponents = 0x%" PRIxLEAST32 "\n", limits->maxVertexOutputComponents ); - printf("\t\tmaxTessellationGenerationLevel = 0x%" PRIxLEAST32 "\n", limits->maxTessellationGenerationLevel ); + printf("\t\tmaxTessellationGenerationLevel = 0x%" PRIxLEAST32 "\n", limits->maxTessellationGenerationLevel ); printf("\t\tmaxTessellationPatchSize = 0x%" PRIxLEAST32 "\n", limits->maxTessellationPatchSize ); printf("\t\tmaxTessellationControlPerVertexInputComponents = 0x%" PRIxLEAST32 "\n", limits->maxTessellationControlPerVertexInputComponents ); printf("\t\tmaxTessellationControlPerVertexOutputComponents = 0x%" PRIxLEAST32 "\n", limits->maxTessellationControlPerVertexOutputComponents); @@ -1032,13 +1031,12 @@ static void app_gpu_dump_props(const struct app_gpu *gpu) fflush(stdout); } +// clang-format on -static void app_dump_extensions( - const char *indent, - const char *layer_name, - const uint32_t extension_count, - const VkExtensionProperties *extension_properties) -{ +static void +app_dump_extensions(const char *indent, const char *layer_name, + const uint32_t extension_count, + const VkExtensionProperties *extension_properties) { uint32_t i; if (layer_name && (strlen(layer_name) > 0)) { printf("%s%s Extensions", indent, layer_name); @@ -1046,38 +1044,36 @@ static void app_dump_extensions( printf("Extensions"); } printf("\tcount = %d\n", extension_count); - for (i=0; i< extension_count; i++) { + for (i = 0; i < extension_count; i++) { VkExtensionProperties const *ext_prop = &extension_properties[i]; printf("%s\t", indent); - printf("%-32s: extension revision %2d\n", - ext_prop->extensionName, ext_prop->specVersion); + printf("%-32s: extension revision %2d\n", ext_prop->extensionName, + ext_prop->specVersion); } printf("\n"); fflush(stdout); } -static void app_gpu_dump_queue_props(const struct app_gpu *gpu, uint32_t id) -{ +static void app_gpu_dump_queue_props(const struct app_gpu *gpu, uint32_t id) { const VkQueueFamilyProperties *props = &gpu->queue_props[id]; printf("VkQueueFamilyProperties[%d]:\n", id); printf("============================\n"); printf("\tqueueFlags = %c%c%c\n", - (props->queueFlags & VK_QUEUE_GRAPHICS_BIT) ? 'G' : '.', - (props->queueFlags & VK_QUEUE_COMPUTE_BIT) ? 'C' : '.', - (props->queueFlags & VK_QUEUE_TRANSFER_BIT) ? 'D' : '.'); - printf("\tqueueCount = %u\n", props->queueCount); - printf("\ttimestampValidBits = %u\n", props->timestampValidBits); + (props->queueFlags & VK_QUEUE_GRAPHICS_BIT) ? 'G' : '.', + (props->queueFlags & VK_QUEUE_COMPUTE_BIT) ? 'C' : '.', + (props->queueFlags & VK_QUEUE_TRANSFER_BIT) ? 'D' : '.'); + printf("\tqueueCount = %u\n", props->queueCount); + printf("\ttimestampValidBits = %u\n", props->timestampValidBits); printf("\tminImageTransferGranularity = (%d, %d, %d)\n", - props->minImageTransferGranularity.width, - props->minImageTransferGranularity.height, - props->minImageTransferGranularity.depth); + props->minImageTransferGranularity.width, + props->minImageTransferGranularity.height, + props->minImageTransferGranularity.depth); fflush(stdout); } -static void app_gpu_dump_memory_props(const struct app_gpu *gpu) -{ +static void app_gpu_dump_memory_props(const struct app_gpu *gpu) { const VkPhysicalDeviceMemoryProperties *props = &gpu->memory_props; printf("VkPhysicalDeviceMemoryProperties:\n"); @@ -1088,16 +1084,16 @@ static void app_gpu_dump_memory_props(const struct app_gpu *gpu) printf("\t\tpropertyFlags = %u\n", props->memoryTypes[i].propertyFlags); printf("\t\theapIndex = %u\n", props->memoryTypes[i].heapIndex); } - printf("\tmemoryHeapCount = %u\n", props->memoryHeapCount); + printf("\tmemoryHeapCount = %u\n", props->memoryHeapCount); for (uint32_t i = 0; i < props->memoryHeapCount; i++) { printf("\tmemoryHeaps[%u] : \n", i); - printf("\t\tsize = " PRINTF_SIZE_T_SPECIFIER "\n", (size_t)props->memoryHeaps[i].size); + printf("\t\tsize = " PRINTF_SIZE_T_SPECIFIER "\n", + (size_t)props->memoryHeaps[i].size); } fflush(stdout); } -static void app_gpu_dump(const struct app_gpu *gpu) -{ +static void app_gpu_dump(const struct app_gpu *gpu) { uint32_t i; printf("Device Extensions and layers:\n"); @@ -1105,7 +1101,8 @@ static void app_gpu_dump(const struct app_gpu *gpu) printf("GPU%u\n", gpu->id); app_gpu_dump_props(gpu); printf("\n"); - app_dump_extensions("", "Device", gpu->device_extension_count, gpu->device_extensions); + app_dump_extensions("", "Device", gpu->device_extension_count, + gpu->device_extensions); printf("\n"); printf("Layers\tcount = %d\n", gpu->device_layer_count); for (uint32_t i = 0; i < gpu->device_layer_count; i++) { @@ -1113,16 +1110,18 @@ static void app_gpu_dump(const struct app_gpu *gpu) char spec_version[64], layer_version[64]; struct layer_extension_list const *layer_info = &gpu->device_layers[i]; - extract_version(layer_info->layer_properties.specVersion, &major, &minor, &patch); - snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", major, minor, patch); - snprintf(layer_version, sizeof(layer_version), "%d", layer_info->layer_properties.implementationVersion); + extract_version(layer_info->layer_properties.specVersion, &major, + &minor, &patch); + snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", major, minor, + patch); + snprintf(layer_version, sizeof(layer_version), "%d", + layer_info->layer_properties.implementationVersion); printf("\t%s (%s) Vulkan version %s, layer version %s\n", layer_info->layer_properties.layerName, - (char*) layer_info->layer_properties.description, - spec_version, layer_version); + (char *)layer_info->layer_properties.description, spec_version, + layer_version); - app_dump_extensions("\t", - layer_info->layer_properties.layerName, + app_dump_extensions("\t", layer_info->layer_properties.layerName, layer_info->extension_count, layer_info->extension_properties); fflush(stdout); @@ -1139,8 +1138,7 @@ static void app_gpu_dump(const struct app_gpu *gpu) app_dev_dump(&gpu->dev); } -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { unsigned int major, minor, patch; struct app_gpu gpus[MAX_GPUS]; VkPhysicalDevice objs[MAX_GPUS]; @@ -1152,7 +1150,7 @@ int main(int argc, char **argv) minor = (VK_API_VERSION >> 12) & 0x3ff; patch = VK_API_VERSION & 0xfff; printf("===========\n"); - printf("VULKAN INFO\n"); + printf("VULKAN INFO\n"); printf("===========\n\n"); printf("Vulkan API Version: %d.%d.%d\n\n", major, minor, patch); @@ -1160,19 +1158,24 @@ int main(int argc, char **argv) printf("Instance Extensions and layers:\n"); printf("===============================\n"); - app_dump_extensions("", "Instance", inst.global_extension_count, inst.global_extensions); + app_dump_extensions("", "Instance", inst.global_extension_count, + inst.global_extensions); printf("Instance Layers\tcount = %d\n", inst.global_layer_count); for (uint32_t i = 0; i < inst.global_layer_count; i++) { uint32_t major, minor, patch; char spec_version[64], layer_version[64]; - VkLayerProperties const *layer_prop = &inst.global_layers[i].layer_properties; + VkLayerProperties const *layer_prop = + &inst.global_layers[i].layer_properties; extract_version(layer_prop->specVersion, &major, &minor, &patch); - snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", major, minor, patch); - snprintf(layer_version, sizeof(layer_version), "%d", layer_prop->implementationVersion); + snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", major, minor, + patch); + snprintf(layer_version, sizeof(layer_version), "%d", + layer_prop->implementationVersion); printf("\t%s (%s) Vulkan version %s, layer version %s\n", - layer_prop->layerName, (char*) layer_prop->description, spec_version, layer_version); + layer_prop->layerName, (char *)layer_prop->description, + spec_version, layer_version); app_dump_extensions("\t", inst.global_layers[i].layer_properties.layerName, @@ -1209,8 +1212,7 @@ int main(int argc, char **argv) // Create a console window with a large scrollback size to which to send stdout. // Returns true if console window was successfully created, false otherwise. -bool SetStdOutToNewConsole() -{ +bool SetStdOutToNewConsole() { // don't do anything if we already have a console if (GetStdHandle(STD_OUTPUT_HANDLE)) return false; @@ -1221,9 +1223,9 @@ bool SetStdOutToNewConsole() // redirect unbuffered STDOUT to the console HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); int fileDescriptor = _open_osfhandle((intptr_t)consoleHandle, _O_TEXT); - FILE *fp = _fdopen( fileDescriptor, "w" ); + FILE *fp = _fdopen(fileDescriptor, "w"); *stdout = *fp; - setvbuf( stdout, NULL, _IONBF, 0 ); + setvbuf(stdout, NULL, _IONBF, 0); // make the console window bigger CONSOLE_SCREEN_BUFFER_INFO csbi; @@ -1231,12 +1233,12 @@ bool SetStdOutToNewConsole() COORD bufferSize; if (!GetConsoleScreenBufferInfo(consoleHandle, &csbi)) return false; - bufferSize.X = csbi.dwSize.X+30; + bufferSize.X = csbi.dwSize.X + 30; bufferSize.Y = 20000; if (!SetConsoleScreenBufferSize(consoleHandle, bufferSize)) return false; r.Left = r.Top = 0; - r.Right = csbi.dwSize.X-1+30; + r.Right = csbi.dwSize.X - 1 + 30; r.Bottom = 50; if (!SetConsoleWindowInfo(consoleHandle, true, &r)) return false; @@ -1248,8 +1250,8 @@ bool SetStdOutToNewConsole() return true; } -int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) -{ +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, + int nCmdShow) { char *argv = pCmdLine; consoleCreated = SetStdOutToNewConsole(); main(1, &argv); |
