geometryc.cpp 27 KB

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