Garbage when parsing obj-file
Feb 9, 2014 at 9:11am UTC
I'm trying to parse an obj-file, which should be simple enough, but have run into some weird issues. My parsing code looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
while (file) {
std::string line;
getline(file, line);
std::vector<std::string> *tokens = split(line, " " );
if (tokens->at(0) == "o" ) {
name = tokens->at(1);
}
if (tokens->at(0) == "v" ) {
vecf v;
v.x = (float )atof(tokens->at(1).c_str());
v.y = (float )atof(tokens->at(2).c_str());
v.z = (float )atof(tokens->at(3).c_str());
vertices.push_back(v);
}
if (tokens->at(0) == "f" ) {
vec f;
std::vector<std::string> *xTokens = split(tokens->at(1), "/" );
std::vector<std::string> *yTokens = split(tokens->at(2), "/" );
std::vector<std::string> *zTokens = split(tokens->at(3), "/" );
f.x = (int )atoi(xTokens->at(0).c_str());
f.y = (int )atoi(yTokens->at(0).c_str());
f.z = (int )atoi(zTokens->at(0).c_str());
faces.push_back(f);
delete xTokens;
delete yTokens;
delete zTokens;
}
delete tokens;
}
Probably not the neatest solution, allocating and deleting a lot of vectors, but it should do the job for now. I have run printouts of this ensuring that the values are read correctly from the file. My drawing code looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void draw(void ) {
glRotatef(xAngle, 0.0f, 1.0f, 0.0f);
for (vec face : faces) {
glBegin(GL_TRIANGLES);
vecf a = vertices[face.x];
vecf b = vertices[face.y];
vecf c = vertices[face.z];
glVertex3f(a.x, a.y, a.z);
glVertex3f(b.x, b.y, b.z);
glVertex3f(c.x, c.y, c.z);
std::cout << "Drawing vertex - x: " << a.x << "\ty: " << a.y << "\tz: " << a.z << std::endl;
std::cout << "Drawing vertex - x: " << b.x << "\ty: " << b.y << "\tz: " << b.z << std::endl;
std::cout << "Drawing vertex - x: " << c.x << "\ty: " << c.y << "\tz: " << c.z << std::endl << std::endl;
glEnd();
}
}
I put those last cout-lines in there because the model was being drawn very strangely, and changing every run of the program. When I run it, it prints out, for example
Drawing vertex - x: 4.48416e-44 y: 4.48416e-44 z: 5.60519e-45
Drawing vertex - x: 1 y: 1 z: 1
Drawing vertex - x: 1 y: 1 z: -1
Drawing vertex - x: 4.48416e-44 y: 4.48416e-44 z: 5.60519e-45
Drawing vertex - x: 1 y: 1 z: -1
Drawing vertex - x: -1 y: 1 z: -1
So my question is, does anyone know why these crazy values would be there, when the file is being parsed and read correctly?
Fafner
Feb 9, 2014 at 10:01am UTC
It doesn't look like you're handling the face elements in the obj file correctly. The first vertex in the file as it is referred to by a face element will be 1, not 0, so you must adjust your index into vertices.
Feb 9, 2014 at 10:07am UTC
Thanks, that was it! Wow, I completely missed the fact that the vertices in a face start from 1, not 0.
Topic archived. No new replies allowed.