我正在尝试解析.obj文件,我将文件解析并分别存储在vec3和int向量中。
然而,当我尝试通过使用面链接一切来创建我的aitVertex
结构以对应顶点和法线时,我得到以下“std :: out_of_range在内存位置”。
以下是相关代码:
bool aitMesh::loadFromObj(std::string path)
{
//Setup vars etc...
//std::vector<float> tempVertices;
//std::vector<float> tempNormals;
float Vertex[3];
float Normal[3];
int Index[6];
std::vector<glm::vec3> tempVertices;
std::vector<glm::vec3> tempNormals;
std::vector<int> tempIndices;
if (name == "v")
{
//sscanf_s matches a sequence of non-whitespace characters
//line.c_str returns a pointer to an array that contains a string..
//in this case and stores in Vertex[1,2,3]
sscanf_s(line.c_str(), "%*s %f %f %f", &Vertex[0], &Vertex[1], &Vertex[2]);
std::cout << "Line: " << line << "\n";
std::cout << "Name: " << name << "\n";
//Adds to tempVertices Array
//tempVertices.push_back(Vertex[0]);
//tempVertices.push_back(Vertex[1]);
//tempVertices.push_back(Vertex[2]);
tempVertices.push_back(glm::vec3(Vertex[0], Vertex[1], Vertex[2]));
continue;
}
if (name == "vn")
{
sscanf_s(line.c_str(), "%*s %f %f %f", &Normal[0], &Normal[1], &Normal[2]);
std::cout << "Line: " << line << "\n";
std::cout << "Name: " << name << "\n";
//tempNormals.push_back(Normal[0]);
//tempNormals.push_back(Normal[1]);
//tempNormals.push_back(Normal[2]);
tempNormals.push_back(glm::vec3(Normal[0], Normal[1], Normal[2]));
continue;
}
if (name == "s")
{
continue;
}
if (name == "f")
{
sscanf_s(line.c_str(), "%*s %d//%d %d//%d %d//%d", &Index[0], &Index[1], &Index[2], &Index[3], &Index[4], &Index[5]);
std::cout << "Line: " << line << "\n";
std::cout << "Name: " << name << "\n";
tempIndices.push_back(Index[0]);
tempIndices.push_back(Index[1]);
tempIndices.push_back(Index[2]);
tempIndices.push_back(Index[3]);
tempIndices.push_back(Index[4]);
tempIndices.push_back(Index[5]);
}
for (int i = 2; i <= tempIndices.size(); i++)
{
if (i % 2 == 0)
{
vertices.push_back(aitVertex(tempVertices.at(tempIndices[i-2]), tempNormals.at(tempIndices[i-1])));
}
}
我的程序正在打破的行是
vertices.push_back(aitVertex(tempVertices.at(tempIndices[i-2]), tempNormals.at(tempIndices[i-1])));
我认为问题出现在我引用tempIndices
的时候,因为当我尝试打印tempIndices[i-2]
时,它会打印出来,因为它应该......
我只是错误地引用它吗?
答案 0 :(得分:1)
我真的不明白你的代码。它仍然不是MCVE(请阅读链接!)。但是,可能导致错误的原因是您只在name
的一个特定情况下填充每个向量:
name == "v"
tempVertices gets populated
name == "vn"
tempNormals gets populated
name == "f"
tempIndices gets populated
and then...
you access all three vectors (if tempIndices.size() >= 2)
因此,至少在name == "f"
的情况下,您可以访问超出向量大小的向量索引。
continue
应该做什么? continue
只在循环中有意义,我不明白你为什么把它放在那里。这可能还不是真正的代码吗?