模型纹理坐标问题opengl

时间:2017-01-13 02:04:32

标签: c opengl assimp wavefront

我有一个程序用于将模型加载到C中的OpenGL中。对于使用Assimp的模型加载(根据我的理解),这个代码非常简单:

const struct aiScene* scene = aiImportFile(objfile, aiProcessPreset_TargetRealtime_Fast);
unsigned int vbo, ibo, tex;

if(scene == NULL)
{
    fprintf(stderr, "Could not load file '%s'\n", objfile);
    return 1;
}
int count = 0, size = 0;
int i, j, k;

for(i = 0; i < scene->mNumMeshes; i ++)
    size += (3 * scene->mMeshes[i]->mNumFaces);

Vertex* vertices = (Vertex*)malloc(size * sizeof(Vertex));
int* indices = (int*)malloc(size * sizeof(int));

for(i = 0; i < scene->mNumMeshes; i ++)
{
    struct aiMesh* mesh = scene->mMeshes[i];
    int meshFaces = mesh->mNumFaces;

    for(j = 0; j < meshFaces; j ++)
    {
        struct aiFace* face = &(mesh->mFaces[j]);
        for(k = 0; k < face->mNumIndices; k ++)
        {
            int index = face->mIndices[k];

            struct aiVector3D pos = mesh->mVertices[index];
            struct aiVector3D uv = mesh->mTextureCoords[0][index];
            struct aiVector3D normal = {.x=1.0f,.y=1.0f,.z=1.0f};

            if(mesh->mNormals != NULL)
                normal = mesh->mNormals[index];

            Vertex _vertex = {.x=pos.x * scale,
                                .y=pos.y * scale,
                                .z=pos.z * scale,
                                .u=uv.x, .v=uv.y,
                                .nx=normal.x * scale,
                                .ny=normal.y * scale,
                                .nz=normal.z * scale};

            vertices[count] = _vertex;
            indices[count] = count;
            count ++;
        }
    }
}
aiReleaseImport(scene);

tex = loadTexture(texfile);
if(tex == 0)
{
    fprintf(stderr, "Could not load file '%s'\n", texfile);
    return 1;
}
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size * sizeof(Vertex), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size * sizeof(int), indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

我的loadTexture函数适用于我使用的所有其他纹理,所以我怀疑这是问题所在。对于我的一些基本模型,我根本没有任何问题。但是当我尝试加载更复杂的模型时,像这样: Quad Shotgun rendered in Blender

纹理坐标被抛出,如下所示:Quad Shotgun rendered first person

另外,为了确保没有正确加载与.mtl相关联的.obj文件的问题,除了定义纹理之外,我除去.mtl中的所有内容文件,所以我仍然可以加载到Blender。结果相同。我已经完成了对Assimp的研究,我确信它不是我的渲染循环的问题。请帮助,我不知道我在这里错过了什么或者我的程序可能出现什么问题!

1 个答案:

答案 0 :(得分:0)

在我的结尾有点错误,虽然所有代码在加载模型及其数据时都是正确的,但我忘记了用于在aiImportScene加载模型的预设标记不包括用于翻转UV的标志。换句话说,而不是:

const struct aiScene* scene = aiImportFile(objfile, aiProcessPreset_TargetRealtime_Fast);

要导入模型,我应该一直使用它:

const struct aiScene* scene = aiImportFile(objfile, aiProcessPreset_TargetRealtime_Fast | aiProcess_FlipUVs);

关键的区别在于我将| aiProcess_FlipUVs添加到标志的末尾。这解决了我在很多模型中遇到的一些纹理问题,这些模型我要么是从Blender导出的,要么是在互联网上找到的,而且它似乎并没有损害以前运行良好的模型。希望如果有其他人遇到类似问题,这个答案会有所帮助!