MXVK Vulkan Framework 0.24.0
C++20 Vulkan rendering framework for practical 2D and 3D application development with SDL3.
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include "mxvk/argz.hpp"
2#include "mxvk/mxvk.hpp"
4
5#include <array>
6#include <chrono>
7#include <cstdlib>
8#include <format>
9#include <iostream>
10#include <string>
11#include <vector>
12
13namespace example {
15 struct PushConstants {
16 float time;
17 float aspect;
18 };
19
20 public:
21 ExampleWindow(const std::string path, const std::string &text, int width, int height, bool fullscreen, bool enable_vsync)
22 : mxvk::VK_Window(text, width, height, fullscreen, MXVK_VALIDATION, enable_vsync),
23 shader_root((path.empty() ? std::string(HELLO_WORLD_ASSET_DIR) : path) + "/data") {
24 setClearColor(0.02f, 0.03f, 0.06f, 1.0f);
25 }
26
27 ~ExampleWindow() override {
28 if (device != VK_NULL_HANDLE) {
29 vkDeviceWaitIdle(device);
30 }
31 destroyGraphicsPipeline();
32 }
33
35 destroyGraphicsPipeline();
36 }
37
38 void onRecordCustomRendering(VkCommandBuffer cmd, [[maybe_unused]] uint32_t image_index) override {
39 if (!ensureGraphicsPipeline()) {
40 return;
41 }
42
43 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline);
44
45 const auto now = std::chrono::steady_clock::now();
46 const float elapsed_seconds = std::chrono::duration<float>(now - start_time).count();
47 const VkExtent2D extent = getSwapchainExtent();
48 const float aspect =
49 (extent.height > 0U) ? static_cast<float>(extent.width) / static_cast<float>(extent.height) : 1.0f;
50
51 const PushConstants push_constants{elapsed_seconds, aspect};
52 vkCmdPushConstants(
53 cmd,
54 pipeline_layout,
55 VK_SHADER_STAGE_VERTEX_BIT,
56 0,
57 sizeof(PushConstants),
58 &push_constants);
59
60 vkCmdDraw(cmd, 3, 1, 0, 0);
61 }
62
63 private:
64 std::string shader_root;
65 std::chrono::steady_clock::time_point start_time{std::chrono::steady_clock::now()};
66
67 void destroyGraphicsPipeline() {
68 if (device == VK_NULL_HANDLE) {
69 pipeline_layout = VK_NULL_HANDLE;
70 graphics_pipeline = VK_NULL_HANDLE;
71 return;
72 }
73
74 if (graphics_pipeline != VK_NULL_HANDLE) {
75 vkDestroyPipeline(device, graphics_pipeline, nullptr);
76 graphics_pipeline = VK_NULL_HANDLE;
77 }
78 if (pipeline_layout != VK_NULL_HANDLE) {
79 vkDestroyPipelineLayout(device, pipeline_layout, nullptr);
80 pipeline_layout = VK_NULL_HANDLE;
81 }
82 }
83
84 bool ensureGraphicsPipeline() {
85 if (graphics_pipeline != VK_NULL_HANDLE && pipeline_layout != VK_NULL_HANDLE) {
86 return true;
87 }
88
89 createGraphicsPipeline();
90 return graphics_pipeline != VK_NULL_HANDLE && pipeline_layout != VK_NULL_HANDLE;
91 }
92
93 void createGraphicsPipeline() {
94 if (device == VK_NULL_HANDLE || swapchain_format == VK_FORMAT_UNDEFINED) {
95 return;
96 }
97
98 const std::string vert_path = shader_root + "/triangle.vert.spv";
99 const std::string frag_path = shader_root + "/triangle.frag.spv";
100 const std::vector<char> vert_bytes = loadSpv(vert_path);
101 const std::vector<char> frag_bytes = loadSpv(frag_path);
102
103 const VkShaderModule vert_module = createShaderModule(device, vert_bytes);
104 VkShaderModule frag_module = VK_NULL_HANDLE;
105 try {
106 frag_module = createShaderModule(device, frag_bytes);
107
108 std::array<VkPipelineShaderStageCreateInfo, 2> shader_stages{};
109 shader_stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
110 shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
111 shader_stages[0].module = vert_module;
112 shader_stages[0].pName = "main";
113 shader_stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
114 shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
115 shader_stages[1].module = frag_module;
116 shader_stages[1].pName = "main";
117
118 VkPipelineVertexInputStateCreateInfo vertex_input{};
119 vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
120
121 VkPipelineInputAssemblyStateCreateInfo input_assembly{};
122 input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
123 input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
124 input_assembly.primitiveRestartEnable = VK_FALSE;
125
126 VkPipelineViewportStateCreateInfo viewport_state{};
127 viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
128 viewport_state.viewportCount = 1;
129 viewport_state.scissorCount = 1;
130
131 const VkDynamicState dynamic_states[] = {
132 VK_DYNAMIC_STATE_VIEWPORT,
133 VK_DYNAMIC_STATE_SCISSOR,
134 };
135 VkPipelineDynamicStateCreateInfo dynamic_state{};
136 dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
137 dynamic_state.dynamicStateCount = 2;
138 dynamic_state.pDynamicStates = dynamic_states;
139
140 VkPipelineRasterizationStateCreateInfo rasterizer{};
141 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
142 rasterizer.depthClampEnable = VK_FALSE;
143 rasterizer.rasterizerDiscardEnable = VK_FALSE;
144 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
145 rasterizer.lineWidth = 1.0f;
146 rasterizer.cullMode = VK_CULL_MODE_NONE;
147 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
148 rasterizer.depthBiasEnable = VK_FALSE;
149
150 VkPipelineMultisampleStateCreateInfo multisampling{};
151 multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
152 multisampling.sampleShadingEnable = VK_FALSE;
153 multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
154
155 VkPipelineDepthStencilStateCreateInfo depth_stencil{};
156 depth_stencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
157 depth_stencil.depthTestEnable = VK_FALSE;
158 depth_stencil.depthWriteEnable = VK_FALSE;
159 depth_stencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
160 depth_stencil.depthBoundsTestEnable = VK_FALSE;
161 depth_stencil.stencilTestEnable = VK_FALSE;
162
163 VkPipelineColorBlendAttachmentState color_blend_attachment{};
164 color_blend_attachment.colorWriteMask =
165 VK_COLOR_COMPONENT_R_BIT |
166 VK_COLOR_COMPONENT_G_BIT |
167 VK_COLOR_COMPONENT_B_BIT |
168 VK_COLOR_COMPONENT_A_BIT;
169 color_blend_attachment.blendEnable = VK_FALSE;
170
171 VkPipelineColorBlendStateCreateInfo color_blending{};
172 color_blending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
173 color_blending.logicOpEnable = VK_FALSE;
174 color_blending.attachmentCount = 1;
175 color_blending.pAttachments = &color_blend_attachment;
176
177 VkPushConstantRange push_constant_range{};
178 push_constant_range.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
179 push_constant_range.offset = 0;
180 push_constant_range.size = sizeof(PushConstants);
181
182 VkPipelineLayoutCreateInfo pipeline_layout_info{};
183 pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
184 pipeline_layout_info.pushConstantRangeCount = 1;
185 pipeline_layout_info.pPushConstantRanges = &push_constant_range;
186 if (vkCreatePipelineLayout(device, &pipeline_layout_info, nullptr, &pipeline_layout) != VK_SUCCESS) {
187 throw mxvk::Exception("Failed to create pipeline layout");
188 }
189
190 VkPipelineRenderingCreateInfo pipeline_rendering_info{};
191 pipeline_rendering_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO;
192 pipeline_rendering_info.viewMask = 0;
193 pipeline_rendering_info.colorAttachmentCount = 1;
194 pipeline_rendering_info.pColorAttachmentFormats = &swapchain_format;
195 const VkFormat depth_format = getDepthFormat();
196 if (depth_format != VK_FORMAT_UNDEFINED) {
197 pipeline_rendering_info.depthAttachmentFormat = depth_format;
198 }
199
200 VkGraphicsPipelineCreateInfo pipeline_info{};
201 pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
202 pipeline_info.pNext = &pipeline_rendering_info;
203 pipeline_info.stageCount = static_cast<uint32_t>(shader_stages.size());
204 pipeline_info.pStages = shader_stages.data();
205 pipeline_info.pVertexInputState = &vertex_input;
206 pipeline_info.pInputAssemblyState = &input_assembly;
207 pipeline_info.pViewportState = &viewport_state;
208 pipeline_info.pRasterizationState = &rasterizer;
209 pipeline_info.pMultisampleState = &multisampling;
210 pipeline_info.pDepthStencilState = &depth_stencil;
211 pipeline_info.pColorBlendState = &color_blending;
212 pipeline_info.pDynamicState = &dynamic_state;
213 pipeline_info.layout = pipeline_layout;
214 pipeline_info.renderPass = VK_NULL_HANDLE;
215 pipeline_info.subpass = 0;
216 pipeline_info.basePipelineHandle = VK_NULL_HANDLE;
217 pipeline_info.basePipelineIndex = -1;
218
219 if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &graphics_pipeline) != VK_SUCCESS) {
220 throw mxvk::Exception("Failed to create graphics pipeline");
221 }
222 } catch (...) {
223 if (graphics_pipeline != VK_NULL_HANDLE) {
224 vkDestroyPipeline(device, graphics_pipeline, nullptr);
225 graphics_pipeline = VK_NULL_HANDLE;
226 }
227 if (pipeline_layout != VK_NULL_HANDLE) {
228 vkDestroyPipelineLayout(device, pipeline_layout, nullptr);
229 pipeline_layout = VK_NULL_HANDLE;
230 }
231 if (frag_module != VK_NULL_HANDLE) {
232 vkDestroyShaderModule(device, frag_module, nullptr);
233 }
234 vkDestroyShaderModule(device, vert_module, nullptr);
235 throw;
236 }
237
238 vkDestroyShaderModule(device, frag_module, nullptr);
239 vkDestroyShaderModule(device, vert_module, nullptr);
240 }
241
242 VkPipeline graphics_pipeline = VK_NULL_HANDLE;
243 VkPipelineLayout pipeline_layout = VK_NULL_HANDLE;
244 };
245} // namespace example
246
247int main(int argc, char **argv) {
248 try {
249 const Arguments args = proc_args(argc, argv);
250 example::ExampleWindow ex_window(args.path, "VK_Example", args.width, args.height, args.fullscreen, args.enable_vsync);
251 ex_window.loop();
252 } catch (mxvk::Exception &e) {
253 std::cerr << std::format("mxvk: Exception: {}\n", e.text());
254 return EXIT_FAILURE;
255 } catch (ArgException<std::string> &e) {
256 std::cerr << std::format("mxvk: Argument Exception: {}\n", e.text());
257 }
258 return EXIT_SUCCESS;
259}
Lightweight, header-only, template command-line argument parser.
Arguments proc_args(int &argc, char **argv)
Parse standard libmx2 command-line options from main()'s argv.
Definition argz.hpp:872
Exception thrown by Argz::proc() on unrecognised or malformed options.
Definition argz.hpp:178
void onSwapchainAboutToRecreate() override
Called right before swapchain-dependent resources are recreated.
Definition main.cpp:34
ExampleWindow(const std::string path, const std::string &text, int width, int height, bool fullscreen, bool enable_vsync)
Definition main.cpp:21
~ExampleWindow() override
Definition main.cpp:27
void onRecordCustomRendering(VkCommandBuffer cmd, uint32_t image_index) override
Optional hook for derived classes to record extra draw commands.
Definition main.cpp:38
std::string text() const
Main Vulkan window wrapper for MXVK.
Definition mxvk.hpp:37
VkExtent2D getSwapchainExtent() const noexcept
Get the current swapchain extent.
Definition mxvk.hpp:186
void loop()
Run the main event/render loop.
Definition mxvk.cpp:600
VkDevice device
Definition mxvk.hpp:485
VkFormat swapchain_format
Definition mxvk.hpp:493
VkFormat depth_format
Definition mxvk.hpp:494
static VkShaderModule createShaderModule(VkDevice device, const std::vector< char > &spv_bytes)
Create a shader module from SPIR-V bytecode.
Definition mxvk.cpp:145
void setClearColor(float r, float g, float b, float a=1.0f)
Set the per-frame color attachment clear color.
Definition mxvk.cpp:593
VK_Window()=default
Construct an empty window object.
VkFormat getDepthFormat() const noexcept
Get the depth format used for dynamic rendering attachments.
Definition mxvk.hpp:189
static std::vector< char > loadSpv(const std::string &path)
Load a SPIR-V file from disk.
Definition mxvk.cpp:141
int main(void)
Definition main.cpp:7
#define MXVK_VALIDATION
Definition mxvk.hpp:27
Utilities for loading and saving PNG images.
Definition mxvk.hpp:30
Plain data structure returned by proc_args() with all common libmx2 CLI options.
Definition argz.hpp:730
bool fullscreen
Whether fullscreen mode was requested.
Definition argz.hpp:736
bool enable_vsync
Enable FIFO present mode / v-sync (--enable-vsync).
Definition argz.hpp:750
int height
Viewport height in pixels (default: 720).
Definition argz.hpp:733
std::string path
Asset root; proc_args() defaults it to the executable directory.
Definition argz.hpp:735
int width
Viewport width in pixels (default: 1280).
Definition argz.hpp:732