1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
|
#ifndef _VKSETUP_H
#define _VKSETUP_H
/* Start header file */
/**
vulkan setup and basic vector math
Single header file with included implementation in the spirit of
stb_* <https://github.com/nothings/stb>
ASSUMPTIONS:
~~~~~~~~~~~~
- Using SDL2 for the window
- Using cglm for maths
- Using shaderc for compiling glsl
- Using vulkan(!)
This is not meant to be a generic werapper around vulkan. It is actively
paired and chaned by the currently in development application, whatever that
might be. Think of it as the vulkan setup configuratior and helper.
USAGE:
~~~~~~
Do this:
#define VKSETUP_IMPLEMENTATION
before you include this file in *one* C or C++ file to create the implementation.
// i.e. it should look like this:
#include ...
#include ...
#include ...
#define VKSETUP_IMPLEMENTATION
#include "vksetup.h"
*/
#include <vulkan/vulkan_core.h>
#define SDL_MAIN_HANDLED
#define VK_USE_PLATFORM_XCB_KHR
#include <stdarg.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>
#include <vulkan/vulkan.h>
#include <vulkan/vk_enum_string_helper.h> // for string_VkResult
#include <shaderc/shaderc.h>
#include "../lib/cglm/include/cglm/cglm.h"
#define VK_ARRAY_LEN(arr) sizeof((arr))/sizeof((arr)[0])
#ifdef __clang__
#define __FILENAME__ __FILE_NAME__
#else
#define __FILENAME__ __FILE__
#endif
#define VK_CHECK(x) \
do { \
VkResult err = x; \
if (err < 0) { \
fprintf(stderr, "src/%s:%d:0: vulkan error: %s \n", \
__FILENAME__, __LINE__, string_VkResult(err)); \
abort(); \
} \
} while (0)
typedef enum {
VK_INFO = 0,
VK_WARN,
VK_ERROR,
} log_type;
static inline void
_vk_log(log_type t, const char * f, ...)
{
#ifdef VKDEBUG
va_list args;
va_start(args, f);
switch (t) {
case VK_INFO:
printf("INFO: ");
vprintf(f, args);
break;
case VK_WARN:
fprintf(stderr, "WARN: ");
vfprintf(stderr, f, args);
break;
case VK_ERROR:
fprintf(stderr, "ERROR: ");
vfprintf(stderr, f, args);
break;
}
va_end(args);
#else
return;
#endif
}
#ifdef VKDEBUG
#define vk_log(t, ...) do { \
fprintf(t == VK_INFO ? stdout : stderr, "src/%s:%d:0: ", \
__FILENAME__, __LINE__); \
_vk_log(t, __VA_ARGS__); \
} while(0)
#else
#define vk_log(t, ...)
#endif
/**********/
/* config */
/**********/
const char *const validation_layers[] = {
"VK_LAYER_KHRONOS_validation"
};
const uint32_t validation_layer_count = VK_ARRAY_LEN(validation_layers);
const char *const device_extensions[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
const uint32_t deviceExtensionCount = VK_ARRAY_LEN(device_extensions);
#ifdef VKDEBUG
const bool enableValidationLayers = true;
#else
const bool enableValidationLayers = false;
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef VKSDEF
#ifdef VKS_STATIC
#define VKSDEF static
#else
#define VKSDEF extern
#endif
#endif
// TODO Create structs for vulkan data
typedef struct vks_swapchain {
VkSwapchainKHR handle;
VkFormat image_format;
VkExtent2D extent;
uint32_t image_count;
VkImage images[5];
VkImageView image_views[5]; // 5 for some reason
} vks_swapchain;
typedef struct vks_buffer {
VkBuffer handle;
VkDeviceMemory memory;
} vks_buffer;
typedef struct vks_image {
VkImage handle;
VkDeviceMemory memory;
VkImageView view;
} vks_image;
typedef struct vks_pipeline {
VkPipeline handle;
VkPipelineLayout layout;
} vks_pipeline;
typedef struct vks_context {
VkInstance instance;
VkPhysicalDevice physical_device;
VkDevice device;
SDL_Window *window;
VkSurfaceKHR surface;
vks_swapchain swapchain;
} vks_context;
typedef struct vks_frame_data {
VkCommandBuffer vk_command_buffer;
VkSemaphore image_available_semaphore;
VkSemaphore render_finished_semaphore;
VkFence in_flight_fence;
vks_buffer uniform_buffer;
void * uniform_buffer_mapped;
VkDescriptorSet vk_descriptor_set;
} vks_frame_data;
/* Exported API */
VKSDEF VkInstance vks_create_instance(bool validation_layers_toggle, const char * const validation_layers[], uint32_t validation_layer_count, SDL_Window *window);
VKSDEF void vks_create_buffer(const vks_context vk, const VkDeviceSize size, const VkBufferUsageFlags usage, const VkMemoryPropertyFlags properties, vks_buffer *buffer);
VKSDEF void vks_create_image(const vks_context vk, const uint32_t width, const uint32_t height, const uint32_t mipLevels, const VkFormat format, const VkImageTiling tiling, const VkImageUsageFlags usage, const VkMemoryPropertyFlags properties, const VkSampleCountFlagBits numSamples, vks_image *image);
/* VKSDEF void vulkan_create_surface(); */
/* VKSDEF void vulkan_pick_physical_device(); */
/* VKSDEF void vulkan_create_logical_device(); */
/* VKSDEF void vulkan_create_swap_chain(); */
/* VKSDEF void vulkan_create_image_views(); */
/* VKSDEF void vulkan_create_descriptor_set_layout(); */
/* VKSDEF void vulkan_create_graphics_pipeline(); */
/* VKSDEF void vulkan_create_command_pool(); */
/* VKSDEF void vulkan_create_depth_resources(); */
/* VKSDEF void vulkan_create_texture_image(); */
/* VKSDEF void vulkan_create_texture_image_view(); */
/* VKSDEF void vulkan_create_texture_sampler(); */
/* VKSDEF void vulkan_create_vertex_buffer(); */
/* VKSDEF void vulkan_create_index_buffer(); */
/* VKSDEF void vulkan_create_uniform_buffers(); */
/* VKSDEF void vulkan_create_descriptor_pool(); */
/* VKSDEF void vulkan_create_descriptor_sets(); */
/* VKSDEF void vulkan_create_command_buffer(); */
/* VKSDEF void vulkan_create_sync_objects(); */
#ifdef __cplusplus
}
#endif
/* End header file */
#endif /* _VKSETUP_H */
#ifdef VKSETUP_IMPLEMENTATION
#include <stddef.h>
#include <stdlib.h>
#include <time.h>
/* Vks helpers */
bool
vks_check_validation_layer_support(const char* const validation_layers[],
uint32_t validation_layer_count)
{
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, NULL);
VkLayerProperties availableLayers[layerCount];
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);
bool layerFound = false;
for (uint32_t i = 0; i < validation_layer_count; i++) {
for (uint32_t j = 0; j < layerCount; j++) {
if (strcmp(validation_layers[i], availableLayers[j].layerName) == 0) {
layerFound = true;
break;
}
}
}
return layerFound;
}
uint32_t
find_memory_type(const vks_context vk,
const uint32_t typeFilter,
const VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties mem_properties;
vkGetPhysicalDeviceMemoryProperties(vk.physical_device, &mem_properties);
for (uint32_t i = 0; i < mem_properties.memoryTypeCount; i++) {
if ((typeFilter & (1 << i)) &&
(mem_properties.memoryTypes[i].propertyFlags & properties) ==
properties) {
return i;
}
}
vk_log(VK_ERROR, "failed to find suitable memory type!\n");
return 9999;
}
/* Vks API implementation */
VKSDEF void
vks_create_image(const vks_context vk,
const uint32_t width,
const uint32_t height,
const uint32_t mipLevels,
const VkFormat format,
const VkImageTiling tiling,
const VkImageUsageFlags usage,
const VkMemoryPropertyFlags properties,
const VkSampleCountFlagBits numSamples,
vks_image* image)
{
VkImageCreateInfo imageInfo = { 0 };
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.samples = numSamples;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(vkCreateImage(vk.device, &imageInfo, NULL, &image->handle));
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(vk.device, image->handle, &memRequirements);
VkMemoryAllocateInfo allocInfo = { 0 };
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex =
find_memory_type(vk, memRequirements.memoryTypeBits, properties);
// TODO: group allocations etc... (allocations limited by hardware)
VK_CHECK(vkAllocateMemory(vk.device, &allocInfo, NULL, &image->memory));
vkBindImageMemory(vk.device, image->handle, image->memory, 0);
}
VKSDEF void
vks_create_buffer(const vks_context vk,
const VkDeviceSize size,
const VkBufferUsageFlags usage,
const VkMemoryPropertyFlags properties,
vks_buffer* buffer)
{
VkBufferCreateInfo bufferInfo = { 0 };
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(vkCreateBuffer(vk.device, &bufferInfo, NULL, &buffer->handle));
VkMemoryRequirements mem_requirements;
vkGetBufferMemoryRequirements(vk.device, buffer->handle, &mem_requirements);
VkMemoryAllocateInfo allocInfo = { 0 };
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = mem_requirements.size;
allocInfo.memoryTypeIndex =
find_memory_type(vk, mem_requirements.memoryTypeBits, properties);
// TODO: group allocations etc... (allocations limited by hardware)
VK_CHECK(vkAllocateMemory(vk.device, &allocInfo, NULL, &buffer->memory));
VK_CHECK(vkBindBufferMemory(vk.device, buffer->handle, buffer->memory, 0));
}
VKSDEF VkInstance
vks_create_instance(bool validation_layers_toggle,
const char* const validation_layers[],
uint32_t validation_layer_count,
SDL_Window* window)
{
if (validation_layers_toggle &&
!vks_check_validation_layer_support(validation_layers,
validation_layer_count)) {
vk_log(VK_ERROR, "validation layers requested, but not available!\n");
abort();
}
uint32_t instanceVersion;
VkResult result = vkEnumerateInstanceVersion(&instanceVersion);
if (result == VK_SUCCESS) {
if (instanceVersion < VK_MAKE_API_VERSION(0, 1, 3, 0)) {
vk_log(VK_ERROR, "Vulkan version 1.3 or greater required!\n");
exit(1);
}
vk_log(VK_INFO,
"Vulkan version found (%d) %d.%d.%d\n",
VK_API_VERSION_VARIANT(instanceVersion),
VK_API_VERSION_MAJOR(instanceVersion),
VK_API_VERSION_MINOR(instanceVersion),
VK_API_VERSION_PATCH(instanceVersion));
} else {
vk_log(VK_ERROR,
"Failed to retrieve vulkan version, is vulkan supported in this "
"system?\n");
exit(1);
}
// Load Vulkan and create instance
VkApplicationInfo appInfo = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pApplicationName = "Vulkan Application",
.applicationVersion = VK_MAKE_API_VERSION(0, 1, 3, 0),
.pEngineName = NULL,
.engineVersion = VK_MAKE_API_VERSION(0, 1, 3, 0),
.apiVersion = VK_MAKE_API_VERSION(0, 1, 3, 0),
};
uint32_t sdlExtensionCount = 0;
if (SDL_Vulkan_GetInstanceExtensions(window, &sdlExtensionCount, NULL) ==
SDL_FALSE) {
vk_log(VK_ERROR,
"SDL_Vulkan_GetInstanceExtensions failed: %s\n",
SDL_GetError());
abort();
}
// make space for debug extenetion
if (validation_layers_toggle) {
sdlExtensionCount++;
}
const char* sdlExtensions[sdlExtensionCount];
if (SDL_Vulkan_GetInstanceExtensions(
window, &sdlExtensionCount, sdlExtensions) == SDL_FALSE) {
vk_log(VK_ERROR,
"SDL_Vulkan_GetInstanceExtensions failed: %s\n",
SDL_GetError());
abort();
}
// add debug extenetion
if (validation_layers_toggle) {
sdlExtensions[sdlExtensionCount] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
}
vk_log(VK_INFO, "The sdl extensions:\n");
for (uint32_t i = 0; i < sdlExtensionCount; i++) {
vk_log(VK_INFO, "\t%s\n", sdlExtensions[i]);
}
VkInstanceCreateInfo createInfo = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pApplicationInfo = &appInfo,
.enabledExtensionCount = sdlExtensionCount,
.ppEnabledExtensionNames = sdlExtensions,
.enabledLayerCount = 0,
};
if (validation_layers_toggle) {
createInfo.enabledLayerCount = validation_layer_count;
createInfo.ppEnabledLayerNames = validation_layers;
}
VkInstance instance;
if (vkCreateInstance(&createInfo, NULL, &instance) != VK_SUCCESS) {
vk_log(VK_ERROR, "Can't start vulkan instance\n");
}
vk_log(VK_INFO, "Vulkan instance created\n");
return instance;
}
#endif /* VKSETUP_IMPLEMENTATION */
|