Fix obj file parser

This commit is contained in:
Théophile Bastian 2018-02-06 19:08:17 +01:00
parent d1c3cbe498
commit 804031dc81
2 changed files with 45 additions and 8 deletions

View File

@ -1,5 +1,8 @@
#include "ObjParser.hpp"
#include <sstream>
#include <cctype>
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);
}

View File

@ -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;
};