summary refs log tree commit diff stats
path: root/src/renderer/shader.cpp
blob: 735fc22478679939a462bbbcd40b83f898a916aa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "shader.h"
#include <fstream>
#include <vector>
#include "util.h"

Shader::Shader(std::string name)
{
  GLShader vertexShader(GL_VERTEX_SHADER);
  GLShader fragmentShader(GL_FRAGMENT_SHADER);

  std::ifstream vertexFile("shaders/" + name + ".vertex");
  std::ifstream fragmentFile("shaders/" + name + ".fragment");

  std::string vertexCode(slurp(vertexFile));
  std::string fragmentCode(slurp(fragmentFile));

  const char* vertexCodePtr = vertexCode.c_str();
  const char* fragmentCodePtr = fragmentCode.c_str();

  glShaderSource(vertexShader.getId(), 1, &vertexCodePtr, nullptr);
  glShaderSource(fragmentShader.getId(), 1, &fragmentCodePtr, nullptr);

  glCompileShader(vertexShader.getId());
  glCompileShader(fragmentShader.getId());

#ifdef DEBUG
  GLint result = GL_FALSE;
  int infoLogLength;

  glGetShaderiv(vertexShader.getId(), GL_COMPILE_STATUS, &result);

  if (result == GL_FALSE)
  {
    glGetShaderiv(vertexShader.getId(), GL_INFO_LOG_LENGTH, &infoLogLength);

    std::vector<char> errMsg(infoLogLength);
    glGetShaderInfoLog(
      vertexShader.getId(),
      infoLogLength,
      nullptr,
      errMsg.data());

    throw std::gl_error("Could not compile shader", errMsg.data());
  }

  glGetShaderiv(fragmentShader.getId(), GL_COMPILE_STATUS, &result);

  if (result == GL_FALSE)
  {
    glGetShaderiv(fragmentShader.getId(), GL_INFO_LOG_LENGTH, &infoLogLength);

    std::vector<char> errMsg(infoLogLength);
    glGetShaderInfoLog(
      fragmentShader.getId(),
      infoLogLength,
      nullptr,
      errMsg.data());

    throw std::gl_error("Could not compile shader", errMsg.data());
  }
#endif

  glAttachShader(program_.getId(), vertexShader.getId());
  glAttachShader(program_.getId(), fragmentShader.getId());
  glLinkProgram(program_.getId());

#ifdef DEBUG
  glGetProgramiv(program_.getId(), GL_LINK_STATUS, &result);

  if (result == GL_FALSE)
  {
    glGetProgramiv(program_.getId(), GL_INFO_LOG_LENGTH, &infoLogLength);

    std::vector<char> errMsg(infoLogLength);
    glGetProgramInfoLog(
      program_.getId(),
      infoLogLength,
      nullptr,
      errMsg.data());

    throw std::gl_error("Could not link shader program", errMsg.data());
  }
#endif
}