kiba-engine
shader.c
1 #include <kiba/renderer/vulkan/shader.h>
2 
4 
5 static array_of(u32) vulkan_shader_load_code(vulkan_context *context, const char *path, usize *read_bytes) {
6  KB_ASSERT(context, "context must not be null");
7  KB_ASSERT(path, "file path must not be null");
8  file_handle file;
9  usize size = 0;
10  array_of(u32) code = KB_NULL;
11  if (filesystem_open(&file, path, false, FILE_MODE_READ)) {
12  if (filesystem_size(&file, &size)
13  && (code = array_create(u32, size / sizeof(code[0]) + 1, &context->alloc.kiba_alloc)) != KB_NULL) {
14  array_resize(&code, array_capacity(code));
15  if (filesystem_read_all_text(&file, array_capacity(code) * sizeof(code[0]), (char *) code, read_bytes)) {
16  if (size != *read_bytes) {
17  KB_WARN("determined size of shader code ({usize}) and actually read data ({usize}) differs",
18  size,
19  read_bytes);
20  }
21  } else {
22  array_destroy(&code);
23  }
24  }
25  filesystem_close(&file);
26  }
27  return code;
28 }
29 
30 b8 vulkan_shader_create(vulkan_context *context, const char *path, shader_type type) {
31  usize size_in_bytes = 0;
32  array_of(u32) code = vulkan_shader_load_code(context, path, &size_in_bytes);
33  if (code == KB_NULL) {
34  return false;
35  }
36 
37  VkShaderModuleCreateInfo shader_info = {
38  .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
39  .codeSize = size_in_bytes,
40  .pCode = (u32 *) code,
41  };
42 
43  VkShaderModule shader_module;
44  // TODO: this will leak in case its not successfull, could add cleanup option to macro
45  VK_CALL_B8(
46  vkCreateShaderModule(context->device.logical, &shader_info, &context->alloc.vulkan_callbacks, &shader_module));
47 
48  VkPipelineShaderStageCreateInfo shader_stage_info = {
49  .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
50  .module = shader_module,
51  .pName = "main",
52  };
53  switch (type) {
54  case SHADER_TYPE_VERTEX:
55  shader_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT;
56  break;
57  case SHADER_TYPE_FRAGMENT:
58  shader_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
59  break;
60  default:
61  KB_FATAL("unhandled shader type {i32}", type);
62  break;
63  }
64  array_push(context->pipeline.shaders, shader_stage_info);
65  array_destroy(&code);
66  return true;
67 }
68 
69 void vulkan_shader_destroy(vulkan_context *context) { UNUSED(context); }
#define UNUSED(x)
Mark parameter as unused.
Definition: defines.h:21
#define KB_NULL
Value of an invalid ptr (nullptr).
Definition: defines.h:18
Interface to access the platform's filesystem.
@ FILE_MODE_READ
Needed to be able to read from a file.
Definition: filesystem.h:17
#define KB_ASSERT(expr,...)
Perform runtime assertion and log failures.
Definition: log.h:133
#define KB_FATAL(...)
Log entry with fatal log level.
Definition: log.h:141
#define KB_WARN(...)
Log entry with warn log level.
Definition: log.h:161
Handle for a file.
Definition: filesystem.h:25