Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "OBJ.h"
- namespace roxlu {
- bool OBJ::import(const string& filepath) {
- ifstream ifs;
- ifs.open(filepath.c_str());
- if(!ifs.is_open()) {
- printf("Cannot open: %s\n", filepath.c_str());
- return false;
- }
- Triangle tri;
- Vec3 v;
- OBJ::Object object;
- string line;
- bool object_added = false;
- bool found_object = false;
- while(getline(ifs, line)) {
- if(line.at(0) == '#') {
- continue;
- }
- int space = line.find(" ");
- if(space == string::npos) {
- continue;
- }
- string cmd = line.substr(0, space);
- // object
- if(cmd == "o") {
- if(found_object) {
- object_added = true;
- objects[object.name] = object;
- }
- found_object = true;
- object.name = line.substr(space+1, line.size()-1);
- }
- // vertex
- else if(found_object && cmd == "v") {
- stringstream ss;
- ss << line.substr(space+1, line.size()-1);
- ss >> v.x >> v.y >> v.z;
- object.vertices.addVertex(v);
- }
- // normal
- else if(found_object && cmd == "vn") {
- stringstream ss;
- ss << line.substr(space+1, line.size()-1);
- ss >> v.x >> v.y >> v.z;
- object.vertices.addNormal(v);
- }
- // face
- else if(found_object && cmd == "f") {
- stringstream ss;
- ss << line.substr(space+1, line.size()-1);
- string face;
- ss >> face;
- extractFace(face, tri.va, tri.na);
- ss >> face;
- extractFace(face, tri.vb, tri.nb);
- ss >> face;
- extractFace(face, tri.vc, tri.nc);
- object.vertices.addTriangle(tri);
- Vec3 vv = object.vertices.vertices[tri.va];
- }
- }
- if(!object_added) {
- objects[object.name] = object;
- }
- }
- bool OBJ::extractFace(string info, int& vertexIndex, int& normalIndex) {
- stringstream fss;
- fss << info;
- string fv;
- // get vertex index
- if(getline(fss, fv, '/')) {
- if(fv.size()) {
- stringstream ofss;
- ofss << fv;
- ofss >> vertexIndex;
- --vertexIndex;
- }
- }
- // get texcoord index
- if(getline(fss, fv, '/')) {
- if(fv.size()) {
- // ofss << fv;
- // ofss >> vertexIndex;
- }
- }
- // get normal index
- if(getline(fss, fv, '/')) {
- if(fv.size()) {
- stringstream ofss;
- ofss << fv;
- ofss >> normalIndex;
- --normalIndex;
- }
- }
- }
- };
Add Comment
Please, Sign In to add comment