diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..a94a2c4 --- /dev/null +++ b/.clang-format @@ -0,0 +1,7 @@ +--- +BasedOnStyle: LLVM +IndentWidth: 2 +TabWidth: 2 +UseTab: Never +BreakBeforeBraces: Attach +Standard: Cpp03 diff --git a/tiny_obj_loader.h b/tiny_obj_loader.h index 9665d42..4240c66 100644 --- a/tiny_obj_loader.h +++ b/tiny_obj_loader.h @@ -8,9 +8,11 @@ // version 0.9.17: Support n-polygon and crease tag(OpenSubdiv extension) // version 0.9.16: Make tinyobjloader header-only // version 0.9.15: Change API to handle no mtl file case correctly(#58) -// version 0.9.14: Support specular highlight, bump, displacement and alpha map(#53) +// version 0.9.14: Support specular highlight, bump, displacement and alpha +// map(#53) // version 0.9.13: Report "Material file not found message" in `err`(#46) -// version 0.9.12: Fix groups being ignored if they have 'usemtl' just before 'g' (#44) +// version 0.9.12: Fix groups being ignored if they have 'usemtl' just before +// 'g' (#44) // version 0.9.11: Invert `Tr` parameter(#43) // version 0.9.10: Fix seg fault on windows. // version 0.9.9 : Replace atof() with custom parser. @@ -20,7 +22,8 @@ // version 0.9.6 : Support Ni(index of refraction) mtl parameter. // Parse transmittance material parameter correctly. // version 0.9.5 : Parse multiple group name. -// Add support of specifying the base path to load material file. +// Add support of specifying the base path to load material +// file. // version 0.9.4 : Initial support of group tag(g) // version 0.9.3 : Fix parsing triple 'x/y/z' // version 0.9.2 : Add more .mtl load support @@ -32,7 +35,7 @@ // Use this in *one* .cc // #define TINYOBJLOADER_IMPLEMENTATION // #include "tiny_obj_loader.h" -// +// #ifndef TINY_OBJ_LOADER_H #define TINY_OBJ_LOADER_H @@ -69,24 +72,23 @@ typedef struct { std::map unknown_parameter; } material_t; -typedef struct -{ - std::string name; +typedef struct { + std::string name; - std::vector intValues; - std::vector floatValues; - std::vector stringValues; + std::vector intValues; + std::vector floatValues; + std::vector stringValues; } tag_t; -typedef struct -{ - std::vector positions; - std::vector normals; - std::vector texcoords; - std::vector indices; - std::vector num_vertices; // The number of vertices per face. Up to 255. - std::vector material_ids; // per-face material ID - std::vector tags; // SubD tag +typedef struct { + std::vector positions; + std::vector normals; + std::vector texcoords; + std::vector indices; + std::vector + num_vertices; // The number of vertices per face. Up to 255. + std::vector material_ids; // per-face material ID + std::vector tags; // SubD tag } mesh_t; typedef struct { @@ -111,9 +113,8 @@ public: : m_mtlBasePath(mtl_basepath) {} virtual ~MaterialFileReader() {} virtual bool operator()(const std::string &matId, - std::vector &materials, - std::map &matMap, - std::string &err); + std::vector &materials, + std::map &matMap, std::string &err); private: std::string m_mtlBasePath; @@ -125,11 +126,13 @@ private: /// Returns true when loading .obj become success. /// Returns warning and error message into `err` /// 'mtl_basepath' is optional, and used for base path for .mtl file. -/// 'triangulate' is optional, and used whether triangulate polygon face in .obj or not. +/// 'triangulate' is optional, and used whether triangulate polygon face in .obj +/// or not. bool LoadObj(std::vector &shapes, // [output] std::vector &materials, // [output] - std::string& err, // [output] - const char *filename, const char *mtl_basepath = NULL, bool triangulate = true); + std::string &err, // [output] + const char *filename, const char *mtl_basepath = NULL, + bool triangulate = true); /// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve /// std::istream for materials. @@ -137,8 +140,9 @@ bool LoadObj(std::vector &shapes, // [output] /// Returns warning and error message into `err` bool LoadObj(std::vector &shapes, // [output] std::vector &materials, // [output] - std::string& err, // [output] - std::istream &inStream, MaterialReader &readMatFn, bool triangulate = true); + std::string &err, // [output] + std::istream &inStream, MaterialReader &readMatFn, + bool triangulate = true); /// Loads materials into std::map void LoadMtl(std::map &material_map, // [output] @@ -166,21 +170,21 @@ namespace tinyobj { MaterialReader::~MaterialReader() {} -#define TINYOBJ_SSCANF_BUFFER_SIZE (4096) +#define TINYOBJ_SSCANF_BUFFER_SIZE (4096) struct vertex_index { int v_idx, vt_idx, vn_idx; - vertex_index(){} - vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx){} + vertex_index() {} + vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {} vertex_index(int vidx, int vtidx, int vnidx) - : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx){} + : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {} }; struct tag_sizes { - tag_sizes() : num_ints(0), num_floats(0), num_strings(0) {} - int num_ints; - int num_floats; - int num_strings; + tag_sizes() : num_ints(0), num_floats(0), num_strings(0) {} + int num_ints; + int num_floats; + int num_strings; }; // for std::map @@ -209,8 +213,10 @@ static inline bool isNewLine(const char c) { // Make index zero-base, and also support relative index. static inline int fixIndex(int idx, int n) { - if (idx > 0) return idx - 1; - if (idx == 0) return 0; + if (idx > 0) + return idx - 1; + if (idx == 0) + return 0; return n + idx; // negative value = relative } @@ -230,7 +236,6 @@ static inline int parseInt(const char *&token) { return i; } - // Tries to parse a floating point number located at s. // // s_end should be a location in the string where reading should absolutely @@ -247,7 +252,7 @@ static inline int parseInt(const char *&token) { // Valid strings are for example: // -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 // -// If the parsing is a success, result is set to the parsed value and true +// If the parsing is a success, result is set to the parsed value and true // is returned. // // The function is greedy and will parse until any of the following happens: @@ -257,121 +262,110 @@ static inline int parseInt(const char *&token) { // The following situations triggers a failure: // - s >= s_end. // - parse failure. -// -static bool tryParseDouble(const char *s, const char *s_end, double *result) -{ - if (s >= s_end) - { - return false; - } +// +static bool tryParseDouble(const char *s, const char *s_end, double *result) { + if (s >= s_end) { + return false; + } - double mantissa = 0.0; - // This exponent is base 2 rather than 10. - // However the exponent we parse is supposed to be one of ten, - // thus we must take care to convert the exponent/and or the - // mantissa to a * 2^E, where a is the mantissa and E is the - // exponent. - // To get the final double we will use ldexp, it requires the - // exponent to be in base 2. - int exponent = 0; + double mantissa = 0.0; + // This exponent is base 2 rather than 10. + // However the exponent we parse is supposed to be one of ten, + // thus we must take care to convert the exponent/and or the + // mantissa to a * 2^E, where a is the mantissa and E is the + // exponent. + // To get the final double we will use ldexp, it requires the + // exponent to be in base 2. + int exponent = 0; - // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED - // TO JUMP OVER DEFINITIONS. - char sign = '+'; - char exp_sign = '+'; - char const *curr = s; + // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED + // TO JUMP OVER DEFINITIONS. + char sign = '+'; + char exp_sign = '+'; + char const *curr = s; - // How many characters were read in a loop. - int read = 0; - // Tells whether a loop terminated due to reaching s_end. - bool end_not_reached = false; + // How many characters were read in a loop. + int read = 0; + // Tells whether a loop terminated due to reaching s_end. + bool end_not_reached = false; - /* - BEGIN PARSING. - */ + /* + BEGIN PARSING. + */ - // Find out what sign we've got. - if (*curr == '+' || *curr == '-') - { - sign = *curr; - curr++; - } - else if (isdigit(*curr)) { /* Pass through. */ } - else - { - goto fail; - } + // Find out what sign we've got. + if (*curr == '+' || *curr == '-') { + sign = *curr; + curr++; + } else if (isdigit(*curr)) { /* Pass through. */ + } else { + goto fail; + } - // Read the integer part. - while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) - { - mantissa *= 10; - mantissa += static_cast(*curr - 0x30); - curr++; read++; - } + // Read the integer part. + while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { + mantissa *= 10; + mantissa += static_cast(*curr - 0x30); + curr++; + read++; + } - // We must make sure we actually got something. - if (read == 0) - goto fail; - // We allow numbers of form "#", "###" etc. - if (!end_not_reached) - goto assemble; + // We must make sure we actually got something. + if (read == 0) + goto fail; + // We allow numbers of form "#", "###" etc. + if (!end_not_reached) + goto assemble; - // Read the decimal part. - if (*curr == '.') - { - curr++; - read = 1; - while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) - { - // NOTE: Don't use powf here, it will absolutely murder precision. - mantissa += static_cast(*curr - 0x30) * pow(10.0, -read); - read++; curr++; - } - } - else if (*curr == 'e' || *curr == 'E') {} - else - { - goto assemble; - } + // Read the decimal part. + if (*curr == '.') { + curr++; + read = 1; + while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { + // NOTE: Don't use powf here, it will absolutely murder precision. + mantissa += static_cast(*curr - 0x30) * pow(10.0, -read); + read++; + curr++; + } + } else if (*curr == 'e' || *curr == 'E') { + } else { + goto assemble; + } - if (!end_not_reached) - goto assemble; + if (!end_not_reached) + goto assemble; - // Read the exponent part. - if (*curr == 'e' || *curr == 'E') - { - curr++; - // Figure out if a sign is present and if it is. - if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-')) - { - exp_sign = *curr; - curr++; - } - else if (isdigit(*curr)) { /* Pass through. */ } - else - { - // Empty E is not allowed. - goto fail; - } + // Read the exponent part. + if (*curr == 'e' || *curr == 'E') { + curr++; + // Figure out if a sign is present and if it is. + if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-')) { + exp_sign = *curr; + curr++; + } else if (isdigit(*curr)) { /* Pass through. */ + } else { + // Empty E is not allowed. + goto fail; + } - read = 0; - while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) - { - exponent *= 10; - exponent += static_cast(*curr - 0x30); - curr++; read++; - } - exponent *= (exp_sign == '+'? 1 : -1); - if (read == 0) - goto fail; - } + read = 0; + while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { + exponent *= 10; + exponent += static_cast(*curr - 0x30); + curr++; + read++; + } + exponent *= (exp_sign == '+' ? 1 : -1); + if (read == 0) + goto fail; + } assemble: - *result = (sign == '+'? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), exponent); - return true; + *result = + (sign == '+' ? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), exponent); + return true; fail: - return false; + return false; } static inline float parseFloat(const char *&token) { token += strspn(token, " \t"); @@ -388,7 +382,6 @@ static inline float parseFloat(const char *&token) { return f; } - static inline void parseFloat2(float &x, float &y, const char *&token) { x = parseFloat(token); y = parseFloat(token); @@ -401,28 +394,27 @@ static inline void parseFloat3(float &x, float &y, float &z, z = parseFloat(token); } -static tag_sizes parseTagTriple(const char* & token) -{ - tag_sizes ts; - - ts.num_ints = atoi(token); - token += strcspn(token, "/ \t\r"); - if (token[0] != '/') { - return ts; - } - token++; - - ts.num_floats = atoi(token); - token += strcspn(token, "/ \t\r"); - if (token[0] != '/') { - return ts; - } - token++; - - ts.num_strings = atoi(token); - token += strcspn(token, "/ \t\r") + 1; +static tag_sizes parseTagTriple(const char *&token) { + tag_sizes ts; + ts.num_ints = atoi(token); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { return ts; + } + token++; + + ts.num_floats = atoi(token); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return ts; + } + token++; + + ts.num_strings = atoi(token); + token += strcspn(token, "/ \t\r") + 1; + + return ts; } // Parse triples: i, i/j/k, i//k, i/j @@ -479,13 +471,15 @@ updateVertex(std::map &vertexCache, positions.push_back(in_positions[3 * static_cast(i.v_idx) + 1]); positions.push_back(in_positions[3 * static_cast(i.v_idx) + 2]); - if ((i.vn_idx >= 0) && (static_cast(i.vn_idx * 3 + 2) < in_normals.size())) { + if ((i.vn_idx >= 0) && + (static_cast(i.vn_idx * 3 + 2) < in_normals.size())) { normals.push_back(in_normals[3 * static_cast(i.vn_idx) + 0]); normals.push_back(in_normals[3 * static_cast(i.vn_idx) + 1]); normals.push_back(in_normals[3 * static_cast(i.vn_idx) + 2]); } - if ((i.vt_idx >= 0) && (static_cast(i.vt_idx * 2 + 1) < in_texcoords.size())) { + if ((i.vt_idx >= 0) && + (static_cast(i.vt_idx * 2 + 1) < in_texcoords.size())) { texcoords.push_back(in_texcoords[2 * static_cast(i.vt_idx) + 0]); texcoords.push_back(in_texcoords[2 * static_cast(i.vt_idx) + 1]); } @@ -525,8 +519,8 @@ static bool exportFaceGroupToShape( const std::vector &in_normals, const std::vector &in_texcoords, const std::vector > &faceGroup, - std::vector &tags, - const int material_id, const std::string &name, bool clearCache, bool triangulate) { + std::vector &tags, const int material_id, const std::string &name, + bool clearCache, bool triangulate) { if (faceGroup.empty()) { return false; } @@ -564,22 +558,20 @@ static bool exportFaceGroupToShape( shape.mesh.num_vertices.push_back(3); shape.mesh.material_ids.push_back(material_id); - } } else { for (size_t k = 0; k < npolys; k++) { - unsigned int v = updateVertex( - vertexCache, shape.mesh.positions, shape.mesh.normals, - shape.mesh.texcoords, in_positions, in_normals, in_texcoords, face[k]); - + unsigned int v = + updateVertex(vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, + in_texcoords, face[k]); + shape.mesh.indices.push_back(v); - } - shape.mesh.num_vertices.push_back(static_cast(npolys)); + shape.mesh.num_vertices.push_back(static_cast(npolys)); shape.mesh.material_ids.push_back(material_id); // per face - } } @@ -593,14 +585,13 @@ static bool exportFaceGroupToShape( } void LoadMtl(std::map &material_map, - std::vector &materials, - std::istream &inStream) { + std::vector &materials, std::istream &inStream) { // Create a default material anyway. material_t material; InitMaterial(material); - size_t maxchars = 8192; // Alloc enough size. + size_t maxchars = 8192; // Alloc enough size. std::vector buf(maxchars); // Alloc enough size. while (inStream.peek() != -1) { inStream.getline(&buf[0], static_cast(maxchars)); @@ -637,8 +628,8 @@ void LoadMtl(std::map &material_map, if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) { // flush previous material. if (!material.name.empty()) { - material_map.insert( - std::pair(material.name, static_cast(materials.size()))); + material_map.insert(std::pair( + material.name, static_cast(materials.size()))); materials.push_back(material); } @@ -816,15 +807,15 @@ void LoadMtl(std::map &material_map, } } // flush last material. - material_map.insert( - std::pair(material.name, static_cast(materials.size()))); + material_map.insert(std::pair( + material.name, static_cast(materials.size()))); materials.push_back(material); } bool MaterialFileReader::operator()(const std::string &matId, std::vector &materials, std::map &matMap, - std::string& err) { + std::string &err) { std::string filepath; if (!m_mtlBasePath.empty()) { @@ -837,16 +828,17 @@ bool MaterialFileReader::operator()(const std::string &matId, LoadMtl(matMap, materials, matIStream); if (!matIStream) { std::stringstream ss; - ss << "WARN: Material file [ " << filepath << " ] not found. Created a default material."; + ss << "WARN: Material file [ " << filepath + << " ] not found. Created a default material."; err += ss.str(); } return true; } -bool LoadObj(std::vector &shapes, // [output] +bool LoadObj(std::vector &shapes, // [output] std::vector &materials, // [output] - std::string &err, - const char *filename, const char *mtl_basepath, bool trianglulate) { + std::string &err, const char *filename, const char *mtl_basepath, + bool trianglulate) { shapes.clear(); @@ -868,10 +860,10 @@ bool LoadObj(std::vector &shapes, // [output] return LoadObj(shapes, materials, err, ifs, matFileReader, trianglulate); } -bool LoadObj(std::vector &shapes, // [output] +bool LoadObj(std::vector &shapes, // [output] std::vector &materials, // [output] - std::string& err, - std::istream &inStream, MaterialReader &readMatFn, bool triangulate) { + std::string &err, std::istream &inStream, + MaterialReader &readMatFn, bool triangulate) { std::stringstream errss; std::vector v; @@ -888,7 +880,7 @@ bool LoadObj(std::vector &shapes, // [output] shape_t shape; - int maxchars = 8192; // Alloc enough size. + int maxchars = 8192; // Alloc enough size. std::vector buf(static_cast(maxchars)); // Alloc enough size. while (inStream.peek() != -1) { inStream.getline(&buf[0], maxchars); @@ -960,8 +952,9 @@ bool LoadObj(std::vector &shapes, // [output] std::vector face; while (!isNewLine(token[0])) { - vertex_index vi = - parseTriple(token, static_cast(v.size() / 3), static_cast(vn.size() / 3), static_cast(vt.size() / 2)); + vertex_index vi = parseTriple(token, static_cast(v.size() / 3), + static_cast(vn.size() / 3), + static_cast(vt.size() / 2)); face.push_back(vi); size_t n = strspn(token, " \t\r"); token += n; @@ -984,10 +977,11 @@ bool LoadObj(std::vector &shapes, // [output] #endif // Create face group per material. - bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, - faceGroup, tags, material, name, true, triangulate); + bool ret = + exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, + material, name, true, triangulate); if (ret) { - shapes.push_back(shape); + shapes.push_back(shape); } shape = shape_t(); faceGroup.clear(); @@ -1015,7 +1009,7 @@ bool LoadObj(std::vector &shapes, // [output] std::string err_mtl; bool ok = readMatFn(namebuf, materials, material_map, err_mtl); err += err_mtl; - + if (!ok) { faceGroup.clear(); // for safety return false; @@ -1028,8 +1022,9 @@ bool LoadObj(std::vector &shapes, // [output] if (token[0] == 'g' && isSpace((token[1]))) { // flush previous face group. - bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, - faceGroup, tags, material, name, true, triangulate); + bool ret = + exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, + material, name, true, triangulate); if (ret) { shapes.push_back(shape); } @@ -1062,8 +1057,9 @@ bool LoadObj(std::vector &shapes, // [output] if (token[0] == 'o' && isSpace((token[1]))) { // flush previous face group. - bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, - faceGroup, tags, material, name, true, triangulate); + bool ret = + exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, + material, name, true, triangulate); if (ret) { shapes.push_back(shape); } @@ -1086,50 +1082,47 @@ bool LoadObj(std::vector &shapes, // [output] } if (token[0] == 't' && isSpace(token[1])) { - tag_t tag; + tag_t tag; - char namebuf[4096]; - token += 2; - sscanf(token, "%s", namebuf); - tag.name = std::string(namebuf); + char namebuf[4096]; + token += 2; + sscanf(token, "%s", namebuf); + tag.name = std::string(namebuf); - token += tag.name.size() + 1; + token += tag.name.size() + 1; - tag_sizes ts = parseTagTriple(token); + tag_sizes ts = parseTagTriple(token); - tag.intValues.resize(static_cast(ts.num_ints)); + tag.intValues.resize(static_cast(ts.num_ints)); - for(size_t i = 0; i < static_cast(ts.num_ints); ++i) - { - tag.intValues[i] = atoi(token); - token += strcspn(token, "/ \t\r") + 1; - } + for (size_t i = 0; i < static_cast(ts.num_ints); ++i) { + tag.intValues[i] = atoi(token); + token += strcspn(token, "/ \t\r") + 1; + } - tag.floatValues.resize(static_cast(ts.num_floats)); - for(size_t i = 0; i < static_cast(ts.num_floats); ++i) - { - tag.floatValues[i] = parseFloat(token); - token += strcspn(token, "/ \t\r") + 1; - } + tag.floatValues.resize(static_cast(ts.num_floats)); + for (size_t i = 0; i < static_cast(ts.num_floats); ++i) { + tag.floatValues[i] = parseFloat(token); + token += strcspn(token, "/ \t\r") + 1; + } - tag.stringValues.resize(static_cast(ts.num_strings)); - for(size_t i = 0; i < static_cast(ts.num_strings); ++i) - { - char stringValueBuffer[4096]; + tag.stringValues.resize(static_cast(ts.num_strings)); + for (size_t i = 0; i < static_cast(ts.num_strings); ++i) { + char stringValueBuffer[4096]; - sscanf(token, "%s", stringValueBuffer); - tag.stringValues[i] = stringValueBuffer; - token += tag.stringValues[i].size() + 1; - } + sscanf(token, "%s", stringValueBuffer); + tag.stringValues[i] = stringValueBuffer; + token += tag.stringValues[i].size() + 1; + } - tags.push_back(tag); + tags.push_back(tag); } // Ignore unknown command. } - bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, - material, name, true, triangulate); + bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, + tags, material, name, true, triangulate); if (ret) { shapes.push_back(shape); } @@ -1141,7 +1134,6 @@ bool LoadObj(std::vector &shapes, // [output] } // namespace - #endif #endif // TINY_OBJ_LOADER_H