diff --git a/util/ObjParser.cpp b/util/ObjParser.cpp index c62bfc1..90a24b4 100644 --- a/util/ObjParser.cpp +++ b/util/ObjParser.cpp @@ -1,5 +1,8 @@ #include "ObjParser.hpp" +#include +#include + ObjParser::ObjParser(const std::string& path) : path(path) {} @@ -11,22 +14,42 @@ Mesh ObjParser::parse() { if(!handle.is_open()) throw std::runtime_error(std::string("Cannot open the file ") + path); - while(!handle.eof()) { + for(std::string line; std::getline(handle, line); ) { + std::istringstream lineStream(strip(line)); char type; - handle >> type; + lineStream >> type; + if(type == 'v') { // vertice double x, y, z; - handle >> x >> y >> z; + lineStream >> x >> y >> z; output.add_vertice(Point(x, y, z)); } - else { + else if(type == 'f') { int v1, v2, v3; - handle >> v1 >> v2 >> v3; - output.add_face(Face(v1, v2, v3)); + lineStream >> v1 >> v2 >> v3; + output.add_face(Face(v1 - 1, v2 - 1, v3 - 1)); + } + else { + throw BadObj(path); } - - handle.ignore('\n'); } return output; } + +std::string ObjParser::strip(const std::string& str) { + size_t fPos, lPos; + for(fPos=0; fPos < str.size(); ++fPos) { + if(!isspace(str[fPos])) + break; + } + if(fPos == str.size()) + return ""; + + for(lPos=str.size() - 1; lPos > 0; --lPos) { + if(!isspace(str[lPos])) + break; + } + + return str.substr(fPos, lPos - fPos + 1); +} diff --git a/util/ObjParser.hpp b/util/ObjParser.hpp index 02ddcb2..2338ff5 100644 --- a/util/ObjParser.hpp +++ b/util/ObjParser.hpp @@ -10,9 +10,23 @@ class ObjParser { public: + class BadObj : public std::exception { + public: + BadObj(const std::string& path): path(path) {} + const char* what() const noexcept { + return (std::string("Badly formed obj file ") + + path).c_str(); + } + + private: + std::string path; + }; + ObjParser(const std::string& path); Mesh parse(); + private: //meth + static std::string strip(const std::string& str); private: std::string path; };