具有交错法线的VertexBufferObject

时间:2013-04-16 21:14:51

标签: c++ opengl vertex-buffer

我有一个工作的Vertex-Buffer-Object但我需要添加法线。 normales存储在与顶点位置相同的数组中。它们是交错的

Vx Vy Vz Nx Ny Nz

到目前为止,这是我的代码:

GLfloat值[NUM_POINTS * 3 + NUM_POINTS * 3]; void initScene(){

for(int i = 0; i < (NUM_POINTS) ; i = i+6){
    values[i+0] = bunny[i];
    values[i+1] = bunny[i+1];
    values[i+2] = bunny[i+2];
    values[i+3] = normals[i];
    values[i+4] = normals[i+1];
    values[i+5] = normals[i+2];
}

glGenVertexArrays(1,&bunnyVAO);
glBindVertexArray(bunnyVAO);


glGenBuffers(1, &bunnyVBO);
glBindBuffer(GL_ARRAY_BUFFER, bunnyVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(bunny), bunny, GL_STATIC_DRAW);

glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 0,0);
glEnableVertexAttribArray(0);

glGenBuffers(1, &bunnyIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bunnyIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(triangles), triangles, GL_STATIC_DRAW);



// unbind active buffers //
  glBindVertexArray(0);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void renderScene() {
  if (bunnyVBO != 0) {
    // x: bind VAO //
      glEnableClientState(GL_VERTEX_ARRAY);
      glBindVertexArray(bunnyVAO);
      glDrawElements(GL_TRIANGLES, NUM_TRIANGLES, GL_UNSIGNED_INT, NULL);
      glDisableClientState(GL_VERTEX_ARRAY);
    // unbind active buffers //
    glBindVertexArray(0);
  }
}

我可以在屏幕上看到一些内容,但由于法线使用不正确而不正确... 到目前为止,如何使用与我的代码正确连接的values数组。

1 个答案:

答案 0 :(得分:2)

你需要两次调用glVertexAttribPointer,一次用于顶点,一次用于法线。这就是告诉OpenGL如何在顶点缓冲区中布置数据的方法。

// Vertices consist of 3 floats, occurring every 24 bytes (6 floats), 
// starting at byte 0.
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, 0);

// Normals consist of 3 floats, occurring every 24 bytes starting at byte 12.
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, 12);

这假设着色器中的普通属性的索引为1。