geometryc.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <stdio.h>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <bx/string.h>
  9. #include <bgfx/bgfx.h>
  10. #include "../../src/vertexdecl.h"
  11. #include <tinystl/allocator.h>
  12. #include <tinystl/unordered_map.h>
  13. #include <tinystl/unordered_set.h>
  14. #include <tinystl/string.h>
  15. namespace stl = tinystl;
  16. #include <meshoptimizer/src/meshoptimizer.h>
  17. #define BGFX_GEOMETRYC_VERSION_MAJOR 1
  18. #define BGFX_GEOMETRYC_VERSION_MINOR 0
  19. #if 0
  20. # define BX_TRACE(_format, ...) \
  21. do { \
  22. printf(BX_FILE_LINE_LITERAL "BGFX " _format "\n", ##__VA_ARGS__); \
  23. } while(0)
  24. # define BX_WARN(_condition, _format, ...) \
  25. do { \
  26. if (!(_condition) ) \
  27. { \
  28. BX_TRACE(BX_FILE_LINE_LITERAL "WARN " _format, ##__VA_ARGS__); \
  29. } \
  30. } while(0)
  31. # define BX_CHECK(_condition, _format, ...) \
  32. do { \
  33. if (!(_condition) ) \
  34. { \
  35. BX_TRACE(BX_FILE_LINE_LITERAL "CHECK " _format, ##__VA_ARGS__); \
  36. bx::debugBreak(); \
  37. } \
  38. } while(0)
  39. #endif // 0
  40. #include <bx/bx.h>
  41. #include <bx/debug.h>
  42. #include <bx/commandline.h>
  43. #include <bx/timer.h>
  44. #include <bx/hash.h>
  45. #include <bx/uint32_t.h>
  46. #include <bx/math.h>
  47. #include <bx/file.h>
  48. #include "bounds.h"
  49. typedef std::vector<bx::Vec3> Vec3Array;
  50. struct Index3
  51. {
  52. int32_t m_position;
  53. int32_t m_texcoord;
  54. int32_t m_normal;
  55. int32_t m_vertexIndex;
  56. int32_t m_vbc; // Barycentric ID. Holds eigher 0, 1 or 2.
  57. };
  58. typedef stl::unordered_map<uint64_t, Index3> Index3Map;
  59. struct TriIndices
  60. {
  61. uint64_t m_index[3];
  62. };
  63. typedef std::vector<TriIndices> TriangleArray;
  64. struct Group
  65. {
  66. uint32_t m_startTriangle;
  67. uint32_t m_numTriangles;
  68. stl::string m_name;
  69. stl::string m_material;
  70. };
  71. typedef std::vector<Group> GroupArray;
  72. struct Primitive
  73. {
  74. uint32_t m_startVertex;
  75. uint32_t m_startIndex;
  76. uint32_t m_numVertices;
  77. uint32_t m_numIndices;
  78. stl::string m_name;
  79. };
  80. typedef std::vector<Primitive> PrimitiveArray;
  81. static uint32_t s_obbSteps = 17;
  82. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x1)
  83. #define BGFX_CHUNK_MAGIC_VBC BX_MAKEFOURCC('V', 'B', 'C', 0x0)
  84. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  85. #define BGFX_CHUNK_MAGIC_IBC BX_MAKEFOURCC('I', 'B', 'C', 0x1)
  86. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  87. long int fsize(FILE* _file)
  88. {
  89. long int pos = ftell(_file);
  90. fseek(_file, 0L, SEEK_END);
  91. long int size = ftell(_file);
  92. fseek(_file, pos, SEEK_SET);
  93. return size;
  94. }
  95. void optimizeVertexCache(uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices)
  96. {
  97. uint16_t* newIndexList = new uint16_t[_numIndices];
  98. meshopt_optimizeVertexCache(newIndexList, _indices, _numIndices, _numVertices);
  99. bx::memCopy(_indices, newIndexList, _numIndices * 2);
  100. delete[] newIndexList;
  101. }
  102. uint32_t optimizeVertexFetch(uint16_t* _indices, uint32_t _numIndices, uint8_t* _vertexData, uint32_t _numVertices, uint16_t _stride)
  103. {
  104. unsigned char* newVertices = (unsigned char*)malloc(_numVertices * _stride );
  105. size_t vertexCount = meshopt_optimizeVertexFetch(newVertices, _indices, _numIndices, _vertexData, _numVertices, _stride);
  106. bx::memCopy(_vertexData, newVertices, _numVertices * _stride);
  107. free(newVertices);
  108. return uint32_t(vertexCount);
  109. }
  110. void writeCompressedIndices(bx::WriterI* _writer, const uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices)
  111. {
  112. size_t maxSize = meshopt_encodeIndexBufferBound(_numIndices, _numVertices);
  113. unsigned char* compressedIndices = (unsigned char*)malloc(maxSize);
  114. size_t compressedSize = meshopt_encodeIndexBuffer(compressedIndices, maxSize, _indices, _numIndices);
  115. printf( "indices uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  116. , _numIndices*2
  117. , (uint32_t)compressedSize
  118. , 100.0f - float(compressedSize ) / float(_numIndices*2)*100.0f
  119. );
  120. bx::write(_writer, (uint32_t)compressedSize);
  121. bx::write(_writer, compressedIndices, (uint32_t)compressedSize );
  122. free(compressedIndices);
  123. }
  124. void writeCompressedVertices(bx::WriterI* _writer, const uint8_t* _vertices, uint32_t _numVertices, uint16_t _stride)
  125. {
  126. size_t maxSize = meshopt_encodeVertexBufferBound(_numVertices, _stride);
  127. unsigned char* compressedVertices = (unsigned char*)malloc(maxSize);
  128. size_t compressedSize = meshopt_encodeVertexBuffer(compressedVertices, maxSize, _vertices, _numVertices, _stride);
  129. printf("vertices uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  130. , _numVertices * _stride
  131. , (uint32_t)compressedSize
  132. , 100.0f - float(compressedSize) / float(_numVertices * _stride)*100.0f
  133. );
  134. bx::write(_writer, (uint32_t)compressedSize);
  135. bx::write(_writer, compressedVertices, (uint32_t)compressedSize );
  136. free(compressedVertices);
  137. }
  138. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexDecl _decl, const uint16_t* _indices, uint32_t _numIndices)
  139. {
  140. struct PosTexcoord
  141. {
  142. float m_x;
  143. float m_y;
  144. float m_z;
  145. float m_pad0;
  146. float m_u;
  147. float m_v;
  148. float m_pad1;
  149. float m_pad2;
  150. };
  151. float* tangents = new float[6*_numVertices];
  152. bx::memSet(tangents, 0, 6*_numVertices*sizeof(float) );
  153. PosTexcoord v0;
  154. PosTexcoord v1;
  155. PosTexcoord v2;
  156. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  157. {
  158. const uint16_t* indices = &_indices[ii*3];
  159. uint32_t i0 = indices[0];
  160. uint32_t i1 = indices[1];
  161. uint32_t i2 = indices[2];
  162. bgfx::vertexUnpack(&v0.m_x, bgfx::Attrib::Position, _decl, _vertices, i0);
  163. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i0);
  164. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _decl, _vertices, i1);
  165. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i1);
  166. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _decl, _vertices, i2);
  167. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i2);
  168. const float bax = v1.m_x - v0.m_x;
  169. const float bay = v1.m_y - v0.m_y;
  170. const float baz = v1.m_z - v0.m_z;
  171. const float bau = v1.m_u - v0.m_u;
  172. const float bav = v1.m_v - v0.m_v;
  173. const float cax = v2.m_x - v0.m_x;
  174. const float cay = v2.m_y - v0.m_y;
  175. const float caz = v2.m_z - v0.m_z;
  176. const float cau = v2.m_u - v0.m_u;
  177. const float cav = v2.m_v - v0.m_v;
  178. const float det = (bau * cav - bav * cau);
  179. const float invDet = 1.0f / det;
  180. const float tx = (bax * cav - cax * bav) * invDet;
  181. const float ty = (bay * cav - cay * bav) * invDet;
  182. const float tz = (baz * cav - caz * bav) * invDet;
  183. const float bx = (cax * bau - bax * cau) * invDet;
  184. const float by = (cay * bau - bay * cau) * invDet;
  185. const float bz = (caz * bau - baz * cau) * invDet;
  186. for (uint32_t jj = 0; jj < 3; ++jj)
  187. {
  188. float* tanu = &tangents[indices[jj]*6];
  189. float* tanv = &tanu[3];
  190. tanu[0] += tx;
  191. tanu[1] += ty;
  192. tanu[2] += tz;
  193. tanv[0] += bx;
  194. tanv[1] += by;
  195. tanv[2] += bz;
  196. }
  197. }
  198. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  199. {
  200. const bx::Vec3 tanu = bx::load<bx::Vec3>(&tangents[ii*6]);
  201. const bx::Vec3 tanv = bx::load<bx::Vec3>(&tangents[ii*6 + 3]);
  202. float nxyzw[4];
  203. bgfx::vertexUnpack(nxyzw, bgfx::Attrib::Normal, _decl, _vertices, ii);
  204. const bx::Vec3 normal = bx::load<bx::Vec3>(nxyzw);
  205. const float ndt = bx::dot(normal, tanu);
  206. const bx::Vec3 nxt = bx::cross(normal, tanu);
  207. const bx::Vec3 tmp = bx::sub(tanu, bx::mul(normal, ndt) );
  208. float tangent[4];
  209. bx::store(tangent, bx::normalize(tmp) );
  210. tangent[3] = bx::dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  211. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _decl, _vertices, ii);
  212. }
  213. delete [] tangents;
  214. }
  215. void write(bx::WriterI* _writer, const void* _vertices, uint32_t _numVertices, uint32_t _stride)
  216. {
  217. Sphere maxSphere;
  218. calcMaxBoundingSphere(maxSphere, _vertices, _numVertices, _stride);
  219. Sphere minSphere;
  220. calcMinBoundingSphere(minSphere, _vertices, _numVertices, _stride);
  221. if (minSphere.radius > maxSphere.radius)
  222. {
  223. bx::write(_writer, maxSphere);
  224. }
  225. else
  226. {
  227. bx::write(_writer, minSphere);
  228. }
  229. Aabb aabb;
  230. toAabb(aabb, _vertices, _numVertices, _stride);
  231. bx::write(_writer, aabb);
  232. Obb obb;
  233. calcObb(obb, _vertices, _numVertices, _stride, s_obbSteps);
  234. bx::write(_writer, obb);
  235. }
  236. void write(bx::WriterI* _writer
  237. , const uint8_t* _vertices
  238. , uint32_t _numVertices
  239. , const bgfx::VertexDecl& _decl
  240. , const uint16_t* _indices
  241. , uint32_t _numIndices
  242. , bool _compress
  243. , const stl::string& _material
  244. , const PrimitiveArray& _primitives
  245. )
  246. {
  247. using namespace bx;
  248. using namespace bgfx;
  249. uint32_t stride = _decl.getStride();
  250. if (_compress)
  251. {
  252. write(_writer, BGFX_CHUNK_MAGIC_VBC);
  253. write(_writer, _vertices, _numVertices, stride);
  254. write(_writer, _decl);
  255. write(_writer, uint16_t(_numVertices) );
  256. writeCompressedVertices(_writer, _vertices, _numVertices, uint16_t(stride));
  257. }
  258. else
  259. {
  260. write(_writer, BGFX_CHUNK_MAGIC_VB);
  261. write(_writer, _vertices, _numVertices, stride);
  262. write(_writer, _decl);
  263. write(_writer, uint16_t(_numVertices) );
  264. write(_writer, _vertices, _numVertices*stride);
  265. }
  266. if (_compress)
  267. {
  268. write(_writer, BGFX_CHUNK_MAGIC_IBC);
  269. write(_writer, _numIndices);
  270. writeCompressedIndices(_writer, _indices, _numIndices, _numVertices);
  271. }
  272. else
  273. {
  274. write(_writer, BGFX_CHUNK_MAGIC_IB);
  275. write(_writer, _numIndices);
  276. write(_writer, _indices, _numIndices*2);
  277. }
  278. write(_writer, BGFX_CHUNK_MAGIC_PRI);
  279. uint16_t nameLen = uint16_t(_material.size() );
  280. write(_writer, nameLen);
  281. write(_writer, _material.c_str(), nameLen);
  282. write(_writer, uint16_t(_primitives.size() ) );
  283. for (PrimitiveArray::const_iterator primIt = _primitives.begin(); primIt != _primitives.end(); ++primIt)
  284. {
  285. const Primitive& prim = *primIt;
  286. nameLen = uint16_t(prim.m_name.size() );
  287. write(_writer, nameLen);
  288. write(_writer, prim.m_name.c_str(), nameLen);
  289. write(_writer, prim.m_startIndex);
  290. write(_writer, prim.m_numIndices);
  291. write(_writer, prim.m_startVertex);
  292. write(_writer, prim.m_numVertices);
  293. write(_writer, &_vertices[prim.m_startVertex*stride], prim.m_numVertices, stride);
  294. }
  295. }
  296. inline uint32_t rgbaToAbgr(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a)
  297. {
  298. return (uint32_t(_r)<<0)
  299. | (uint32_t(_g)<<8)
  300. | (uint32_t(_b)<<16)
  301. | (uint32_t(_a)<<24)
  302. ;
  303. }
  304. struct GroupSortByMaterial
  305. {
  306. bool operator()(const Group& _lhs, const Group& _rhs)
  307. {
  308. return 0 < bx::strCmp(_lhs.m_material.c_str(), _rhs.m_material.c_str() );
  309. }
  310. };
  311. void help(const char* _error = NULL)
  312. {
  313. if (NULL != _error)
  314. {
  315. fprintf(stderr, "Error:\n%s\n\n", _error);
  316. }
  317. fprintf(stderr
  318. , "geometryc, bgfx geometry compiler tool, version %d.%d.%d.\n"
  319. "Copyright 2011-2019 Branimir Karadzic. All rights reserved.\n"
  320. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n\n"
  321. , BGFX_GEOMETRYC_VERSION_MAJOR
  322. , BGFX_GEOMETRYC_VERSION_MINOR
  323. , BGFX_API_VERSION
  324. );
  325. fprintf(stderr
  326. , "Usage: geometryc -f <in> -o <out>\n"
  327. "\n"
  328. "Supported input file types:\n"
  329. " *.obj Wavefront\n"
  330. "\n"
  331. "Options:\n"
  332. " -h, --help Help.\n"
  333. " -v, --version Version information only.\n"
  334. " -f <file path> Input file path.\n"
  335. " -o <file path> Output file path.\n"
  336. " -s, --scale <num> Scale factor.\n"
  337. " --ccw Counter-clockwise winding order.\n"
  338. " --flipv Flip texture coordinate V.\n"
  339. " --obb <num> Number of steps for calculating oriented bounding box.\n"
  340. " Default value is 17. Less steps less precise OBB is.\n"
  341. " More steps slower calculation.\n"
  342. " --packnormal <num> Normal packing.\n"
  343. " 0 - unpacked 12 bytes (default).\n"
  344. " 1 - packed 4 bytes.\n"
  345. " --packuv <num> Texture coordinate packing.\n"
  346. " 0 - unpacked 8 bytes (default).\n"
  347. " 1 - packed 4 bytes.\n"
  348. " --tangent Calculate tangent vectors (packing mode is the same as normal).\n"
  349. " --barycentric Adds barycentric vertex attribute (packed in bgfx::Attrib::Color1).\n"
  350. " -c, --compress Compress indices.\n"
  351. "\n"
  352. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  353. );
  354. }
  355. int main(int _argc, const char* _argv[])
  356. {
  357. bx::CommandLine cmdLine(_argc, _argv);
  358. if (cmdLine.hasArg('v', "version") )
  359. {
  360. fprintf(stderr
  361. , "geometryc, bgfx geometry compiler tool, version %d.%d.%d.\n"
  362. , BGFX_GEOMETRYC_VERSION_MAJOR
  363. , BGFX_GEOMETRYC_VERSION_MINOR
  364. , BGFX_API_VERSION
  365. );
  366. return bx::kExitSuccess;
  367. }
  368. if (cmdLine.hasArg('h', "help") )
  369. {
  370. help();
  371. return bx::kExitFailure;
  372. }
  373. const char* filePath = cmdLine.findOption('f');
  374. if (NULL == filePath)
  375. {
  376. help("Input file name must be specified.");
  377. return bx::kExitFailure;
  378. }
  379. const char* outFilePath = cmdLine.findOption('o');
  380. if (NULL == outFilePath)
  381. {
  382. help("Output file name must be specified.");
  383. return bx::kExitFailure;
  384. }
  385. float scale = 1.0f;
  386. const char* scaleArg = cmdLine.findOption('s', "scale");
  387. if (NULL != scaleArg)
  388. {
  389. if (!bx::fromString(&scale, scaleArg))
  390. {
  391. scale = 1.0f;
  392. }
  393. }
  394. bool compress = cmdLine.hasArg('c', "compress");
  395. cmdLine.hasArg(s_obbSteps, '\0', "obb");
  396. s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90);
  397. uint32_t packNormal = 0;
  398. cmdLine.hasArg(packNormal, '\0', "packnormal");
  399. uint32_t packUv = 0;
  400. cmdLine.hasArg(packUv, '\0', "packuv");
  401. bool ccw = cmdLine.hasArg("ccw");
  402. bool flipV = cmdLine.hasArg("flipv");
  403. bool hasTangent = cmdLine.hasArg("tangent");
  404. bool hasBc = cmdLine.hasArg("barycentric");
  405. FILE* file = fopen(filePath, "r");
  406. if (NULL == file)
  407. {
  408. printf("Unable to open input file '%s'.", filePath);
  409. exit(bx::kExitFailure);
  410. }
  411. int64_t parseElapsed = -bx::getHPCounter();
  412. int64_t triReorderElapsed = 0;
  413. uint32_t size = (uint32_t)fsize(file);
  414. char* data = new char[size+1];
  415. size = (uint32_t)fread(data, 1, size, file);
  416. data[size] = '\0';
  417. fclose(file);
  418. // Reference(s):
  419. // - Wavefront .obj file
  420. // https://en.wikipedia.org/wiki/Wavefront_.obj_file
  421. Vec3Array positions;
  422. Vec3Array normals;
  423. Vec3Array texcoords;
  424. Index3Map indexMap;
  425. TriangleArray triangles;
  426. GroupArray groups;
  427. uint32_t num = 0;
  428. Group group;
  429. group.m_startTriangle = 0;
  430. group.m_numTriangles = 0;
  431. char commandLine[2048];
  432. uint32_t len = sizeof(commandLine);
  433. int argc;
  434. char* argv[64];
  435. for (bx::StringView next(data, size); !next.isEmpty(); )
  436. {
  437. next = bx::tokenizeCommandLine(next, commandLine, len, argc, argv, BX_COUNTOF(argv), '\n');
  438. if (0 < argc)
  439. {
  440. if (0 == bx::strCmp(argv[0], "#") )
  441. {
  442. if (2 < argc
  443. && 0 == bx::strCmp(argv[2], "polygons") )
  444. {
  445. }
  446. }
  447. else if (0 == bx::strCmp(argv[0], "f") )
  448. {
  449. TriIndices triangle;
  450. bx::memSet(&triangle, 0, sizeof(TriIndices) );
  451. const int numNormals = (int)normals.size();
  452. const int numTexcoords = (int)texcoords.size();
  453. const int numPositions = (int)positions.size();
  454. for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
  455. {
  456. Index3 index;
  457. index.m_texcoord = -1;
  458. index.m_normal = -1;
  459. index.m_vertexIndex = -1;
  460. if (hasBc)
  461. {
  462. index.m_vbc = edge < 3 ? edge : (1+(edge+1) )&1;
  463. }
  464. else
  465. {
  466. index.m_vbc = 0;
  467. }
  468. {
  469. bx::StringView triplet(argv[edge + 1]);
  470. bx::StringView vertex(triplet);
  471. bx::StringView texcoord = bx::strFind(triplet, '/');
  472. if (!texcoord.isEmpty())
  473. {
  474. vertex.set(vertex.getPtr(), texcoord.getPtr());
  475. const bx::StringView normal = bx::strFind(bx::StringView(texcoord.getPtr() + 1, triplet.getTerm()), '/');
  476. if (!normal.isEmpty())
  477. {
  478. int32_t nn;
  479. bx::fromString(&nn, bx::StringView(normal.getPtr() + 1, triplet.getTerm()));
  480. index.m_normal = (nn < 0) ? nn + numNormals : nn - 1;
  481. }
  482. texcoord.set(texcoord.getPtr() + 1, normal.getPtr());
  483. // Reference(s):
  484. // - Wavefront .obj file / Vertex normal indices without texture coordinate indices
  485. // https://en.wikipedia.org/wiki/Wavefront_.obj_file#Vertex_Normal_Indices_Without_Texture_Coordinate_Indices
  486. if (!texcoord.isEmpty())
  487. {
  488. int32_t tex;
  489. bx::fromString(&tex, texcoord);
  490. index.m_texcoord = (tex < 0) ? tex + numTexcoords : tex - 1;
  491. }
  492. }
  493. int32_t pos;
  494. bx::fromString(&pos, vertex);
  495. index.m_position = (pos < 0) ? pos + numPositions : pos - 1;
  496. }
  497. const uint64_t hash0 = uint64_t(index.m_position)<< 0;
  498. const uint64_t hash1 = uint64_t(index.m_texcoord)<<20;
  499. const uint64_t hash2 = uint64_t(index.m_normal )<<40;
  500. const uint64_t hash3 = uint64_t(index.m_vbc )<<60;
  501. const uint64_t hash = hash0^hash1^hash2^hash3;
  502. stl::pair<Index3Map::iterator, bool> result = indexMap.insert(stl::make_pair(hash, index) );
  503. if (!result.second)
  504. {
  505. Index3& oldIndex = result.first->second;
  506. BX_UNUSED(oldIndex);
  507. BX_CHECK(true
  508. && oldIndex.m_position == index.m_position
  509. && oldIndex.m_texcoord == index.m_texcoord
  510. && oldIndex.m_normal == index.m_normal
  511. , "Hash collision!"
  512. );
  513. }
  514. switch (edge)
  515. {
  516. case 0: case 1: case 2:
  517. triangle.m_index[edge] = hash;
  518. if (2 == edge)
  519. {
  520. if (ccw)
  521. {
  522. std::swap(triangle.m_index[1], triangle.m_index[2]);
  523. }
  524. triangles.push_back(triangle);
  525. }
  526. break;
  527. default:
  528. if (ccw)
  529. {
  530. triangle.m_index[2] = triangle.m_index[1];
  531. triangle.m_index[1] = hash;
  532. }
  533. else
  534. {
  535. triangle.m_index[1] = triangle.m_index[2];
  536. triangle.m_index[2] = hash;
  537. }
  538. triangles.push_back(triangle);
  539. break;
  540. }
  541. }
  542. }
  543. else if (0 == bx::strCmp(argv[0], "g") )
  544. {
  545. group.m_name = argv[1];
  546. }
  547. else if (*argv[0] == 'v')
  548. {
  549. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  550. if (0 < group.m_numTriangles)
  551. {
  552. groups.push_back(group);
  553. group.m_startTriangle = (uint32_t)(triangles.size() );
  554. group.m_numTriangles = 0;
  555. }
  556. if (0 == bx::strCmp(argv[0], "vn") )
  557. {
  558. bx::Vec3 normal;
  559. bx::fromString(&normal.x, argv[1]);
  560. bx::fromString(&normal.y, argv[2]);
  561. bx::fromString(&normal.z, argv[3]);
  562. normals.push_back(normal);
  563. }
  564. else if (0 == bx::strCmp(argv[0], "vp") )
  565. {
  566. static bool once = true;
  567. if (once)
  568. {
  569. once = false;
  570. printf("warning: 'parameter space vertices' are unsupported.\n");
  571. }
  572. }
  573. else if (0 == bx::strCmp(argv[0], "vt") )
  574. {
  575. bx::Vec3 texcoord;
  576. texcoord.y = 0.0f;
  577. texcoord.z = 0.0f;
  578. bx::fromString(&texcoord.x, argv[1]);
  579. switch (argc)
  580. {
  581. case 4:
  582. bx::fromString(&texcoord.z, argv[3]);
  583. BX_FALLTHROUGH;
  584. case 3:
  585. bx::fromString(&texcoord.y, argv[2]);
  586. break;
  587. default:
  588. break;
  589. }
  590. texcoords.push_back(texcoord);
  591. }
  592. else
  593. {
  594. float px, py, pz, pw;
  595. bx::fromString(&px, argv[1]);
  596. bx::fromString(&py, argv[2]);
  597. bx::fromString(&pz, argv[3]);
  598. if (argc == 5 || argc == 8)
  599. {
  600. bx::fromString(&pw, argv[4]);
  601. }
  602. else
  603. {
  604. pw = 1.0f;
  605. }
  606. float invW = scale/pw;
  607. px *= invW;
  608. py *= invW;
  609. pz *= invW;
  610. bx::Vec3 pos;
  611. pos.x = px;
  612. pos.y = py;
  613. pos.z = pz;
  614. positions.push_back(pos);
  615. }
  616. }
  617. else if (0 == bx::strCmp(argv[0], "usemtl") )
  618. {
  619. stl::string material(argv[1]);
  620. if (0 != bx::strCmp(material.c_str(), group.m_material.c_str() ) )
  621. {
  622. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  623. if (0 < group.m_numTriangles)
  624. {
  625. groups.push_back(group);
  626. group.m_startTriangle = (uint32_t)(triangles.size() );
  627. group.m_numTriangles = 0;
  628. }
  629. }
  630. group.m_material = material;
  631. }
  632. // unsupported tags
  633. // else if (0 == bx::strCmp(argv[0], "mtllib") )
  634. // {
  635. // }
  636. // else if (0 == bx::strCmp(argv[0], "o") )
  637. // {
  638. // }
  639. // else if (0 == bx::strCmp(argv[0], "s") )
  640. // {
  641. // }
  642. }
  643. ++num;
  644. }
  645. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  646. if (0 < group.m_numTriangles)
  647. {
  648. groups.push_back(group);
  649. group.m_startTriangle = (uint32_t)(triangles.size() );
  650. group.m_numTriangles = 0;
  651. }
  652. delete [] data;
  653. int64_t now = bx::getHPCounter();
  654. parseElapsed += now;
  655. int64_t convertElapsed = -now;
  656. std::sort(groups.begin(), groups.end(), GroupSortByMaterial() );
  657. bool hasColor = false;
  658. bool hasNormal;
  659. bool hasTexcoord;
  660. {
  661. Index3Map::const_iterator it = indexMap.begin();
  662. hasNormal = -1 != it->second.m_normal;
  663. hasTexcoord = -1 != it->second.m_texcoord;
  664. if (!hasTexcoord)
  665. {
  666. for (Index3Map::iterator jt = indexMap.begin(), jtEnd = indexMap.end(); jt != jtEnd && !hasTexcoord; ++jt)
  667. {
  668. hasTexcoord |= -1 != jt->second.m_texcoord;
  669. }
  670. if (hasTexcoord)
  671. {
  672. for (Index3Map::iterator jt = indexMap.begin(), jtEnd = indexMap.end(); jt != jtEnd; ++jt)
  673. {
  674. jt->second.m_texcoord = -1 == jt->second.m_texcoord ? 0 : jt->second.m_texcoord;
  675. }
  676. }
  677. }
  678. if (!hasNormal)
  679. {
  680. for (Index3Map::iterator jt = indexMap.begin(), jtEnd = indexMap.end(); jt != jtEnd && !hasNormal; ++jt)
  681. {
  682. hasNormal |= -1 != jt->second.m_normal;
  683. }
  684. if (hasNormal)
  685. {
  686. for (Index3Map::iterator jt = indexMap.begin(), jtEnd = indexMap.end(); jt != jtEnd; ++jt)
  687. {
  688. jt->second.m_normal = -1 == jt->second.m_normal ? 0 : jt->second.m_normal;
  689. }
  690. }
  691. }
  692. }
  693. bgfx::VertexDecl decl;
  694. decl.begin();
  695. decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  696. if (hasColor)
  697. {
  698. decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  699. }
  700. if (hasBc)
  701. {
  702. decl.add(bgfx::Attrib::Color1, 4, bgfx::AttribType::Uint8, true);
  703. }
  704. if (hasTexcoord)
  705. {
  706. switch (packUv)
  707. {
  708. default:
  709. case 0:
  710. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  711. break;
  712. case 1:
  713. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  714. break;
  715. }
  716. }
  717. if (hasNormal)
  718. {
  719. hasTangent &= hasTexcoord;
  720. switch (packNormal)
  721. {
  722. default:
  723. case 0:
  724. decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  725. if (hasTangent)
  726. {
  727. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
  728. }
  729. break;
  730. case 1:
  731. decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  732. if (hasTangent)
  733. {
  734. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
  735. }
  736. break;
  737. }
  738. }
  739. decl.end();
  740. uint32_t stride = decl.getStride();
  741. uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride];
  742. uint16_t* indexData = new uint16_t[triangles.size() * 3];
  743. int32_t numVertices = 0;
  744. int32_t numIndices = 0;
  745. int32_t writtenPrimitives = 0;
  746. int32_t writtenVertices = 0;
  747. int32_t writtenIndices = 0;
  748. uint8_t* vertices = vertexData;
  749. uint16_t* indices = indexData;
  750. stl::string material = groups.begin()->m_material;
  751. PrimitiveArray primitives;
  752. bx::FileWriter writer;
  753. if (!bx::open(&writer, outFilePath) )
  754. {
  755. printf("Unable to open output file '%s'.", outFilePath);
  756. exit(bx::kExitFailure);
  757. }
  758. Primitive prim;
  759. prim.m_startVertex = 0;
  760. prim.m_startIndex = 0;
  761. uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position);
  762. uint32_t color0Offset = decl.getOffset(bgfx::Attrib::Color0);
  763. Group sentinelGroup;
  764. sentinelGroup.m_startTriangle = 0;
  765. sentinelGroup.m_numTriangles = UINT32_MAX;
  766. groups.push_back(sentinelGroup);
  767. uint32_t ii = 0;
  768. for (GroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii)
  769. {
  770. bool sentinel = groupIt->m_startTriangle == 0 && groupIt->m_numTriangles == UINT32_MAX;
  771. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  772. {
  773. if (0 != bx::strCmp(material.c_str(), groupIt->m_material.c_str() )
  774. || sentinel
  775. || 65533 <= numVertices)
  776. {
  777. prim.m_numVertices = numVertices - prim.m_startVertex;
  778. prim.m_numIndices = numIndices - prim.m_startIndex;
  779. if (0 < prim.m_numVertices)
  780. {
  781. primitives.push_back(prim);
  782. }
  783. if (hasTangent)
  784. {
  785. calcTangents(vertexData, uint16_t(numVertices), decl, indexData, numIndices);
  786. }
  787. triReorderElapsed -= bx::getHPCounter();
  788. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  789. {
  790. const Primitive& prim1 = *primIt;
  791. optimizeVertexCache(indexData + prim1.m_startIndex, prim1.m_numIndices, numVertices);
  792. }
  793. numVertices = optimizeVertexFetch(indexData, numIndices, vertexData, numVertices, uint16_t(stride));
  794. triReorderElapsed += bx::getHPCounter();
  795. write(&writer
  796. , vertexData
  797. , numVertices
  798. , decl
  799. , indexData
  800. , numIndices
  801. , compress
  802. , material
  803. , primitives
  804. );
  805. primitives.clear();
  806. for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt)
  807. {
  808. indexIt->second.m_vertexIndex = -1;
  809. }
  810. ++writtenPrimitives;
  811. writtenVertices += numVertices;
  812. writtenIndices += numIndices;
  813. vertices = vertexData;
  814. indices = indexData;
  815. numVertices = 0;
  816. numIndices = 0;
  817. prim.m_startVertex = 0;
  818. prim.m_startIndex = 0;
  819. material = groupIt->m_material;
  820. if (sentinel)
  821. break;
  822. }
  823. TriIndices& triangle = triangles[tri];
  824. for (uint32_t edge = 0; edge < 3; ++edge)
  825. {
  826. uint64_t hash = triangle.m_index[edge];
  827. Index3& index = indexMap[hash];
  828. if (index.m_vertexIndex == -1)
  829. {
  830. index.m_vertexIndex = numVertices++;
  831. float* position = (float*)(vertices + positionOffset);
  832. bx::memCopy(position, &positions[index.m_position], 3*sizeof(float) );
  833. if (hasColor)
  834. {
  835. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  836. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  837. }
  838. if (hasBc)
  839. {
  840. const float bc[3] =
  841. {
  842. (index.m_vbc == 0) ? 1.0f : 0.0f,
  843. (index.m_vbc == 1) ? 1.0f : 0.0f,
  844. (index.m_vbc == 2) ? 1.0f : 0.0f,
  845. };
  846. bgfx::vertexPack(bc, true, bgfx::Attrib::Color1, decl, vertices);
  847. }
  848. if (hasTexcoord)
  849. {
  850. float uv[2];
  851. bx::memCopy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) );
  852. if (flipV)
  853. {
  854. uv[1] = -uv[1];
  855. }
  856. bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, decl, vertices);
  857. }
  858. if (hasNormal)
  859. {
  860. float normal[4];
  861. bx::store(normal, bx::normalize(bx::load<bx::Vec3>(&normals[index.m_normal]) ) );
  862. bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, decl, vertices);
  863. }
  864. vertices += stride;
  865. }
  866. *indices++ = (uint16_t)index.m_vertexIndex;
  867. ++numIndices;
  868. }
  869. }
  870. prim.m_numVertices = numVertices - prim.m_startVertex;
  871. if (0 < prim.m_numVertices)
  872. {
  873. prim.m_numIndices = numIndices - prim.m_startIndex;
  874. prim.m_name = groupIt->m_name;
  875. primitives.push_back(prim);
  876. prim.m_startVertex = numVertices;
  877. prim.m_startIndex = numIndices;
  878. }
  879. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  880. , ii
  881. , groupIt->m_startTriangle
  882. , groupIt->m_numTriangles
  883. , groupIt->m_material.c_str()
  884. );
  885. }
  886. BX_CHECK(0 == primitives.size(), "Not all primitives are written");
  887. printf("size: %d\n", uint32_t(bx::seek(&writer) ) );
  888. bx::close(&writer);
  889. delete [] indexData;
  890. delete [] vertexData;
  891. now = bx::getHPCounter();
  892. convertElapsed += now;
  893. printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n"
  894. , double(parseElapsed)/bx::getHPFrequency()
  895. , double(triReorderElapsed)/bx::getHPFrequency()
  896. , double(convertElapsed)/bx::getHPFrequency()
  897. , num
  898. , uint32_t(groups.size() )
  899. , writtenPrimitives
  900. , writtenVertices
  901. , writtenIndices
  902. );
  903. return bx::kExitSuccess;
  904. }