这个着色器似乎无法编译我正在使用 c++ 和 glew,openGL。 glew 版本为 2.2.0,openGL 版本为 4.6。 glGetShaderInfoLog() 函数只返回废话。已编译的着色器 ID 仅返回 0。glGetShaderiv() 返回 GLEW_ERROR_NO_GL_VERSION。这是着色器和用于编译和链接着色器的 C++ 代码。
初始化
glfwSetErrorCallback(GlfwErrorCallback);
if(!glfwInit()) ERROR("failed to initialize glfw\n");
LOG("glfw version: " << glfwGetVersionString() << "\n");
m_Window = glfwCreateWindow(800, 800, "Cotton Game Engine", NULL, NULL);
if(!m_Window) ERROR("failed to create window\n");
glfwMakeContextCurrent(m_Window);
if(glewInit() != GLEW_OK) ERROR("failed to initialize glew\n");
LOG("glew version: " << glewGetString(GLEW_VERSION) << "\n");
LOG("opengl version: " << glGetString(GL_VERSION) << "\n");
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(GlErrorCallback, 0);
顶点着色器
#version 460 core
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec4 a_Color;
layout(location = 2) in vec2 a_TexCoord;
layout(location = 3) in float a_TexIndex;
uniform mat4 u_MVP;
out vec4 v_Color;
out vec2 v_TexCoord;
out float v_TexIndex;
void main()
{
v_TexCoord = a_TexCoord;
v_Color = a_Color;
v_TexIndex = a_TexIndex;
gl_Position = u_MVP * vec4(a_Position, 1.0);
}
片段着色器
#version 460 core
layout(location = 0) out vec4 o_Color;
in vec4 v_Color;
in vec2 v_TexCoord;
in float v_TexIndex;
uniform sampler2D u_Textures[10];
void main()
{
o_Color = texture(u_Textures[int(v_TexIndex)], v_TexCoord) * v_Color;
}
C++ 方面
Shader::Shader(const std::string &vertexFilepath, const std::string &fragmentFilepath)
{
std::string vertexSource = ReadFileIntoString(vertexFilepath);
std::string fragmentSource = ReadFileIntoString(fragmentFilepath);
m_ID = CreateShader(vertexSource, fragmentSource);
}
unsigned int Shader::CreateShader(const std::string& vertexSource, const std::string& fragmentSource)
{
unsigned int program = glCreateProgram();
unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexSource);
unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentSource);
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vs);
glDeleteShader(fs);
return program;
}
unsigned int Shader::CompileShader(unsigned int type, const std::string& source)
{
unsigned int id = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if(result != GLEW_OK) {
char message[128];
glGetShaderInfoLog(id, sizeof(message), NULL, message);
ERROR("could not compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " shader: " << message << "\n");
glDeleteShader(id);
return 0;
}
return id;
}