我正在尝试创建余弦曲线和轴的折线图。我遇到的问题是line_strip将在绘制线后继续绘制轴(即我预期线要绘制,停止,然后轴开始分别绘制。现在发生的是线绘制线和轴全部作为一个line_strip)。一个更奇怪的事情,我不明白的是,即使我删除线:
//Draw axes
glBindBuffer(GL_ARRAY_BUFFER, axesBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_LINE_STRIP, 0, 2); // x axis
glDrawArrays(GL_LINE_STRIP, 2, 2); // y axis
glDrawArrays(GL_LINE_STRIP, 4, 2); // z axis
glDisableVertexAttribArray(0);
我认为它会完全停止绘制轴,它们仍然被绘制!
相关代码如下所示:
//Vertices for the axes in 3 dimesions
const float axesPositions[] = {
-1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, -1.0, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, -1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
};
//calculates cosine line vertices
std::vector<float> fillPositions()
{
std::vector<float> arr;
for (float x = -1.0f; x < 1.0f; x += 0.01f)
{
float y;
if (x == 0) y = 1; //divide by zero check
y = cos(x);
arr.push_back(x);
arr.push_back(y);
arr.push_back(0.0f);
arr.push_back(1.0f);
}
return arr;
}
GLuint positionBufferObject;
GLuint axesBufferObject;
GLuint vao;
std::vector<float> linePositions;
void InitializeVertexBuffers()
{
//genereate line graph vertex buffer
glGenBuffers(1, &positionBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * linePositions.size(), &linePositions[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//generate axes vertex buffer
glGenBuffers(1, &axesBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, axesBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(axesPositions), axesPositions, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//Called after the window and OpenGL are initialized. Called exactly once, before the main loop.
void init()
{
InitializeProgram();
linePositions = fillPositions();
InitializeVertexBuffers();
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
}
//Called to update the display.
void display()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(theProgram);
// Draw line
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_LINE_STRIP, 0, linePositions.size());
glDisableVertexAttribArray(0);
//Draw axes
glBindBuffer(GL_ARRAY_BUFFER, axesBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_LINE_STRIP, 0, 2); // x axis
glDrawArrays(GL_LINE_STRIP, 2, 2); // y axis
glDrawArrays(GL_LINE_STRIP, 4, 2); // z axis
glDisableVertexAttribArray(0);
glUseProgram(0);
glutSwapBuffers();
glutPostRedisplay();
}
答案 0 :(得分:3)
linePositions.size()是数组中的浮点数,而不是要绘制的顶点数。
更改此行:
glDrawArrays(GL_LINE_STRIP, 0, linePositions.size());
到此:
glDrawArrays(GL_LINE_STRIP, 0, linePositions.size()/4);