Today I spent about two and a half hours on the course and I got my renderer loading OBJ files! So I had to render the Blender Suzanne monkey:
I’m pretty sure my method of parsing OBJ files is awful, so I’ll probably rewrite it at some point. Here’s the code snippet:
int load_obj_file_data(char* filename) {
// Load the vertices and faces to the mesh.vertices and mesh.faces arrays
// For each line in file:
// If line starts with "n", parse a vertex and add it to the list of vertices.
// If the line starts with "f", parse a face and add it to the list of faces.
FILE* fp = NULL;
char buffer[60]; // Probably shouldn't hard code this.
char* delimiter = " ";
fp = fopen(filename, "r");
if (fp == NULL) { // Exit if there's an error opening the file
return 1;
}
// Read the file
while (fgets(buffer, 60, fp) != NULL) {
if (buffer[0] == 'v' && buffer[1] != 'n') { // Process a vertex.
char* ptr = strtok(buffer, delimiter); // Advance the pointer once to skip the "i"
vec3_t new_vertex;
ptr = strtok(NULL, delimiter);
new_vertex.x = strtof(ptr, NULL);
ptr = strtok(NULL, delimiter);
new_vertex.y = strtof(ptr, NULL);
ptr = strtok(NULL, delimiter);
new_vertex.z = strtof(ptr, NULL);
array_push(mesh.vertices, new_vertex);
} else if (buffer[0] == 'f') { // Process a face.
strtok(buffer, delimiter); // Advance the pointer once to skip the "f"
char* ap;
char* bp;
char* cp;
int a,b,c;
face_t new_face;
ap = strtok(NULL, delimiter);// Get pointers to each of the elements in the line
bp = strtok(NULL, delimiter);
cp = strtok(NULL, delimiter);
a = strtol(strtok(ap, "/"), NULL, 10); // Get just the first number in each element and convert it to an integer.
b = strtol(strtok(bp, "/"), NULL, 10);
c = strtol(strtok(cp, "/"), NULL, 10);
new_face.a = a; // Populate the face with the new values.
new_face.b = b;
new_face.c = c;
array_push(mesh.faces, new_face); // Push the new face onto the mesh faces array.
}
}
fclose(fp);
return 0;
}
I’ll see you tomorrow!
Your data is processed in accordance with my privacy policy. Comments are manually approved and may take a while to appear.