engine/src/resources/shader.cpp

50 lines
1.6 KiB
C++
Raw Normal View History

2022-09-02 11:06:59 +00:00
#include "resources/shader.hpp"
2022-10-27 22:06:56 +00:00
#include "log.hpp"
2022-09-02 11:06:59 +00:00
2022-10-27 22:06:56 +00:00
#include "gfx_device.hpp"
2022-09-02 11:06:59 +00:00
#include <string>
#include <fstream>
#include <vector>
#include <span>
static std::unique_ptr<std::vector<char>> readFile(const char * path)
{
std::ifstream file(path, std::ios::binary | std::ios::ate);
//file.exceptions(std::ifstream::failbit); // throw exception if file cannot be opened
if (file.fail()) {
throw std::runtime_error("Failed to open file for reading: " + std::string(path));
}
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
auto buf = std::make_unique<std::vector<char>>();
buf->resize(size);
file.rdbuf()->sgetn(buf->data(), size);
return buf;
}
2022-10-06 10:30:44 +00:00
namespace engine::resources {
2022-09-02 11:06:59 +00:00
Shader::Shader(const std::filesystem::path& resPath) : Resource(resPath, "shader")
{
2022-10-27 22:06:56 +00:00
gfx::VertexFormat vertexFormat {};
vertexFormat.attributeDescriptions.emplace_back(0, gfx::VertexAttribFormat::VEC3, 0); // pos
vertexFormat.attributeDescriptions.emplace_back(1, gfx::VertexAttribFormat::VEC3, sizeof(glm::vec3)); // norm
vertexFormat.attributeDescriptions.emplace_back(2, gfx::VertexAttribFormat::VEC2, sizeof(glm::vec3) + sizeof(glm::vec3)); // uv
2022-09-02 11:06:59 +00:00
2022-10-27 22:06:56 +00:00
const std::string vertexShaderPath = (resPath.parent_path()/std::filesystem::path(resPath.stem().string() + ".vert.spv")).string();
const std::string fragmentShaderPath = (resPath.parent_path()/std::filesystem::path(resPath.stem().string() + ".frag.spv")).string();
2022-09-02 11:06:59 +00:00
2022-10-27 22:06:56 +00:00
m_pipeline = gfxdev->createPipeline(vertexShaderPath.c_str(), fragmentShaderPath.c_str(), vertexFormat, sizeof(UniformBuffer));
2022-09-02 11:06:59 +00:00
}
Shader::~Shader()
{
2022-10-27 22:06:56 +00:00
gfxdev->destroyPipeline(m_pipeline);
2022-09-02 11:06:59 +00:00
}
}