25 Commits

Author SHA1 Message Date
Syoyo Fujita
51d13700d8 Skip trailing whitespace in mtl. Fixes #92. 2016-08-02 16:55:50 +09:00
Syoyo Fujita
d5c722125a Show parsing time. 2016-07-09 00:52:27 +09:00
Syoyo Fujita
16ed0ac129 Update README. 2016-07-06 01:36:16 +09:00
Syoyo Fujita
b69d2a2c55 Add more links. 2016-05-29 16:37:30 +09:00
Syoyo Fujita
e210379335 Add Probulator 2016-05-29 14:08:27 +09:00
Syoyo Fujita
659976b8f3 Merge branch 'master' of github.com:syoyo/tinyobjloader 2016-05-29 13:32:24 +09:00
Syoyo Fujita
96ba498d70 Add voxelizer. 2016-05-29 13:09:00 +09:00
Syoyo Fujita
7ecb0b2f37 Use sefe getline for files with different line breaks. Fixes #81. 2016-05-15 16:20:35 +09:00
Syoyo Fujita
a14bbdb065 Merge pull request #80 from Vazquinhos/master
Fixing errors normal generation no triangulation. Remove warnings. Coding Style.
2016-05-13 21:18:48 +09:00
Vazquinhos
bfedfbb1fb Merge remote-tracking branch 'refs/remotes/syoyo/master'
# Conflicts:
#	tiny_obj_loader.h
2016-05-13 14:03:03 +02:00
Vazquinhos
41f46c7fd7 Error fixed with no triangulation. Removed warnings and modified coding brace style 2016-05-13 13:54:27 +02:00
Vazquinhos
a62dd278e2 Merge remote-tracking branch 'refs/remotes/syoyo/master' 2016-05-13 13:19:09 +02:00
Syoyo Fujita
a20e4ede85 Update document and version. 2016-05-13 20:09:49 +09:00
Syoyo Fujita
1ab0d147cb Merge pull request #79 from Vazquinhos/master
Flat normals calculation of obj without normals
2016-05-13 19:46:47 +09:00
Vazquinhos
9aee576b99 Added dependencies to cmath in order to use sqrt 2016-05-13 12:37:24 +02:00
Vazquinhos
0dcc72239d Files deleted of compilation log 2016-05-13 12:29:42 +02:00
Vazquinhos
33d5e9aa07 Test.cc modified with the new flags 2016-05-13 12:28:10 +02:00
Vazquinhos
e528741a8b Flat normals calculation of objects that their normals are empty 2016-05-13 12:25:48 +02:00
Syoyo Fujita
9c81fcb4cc Merge branch 'master' of github.com:syoyo/tinyobjloader 2016-04-15 12:32:06 +09:00
Syoyo Fujita
d119dcb976 Cosmetics. 2016-04-15 12:31:47 +09:00
Syoyo Fujita
6cdb3ec832 Merge pull request #72 from jlfwong/patch-1
Fix typo in README.md
2016-04-13 01:04:59 +09:00
Jamie Wong
1b24514ed9 Fix typo in README.md 2016-04-12 22:36:56 +08:00
Syoyo Fujita
0dd90f853d Merge pull request #71 from nlguillemot/master
use sscanf_s in MSVC
2016-04-05 19:00:54 +09:00
Nicolas Guillemot
b40e8c9427 use sscanf_s in MSVC
consistent with other uses of sscanf in the library
2016-04-02 15:15:29 -07:00
Syoyo Fujita
ad9911ef1b Initialize vertex_index. Fixes #70. 2016-03-25 18:43:52 +09:00
3 changed files with 285 additions and 45 deletions

View File

