使用openGL渲染场景

时间:2013-10-25 10:38:25

标签: opengl c++11 vertex-array

我将使用openGL渲染包含各种网格的场景。网格定义如下:

struct Mesh {
frame3f         frame;      // frame
vector<vec3f>   pos;        // vertex position
vector<vec3f>   norm;       // vertex normal
vector<vec2f>   texcoord;   // vertex texcture coordinates
vector<vec3i>   triangle;   // triangle
vector<vec4i>   quad;       // quad
Material*       mat;        // material}

网格可以由三角形和四边形组成,我尝试使用以下代码渲染顶点:

for (auto mesh : scene->meshes)
{
    // bind material kd, ks, n
    glVertexAttrib3f(material_kd_loc, mesh->mat->kd.x, mesh->mat->kd.y, mesh->mat->kd.z);
    glVertexAttrib3f(material_ks_loc, mesh->mat->ks.x, mesh->mat->ks.y, mesh->mat->ks.z);
    glVertexAttrib1f(material_n_loc, mesh->mat->n);

    // bind mesh frame - use frame_to_matrix
    mat4f mesh_mat = frame_to_matrix(mesh->frame);
    glUniformMatrix4fv(mesh_frame_loc, 1, GL_TRUE, &mesh_mat[0][0]);

    // enable vertex attributes arrays
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    //and set up pointers to the mesh data
    glVertexAttribPointer(vertex_pos_loc, mesh->pos.size(), GL_FLOAT, GL_FALSE, 0, mesh->pos.data());
    glVertexAttribPointer(vertex_norm_loc, mesh->norm.size(), GL_FLOAT, GL_TRUE, 0, mesh->norm.data());

    // draw triangles and quads
    if (mesh->triangle.size() != 0){

        glDrawElements(GL_TRIANGLES, mesh->pos.size(), GL_UNSIGNED_INT, mesh->triangle.data());
    }
    if (mesh->quad.size() != 0){
        glDrawElements(GL_QUADS, mesh->pos.size(), GL_UNSIGNED_INT, mesh->quad.data());

    }
    // disable vertex attribute arrays
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

} 这是我画的(不关心颜色,因为我还没有计算它们) this is what i draw (don't care about colors as i don't calculate them yet)

如果我的代码是正确的,这就是我应该看到的 this is what i should see if my code is correct

任何人都知道错误在哪里?

2 个答案:

答案 0 :(得分:0)

glDrawElements(GL_TRIANGLES, mesh->pos.size(), GL_UNSIGNED_INT, mesh->triangle.data());
glDrawElements(GL_QUADS, mesh->quad.size(), GL_UNSIGNED_INT, mesh->quad.data());

看看两个电话的第二个参数。四边形不正确。

glVertexAttribPointer(vertex_pos_loc, mesh->pos.size(), GL_FLOAT, GL_FALSE, 0, mesh->pos.data());

也不正确 - 第二个参数是每个顶点的组件数,而不是数组的大小。

答案 1 :(得分:0)

看起来像opengl函数想要写入vertecx的总数而不仅仅是不同顶点的数量。这样:

glDrawElements(GL_TRIANGLES, mesh->triangle.size()*3, GL_UNSIGNED_INT, mesh->triangle.data());
glDrawElements(GL_QUADS, mesh->quad.size()*4, GL_UNSIGNED_INT, mesh->quad.data());