简体   繁体   中英

Some Triangles not displaying when trying to draw a mesh from a .obj in OpenGL

I'm attempting to display an object loaded from a .obj file. I use this function to read in the .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;
}

I then call this function in my init function. Once the mesh is loaded I display it by looping through the vertices here:

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();

    }

However, when the program runs, the far side of the object doesn't load at all and random triangles are missing. Like this:

屏幕截图

You don't want to loop the size of the vertices, but the size of the faces.

Your loop should read for (unsigned int i = 0; i < faceIndices.size(); i++)

You are looping through the variable faceIndices[i] and I suppose that you want to draw all the triangles, not all the point (vertices)!


On a side note: Am I teaching you this course? :D That code looks familiar...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM