render_system.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "render_system.h"
  2. #include "vk_initializers.h"
  3. #include <stdexcept>
  4. using namespace coral_3d;
  5. struct PushConstant
  6. {
  7. alignas(16) glm::mat3 transform;
  8. alignas(16) glm::vec3 offset;
  9. alignas(16) glm::vec3 color;
  10. };
  11. render_system::render_system(coral_device& device, VkRenderPass render_pass)
  12. : device_{device}
  13. {
  14. create_pipeline_layout();
  15. create_pipeline(render_pass);
  16. }
  17. render_system::~render_system()
  18. {
  19. vkDestroyPipelineLayout(device_.device(), pipeline_layout_, nullptr);
  20. }
  21. void render_system::render_gameobjects(VkCommandBuffer command_buffer, std::vector<coral_gameobject>& gameobjects)
  22. {
  23. pipeline_->bind(command_buffer);
  24. for (auto& obj : gameobjects)
  25. {
  26. PushConstant push{};
  27. push.offset = obj.transform_.translation;
  28. push.color = obj.color_;
  29. push.transform = obj.transform_.mat3();
  30. vkCmdPushConstants(
  31. command_buffer,
  32. pipeline_layout_,
  33. VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
  34. 0, sizeof(PushConstant), &push);
  35. obj.mesh_->bind(command_buffer);
  36. obj.mesh_->draw(command_buffer);
  37. }
  38. }
  39. void render_system::create_pipeline_layout()
  40. {
  41. VkPushConstantRange push_constant_range{};
  42. push_constant_range.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
  43. push_constant_range.offset = 0;
  44. push_constant_range.size = sizeof(PushConstant);
  45. VkPipelineLayoutCreateInfo layout_info{ vkinit::pipeline_layout_ci() };
  46. layout_info.pushConstantRangeCount = 1;
  47. layout_info.pPushConstantRanges = &push_constant_range;
  48. if (vkCreatePipelineLayout(device_.device(), &layout_info, nullptr, &pipeline_layout_) != VK_SUCCESS)
  49. throw std::runtime_error("ERROR! first_app::create_pipeline_layout() >> Failed to create pipeline layout!");
  50. }
  51. void render_system::create_pipeline(VkRenderPass render_pass)
  52. {
  53. assert(pipeline_layout_ != nullptr &&
  54. "ERROR! first_app::create_pipeline() >> Cannot create pipeline before pipeline layout!");
  55. PipelineConfigInfo pipeline_config{};
  56. coral_pipeline::default_pipeline_config_info(pipeline_config);
  57. pipeline_config.render_pass = render_pass;
  58. pipeline_config.pipeline_layout = pipeline_layout_;
  59. pipeline_ = std::make_unique<coral_pipeline>(
  60. device_,
  61. // "shaders/PosNormCol.vert.spv",
  62. // "shaders/PosNormCol.frag.spv",
  63. "shaders/simple_shader.vert.spv",
  64. "shaders/simple_shader.frag.spv",
  65. pipeline_config
  66. );
  67. }