尝试从OpenGL中的.obj绘制网格时,某些三角形不显示

时间:2014-11-27 16:59:00

标签: c++ opengl 3d mesh

我试图显示从.obj文件加载的对象。我用这个函数来读取.obj:

bool loadOBJ(
    const char * path, 
    std::vector<glm::vec3> & vertices,
    std::vector<glm::vec3> & vertexIndices
){
    printf("Loading OBJ file %s...\n", path);

    FILE * file = fopen(path, "r");
    if( file == NULL ){
            printf("Impossible to open the file ! Are you in the right path ? \n");
            getchar();
            return false;
    }

    while( 1 ){

            char lineHeader[128];
            // read the first word of the line
            int res = fscanf(file, "%s", lineHeader);
            if (res == EOF)
                    break; // EOF = End Of File. Quit the loop.

            // else : parse lineHeader

            if ( strcmp( lineHeader, "v" ) == 0 ){
                    glm::vec3 vertex;
                    fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
                    vertices.push_back(vertex);
            }else if ( strcmp( lineHeader, "f" ) == 0 ){

                    glm::vec3 vertexIndex;
                    fscanf(file, "%f %f %f\n", &vertexIndex.x, &vertexIndex.y, &vertexIndex.z );
                    vertexIndices.push_back(vertexIndex);
            }else{
                    // Probably a comment, eat up the rest of the line
                    char stupidBuffer[1000];
                    fgets(stupidBuffer, 1000, file);
            }

    }

    return true;
}

然后我在init函数中调用此函数。 加载网格后,我通过循环遍历顶点来显示它:

for (unsigned int i = 0; i < meshVertices.size(); i++)
    {
        glBegin(GL_TRIANGLES); 
            glVertex3f(meshVertices[faceIndices[i].x-1].x, meshVertices[faceIndices[i].x-1].y, meshVertices[faceIndices[i].x-1].z); 
            glVertex3f(meshVertices[faceIndices[i].y-1].x, meshVertices[faceIndices[i].y-1].y, meshVertices[faceIndices[i].y-1].z); 
            glVertex3f(meshVertices[faceIndices[i].z-1].x, meshVertices[faceIndices[i].z-1].y, meshVertices[faceIndices[i].z-1].z); 
        glEnd();

    }

但是,当程序运行时,对象的远端根本不会加载,并且缺少随机三角形。像这样:

Screenshot

1 个答案:

答案 0 :(得分:5)

您不希望循环顶点的大小,而是循环面的大小。

您的循环应为for (unsigned int i = 0; i < faceIndices.size(); i++)

你正在循环变量faceIndices[i],我想你想绘制所有三角形,而不是所有的点(顶点)!


旁注:我教你这门课程吗? :d 该代码看起来很熟悉......