关于glShaderSource的openGL,GLFW,1281错误,下一个glShaderSource工作得很好

时间:2016-07-01 12:01:21

标签: c++ opengl glsl glfw

我一直试图让着色器工作。他们没有。

std::cout << "a " << glGetError() <<std::endl; //making sure things work
GLuint vertexShader = 0;
GLuint fragmentShader = 1;
glCreateShader(GL_VERTEX_SHADER);
std::cout <<"b " << glGetError() <<std::endl;
glCreateShader(GL_FRAGMENT_SHADER);
std::cout <<"c " << glGetError() <<std::endl;
glShaderSource(vertexShader, GLsizei(1), (const char**)&VertexShaderSource, NULL);//ERROR
std::cout <<"d " << glGetError() <<std::endl;
glShaderSource(fragmentShader, GLsizei(1), (const char**)&FragmentShaderSource, NULL);//is somehow fine
std::cout <<"e " << glGetError() <<std::endl;
glCompileShader(vertexShader);
std::cout <<"f " << glGetError() <<std::endl;
glCompileShader(fragmentShader);
std::cout <<"g " << glGetError() <<std::endl;'

现在,输出是:

a 0
b 0
c 0
d 1281
e 0
f 1281
g 0

这意味着第一个glShaderSource调用无效,但由于某种原因,下一个glShaderSource有效,而我认为完全相同的事情。 这里发生了什么???

着色器是:

const std::string VertexShaderSource ="#version 330 core"
                                  ""
                                  "layout (location = 0) in vec3 position;"
                                  ""
                                  "void main()"
                                  "{"
                                  "    gl_Position = vec4(position.x, position.y, position.z, 1.0);"
                                  "}";

const std::string FragmentShaderSource ="#version 330 core"
                                    ""
                                    "out vec4 color;"
                                    ""
                                    "void main()"
                                    "{"
                                    "    color = vec4(1.0f, 1.0f, 1.0f, 1.0f);"
                                    "}";

如果以这种方式传递字符串((const char**)&VertexShaderSource)是错误的,那么为什么第二次调用工作正常呢?

2 个答案:

答案 0 :(得分:3)

您必须将vertexShaderfragmentShader设置为glCreateShader的结果,而不是将其硬编码为01

GLuint vertexShader;
GLuint fragmentShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
std::cout <<"b " << glGetError() <<std::endl;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
std::cout <<"c " << glGetError() <<std::endl;

如果调用不成功,函数glCreateShader将返回0

在您的代码中,您将vertexShader硬编码为0,并且opengl报告glShaderSource(vertexShader, ...错误,因为您将0作为ID传递给glShaderSource。< / p>

1281出现GL_INVALID_VALUE错误,并报告if shader is not a value generated by OpenGL. glShaderSource: Errors

除了(const char**)&VertexShaderSource获取std::string存储您必须使用的数据的内存地址.c_str()之外display:inline-block;How to pass an std::string to glShaderSource?

答案 1 :(得分:0)

您错误地传递了字符串,正确的方法是VertexShaderSource.c_str()