openGL 绘图 GL_LINES 给出不正确的结果

openGL drawing GL_LINES giving incorrect result

我正在尝试绘制速度矢量网格,我希望每个网格点的速度是一条斜率为 1 的线。一条斜线,但我总是以一条垂直线结束。我不确定我做错了什么。有什么我忽略的吗?

这是我的顶点缓冲区的样子:

float vel_pos[6*(N+2)*(N+2)];
int index1 = 0;
for (int i=0;i<N+2;i++)
{
    for (int j=0;j<N+2;j++)
    {
        vel_pos[index1] = float(i);
        vel_pos[index1+1] = float(j);
        vel_pos[index1+2] = 0.0f;
        vel_pos[index1+3] = float(i) +0.5f;
        vel_pos[index1+4] = float(j) + 0.5f;
        vel_pos[index1+5] = 0.0f;
        index1 += 6;
    }
}

以下是我创建 VBO 和 VAO 的方式:

unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);

// Bind vertex array object first and then bind the vertex buffer objects
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

glBufferData(GL_ARRAY_BUFFER, sizeof(vel_pos), vel_pos, GL_STREAM_DRAW);


GLint velAttrib = glGetAttribLocation(ourShader.ID, "aPos");

// iterpreting data from buffer 
glVertexAttribPointer(velAttrib, 3, GL_FLOAT, GL_FALSE,  6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

这是我的顶点着色器:

  out vec4 vertexColor;
  layout (location = 0) in vec3 aPos; 
  layout (location = 1) in float densitySource; /* source of density */
  uniform mat4 transform;
  uniform mat4 projection;

  void main()
  {
  gl_Position = projection*transform * vec4(aPos, 1.0);
  vertexColor = vec4(1, 0.0, 0.0, 1.0);
  }

这是我的绘图代码:

  ourShader.use();

    glm::mat4 trans = glm::mat4(1.0f);
    trans = glm::translate(trans, glm::vec3(-0.5f, -0.5f, 0.0f));
    unsigned int transformMatrixLocation = glGetUniformLocation(ourShader.ID, "transform");
    glUniformMatrix4fv(transformMatrixLocation, 1, GL_FALSE, glm::value_ptr(trans));

    glm::mat4 projection = glm::ortho(-10.0f, 110.0f, -1.0f, 110.0f, -1.0f, 100.0f);

    unsigned int projectionMatrixLocation = glGetUniformLocation(ourShader.ID, "projection");
    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projection));

    glBindVertexArray(VAO); 
    glLineWidth(1.0f);
    glDrawArrays(GL_LINES,  0, (N+2)*(N+2));

这是我得到的图像: resulting image

glVertexAttribPointer 的第 5 个参数 (stride) 是两个顶点坐标之间的偏移量,而不是图元之间的偏移量。由于您的顶点坐标有 3 个 float 类型的分量,因此偏移量必须为 3 * sizeof(float):

glVertexAttribPointer(velAttrib, 3, GL_FLOAT, GL_FALSE,  3 * sizeof(float), (void*)0);

因为您设置了 6 * sizeof(float) 的偏移量,所以您跳过了每 2 个坐标并在网格点之间画了线。

但请注意,如果 stride 为 0,则通用顶点属性被理解为紧密打包在数组中。情况就是这样,所以你不能使用偏移量 0:

glVertexAttribPointer(velAttrib, 3, GL_FLOAT, GL_FALSE,  0, (void*)0);