Shader.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <iostream>
  2. #include "rendering/Shader.h"
  3. #include "rendering/GL.h"
  4. static const GLchar* vertexShader =
  5. "#version 430\n"
  6. "layout (location = 0) in vec2 position;\n"
  7. "layout (location = 1) in vec3 color;\n"
  8. "out vec3 varColor;\n"
  9. "void main() {\n"
  10. "gl_Position = vec4(position, 0.0, 1.0);\n"
  11. "varColor = color;\n"
  12. "}";
  13. static const GLchar* fragmentShader =
  14. "#version 430\n"
  15. "in vec3 varColor;\n"
  16. "out vec4 color;"
  17. "void main() {\n"
  18. "color = vec4(varColor, 1.0);"
  19. "}";
  20. Shader::Shader() : vShader(0), fShader(0), program(0) {
  21. if(compile(vShader, vertexShader, GL_VERTEX_SHADER) || compile(fShader, fragmentShader, GL_FRAGMENT_SHADER)) {
  22. return;
  23. }
  24. program = glCreateProgram();
  25. glAttachShader(program, vShader);
  26. glAttachShader(program, fShader);
  27. glLinkProgram(program);
  28. if(GL::checkAndPrintError("shader linking error")) {
  29. clean();
  30. return;
  31. }
  32. GLint linked;
  33. glGetProgramiv(program, GL_LINK_STATUS, &linked);
  34. if(linked == GL_FALSE) {
  35. GLchar buffer[512];
  36. glGetProgramInfoLog(program, 512, nullptr, buffer);
  37. std::cout << "programm linking info log: " << buffer << "\n";
  38. clean();
  39. return;
  40. }
  41. }
  42. Shader::~Shader() {
  43. clean();
  44. }
  45. void Shader::clean() {
  46. glDeleteProgram(program);
  47. glDeleteShader(vShader);
  48. glDeleteShader(fShader);
  49. program = 0;
  50. vShader = 0;
  51. fShader = 0;
  52. }
  53. bool Shader::hasError() const {
  54. return vShader == 0 || fShader == 0 || program == 0;
  55. }
  56. bool Shader::compile(GLuint& shader, const GLchar* code, GLenum shaderType) {
  57. shader = glCreateShader(shaderType);
  58. glShaderSource(shader, 1, &code, nullptr);
  59. glCompileShader(shader);
  60. if(GL::checkAndPrintError("shader error")) {
  61. return true;
  62. }
  63. GLint compiled;
  64. glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  65. if(compiled == GL_FALSE) {
  66. GLchar buffer[512];
  67. glGetShaderInfoLog(shader, 512, nullptr, buffer);
  68. std::cout << "shader info log: " << buffer << "\n";
  69. return true;
  70. }
  71. return false;
  72. }
  73. void Shader::use() const {
  74. glUseProgram(program);
  75. }