-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShader.cpp
More file actions
94 lines (76 loc) · 2.34 KB
/
Shader.cpp
File metadata and controls
94 lines (76 loc) · 2.34 KB
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
90
91
92
93
94
#include <Shader.h>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
// --- Load GLSL source from file ----
string Shader::loadFile(const string& path)
{
ifstream file(path);
if (!file.is_open())
{
cerr << "[Shader] Cannotopen: " << path << endl;
return "";
}
stringstream buf;
buf << file.rdbuf();
return buf.str();
}
// --- Compile one shader stage ---
GLuint Shader::compile(const string& src, GLenum type)
{
const char* c = src.c_str();
GLuint id = glCreateShader(type);
glShaderSource(id, 1, &c, NULL);
glCompileShader(id);
int ok;
glGetShaderiv(id, GL_COMPILE_STATUS, &ok);
if (!ok){
char log[1024];
glGetShaderInfoLog(id, 1024, NULL, log);
cerr << "[Shader] Compile error ("
<< (type == GL_VERTEX_SHADER ? "VERT" : "FRAG")
<< "):\n" << log << endl;
}
return id;
}
// ------ Constructor: compile + link ------
Shader::Shader(const string& vertPath, const string& fragPath)
{
GLuint vert = compile(loadFile(vertPath), GL_VERTEX_SHADER);
GLuint frag = compile(loadFile(fragPath), GL_FRAGMENT_SHADER);
ID = glCreateProgram();
glAttachShader(ID, vert);
glAttachShader(ID, frag);
glLinkProgram(ID);
int ok;
glGetProgramiv(ID, GL_LINK_STATUS, &ok);
if (!ok)
{
char log[1024];
glGetProgramInfoLog(ID, 1024, NULL, log);
cerr << "[Shader] Link error:\n" << log << endl;
}
glDeleteShader(vert);
glDeleteShader(frag);
}
void Shader::use() { glUseProgram(ID); }
GLuint Shader::getID() const { return ID; }
void Shader::setInt(const string& name, int v){
glUniform1i(glGetUniformLocation(ID, name.c_str()), v);
}
void Shader::setFloat(const string& name, float v){
glUniform1f(glGetUniformLocation(ID, name.c_str()), v);
}
void Shader::setBool(const string& name, bool v){
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)v);
}
void Shader::setVec2(const string& name, float x, float y) {
glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
}
void Shader::setVec3(const string& name, float x, float y, float z){
glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
}
void Shader::setMat4(const string& name, const float* v){
glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, v);
}