我一直在尝试使用ASSIMP加载Wavefront obj模型。但是,我无法使 mtl Material 颜色正常工作(Kd rgb)
。我知道如何加载,但是,我不知道如何为每个顶点获取相应的颜色。
usemtl material_11
f 7//1 8//1 9//2
f 10//1 11//1 12//2
例如,上面的 Wavefront obj 代码片段意味着那些顶点使用 Material _11。
问:那么如何获取每个顶点对应的 Material 呢?
错误
波前对象 Material 不在正确的顶点:
原始模型(使用 ASSIMP 模型查看器渲染):
使用我的代码渲染的模型:
代码:
我用于加载 mtl Material 颜色的代码:
std::vector<color4<float>> colors = std::vector<color4<float>>();
...
for (unsigned int i = 0; i < scene->mNumMeshes; i++)
{
const aiMesh* model = scene->mMeshes[i];
const aiMaterial *mtl = scene->mMaterials[model->mMaterialIndex];
color4<float> color = color4<float>(1.0f, 1.0f, 1.0f, 1.0f);
aiColor4D diffuse;
if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_DIFFUSE, &diffuse))
color = color4<float>(diffuse.r, diffuse.g, diffuse.b, diffuse.a);
colors.push_back(color);
...
}
创建顶点的代码:
vertex* vertices_arr = new vertex[positions.size()];
for (unsigned int i = 0; i < positions.size(); i++)
{
vertices_arr[i].SetPosition(positions.at(i));
vertices_arr[i].SetTextureCoordinate(texcoords.at(i));
}
// Code for setting vertices colors (I'm just setting it in ASSIMP vertices order, since I don't know how to set it in the correct order).
for (unsigned int i = 0; i < scene->mNumMeshes; i++)
{
const unsigned int vertices_size = scene->mMeshes[i]->mNumVertices;
for (unsigned int k = 0; k < vertices_size; k++)
{
vertices_arr[k].SetColor(colors.at(i));
}
}
编辑:
看起来模型顶点位置也没有正确加载。即使我禁用面部剔除并更改背景颜色。
最佳答案
忽略与绘制调用数量以及额外存储、带宽和顶点颜色处理相关的问题,
看起来 vertex* vertices_arr = new vertex[positions.size()];
是您正在创建的一个大数组,用于保存整个模型(其中有许多网格,每个网格都有一种 Material ) )。假设您的第一个循环是正确的,并且 positions
包含模型所有网格的所有位置。第二个循环开始为网格内的每个顶点复制网格颜色。但是,vertices_arr[k] 始终从零开始,并且需要在前一个网格的最后一个顶点之后开始。相反,请尝试:
int colIdx = 0;
for (unsigned int i = 0; i < scene->mNumMeshes; i++)
{
const unsigned int vertices_size = scene->mMeshes[i]->mNumVertices;
for (unsigned int k = 0; k < vertices_size; k++)
{
vertices_arr[colIdx++].SetColor(colors.at(i));
}
}
assert(colIdx == positions.size()); //double check
正如您所说,如果几何图形未正确绘制,则可能 positions
不包含所有顶点数据。也许与上面的代码有类似的问题?另一个问题可能是加入每个网格的索引。所有索引都需要使用 vertices_arr
数组中新顶点位置的偏移量进行更新。虽然现在我只是抛出猜测。
关于c++ - 使用assimp加载mtl颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27517114/