我试图操纵一些代码来绘制一个圆而不是教程已经打印的三角形。我不熟悉C ++或OpenGL,这就是为什么我只是尝试一下。
我的代码的任何建议或更正将不胜感激。 我在这行上的XCODE中一直遇到断点错误:
glDrawArrays(GL_TRIANGLE_FAN, 0, numPoints); // draw the points and fill it in
它说:
Thread 1: EXC_BAD_ACCESS(code=1, address=0x0)
以下是教程I' m中三角形的原始矢量缓冲区:
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
我很确定我的计算是正确的,但我不知道为什么会这样做。不画圆圈。这是我的操纵:
// Make a circle
GLfloat x;
GLfloat y;
GLfloat z = 0.0f;
int theta = 0;
float radius = 50.0f;
int currentSize = 0;
int numPoints = 30;
GLfloat g_vertex_buffer_data[numPoints*3];
while (theta <= 360) {
x = (GLfloat) radius * cosf(theta);
y = (GLfloat) radius * sinf(theta);
g_vertex_buffer_data[currentSize++] = x;
g_vertex_buffer_data[currentSize++] = y;
g_vertex_buffer_data[currentSize++] = z;
/*
cout << "Theta: " << theta << endl;
for (int i = 0; i < currentSize; i++) {
cout << "g_vertex_buffer_data[" << g_vertex_buffer_data[i] << "]" << endl;
}
*/
theta = theta + (360/numPoints);
}
以下是.cpp文件中的其余代码:
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data),g_vertex_buffer_data, GL_STATIC_DRAW);
do{
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT );
// Use our shader
glUseProgram(programID);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(vertexPosition_modelspaceID);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
vertexPosition_modelspaceID, // The attribute we want to configure
numPoints, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the circle!
glDrawArrays(GL_TRIANGLE_FAN, 0, numPoints); // draw the points and fill it in
glDisableVertexAttribArray(vertexPosition_modelspaceID);
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
// Cleanup VBO
glDeleteBuffers(1, &vertexbuffer);
glDeleteProgram(programID);
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
答案 0 :(得分:2)
此代码中存在一些问题。可能导致崩溃的最严重的一个是:
glVertexAttribPointer(
vertexPosition_modelspaceID, // The attribute we want to configure
numPoints, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glVertexAttribPointer()
的第二个参数是每个顶点的组件数。由于每个顶点有3个浮点数(x,y和z),因此正确的值为3.因此调用应为:
glVertexAttribPointer(
vertexPosition_modelspaceID, // The attribute we want to configure
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
创建点时还存在一次性错误:
while (theta <= 360) {
如果在范围中包含360,则将有效地重复第一个顶点,并写入比分配的空间多一个顶点。这应该是:
while (theta < 360) {
此外,cosf()
和sinf()
的参数都是弧度。因此,您必须将这些角度从度数转换为弧度:
x = (GLfloat) radius * cosf(theta * M_PI / 180.0f);
y = (GLfloat) radius * sinf(theta * M_PI / 180.0f);