-
Notifications
You must be signed in to change notification settings - Fork 1
/
shader.cpp
89 lines (75 loc) · 2.55 KB
/
shader.cpp
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
85
86
87
88
89
#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include "shader.h"
int CompileShader(const char *ShaderPath, const GLuint ShaderID)
{
// Read shader code from file
std::string ShaderCode;
std::ifstream ShaderStream (ShaderPath, std::ios::in);
if (ShaderStream.is_open()) {
std::string Line = "";
while (getline(ShaderStream, Line)) {
ShaderCode += "\n" + Line;
}
ShaderStream.close();
}
else {
std::cerr << "Cannot open " << ShaderPath << ". Are you in the right directory?" << std::endl;
return 0;
}
// Compile Shader
char const *SourcePointer = ShaderCode.c_str();
glShaderSource(ShaderID, 1, &SourcePointer , NULL);
glCompileShader(ShaderID);
// Check Shader
GLint Result = GL_FALSE;
int InfoLogLength;
glGetShaderiv(ShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(ShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
printf("compiled shader %d %d\n", Result, InfoLogLength);
if ( InfoLogLength > 1 ) {
char ShaderErrorMessage[InfoLogLength+1];
glGetShaderInfoLog( ShaderID,
InfoLogLength,
NULL,
&ShaderErrorMessage[0]);
std::cerr << &ShaderErrorMessage[0] << std::endl;
return 0;
}
return 1;
}
GLuint LoadShaders(const char * vertex_file_path,
const char * fragment_file_path )
{
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
std::cout << "Created Shaders" << std::endl;
// Compile both shaders. Exit if compile errors.
if ( !CompileShader(vertex_file_path, VertexShaderID)
|| !CompileShader(fragment_file_path, FragmentShaderID) ) {
return 0;
}
// Link the program
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
GLint Result = GL_FALSE;
int InfoLogLength;
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ) {
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
std::cerr << &ProgramErrorMessage[0] << std::endl;
}
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}