我昨天开始学习GLSL,并按照OpenGL 4.0 Shading Language Cookbook中的第一个例子逐步绘制三角形。
以下是我的代码:
1.shader.vert
#version 400
in vec3 VertexPosition;
in vec3 VertexColor;
out vec3 Color;
void main()
{
Color = VertexColor;
gl_Position = vec4(VertexPosition, 1.0);
}
2.shader.frag
#version 400
in vec3 Color;
out vec4 FragColor;
void main(){
FragColor = vec4(Color, 1.0);
}
3.main.cpp
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(500, 500);
glutCreateWindow("Project1");
glutDisplayFunc(render);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 100, 0, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_POINT_SMOOTH);
// init glew
GLenum err = glewInit();
if (GLEW_OK != err){
printf("Error: %s\n", glewGetErrorString(err));
}
else{
printf("OK: glew init.\n");
}
// check gl version
const GLubyte *renderer = glGetString(GL_RENDERER);
const GLubyte *vendor = glGetString(GL_VENDOR);
const GLubyte *version = glGetString(GL_VERSION);
const GLubyte *glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
printf("GL Vendor : %s\n", vendor);
printf("GL Renderer : %s\n", renderer);
printf("GL Version (string) : %s\n", version);
printf("GL Version (integer): %d.%d\n", major, minor);
printf("GLSL Version: %s\n", glslVersion);
// vertex shader
GLuint vertShader = createAndCompileShader("shader.vert", VERTEX);
// fragment shader
GLuint fragShader = createAndCompileShader("shader.frag", FRAGMENT);
// program
GLuint programHandle = glCreateProgram();
if (programHandle == 0)
{
printf("Error creating program object.\n");
}
glAttachShader(programHandle, vertShader);
glAttachShader(programHandle, fragShader);
glLinkProgram(programHandle);
GLint status;
glGetProgramiv(programHandle, GL_LINK_STATUS, &status);
if (GL_FALSE == status){
printf("Failed to link shader program");
}
else{
printf("OK\n");
glUseProgram(programHandle);
}
glutMainLoop();
return EXIT_SUCCESS;
}
我在createAndCompileShader
中创建并编译着色器,编译状态成功。
我在render
函数中绘制了一个三角形。
void render()
{
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(20, 20);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(80, 20);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(50, 80);
glEnd();
glPopMatrix();
glutSwapBuffers();
}
链接的状态也是成功的。但是,窗口中没有任何内容。我确定函数render
是正确的。
有什么不对吗?
答案 0 :(得分:1)
如果您没有绑定任何GLSL着色器,您的三角形是否可见?
glDisable(GL_CULL_FACE);
你有什么显卡和驱动程序?
您不在顶点着色器中应用任何投影或模型视图矩阵
<-1,+1>
(-0.5,-0.5),(+0.5,-0.5),(0.0,+0.5)
//gluOrtho2D(0, 100, 0, 100);
以确保gl_Position = ftransform();
[edit1]您正在使用glVertex
代替VAO
,因此您应该使用compatibility
个人资料
// vertex shader
#version 400 compatibility
out vec3 Color;
void main()
{
Color = gl_Color.rgb;
gl_Position = ftransform();
}