geometryc.cpp 27 KB

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