下面的代码工作正常并绘制一个等边的彩色三角形:
GLfloat triangle_pos[] =
{
-0.5, -0.25, 0.0,
0.5, -0.25, 0.0,
0.0, 0.559016994, 0.0
};
void draw_triangle()
{
glUseProgram(SHADER.program);
matrix mv;
multiply_matrix(VIEW_MATRIX/*ident*/, MODEL_MATRIX/*ident*/, mv);
matrix mvp;
multiply_matrix(PROJECTION_MATRIX/*ortho*/, mv, mvp);
glUniformMatrix4fv(SHADER.uniforms[0]/*um_mvp*/, 1, GL_FALSE, mvp);
glEnableVertexAttribArray(SHADER.atributes[0]/*av_pos*/);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, triangle_pos);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(SHADER.atributes[0]/*av_pos*/);
glUseProgram(0);
}
顶点着色器:
attribute vec4 av_pos;
varying vec4 vv_col;
uniform mat4 um_mvp;
void main()
{
vv_col = um_mvp * av_pos;
gl_Position = vv_col;
}
片段着色器:
precision lowp float;
varying vec4 vv_col;
void main()
{
gl_FragColor = vv_col;
}
让我们更改顶点着色器以从外部加载颜色值:
attribute vec4 av_pos;
attribute vec4 av_col;
varying vec4 vv_col;
uniform mat4 um_mvp;
void main()
{
vv_col = av_col
gl_Position = um_mvp * av_pos;
}
修改后的代码将是:
GLfloat triangle_pos[] =
{
-0.5, -0.25, 0.0,
0.5, -0.25, 0.0,
0.0, 0.559016994, 0.0
};
GLfloat triangle_col[]=
{
1.0,0.0,1.0,1.0,
0.0,1.0,1.0,1.0,
1.0,0.0,0.0,1.0
};
void draw_triangle()
{
glUseProgram(SHADER.program);
matrix mv;
multiply_matrix(VIEW_MATRIX, MODEL_MATRIX, mv);
matrix mvp;
multiply_matrix(PROJECTION_MATRIX, mv, mvp);
glUniformMatrix4fv(SHADER.uniforms[0]/*um_mvp*/, 1, GL_FALSE, mvp);
glEnableVertexAttribArray(SHADER.atributes[0]/*av_pos*/);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, triangle_pos);
glEnableVertexAttribArray(SHADER.atributes[1]/*av_col*/);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, triangle_col);
glDrawArrays(GL_TRIANGLES, 0, 3); // just crashing i can't even glGetError() after that line
glDisableVertexAttribArray(SHADER.atributes[0]);
glDisableVertexAttribArray(SHADER.atributes[1]);
glUseProgram(0);
}
为什么glDrawArrays崩溃以及如何解决?
答案 0 :(得分:4)
glEnableVertexAttribArray(SHADER.atributes[0]/*av_pos*/);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, triangle_pos);
glEnableVertexAttribArray(SHADER.atributes[1]/*av_col*/);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, triangle_col);
glVertexAttribPointer
的第一个参数是要设置的属性。它与您给glEnableVertexAttribArray
的值相同。所以这应该是:
glEnableVertexAttribArray(SHADER.atributes[0]/*av_pos*/);
glVertexAttribPointer(SHADER.atributes[0], 3, GL_FLOAT, GL_FALSE, 0, triangle_pos);
glEnableVertexAttribArray(SHADER.atributes[1]/*av_col*/);
glVertexAttribPointer(SHADER.atributes[1], 4, GL_FLOAT, GL_FALSE, 0, triangle_col);