geometryc.cpp 22 KB

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