Shader.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #ifndef SHADER_H
  2. #define SHADER_H
  3. #include "data/Array.h"
  4. #include "data/List.h"
  5. #include "math/Matrix.h"
  6. #include "rendering/GL.h"
  7. #include "utils/Error.h"
  8. class Shader final {
  9. static constexpr int MAX_SHADERS = 5;
  10. Array<GL::Shader, MAX_SHADERS> shaders;
  11. GL::Program program;
  12. public:
  13. Shader();
  14. ~Shader();
  15. Shader(const Shader& other) = delete;
  16. Shader(Shader&& other) = delete;
  17. Shader& operator=(const Shader& other) = delete;
  18. Shader& operator=(Shader&& other) = delete;
  19. template<typename... Args>
  20. Error compile(Args&&... args) {
  21. const int size = sizeof...(args);
  22. const char* paths[static_cast<unsigned int>(size)] = {args...};
  23. static_assert(size <= MAX_SHADERS, "too much shaders paths given");
  24. for(int i = 0; i < size; i++) {
  25. GL::ShaderType type = getShaderType(paths[i]);
  26. if(type == GL::NO_SHADER) {
  27. Error error = {"'"};
  28. error.message.append(paths[i]).append(
  29. "' is not a valid shader type");
  30. return error;
  31. }
  32. Error error = readAndCompile(paths[i], shaders[i], type);
  33. if(error.has()) {
  34. return error;
  35. }
  36. }
  37. program = GL::createProgram();
  38. for(GL::Shader shader : shaders) {
  39. if(shader != 0) {
  40. GL::attachShader(program, shader);
  41. }
  42. }
  43. GL::linkProgram(program);
  44. Error error = GL::getError("cannot link");
  45. if(error.has()) {
  46. return error;
  47. }
  48. return GL::getLinkerError(program);
  49. }
  50. void use() const;
  51. void setMatrix(const char* name, const float* data);
  52. void setMatrix(const char* name, const Matrix& m);
  53. void setInt(const char* name, int data);
  54. void setFloat(const char* name, float data);
  55. void setVector(const char* name, const Vector2& v);
  56. void setVector(const char* name, const Vector3& v);
  57. void setVector(const char* name, const Vector4& v);
  58. private:
  59. GL::ShaderType getShaderType(const char* path) const;
  60. Error readAndCompile(const char* path, GL::Shader& s, GL::ShaderType st);
  61. Error readFile(List<char>& code, const char* path) const;
  62. Error compileType(GL::Shader& s, const List<char>& code, GL::ShaderType st);
  63. };
  64. #endif