@@ -17,10 +17,17 @@ Tiny but powerful single file wavefront obj loader written in C++. No dependency
`tinyobjloader` is good for embedding .obj loader to your (global illumination) renderer ;-) `tinyobjloader` is good for embedding .obj loader to your (global illumination) renderer ;-)
Notice!
-------
`master` branch will be replaced with `develop` branch in the near future: https://github.com/syoyo/tinyobjloader/tree/develop
`develop` branch has more better support and clean API interface for loading .obj and also it has optimized multi-threaded parser(probably 10x faster than `master`). If you are new to use `TinyObjLoader`, I highly recommend to use `develop` branch.
What's new What's new
---------- ----------
* Mar 13, 2016 : Introduce `load_flag_t` and flat normal calculation flag! Thanks Vazquinhos!
* Jan 29, 2016 : Support n-polygon(no triangulation) and OpenSubdiv crease tag! Thanks dboogert! * Jan 29, 2016 : Support n-polygon(no triangulation) and OpenSubdiv crease tag! Thanks dboogert!
* Nov 26, 2015 : Now single-header only!. * Nov 26, 2015 : Now single-header only!.
* Nov 08, 2015 : Improved API. * Nov 08, 2015 : Improved API.
@@ -60,6 +67,12 @@ TinyObjLoader is successfully used in ...
* pbrt-v3 https://github.com/mmp/pbrt-v3 * pbrt-v3 https://github.com/mmp/pbrt-v3
* cocos2d-x https://github.com/cocos2d/cocos2d-x/ * cocos2d-x https://github.com/cocos2d/cocos2d-x/
* Android Vulkan demo https://github.com/SaschaWillems/Vulkan * Android Vulkan demo https://github.com/SaschaWillems/Vulkan
* voxelizer https://github.com/karimnaaji/voxelizer
* Probulator https://github.com/kayru/Probulator
* OptiX Prime baking https://github.com/nvpro-samples/optix_prime_baking
* FireRays SDK https://github.com/GPUOpen-LibrariesAndSDKs/FireRays_SDK
* parg, tiny C library of various graphics utilities and GL demos https://github.com/prideout/parg
* Opengl unit of ChronoEngine https://github.com/projectchrono/chrono-opengl
* Your project here! * Your project here!
Features Features
@@ -163,8 +176,8 @@ std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials; std::vector<tinyobj::material_t> materials;
std::string err; std::string err;
bool triangulate = false; int flags = 1; // see load_flags_t enum for more information.
bool ret = tinyobj::LoadObj(shapes, materials, err, inputfile.c_str(), triangulate); bool ret = tinyobj::LoadObj(shapes, materials, err, inputfile.c_str(), flags);
if (!err.empty()) { // `err` may contain warning message. if (!err.empty()) { // `err` may contain warning message.
std::cerr << err << std::endl; std::cerr << err << std::endl;
@@ -180,7 +193,7 @@ for (size_t i = 0; i < shapes.size(); i++) {
for (size_t n = 0; n < shapes[i].mesh.num_vertices.size(); n++) { for (size_t n = 0; n < shapes[i].mesh.num_vertices.size(); n++) {
int ngon = shapes[i].mesh.num_vertices[n]; int ngon = shapes[i].mesh.num_vertices[n];
for (size_t f = 0; f < ngon; f++) { for (size_t f = 0; f < ngon; f++) {
unsigend int v = shapes[i].mesh.indices[indexOffset + f]; unsigned int v = shapes[i].mesh.indices[indexOffset + f];
printf(" face[%ld] v[%ld] = (%f, %f, %f)\n", n, printf(" face[%ld] v[%ld] = (%f, %f, %f)\n", n,
shapes[i].mesh.positions[3*v+0], shapes[i].mesh.positions[3*v+0],
shapes[i].mesh.positions[3*v+1], shapes[i].mesh.positions[3*v+1],

108
test.cc
View File

@@ -8,6 +8,90 @@
#include <sstream> #include <sstream>
#include <fstream> #include <fstream>
#ifdef _WIN32
#ifdef __cplusplus
extern "C" {
#endif
#include <windows.h>
#include <mmsystem.h>
#ifdef __cplusplus
}
#endif
#pragma comment(lib, "winmm.lib")
#else
#if defined(__unix__) || defined(__APPLE__)
#include <sys/time.h>
#else
#include <ctime>
#endif
#endif
// not thread-safe
class timerutil {
public:
#ifdef _WIN32
typedef DWORD time_t;
timerutil() { ::timeBeginPeriod(1); }
~timerutil() { ::timeEndPeriod(1); }
void start() { t_[0] = ::timeGetTime(); }
void end() { t_[1] = ::timeGetTime(); }
time_t sec() { return (time_t)((t_[1] - t_[0]) / 1000); }
time_t msec() { return (time_t)((t_[1] - t_[0])); }
time_t usec() { return (time_t)((t_[1] - t_[0]) * 1000); }
time_t current() { return ::timeGetTime(); }
#else
#if defined(__unix__) || defined(__APPLE__)
typedef unsigned long int time_t;
void start() { gettimeofday(tv + 0, &tz); }
void end() { gettimeofday(tv + 1, &tz); }
time_t sec() { return (time_t)(tv[1].tv_sec - tv[0].tv_sec); }
time_t msec() {
return this->sec() * 1000 +
(time_t)((tv[1].tv_usec - tv[0].tv_usec) / 1000);
}
time_t usec() {
return this->sec() * 1000000 + (time_t)(tv[1].tv_usec - tv[0].tv_usec);
}
time_t current() {
struct timeval t;
gettimeofday(&t, NULL);
return (time_t)(t.tv_sec * 1000 + t.tv_usec);
}
#else // C timer
// using namespace std;
typedef clock_t time_t;
void start() { t_[0] = clock(); }
void end() { t_[1] = clock(); }
time_t sec() { return (time_t)((t_[1] - t_[0]) / CLOCKS_PER_SEC); }
time_t msec() { return (time_t)((t_[1] - t_[0]) * 1000 / CLOCKS_PER_SEC); }
time_t usec() { return (time_t)((t_[1] - t_[0]) * 1000000 / CLOCKS_PER_SEC); }
time_t current() { return (time_t)clock(); }
#endif
#endif
private:
#ifdef _WIN32
DWORD t_[2];
#else
#if defined(__unix__) || defined(__APPLE__)
struct timeval tv[2];
struct timezone tz;
#else
time_t t_[2];
#endif
#endif
};
static void PrintInfo(const std::vector<tinyobj::shape_t>& shapes, const std::vector<tinyobj::material_t>& materials, bool triangulate = true) static void PrintInfo(const std::vector<tinyobj::shape_t>& shapes, const std::vector<tinyobj::material_t>& materials, bool triangulate = true)
{ {
std::cout << "# of shapes : " << shapes.size() << std::endl; std::cout << "# of shapes : " << shapes.size() << std::endl;
@@ -124,15 +208,18 @@ static bool
TestLoadObj( TestLoadObj(
const char* filename, const char* filename,
const char* basepath = NULL, const char* basepath = NULL,
bool triangulate = true) unsigned int flags = 1 )
{ {
std::cout << "Loading " << filename << std::endl; std::cout << "Loading " << filename << std::endl;
std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials; std::vector<tinyobj::material_t> materials;
timerutil t;
t.start();
std::string err; std::string err;
bool ret = tinyobj::LoadObj(shapes, materials, err, filename, basepath, triangulate); bool ret = tinyobj::LoadObj(shapes, materials, err, filename, basepath, flags);
t.end();
if (!err.empty()) { if (!err.empty()) {
std::cerr << err << std::endl; std::cerr << err << std::endl;
@@ -143,7 +230,10 @@ TestLoadObj(
return false; return false;
} }
PrintInfo(shapes, materials, triangulate); printf("Parse time: %lu [msecs]\n", t.msec());
bool triangulate( ( flags & tinyobj::triangulation ) == tinyobj::triangulation );
PrintInfo(shapes, materials, triangulate );
return true; return true;
} }
@@ -212,7 +302,8 @@ std::string matStream(
"newmtl light\n" "newmtl light\n"
"Ka 20 20 20\n" "Ka 20 20 20\n"
"Kd 1 1 1\n" "Kd 1 1 1\n"
"Ks 0 0 0"); "Ks 0 0 0\n"
"map_Kd tmp.png \n"); // #92(whitespace after filename)
using namespace tinyobj; using namespace tinyobj;
class MaterialStringStreamReader: class MaterialStringStreamReader:
@@ -253,6 +344,13 @@ std::string matStream(
PrintInfo(shapes, materials); PrintInfo(shapes, materials);
// #92
for (size_t i = 0; i < materials.size(); i++) {
if (materials[i].name.compare("light") == 0) {
assert(materials[i].diffuse_texname.compare("tmp.png") == 0);
}
}
return true; return true;
} }
@@ -271,7 +369,7 @@ main(
//assert(true == TestLoadObj("cornell_box.obj")); //assert(true == TestLoadObj("cornell_box.obj"));
//assert(true == TestLoadObj("cube.obj")); //assert(true == TestLoadObj("cube.obj"));
assert(true == TestStreamLoadObj()); assert(true == TestStreamLoadObj());
assert(true == TestLoadObj("catmark_torus_creases0.obj", NULL, false)); assert(true == TestLoadObj("catmark_torus_creases0.obj", NULL, 0));
} }
return 0; return 0;

View File

@@ -1,10 +1,11 @@
// //
// Copyright 2012-2015, Syoyo Fujita. // Copyright 2012-2016, Syoyo Fujita.
// //
// Licensed under 2-clause BSD license. // Licensed under 2-clause BSD license.
// //
// //
// version 0.9.22: Introduce `load_flags_t`.
// version 0.9.20: Fixes creating per-face material using `usemtl`(#68) // version 0.9.20: Fixes creating per-face material using `usemtl`(#68)
// version 0.9.17: Support n-polygon and crease tag(OpenSubdiv extension) // version 0.9.17: Support n-polygon and crease tag(OpenSubdiv extension)
// version 0.9.16: Make tinyobjloader header-only // version 0.9.16: Make tinyobjloader header-only
@@ -38,12 +39,13 @@
// #include "tiny_obj_loader.h" // #include "tiny_obj_loader.h"
// //
#ifndef TINY_OBJ_LOADER_H #ifndef TINY_OBJ_LOADER_H_
#define TINY_OBJ_LOADER_H #define TINY_OBJ_LOADER_H_
#include <cmath>
#include <map>
#include <string> #include <string>
#include <vector> #include <vector>
#include <map>
namespace tinyobj { namespace tinyobj {
@@ -97,6 +99,52 @@ typedef struct {
mesh_t mesh; mesh_t mesh;
} shape_t; } shape_t;
typedef enum {
triangulation = 1, // used whether triangulate polygon face in .obj
calculate_normals =
2, // used whether calculate the normals if the .obj normals are empty
// Some nice stuff here
} load_flags_t;
class float3 {
public:
float3() : x(0.0f), y(0.0f), z(0.0f) {}
float3(float coord_x, float coord_y, float coord_z)
: x(coord_x), y(coord_y), z(coord_z) {}
float3(const float3 &from, const float3 &to) {
coord[0] = to.coord[0] - from.coord[0];
coord[1] = to.coord[1] - from.coord[1];
coord[2] = to.coord[2] - from.coord[2];
}
float3 crossproduct(const float3 &vec) {
float a = y * vec.z - z * vec.y;
float b = z * vec.x - x * vec.z;
float c = x * vec.y - y * vec.x;
return float3(a, b, c);
}
void normalize() {
const float length = std::sqrt(
(coord[0] * coord[0]) + (coord[1] * coord[1]) + (coord[2] * coord[2]));
if (length != 1) {
coord[0] = (coord[0] / length);
coord[1] = (coord[1] / length);
coord[2] = (coord[2] / length);
}
}
private:
union {
float coord[3];
struct {
float x, y, z;
};
};
};
class MaterialReader { class MaterialReader {
public: public:
MaterialReader() {} MaterialReader() {}
@@ -127,13 +175,12 @@ private:
/// Returns true when loading .obj become success. /// Returns true when loading .obj become success.
/// Returns warning and error message into `err` /// Returns warning and error message into `err`
/// 'mtl_basepath' is optional, and used for base path for .mtl file. /// 'mtl_basepath' is optional, and used for base path for .mtl file.
/// 'triangulate' is optional, and used whether triangulate polygon face in .obj /// 'optional flags
/// or not.
bool LoadObj(std::vector<shape_t> &shapes, // [output] bool LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output] std::vector<material_t> &materials, // [output]
std::string &err, // [output] std::string &err, // [output]
const char *filename, const char *mtl_basepath = NULL, const char *filename, const char *mtl_basepath = NULL,
bool triangulate = true); unsigned int flags = 1);
/// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve /// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve
/// std::istream for materials. /// std::istream for materials.
@@ -143,7 +190,7 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output] std::vector<material_t> &materials, // [output]
std::string &err, // [output] std::string &err, // [output]
std::istream &inStream, MaterialReader &readMatFn, std::istream &inStream, MaterialReader &readMatFn,
bool triangulate = true); unsigned int flags = 1);
/// Loads materials into std::map /// Loads materials into std::map
void LoadMtl(std::map<std::string, int> &material_map, // [output] void LoadMtl(std::map<std::string, int> &material_map, // [output]
@@ -152,16 +199,13 @@ void LoadMtl(std::map<std::string, int> &material_map, // [output]
} }
#ifdef TINYOBJLOADER_IMPLEMENTATION #ifdef TINYOBJLOADER_IMPLEMENTATION
#include <cstdlib>
#include <cstring>
#include <cassert> #include <cassert>
#include <cctype>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
#include <cctype> #include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
@@ -175,8 +219,8 @@ MaterialReader::~MaterialReader() {}
struct vertex_index { struct vertex_index {
int v_idx, vt_idx, vn_idx; int v_idx, vt_idx, vn_idx;
vertex_index() {} vertex_index() : v_idx(-1), vt_idx(-1), vn_idx(-1) {}
vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {} explicit vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {}
vertex_index(int vidx, int vtidx, int vnidx) 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) {}
}; };
@@ -206,9 +250,43 @@ struct obj_shape {
std::vector<float> vt; std::vector<float> vt;
}; };
#define IS_SPACE( x ) ( ( (x) == ' ') || ( (x) == '\t') ) // See
#define IS_DIGIT( x ) ( (unsigned int)( (x) - '0' ) < (unsigned int)10 ) // http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf
#define IS_NEW_LINE( x ) ( ( (x) == '\r') || ( (x) == '\n') || ( (x) == '\0') ) std::istream &safeGetline(std::istream &is, std::string &t) {
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf *sb = is.rdbuf();
for (;;) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if (sb->sgetc() == '\n')
sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if (t.empty())
is.setstate(std::ios::eofbit);
return is;
default:
t += (char)c;
}
}
}
#define IS_SPACE(x) (((x) == ' ') || ((x) == '\t'))
#define IS_DIGIT(x) ((unsigned int)((x) - '0') < (unsigned int)10)
#define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0'))
// Make index zero-base, and also support relative index. // Make index zero-base, and also support relative index.
static inline int fixIndex(int idx, int n) { static inline int fixIndex(int idx, int n) {
@@ -519,11 +597,14 @@ static bool exportFaceGroupToShape(
const std::vector<float> &in_texcoords, const std::vector<float> &in_texcoords,
const std::vector<std::vector<vertex_index> > &faceGroup, const std::vector<std::vector<vertex_index> > &faceGroup,
std::vector<tag_t> &tags, const int material_id, const std::string &name, std::vector<tag_t> &tags, const int material_id, const std::string &name,
bool clearCache, bool triangulate) { bool clearCache, unsigned int flags, std::string &err) {
if (faceGroup.empty()) { if (faceGroup.empty()) {
return false; return false;
} }
bool triangulate((flags & triangulation) == triangulation);
bool normals_calculation((flags & calculate_normals) == calculate_normals);
// Flatten vertices and indices // Flatten vertices and indices
for (size_t i = 0; i < faceGroup.size(); i++) { for (size_t i = 0; i < faceGroup.size(); i++) {
const std::vector<vertex_index> &face = faceGroup[i]; const std::vector<vertex_index> &face = faceGroup[i];
@@ -574,6 +655,44 @@ static bool exportFaceGroupToShape(
} }
} }
if (normals_calculation && shape.mesh.normals.empty()) {
const size_t nIndexs = shape.mesh.indices.size();
if (nIndexs % 3 == 0) {
shape.mesh.normals.resize(shape.mesh.positions.size());
for (register size_t iIndices = 0; iIndices < nIndexs; iIndices += 3) {
float3 v1, v2, v3;
memcpy(&v1, &shape.mesh.positions[shape.mesh.indices[iIndices] * 3],
sizeof(float3));
memcpy(&v2, &shape.mesh.positions[shape.mesh.indices[iIndices + 1] * 3],
sizeof(float3));
memcpy(&v3, &shape.mesh.positions[shape.mesh.indices[iIndices + 2] * 3],
sizeof(float3));
float3 v12(v1, v2);
float3 v13(v1, v3);
float3 normal = v12.crossproduct(v13);
normal.normalize();
memcpy(&shape.mesh.normals[shape.mesh.indices[iIndices] * 3], &normal,
sizeof(float3));
memcpy(&shape.mesh.normals[shape.mesh.indices[iIndices + 1] * 3],
&normal, sizeof(float3));
memcpy(&shape.mesh.normals[shape.mesh.indices[iIndices + 2] * 3],
&normal, sizeof(float3));
}
} else {
std::stringstream ss;
ss << "WARN: The shape " << name
<< " does not have a topology of triangles, therfore the normals "
"calculation could not be performed. Select the "
"tinyobj::triangulation flag for this object."
<< std::endl;
err += ss.str();
}
}
shape.name = name; shape.name = name;
shape.mesh.tags.swap(tags); shape.mesh.tags.swap(tags);
@@ -590,12 +709,14 @@ void LoadMtl(std::map<std::string, int> &material_map,
material_t material; material_t material;
InitMaterial(material); InitMaterial(material);
size_t maxchars = 8192; // Alloc enough size.
std::vector<char> buf(maxchars); // Alloc enough size.
while (inStream.peek() != -1) { while (inStream.peek() != -1) {
inStream.getline(&buf[0], static_cast<std::streamsize>(maxchars)); std::string linebuf;
safeGetline(inStream, linebuf);
std::string linebuf(&buf[0]); // Trim trailing whitespace
if (linebuf.size() > 0) {
linebuf = linebuf.substr(0, linebuf.find_last_not_of(" \t") + 1);
}
// Trim newline '\r\n' or '\n' // Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) { if (linebuf.size() > 0) {
@@ -837,7 +958,7 @@ bool MaterialFileReader::operator()(const std::string &matId,
bool LoadObj(std::vector<shape_t> &shapes, // [output] bool LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output] std::vector<material_t> &materials, // [output]
std::string &err, const char *filename, const char *mtl_basepath, std::string &err, const char *filename, const char *mtl_basepath,
bool trianglulate) { unsigned int flags) {
shapes.clear(); shapes.clear();
@@ -856,13 +977,14 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
} }
MaterialFileReader matFileReader(basePath); MaterialFileReader matFileReader(basePath);
return LoadObj(shapes, materials, err, ifs, matFileReader, trianglulate); return LoadObj(shapes, materials, err, ifs, matFileReader, flags);
} }
bool LoadObj(std::vector<shape_t> &shapes, // [output] bool LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output] std::vector<material_t> &materials, // [output]
std::string &err, std::istream &inStream, std::string &err, std::istream &inStream,
MaterialReader &readMatFn, bool triangulate) { MaterialReader &readMatFn, unsigned int flags) {
std::stringstream errss; std::stringstream errss;
std::vector<float> v; std::vector<float> v;
@@ -879,12 +1001,9 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
shape_t shape; shape_t shape;
int maxchars = 8192; // Alloc enough size.
std::vector<char> buf(static_cast<size_t>(maxchars)); // Alloc enough size.
while (inStream.peek() != -1) { while (inStream.peek() != -1) {
inStream.getline(&buf[0], maxchars); std::string linebuf;
safeGetline(inStream, linebuf);
std::string linebuf(&buf[0]);
// Trim newline '\r\n' or '\n' // Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) { if (linebuf.size() > 0) {
@@ -989,7 +1108,7 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
if (newMaterialId != material) { if (newMaterialId != material) {
// Create per-face material // Create per-face material
exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags,
material, name, true, triangulate); material, name, true, flags, err);
faceGroup.clear(); faceGroup.clear();
material = newMaterialId; material = newMaterialId;
} }
@@ -1025,7 +1144,7 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
// flush previous face group. // flush previous face group.
bool ret = bool ret =
exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags,
material, name, true, triangulate); material, name, true, flags, err);
if (ret) { if (ret) {
shapes.push_back(shape); shapes.push_back(shape);
} }
@@ -1062,7 +1181,7 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
// flush previous face group. // flush previous face group.
bool ret = bool ret =
exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags,
material, name, true, triangulate); material, name, true, flags, err);
if (ret) { if (ret) {
shapes.push_back(shape); shapes.push_back(shape);
} }
@@ -1089,7 +1208,11 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
char namebuf[4096]; char namebuf[4096];
token += 2; token += 2;
#ifdef _MSC_VER
sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf));
#else
sscanf(token, "%s", namebuf); sscanf(token, "%s", namebuf);
#endif
tag.name = std::string(namebuf); tag.name = std::string(namebuf);
token += tag.name.size() + 1; token += tag.name.size() + 1;
@@ -1113,7 +1236,12 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) { for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) {
char stringValueBuffer[4096]; char stringValueBuffer[4096];
#ifdef _MSC_VER
sscanf_s(token, "%s", stringValueBuffer,
(unsigned)_countof(stringValueBuffer));
#else
sscanf(token, "%s", stringValueBuffer); sscanf(token, "%s", stringValueBuffer);
#endif
tag.stringValues[i] = stringValueBuffer; tag.stringValues[i] = stringValueBuffer;
token += tag.stringValues[i].size() + 1; token += tag.stringValues[i].size() + 1;
} }
@@ -1125,13 +1253,14 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
} }
bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup,
tags, material, name, true, triangulate); tags, material, name, true, flags, err);
if (ret) { if (ret) {
shapes.push_back(shape); shapes.push_back(shape);
} }
faceGroup.clear(); // for safety faceGroup.clear(); // for safety
err += errss.str(); err += errss.str();
return true; return true;
} }
@@ -1139,4 +1268,4 @@ bool LoadObj(std::vector<shape_t> &shapes, // [output]
#endif #endif
#endif // TINY_OBJ_LOADER_H #endif // TINY_OBJ_LOADER_H_