【问题标题】:Some Triangles not displaying when trying to draw a mesh from a .obj in OpenGL尝试从 OpenGL 中的 .obj 绘制网格时,某些三角形未显示
【发布时间】:2015-01-26 08:23:25
【问题描述】:

我正在尝试显示从 .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();

    }

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

【问题讨论】:

  • 谢谢,我想内联添加图片,但我的声誉不够高。
  • 我认为你解析“f”记录是不够的。面可以由任意数量的顶点组成,面的每个顶点由斜线分隔的 3 个索引(顶点、纹理坐标、法线)描述,其中数字可能会丢失。看几个 OBJ 文件的例子就会更清楚。

标签: c++ opengl 3d mesh


【解决方案1】:

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

你的循环应该是for (unsigned int i = 0; i &lt; faceIndices.size(); i++)

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


附带说明:我在教你这门课程吗? :D 这段代码看起来很眼熟……

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 1970-01-01
    • 2012-11-19
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2017-12-15
    相关资源
    最近更新 更多